diff --git a/.idea/icon.svg b/.idea/icon.svg new file mode 100644 index 0000000000..c032cea149 --- /dev/null +++ b/.idea/icon.svg @@ -0,0 +1 @@ + diff --git a/build.gradle b/build.gradle index c567cbba15..5ae3d425b9 100644 --- a/build.gradle +++ b/build.gradle @@ -1,24 +1,27 @@ plugins { id('idea') - id("maven-publish") + id('maven-publish') + // todo replace with mc-publish, as these plugins do not support Gradle configuration cache id('com.modrinth.minotaur') version '2.+' id('com.matthewprenger.cursegradle') version '1.4.0' - id "org.jetbrains.gradle.plugin.idea-ext" version "1.1.9" - id 'net.neoforged.moddev.legacyforge' version '2.0.80' + id('net.neoforged.moddev') version '2.0.80' } -group = "thedarkcolour.forestry" +tasks.named('wrapper', Wrapper).configure { + distributionType = Wrapper.DistributionType.BIN +} + +group = 'forestry' version = forestryVersion -archivesBaseName = "forestry-$minecraftVersion" +base.archivesName = "forestry-$minecraftVersion" -java.toolchain.languageVersion = JavaLanguageVersion.of(17) +java.toolchain.languageVersion = JavaLanguageVersion.of(21) -legacyForge { - version = "1.20.1-$forgeVersion" +neoForge { + version = "$neoForgeVersion" accessTransformers = files('src/main/resources/META-INF/accesstransformer.cfg') - // Set to false because Forge has broken access transformers - //validateAccessTransformers = true + validateAccessTransformers = true // Add Parchment parameter mappings parchment { @@ -60,21 +63,22 @@ repositories { maven { name = 'jei' url = 'https://maven.blamejared.com/' - content { includeGroup "mezz.jei" } + content { includeGroup 'mezz.jei' } } maven { - name = "Patchouli" - url = "https://maven.blamejared.com/" + name = 'Patchouli' + url = 'https://maven.blamejared.com/' + content { includeGroup 'vazkii.patchouli' } } maven { name = 'Architectury API' - url = "https://maven.architectury.dev" - content { includeGroup "dev.architectury" } + url = 'https://maven.architectury.dev' + content { includeGroup 'dev.architectury' } } maven { name = 'KubeJS and Rhino' url = 'https://maven.latvian.dev/releases' - content { includeGroup 'dev.latvian.mods' } + content { includeGroupAndSubgroups 'dev.latvian' } } maven { name = 'Mekanism' @@ -87,62 +91,55 @@ repositories { content { includeGroup 'top.theillusivec4.curios' } } maven { - url "https://cursemaven.com" - content { - includeGroup "curse.maven" - } + url = 'https://cursemaven.com' + content { includeGroup 'curse.maven' } } maven { - name = 'ModKit' - url 'https://jitpack.io' - content { includeGroup 'com.github.thedarkcolour' } + name = 'ModKit and KubeJS transitive dep' + url = 'https://jitpack.io' + content { + includeGroup 'com.github.thedarkcolour' + includeGroup 'com.github.rtyley' + } } } dependencies { // JEI OPTIONAL - modCompileOnly "mezz.jei:jei-$minecraftVersion-common-api:$jeiVersion" - modCompileOnly "mezz.jei:jei-$minecraftVersion-forge-api:$jeiVersion" - modRuntimeOnly "mezz.jei:jei-$minecraftVersion-forge:$jeiVersion" + compileOnly "mezz.jei:jei-$minecraftVersion-neoforge-api:$jeiVersion" + runtimeOnly "mezz.jei:jei-$minecraftVersion-neoforge:$jeiVersion" // KubeJS OPTIONAL - modImplementation "dev.architectury:architectury-forge:${architectury_version}" - modImplementation "dev.latvian.mods:rhino-forge:${rhino_version}" - modImplementation "dev.latvian.mods:kubejs-forge:${kubejs_version}" + implementation "dev.architectury:architectury-neoforge:${architectury_version}" + implementation "dev.latvian.mods:rhino:${rhino_version}" + implementation "dev.latvian.mods:kubejs-neoforge:${kubejs_version}" // Curios Optional - modImplementation "top.theillusivec4.curios:curios-forge:${curiosVersion}+${minecraftVersion}" + implementation "top.theillusivec4.curios:curios-neoforge:${curiosVersion}+${minecraftVersion}" // PATCHOULI REQUIRED - modCompileOnly "vazkii.patchouli:Patchouli:$patchouliVersion-FORGE:api" - modRuntimeOnly "vazkii.patchouli:Patchouli:$patchouliVersion-FORGE" + compileOnly "vazkii.patchouli:Patchouli:$patchouliVersion-NEOFORGE:api" + runtimeOnly "vazkii.patchouli:Patchouli:$patchouliVersion-NEOFORGE" // ModKit DEV ONLY - modImplementation 'com.github.thedarkcolour:ModKit:cc8f1c11ec' - - // DEV ONLY - compileOnly "org.jetbrains:annotations:23.0.0" + implementation 'com.github.thedarkcolour:ModKit:0cfafa780c' } sourceSets.main.resources { srcDir 'src/generated/resources' } -var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) { +var generateModMetadata = tasks.register('generateModMetadata', ProcessResources) { var replaceProperties = [ - "version" : project.version, - "forgeVersionRange" : forgeVersionRange, - "jeiVersionRange" : jeiVersionRange, - "patchouliVersionRange": patchouliVersionRange, - "fmlVersionRange" : fmlVersionRange, + 'version' : project.version, + 'forgeVersionRange' : forgeVersionRange, + 'jeiVersionRange' : jeiVersionRange, + 'patchouliVersionRange': patchouliVersionRange, + 'fmlVersionRange' : fmlVersionRange, ] inputs.properties replaceProperties expand replaceProperties - from "src/main/templates" - into "build/generated/sources/modMetadata" + from 'src/main/templates' + into 'build/generated/sources/modMetadata' } sourceSets.main.resources.srcDir generateModMetadata -idea.project.settings { - taskTriggers { - afterSync generateModMetadata - } -} +neoForge.ideSyncTask generateModMetadata jar { from sourceSets.main.output.classesDirs @@ -150,20 +147,20 @@ jar { manifest { attributes([ - "Specification-Title" : "Forestry", - "Specification-Vendor" : "SirSengir", - "Specification-Version" : "${project.version}", - "Implementation-Title" : "${project.name}", - "Implementation-Version" : "${project.version}", - "Implementation-Vendor" : "SirSengir", - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + "Specification-Title" : "Forestry", + "Specification-Vendor" : "SirSengir", + "Specification-Version" : "${project.version}", + "Implementation-Title" : "${project.name}", + "Implementation-Version" : "${project.version}", + "Implementation-Vendor" : "SirSengir", + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") ]) } } tasks.withType(JavaCompile).configureEach { options.encoding = "UTF-8" - options.compilerArgs << "-Xmaxerrs" << "400" + options.compilerArgs << "-Xmaxerrs" << "2000" } idea { @@ -214,7 +211,7 @@ publishing { publications { mavenJava(MavenPublication) { groupId = project.group - artifactId = project.archivesBaseName + artifactId = project.base.archivesName version = project.version // ForgeGradle will generate wild dependency definitions, see https://github.com/MinecraftForge/ForgeGradle/issues/584 @@ -242,8 +239,8 @@ publishing { maven { credentials { - username System.getenv("MODMAVEN_USER") - password System.getenv("MODMAVEN_PASSWORD") + username = System.getenv("MODMAVEN_USER") + password = System.getenv("MODMAVEN_PASSWORD") } name = "Modmaven" @@ -288,7 +285,7 @@ modrinth { loaders = ["forge"] changelog = getChangelog(project.version) - uploadFile = reobfJar + uploadFile = jar additionalFiles.add(sourcesJar) additionalFiles.add(apiJar) additionalFiles.add(javadocJar) @@ -324,4 +321,3 @@ static def getChangelog(Object version) { // Fallback in case this fails return "Forestry Update ${version}" } - diff --git a/changelog.md b/changelog.md index b235f4941e..7140558cc3 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,6 @@ +## Forestry 3.0.0 +- Moistener, Fermenter, Rainmaker, Biogas Engine, and Peat Engine fuels are now data-driven + ## Forestry 2.6.1 - Fixed Research Notes voiding items when used in the offhand (#222) - Fix tags for Survivalist tools (#221) diff --git a/gradle.properties b/gradle.properties index e790900135..692a4346ca 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,8 @@ -org.gradle.daemon=false -org.gradle.jvmargs=-Xmx3G +org.gradle.jvmargs=-Xmx1G +org.gradle.daemon=true +org.gradle.parallel=true org.gradle.caching=true +org.gradle.configuration-cache=true curseforgeId=1056828 modrinthId=2oORTOi2 @@ -9,21 +11,21 @@ modrinthId=2oORTOi2 forestryVersion=2.6.1 # Minecraft -minecraftVersion=1.20.1 -mappingsVersion=2023.06.26 +minecraftVersion=1.21.1 +mappingsVersion=2024.11.17 # Forge -forgeVersion=47.4.0 -forgeVersionRange=[47.3.5,) -fmlVersionRange=[43,) +neoForgeVersion=21.1.172 +forgeVersionRange=[21.1,) +fmlVersionRange=[4,) # JEI -jeiVersion=15.20.0.106 -jeiVersionRange=[15,) +jeiVersion=19.19.6.236 +jeiVersionRange=[19,) # Patchouli -patchouliVersion=1.20.1-84 -patchouliVersionRange=[1.20.1-84,) +patchouliVersion=1.21-88 +patchouliVersionRange=[1.21-88,) # KubeJS -kubejs_version=2001.6.5-build.16 -rhino_version=2001.2.3-build.10 -architectury_version=9.2.14 +kubejs_version=2101.7.1-build.181 +rhino_version=2101.2.7-build.74 +architectury_version=13.0.8 # Curios -curiosVersion=5.14.1 +curiosVersion=9.5.1 diff --git a/src/main/java/forestry/Forestry.java b/src/main/java/forestry/Forestry.java index 0b751486aa..23a2d9748b 100755 --- a/src/main/java/forestry/Forestry.java +++ b/src/main/java/forestry/Forestry.java @@ -5,13 +5,12 @@ import forestry.apiimpl.plugin.PluginManager; import forestry.core.EventHandlerCore; import forestry.core.config.ForestryConfig; -import forestry.core.network.NetworkHandler; import forestry.modules.ForestryModuleManager; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.ModLoadingContext; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.ModList; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.NeoForgeMod; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -25,17 +24,18 @@ public class Forestry { public static final boolean DEBUG = ModList.get().isLoaded("modkit"); public static final Logger LOGGER = LogManager.getLogger(ForestryConstants.MOD_ID); - public Forestry() { + public Forestry(ModContainer container) { + // IForestryModule - registration of game objects ForestryModuleManager moduleManager = (ForestryModuleManager) IForestryApi.INSTANCE.getModuleManager(); moduleManager.init(); - NetworkHandler.register(); - MinecraftForge.EVENT_BUS.register(EventHandlerCore.class); + NeoForge.EVENT_BUS.register(EventHandlerCore.class); + // IForestryPlugin - registration of Forestry data PluginManager.loadPlugins(); PluginManager.registerErrors(); - ForestryConfig.register(ModLoadingContext.get()); + ForestryConfig.register(container); - ForgeMod.enableMilkFluid(); + NeoForgeMod.enableMilkFluid(); } } diff --git a/src/main/java/forestry/api/ForestryCapabilities.java b/src/main/java/forestry/api/ForestryCapabilities.java index 281c02e992..01303cdaf6 100644 --- a/src/main/java/forestry/api/ForestryCapabilities.java +++ b/src/main/java/forestry/api/ForestryCapabilities.java @@ -1,33 +1,28 @@ package forestry.api; -import forestry.api.apiculture.IArmorApiarist; -import forestry.api.core.IArmorNaturalist; +import forestry.api.apiculture.IBeeProtection; +import forestry.api.core.ISpectacleVision; import forestry.api.genetics.capability.IIndividualHandlerItem; -import forestry.api.genetics.filter.IFilterLogic; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityManager; -import net.minecraftforge.common.capabilities.CapabilityToken; +import net.neoforged.neoforge.capabilities.ItemCapability; + +import static forestry.api.ForestryConstants.forestry; /** * All capabilities added by base Forestry. - *

- * If your mod does not require a dependency on Forestry, it is recommended to use your own CapabilityTokens instead - * of the ones below, as recommended by {@link net.minecraftforge.common.capabilities.ForgeCapabilities}. */ public class ForestryCapabilities { - // Apiculture - public static Capability ARMOR_APIARIST = CapabilityManager.get(new CapabilityToken<>() { - }); - - // Arboriculture - public static Capability ARMOR_NATURALIST = CapabilityManager.get(new CapabilityToken<>() { - }); + /** + * Items with this capability can protect the wearer from harmful bee effects. + */ + public static ItemCapability BEE_PROTECTION = ItemCapability.createVoid(forestry("bee_protection"), IBeeProtection.class); - // Genetics - public static Capability INDIVIDUAL_HANDLER_ITEM = CapabilityManager.get(new CapabilityToken<>() { - }); + /** + * Grants the wearer the ability to see wild bee hives and pollinated leaves more easily. + */ + public static ItemCapability SPECTACLE_VISION = ItemCapability.createVoid(forestry("spectacle_vision"), ISpectacleVision.class); - // Genetic Filter - public static Capability FILTER_LOGIC = CapabilityManager.get(new CapabilityToken<>() { - }); + /** + * Items with this capability support Forestry's genetic data. + */ + public static ItemCapability INDIVIDUAL_HANDLER_ITEM = ItemCapability.createVoid(forestry("individual"), IIndividualHandlerItem.class); } diff --git a/src/main/java/forestry/api/ForestryConstants.java b/src/main/java/forestry/api/ForestryConstants.java index 13eabf6049..092063f3cc 100644 --- a/src/main/java/forestry/api/ForestryConstants.java +++ b/src/main/java/forestry/api/ForestryConstants.java @@ -15,6 +15,6 @@ public class ForestryConstants { * @return A new resource location under the Forestry namespace. In most cases, mods should use their own namespace instead. */ public static ResourceLocation forestry(String path) { - return new ResourceLocation(MOD_ID, path); + return ResourceLocation.fromNamespaceAndPath(MOD_ID, path); } } diff --git a/src/main/java/forestry/api/ForestryDataMaps.java b/src/main/java/forestry/api/ForestryDataMaps.java new file mode 100644 index 0000000000..267a82c570 --- /dev/null +++ b/src/main/java/forestry/api/ForestryDataMaps.java @@ -0,0 +1,60 @@ +package forestry.api; + +import com.mojang.serialization.Codec; +import forestry.api.fuels.*; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.material.Fluid; + +import net.neoforged.neoforge.registries.datamaps.DataMapType; + +public class ForestryDataMaps { + /** + * Add new fuels for the fermenter here (i.e. fertilizer) + */ + public static final DataMapType FERMENTER_FUELS = create("fermenter_fuels", Registries.ITEM, FermenterFuel.CODEC) + .build(); + + /** + * Add new resources for the moistener here (i.e. wheat) + */ + public static final DataMapType MOISTENER_FUELS = create("moistener_fuels", Registries.ITEM, MoistenerFuel.CODEC) + .build(); + + /** + * Add new substrates for the rainmaker here + */ + public static final DataMapType RAINMAKER_FUELS = create("rainmaker_fuels", Registries.ITEM, RainmakerFuel.CODEC) + .synced(RainmakerFuel.CODEC, true) + .build(); + + /** + * Add new fuels for the Biogas Engine here + */ + public static final DataMapType BIOGAS_FUELS = create("biogas_fuels", Registries.FLUID, BiogasEngineFuel.CODEC) + .build(); + + /** + * Add new fuels for the Peat Engine here + */ + public static final DataMapType PEAT_FUELS = create("peat_fuels", Registries.ITEM, PeatEngineFuel.CODEC) + .build(); + + /** + * Add new fertilizers to use in Multiblock Farms and Planters + */ + public static final DataMapType FARM_FERTILIZERS = create("farm_fertilizers", Registries.ITEM, Codec.INT) + .build(); + + /** + * Add new items to be used as feed for the Alveary Swarmer + */ + public static final DataMapType SWARMER_FEED = create("swarmer_feed", Registries.ITEM, Codec.INT) + .build(); + + private static DataMapType.Builder create(String id, ResourceKey> registry, Codec codec) { + return DataMapType.builder(ForestryConstants.forestry(id), registry, codec); + } +} diff --git a/src/main/java/forestry/api/ForestryRegistries.java b/src/main/java/forestry/api/ForestryRegistries.java new file mode 100644 index 0000000000..cfbbf33e73 --- /dev/null +++ b/src/main/java/forestry/api/ForestryRegistries.java @@ -0,0 +1,28 @@ +package forestry.api; + +import forestry.api.circuits.ICircuit; +import forestry.api.genetics.ISpeciesType; +import forestry.api.mail.IPostalCarrier; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.neoforged.neoforge.registries.RegistryBuilder; + +public class ForestryRegistries { + public static final Registry CIRCUIT = new RegistryBuilder<>(Keys.CIRCUIT_TYPE) + .sync(true) + .create(); + + public static final Registry POSTAL_CARRIER = new RegistryBuilder<>(Keys.POSTAL_CARRIER) + .sync(true) + .create(); + + public static final Registry> SPECIES_TYPE = new RegistryBuilder<>(Keys.SPECIES_TYPE) + .sync(true) + .create(); + + public static class Keys { + public static final ResourceKey> CIRCUIT_TYPE = ResourceKey.createRegistryKey(ForestryConstants.forestry("circuit")); + public static final ResourceKey> POSTAL_CARRIER = ResourceKey.createRegistryKey(ForestryConstants.forestry("postal_carrier")); + public static final ResourceKey>> SPECIES_TYPE = ResourceKey.createRegistryKey(ForestryConstants.forestry("species_type")); + } +} diff --git a/src/main/java/forestry/api/ForestryTags.java b/src/main/java/forestry/api/ForestryTags.java index 54bba08783..47f97c8f4a 100644 --- a/src/main/java/forestry/api/ForestryTags.java +++ b/src/main/java/forestry/api/ForestryTags.java @@ -1,16 +1,13 @@ package forestry.api; -import forestry.arboriculture.ForestryWoodType; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; -import net.minecraft.tags.FluidTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.material.Fluid; import org.jetbrains.annotations.ApiStatus; public class ForestryTags { @@ -32,36 +29,6 @@ public static class Blocks { public static final TagKey STORAGE_BLOCKS_RAW_TIN = forgeTag("storage_blocks/raw_tin"); - // todo remove in favor of directly using IWoodAccess - public static final TagKey LARCH_LOGS = ForestryWoodType.LARCH.blockTag; - public static final TagKey TEAK_LOGS = ForestryWoodType.TEAK.blockTag; - public static final TagKey ACACIA_DESERT_LOGS = ForestryWoodType.ACACIA_DESERT.blockTag; - public static final TagKey LIME_LOGS = ForestryWoodType.LIME.blockTag; - public static final TagKey CHESTNUT_LOGS = ForestryWoodType.CHESTNUT.blockTag; - public static final TagKey WENGE_LOGS = ForestryWoodType.WENGE.blockTag; - public static final TagKey BAOBAB_LOGS = ForestryWoodType.BAOBAB.blockTag; - public static final TagKey SEQUOIA_LOGS = ForestryWoodType.SEQUOIA.blockTag; - public static final TagKey KAPOK_LOGS = ForestryWoodType.KAPOK.blockTag; - public static final TagKey EBONY_LOGS = ForestryWoodType.EBONY.blockTag; - public static final TagKey MAHOGANY_LOGS = ForestryWoodType.MAHOGANY.blockTag; - public static final TagKey BALSA_LOGS = ForestryWoodType.BALSA.blockTag; - public static final TagKey WILLOW_LOGS = ForestryWoodType.WILLOW.blockTag; - public static final TagKey WALNUT_LOGS = ForestryWoodType.WALNUT.blockTag; - public static final TagKey GREENHEART_LOGS = ForestryWoodType.GREENHEART.blockTag; - public static final TagKey MAHOE_LOGS = ForestryWoodType.MAHOE.blockTag; - public static final TagKey POPLAR_LOGS = ForestryWoodType.POPLAR.blockTag; - public static final TagKey PALM_LOGS = ForestryWoodType.PALM.blockTag; - public static final TagKey PAPAYA_LOGS = ForestryWoodType.PAPAYA.blockTag; - public static final TagKey PINE_LOGS = ForestryWoodType.PINE.blockTag; - public static final TagKey PLUM_LOGS = ForestryWoodType.PLUM.blockTag; - public static final TagKey MAPLE_LOGS = ForestryWoodType.MAPLE.blockTag; - public static final TagKey CITRUS_LOGS = ForestryWoodType.CITRUS.blockTag; - public static final TagKey GIGANTEUM_LOGS = ForestryWoodType.GIGANTEUM.blockTag; - public static final TagKey IPE_LOGS = ForestryWoodType.IPE.blockTag; - public static final TagKey PADAUK_LOGS = ForestryWoodType.PADAUK.blockTag; - public static final TagKey COCOBOLO_LOGS = ForestryWoodType.COCOBOLO.blockTag; - public static final TagKey ZEBRAWOOD_LOGS = ForestryWoodType.ZEBRAWOOD.blockTag; - // Categories of flowers public static final TagKey VANILLA_FLOWERS = blockTag("flowers/vanilla"); public static final TagKey NETHER_FLOWERS = blockTag("flowers/nether"); @@ -93,7 +60,7 @@ public static class Blocks { public static final TagKey SWARM_BEE_GROUND = blockTag("hive_grounds/swarm"); private static TagKey forgeTag(String name) { - return BlockTags.create(new ResourceLocation("forge", name)); + return BlockTags.create(ResourceLocation.fromNamespaceAndPath("c", name)); } } @@ -129,38 +96,10 @@ public static class Items { public static final TagKey STORAGE_BLOCKS_RAW_TIN = forgeTag("storage_blocks/raw_tin"); - public static final TagKey LARCH_LOGS = ForestryWoodType.LARCH.itemTag; - public static final TagKey TEAK_LOGS = ForestryWoodType.TEAK.itemTag; - public static final TagKey ACACIA_DESERT_LOGS = ForestryWoodType.ACACIA_DESERT.itemTag; - public static final TagKey LIME_LOGS = ForestryWoodType.LIME.itemTag; - public static final TagKey CHESTNUT_LOGS = ForestryWoodType.CHESTNUT.itemTag; - public static final TagKey WENGE_LOGS = ForestryWoodType.WENGE.itemTag; - public static final TagKey BAOBAB_LOGS = ForestryWoodType.BAOBAB.itemTag; - public static final TagKey SEQUOIA_LOGS = ForestryWoodType.SEQUOIA.itemTag; - public static final TagKey KAPOK_LOGS = ForestryWoodType.KAPOK.itemTag; - public static final TagKey EBONY_LOGS = ForestryWoodType.EBONY.itemTag; - public static final TagKey MAHOGANY_LOGS = ForestryWoodType.MAHOGANY.itemTag; - public static final TagKey BALSA_LOGS = ForestryWoodType.BALSA.itemTag; - public static final TagKey WILLOW_LOGS = ForestryWoodType.WILLOW.itemTag; - public static final TagKey WALNUT_LOGS = ForestryWoodType.WALNUT.itemTag; - public static final TagKey GREENHEART_LOGS = ForestryWoodType.GREENHEART.itemTag; - public static final TagKey MAHOE_LOGS = ForestryWoodType.MAHOE.itemTag; - public static final TagKey POPLAR_LOGS = ForestryWoodType.POPLAR.itemTag; - public static final TagKey PALM_LOGS = ForestryWoodType.PALM.itemTag; - public static final TagKey PAPAYA_LOGS = ForestryWoodType.PAPAYA.itemTag; - public static final TagKey PINE_LOGS = ForestryWoodType.PINE.itemTag; - public static final TagKey PLUM_LOGS = ForestryWoodType.PLUM.itemTag; - public static final TagKey MAPLE_LOGS = ForestryWoodType.MAPLE.itemTag; - public static final TagKey CITRUS_LOGS = ForestryWoodType.CITRUS.itemTag; - public static final TagKey GIGANTEUM_LOGS = ForestryWoodType.GIGANTEUM.itemTag; - public static final TagKey IPE_LOGS = ForestryWoodType.IPE.itemTag; - public static final TagKey PADAUK_LOGS = ForestryWoodType.PADAUK.itemTag; - public static final TagKey COCOBOLO_LOGS = ForestryWoodType.COCOBOLO.itemTag; - public static final TagKey ZEBRAWOOD_LOGS = ForestryWoodType.ZEBRAWOOD.itemTag; - public static final TagKey STAMPS = itemTag("stamps"); public static final TagKey SCOOPS = itemTag("scoops"); + public static final TagKey SOLDERING_IRONS = itemTag("soldering_irons"); public static final TagKey FORESTRY_FRUITS = itemTag("forestry_fruits"); public static final TagKey FRUITS = forgeTag("fruits"); @@ -190,14 +129,10 @@ public static class Items { public static final TagKey HUNTER_ALLOW = itemTag("backpack/allow/hunter"); public static final TagKey HUNTER_REJECT = itemTag("backpack/reject/hunter"); - // needed because forge doesn't have it and mods can't agree on a crafting table tag... - // todo: remove in 1.21 when Neo merges the tags unification PR - public static final TagKey CRAFTING_TABLES = itemTag("crafting_tables"); - public static final TagKey BEES = itemTag("bees"); private static TagKey forgeTag(String name) { - return ItemTags.create(new ResourceLocation("forge", name)); + return ItemTags.create(ResourceLocation.fromNamespaceAndPath("c", name)); } } @@ -224,14 +159,6 @@ private static TagKey tag(String path) { } } - public static class Fluids { - public static final TagKey HONEY = forgeTag("honey"); - - private static TagKey forgeTag(String name) { - return FluidTags.create(new ResourceLocation("forge", name)); - } - } - // These have to be outside of Blocks and Items classes so that ForestryWoodType doesn't cause a circular dependency @ApiStatus.Internal public static TagKey blockTag(String name) { diff --git a/src/main/java/forestry/api/apiculture/BeeManager.java b/src/main/java/forestry/api/apiculture/BeeManager.java deleted file mode 100644 index a6581dc717..0000000000 --- a/src/main/java/forestry/api/apiculture/BeeManager.java +++ /dev/null @@ -1,14 +0,0 @@ -package forestry.api.apiculture; - -import javax.annotation.Nullable; - -/** - * Some miscellaneous lists and settings for bees. - */ -public class BeeManager { - /** - * Used to check whether a player is wearing Apiarist Armor. - */ - @Nullable - public static IArmorApiaristHelper armorApiaristHelper; -} diff --git a/src/main/java/forestry/api/apiculture/IApiaristTracker.java b/src/main/java/forestry/api/apiculture/IApiaristTracker.java index 50088a221d..7381eb7517 100644 --- a/src/main/java/forestry/api/apiculture/IApiaristTracker.java +++ b/src/main/java/forestry/api/apiculture/IApiaristTracker.java @@ -1,6 +1,6 @@ package forestry.api.apiculture; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesType; diff --git a/src/main/java/forestry/api/apiculture/IArmorApiarist.java b/src/main/java/forestry/api/apiculture/IArmorApiarist.java deleted file mode 100644 index 9351e461c2..0000000000 --- a/src/main/java/forestry/api/apiculture/IArmorApiarist.java +++ /dev/null @@ -1,26 +0,0 @@ -package forestry.api.apiculture; - -import forestry.api.ForestryCapabilities; -import forestry.api.apiculture.genetics.IBeeEffect; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nullable; - -/** - * When implemented as a capability by armor items, protects the wearer from negative bee effects. - * - * @see ForestryCapabilities#ARMOR_APIARIST - */ -public interface IArmorApiarist { - /** - * Called when the apiarist's armor acts as protection against an attack. - * - * @param entity Entity being attacked - * @param armor Armor item - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return Whether or not the armor should protect the player from that attack - */ - boolean protectEntity(LivingEntity entity, ItemStack armor, @Nullable IBeeEffect cause, boolean doProtect); -} diff --git a/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java b/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java deleted file mode 100644 index acd199e9a8..0000000000 --- a/src/main/java/forestry/api/apiculture/IArmorApiaristHelper.java +++ /dev/null @@ -1,38 +0,0 @@ -package forestry.api.apiculture; - -import forestry.api.apiculture.genetics.IBeeEffect; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nullable; - -/** - * Helper class for checking whether an entity is wearing Apiarist Armor - * - * @author Vexatos - */ -public interface IArmorApiaristHelper { - /** - * Called when the apiarist's armor acts as protection against an attack. - * - * @param stack ItemStack to check - * @param entity Entity being attacked - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return Whether or not the item is valid Apiarist Armor and should protect the player from that attack - * @since Forestry 4.2 - */ - boolean isArmorApiarist(ItemStack stack, LivingEntity entity, IBeeEffect cause, boolean doProtect); - - /** - * Called when the apiarist's armor acts as protection against an attack. - * - * @param entity Entity being attacked - * @param cause Optional cause of attack, such as a bee effect identifier - * @param doProtect Whether or not to actually do the side effects of protection - * @return The number of valid Apiarist Armor pieces the player is wearing that are actually protecting. - * 4 means full protection, but it can go higher if they are holding items like the smoker. - * @since Forestry 4.2 - */ - int wearsItems(LivingEntity entity, @Nullable IBeeEffect cause, boolean doProtect); -} diff --git a/src/main/java/forestry/api/apiculture/IBeeHousing.java b/src/main/java/forestry/api/apiculture/IBeeHousing.java index 436e2d479f..3004cd007c 100644 --- a/src/main/java/forestry/api/apiculture/IBeeHousing.java +++ b/src/main/java/forestry/api/apiculture/IBeeHousing.java @@ -1,19 +1,18 @@ package forestry.api.apiculture; import com.mojang.authlib.GameProfile; -import forestry.api.apiculture.genetics.IBeeSpeciesType; import forestry.api.climate.IBiomeProvider; import forestry.api.climate.IClimateProvider; import forestry.api.core.IErrorLogicSource; import forestry.api.core.ILocationProvider; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.phys.Vec3; import javax.annotation.Nullable; public interface IBeeHousing extends IErrorLogicSource, IClimateProvider, IBiomeProvider, ILocationProvider { - /** - * Used by {@link IBeeSpeciesType#createBeeHousingModifier(IBeeHousing)} + * Used by {@link forestry.api.apiculture.hives.IHiveManager#createBeeHousingModifier(IBeeHousing)} * to combine bee modifiers from several sources that can change over time. * * @return IBeeModifiers from the housing, frames, etc. @@ -21,7 +20,7 @@ public interface IBeeHousing extends IErrorLogicSource, IClimateProvider, IBiome Iterable getBeeModifiers(); /** - * Used by {@link IBeeSpeciesType#createBeeHousingListener(IBeeHousing)} + * Used by {@link forestry.api.apiculture.hives.IHiveManager#createBeeHousingListener(IBeeHousing)} * to combine bee listeners from several sources that can change over time. * * @return IBeeListeners from the housing, multiblock parts, etc. @@ -39,7 +38,7 @@ public interface IBeeHousing extends IErrorLogicSource, IClimateProvider, IBiome boolean isRaining(); @Nullable - GameProfile getOwner(); + ResolvableProfile getOwner(); /** * @return exact coordinates where bee particle FX should spawn from diff --git a/src/main/java/forestry/api/apiculture/IBeeModelProvider.java b/src/main/java/forestry/api/apiculture/IBeeModelProvider.java deleted file mode 100644 index 3184ff8764..0000000000 --- a/src/main/java/forestry/api/apiculture/IBeeModelProvider.java +++ /dev/null @@ -1,9 +0,0 @@ -package forestry.api.apiculture; - -import forestry.api.apiculture.genetics.BeeLifeStage; -import net.minecraft.client.resources.model.ModelResourceLocation; - -public interface IBeeModelProvider { - - ModelResourceLocation getModel(BeeLifeStage type); -} diff --git a/src/main/java/forestry/api/apiculture/IBeeModifier.java b/src/main/java/forestry/api/apiculture/IBeeModifier.java index 33e1ef71a5..32e0de7ec9 100644 --- a/src/main/java/forestry/api/apiculture/IBeeModifier.java +++ b/src/main/java/forestry/api/apiculture/IBeeModifier.java @@ -1,6 +1,6 @@ package forestry.api.apiculture; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.core.TemperatureType; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutation; diff --git a/src/main/java/forestry/api/apiculture/IBeeProtection.java b/src/main/java/forestry/api/apiculture/IBeeProtection.java new file mode 100644 index 0000000000..9493475511 --- /dev/null +++ b/src/main/java/forestry/api/apiculture/IBeeProtection.java @@ -0,0 +1,48 @@ +package forestry.api.apiculture; + +import forestry.api.ForestryCapabilities; +import forestry.api.apiculture.bee.IBeeEffect; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; + +import javax.annotation.Nullable; + +/** + * When implemented as a capability by armor items, protects the wearer from negative bee effects. + * + * @see ForestryCapabilities#BEE_PROTECTION + */ +public interface IBeeProtection { + /** + * Called when the apiarist's armor acts as protection against an attack. + * + * @param entity Entity being attacked + * @param armor Armor item + * @param cause Optional cause of attack, such as a bee effect identifier + * @param execute Whether or not to actually do the side effects of protection, use {@code false} if simulating + * @return Whether or not the armor should protect the player from that attack + */ + boolean doBeeProtection(LivingEntity entity, ItemStack armor, @Nullable IBeeEffect cause, boolean execute); + + /** + * Called when the apiarist's armor acts as protection against an attack. + * + * @param entity Entity being attacked + * @param cause Optional cause of attack, such as a bee effect identifier + * @param doProtect Whether or not to actually do the side effects of protection + * @return The number of valid Apiarist Armor pieces the player is wearing that are actually protecting. + * 4 means full protection. + */ + static int getBeeProtectionLevel(LivingEntity entity, @Nullable IBeeEffect cause, boolean doProtect) { + int count = 0; + + for (ItemStack armorItem : entity.getArmorSlots()) { + IBeeProtection capability = armorItem.getCapability(ForestryCapabilities.BEE_PROTECTION); + if (capability != null && capability.doBeeProtection(entity, armorItem, cause, doProtect)) { + count++; + } + } + + return count; + } +} diff --git a/src/main/java/forestry/api/apiculture/IBeeSpriteColourProvider.java b/src/main/java/forestry/api/apiculture/IBeeSpriteColourProvider.java deleted file mode 100644 index ee01985b33..0000000000 --- a/src/main/java/forestry/api/apiculture/IBeeSpriteColourProvider.java +++ /dev/null @@ -1,8 +0,0 @@ -package forestry.api.apiculture; - -/** - * Custom colour provider for bees with complicated colors. - */ -public interface IBeeSpriteColourProvider { - int getSpriteColour(int renderPass); -} diff --git a/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java b/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java index 92e15745ca..3185a966aa 100644 --- a/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java +++ b/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java @@ -3,10 +3,10 @@ import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.List; @@ -54,7 +54,7 @@ default void setWorkThrottle(int workThrottle) { /* CLIENT */ /** - * Sync to client by using {@link #write(net.minecraft.nbt.CompoundTag)} in your {@link net.minecraft.world.level.block.entity.BlockEntity#getUpdateTag()} + * Sync to client by using {@link INbtWritable#write(net.minecraft.nbt.CompoundTag, net.minecraft.core.HolderLookup.Provider)} in your {@link net.minecraft.world.level.block.entity.BlockEntity#getUpdateTag()} */ void syncToClient(); @@ -87,9 +87,9 @@ default void setWorkThrottle(int workThrottle) { */ List getFlowerPositions(); - default void readData(FriendlyByteBuf data) { + default void readData(RegistryFriendlyByteBuf buffer) { } - default void writeData(FriendlyByteBuf data) { + default void writeData(RegistryFriendlyByteBuf buffer) { } } diff --git a/src/main/java/forestry/api/apiculture/IBeekeepingMode.java b/src/main/java/forestry/api/apiculture/IBeekeepingMode.java deleted file mode 100644 index 93f3e7fc30..0000000000 --- a/src/main/java/forestry/api/apiculture/IBeekeepingMode.java +++ /dev/null @@ -1,55 +0,0 @@ -package forestry.api.apiculture; - -import forestry.api.apiculture.genetics.IBee; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; - -import java.util.List; - -public interface IBeekeepingMode { - - /** - * @return Localized name of this beekeeping mode. - */ - String getName(); - - /** - * @return Localized list of strings outlining the behaviour of this beekeeping mode. - */ - List getDescription(); - - /** - * @return Float used to modify the wear on comb frames. - */ - float getWearModifier(); - - /** - * @return fertility taking into account the birthing queen and surroundings. - */ - int getFinalFertility(IBee queen, Level world, BlockPos pos); - - /** - * @return true if the queen is genetically "fatigued" and should not be reproduced anymore. - */ - boolean isFatigued(IBee queen, IBeeHousing housing); - - /** - * @return true if the genetic structure of the queen is breaking down during spawning of the offspring (with chance). will trigger a negative effect. - */ - boolean isDegenerating(IBee queen, IBee offspring, IBeeHousing housing); - - /** - * @return {@code true} if an offspring of this queen is considered pristine - */ - boolean isOffspringPristine(IBee queen); - - /** - * @return true if this mode allows the passed queen or princess to be multiplied - */ - boolean mayMultiplyPrincess(IBee queen); - - /** - * @return the bee modifier for this mode - */ - IBeeModifier getBeeModifier(); -} diff --git a/src/main/java/forestry/api/apiculture/IJubilanceFactory.java b/src/main/java/forestry/api/apiculture/IJubilanceFactory.java deleted file mode 100644 index 749abea1bb..0000000000 --- a/src/main/java/forestry/api/apiculture/IJubilanceFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -package forestry.api.apiculture; - -import net.minecraft.world.level.block.state.BlockState; - -public interface IJubilanceFactory { - /** - * The default Jubilance Provider is satisfied when the humidity and temperature are ideal for the bee. - */ - IBeeJubilance getDefault(); - - /** - * The jubilance provider for bees who prefer not to live near other creatures (other bees are fine). - */ - IBeeJubilance getHermit(); - - /** - * The Requires Resource Jubilance Provider is satisfied when a specific block is under the hive. - */ - IBeeJubilance getRequiresResource(BlockState... acceptedBlockStates); -} diff --git a/src/main/java/forestry/api/apiculture/genetics/BeeLifeStage.java b/src/main/java/forestry/api/apiculture/bee/BeeLifeStage.java similarity index 94% rename from src/main/java/forestry/api/apiculture/genetics/BeeLifeStage.java rename to src/main/java/forestry/api/apiculture/bee/BeeLifeStage.java index 36e33385ee..13176c1b7a 100644 --- a/src/main/java/forestry/api/apiculture/genetics/BeeLifeStage.java +++ b/src/main/java/forestry/api/apiculture/bee/BeeLifeStage.java @@ -1,4 +1,4 @@ -package forestry.api.apiculture.genetics; +package forestry.api.apiculture.bee; import forestry.api.genetics.ILifeStage; import forestry.apiculture.features.ApicultureItems; diff --git a/src/main/java/forestry/api/apiculture/IActivityType.java b/src/main/java/forestry/api/apiculture/bee/IActivityType.java similarity index 96% rename from src/main/java/forestry/api/apiculture/IActivityType.java rename to src/main/java/forestry/api/apiculture/bee/IActivityType.java index 8d755307d0..23da8874ff 100644 --- a/src/main/java/forestry/api/apiculture/IActivityType.java +++ b/src/main/java/forestry/api/apiculture/bee/IActivityType.java @@ -1,5 +1,6 @@ -package forestry.api.apiculture; +package forestry.api.apiculture.bee; +import forestry.api.apiculture.ForestryActivityTypes; import forestry.api.core.IError; import forestry.api.genetics.alleles.IRegistryAlleleValue; import net.minecraft.core.BlockPos; diff --git a/src/main/java/forestry/api/apiculture/genetics/IBee.java b/src/main/java/forestry/api/apiculture/bee/IBee.java similarity index 88% rename from src/main/java/forestry/api/apiculture/genetics/IBee.java rename to src/main/java/forestry/api/apiculture/bee/IBee.java index 6d3571da24..e0bf580f32 100644 --- a/src/main/java/forestry/api/apiculture/genetics/IBee.java +++ b/src/main/java/forestry/api/apiculture/bee/IBee.java @@ -1,4 +1,4 @@ -package forestry.api.apiculture.genetics; +package forestry.api.apiculture.bee; import forestry.api.apiculture.IBeeHousing; import forestry.api.core.IError; @@ -7,13 +7,10 @@ import forestry.api.genetics.IIndividualLiving; import forestry.api.genetics.pollen.IPollen; import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.Iterator; @@ -52,8 +49,6 @@ public interface IBee extends IIndividualLiving { */ Set getCanWork(IBeeHousing housing); - List> getSuitableBiomes(Registry registry); - /** * @return A list of item stacks used for displaying this bee's products in the Analyzer GUI. */ diff --git a/src/main/java/forestry/api/apiculture/genetics/IBeeEffect.java b/src/main/java/forestry/api/apiculture/bee/IBeeEffect.java similarity index 96% rename from src/main/java/forestry/api/apiculture/genetics/IBeeEffect.java rename to src/main/java/forestry/api/apiculture/bee/IBeeEffect.java index df5c0301f9..193871bf5e 100644 --- a/src/main/java/forestry/api/apiculture/genetics/IBeeEffect.java +++ b/src/main/java/forestry/api/apiculture/bee/IBeeEffect.java @@ -1,7 +1,8 @@ -package forestry.api.apiculture.genetics; +package forestry.api.apiculture.bee; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeekeepingLogic; +import forestry.api.core.IEffect; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.IRegistryAlleleValue; diff --git a/src/main/java/forestry/api/apiculture/IBeeJubilance.java b/src/main/java/forestry/api/apiculture/bee/IBeeJubilance.java similarity index 74% rename from src/main/java/forestry/api/apiculture/IBeeJubilance.java rename to src/main/java/forestry/api/apiculture/bee/IBeeJubilance.java index 928bb36fc2..902ed1337c 100644 --- a/src/main/java/forestry/api/apiculture/IBeeJubilance.java +++ b/src/main/java/forestry/api/apiculture/bee/IBeeJubilance.java @@ -1,6 +1,7 @@ -package forestry.api.apiculture; +package forestry.api.apiculture.bee; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IGenome; /** diff --git a/src/main/java/forestry/api/apiculture/genetics/IBeeSpecies.java b/src/main/java/forestry/api/apiculture/bee/IBeeSpecies.java similarity index 94% rename from src/main/java/forestry/api/apiculture/genetics/IBeeSpecies.java rename to src/main/java/forestry/api/apiculture/bee/IBeeSpecies.java index 5db80ec841..2cd8e11ee9 100644 --- a/src/main/java/forestry/api/apiculture/genetics/IBeeSpecies.java +++ b/src/main/java/forestry/api/apiculture/bee/IBeeSpecies.java @@ -1,4 +1,4 @@ -package forestry.api.apiculture.genetics; +package forestry.api.apiculture.bee; import forestry.api.apiculture.IBeeHousing; import forestry.api.core.HumidityType; @@ -33,7 +33,7 @@ public interface IBeeSpecies extends ISpecies, IProductProducer, ISpecialt * @param genome The genome of a bee of this species. * @param housing The hive where the bee is working. Provides access to the bee's working environment. * @return Whether this bee should produce its specialty products. - * @see forestry.api.apiculture.IBeeJubilance + * @see IBeeJubilance */ boolean isJubilant(IGenome genome, IBeeHousing housing); diff --git a/src/main/java/forestry/api/apiculture/genetics/IBeeSpeciesType.java b/src/main/java/forestry/api/apiculture/bee/IBeeSpeciesType.java similarity index 83% rename from src/main/java/forestry/api/apiculture/genetics/IBeeSpeciesType.java rename to src/main/java/forestry/api/apiculture/bee/IBeeSpeciesType.java index e49746ac1d..a8d71386b1 100644 --- a/src/main/java/forestry/api/apiculture/genetics/IBeeSpeciesType.java +++ b/src/main/java/forestry/api/apiculture/bee/IBeeSpeciesType.java @@ -1,20 +1,19 @@ -package forestry.api.apiculture.genetics; +package forestry.api.apiculture.bee; -import com.mojang.authlib.GameProfile; import forestry.api.apiculture.IApiaristTracker; import forestry.api.genetics.ISpeciesType; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.LevelAccessor; import javax.annotation.Nullable; -// todo reimplement beekeeping mode public interface IBeeSpeciesType extends ISpeciesType { /** * @return {@link IApiaristTracker} associated with the passed world. */ @Override - IApiaristTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile); + IApiaristTracker getBreedingTracker(LevelAccessor level, @Nullable @Nullable ResolvableProfile profile); /** * @return true if passed item is a drone. Equal to getLifeStage(ItemStack stack) == EnumBeeType.DRONE diff --git a/src/main/java/forestry/api/apiculture/IFlowerType.java b/src/main/java/forestry/api/apiculture/bee/IFlowerType.java similarity index 97% rename from src/main/java/forestry/api/apiculture/IFlowerType.java rename to src/main/java/forestry/api/apiculture/bee/IFlowerType.java index 1de8226a38..7db6697019 100644 --- a/src/main/java/forestry/api/apiculture/IFlowerType.java +++ b/src/main/java/forestry/api/apiculture/bee/IFlowerType.java @@ -1,4 +1,4 @@ -package forestry.api.apiculture; +package forestry.api.apiculture.bee; import forestry.api.genetics.IIndividual; import forestry.api.genetics.alleles.IRegistryAlleleValue; diff --git a/src/main/java/forestry/api/apiculture/LightPreference.java b/src/main/java/forestry/api/apiculture/bee/LightPreference.java similarity index 89% rename from src/main/java/forestry/api/apiculture/LightPreference.java rename to src/main/java/forestry/api/apiculture/bee/LightPreference.java index 178747c9f7..3046621f3c 100644 --- a/src/main/java/forestry/api/apiculture/LightPreference.java +++ b/src/main/java/forestry/api/apiculture/bee/LightPreference.java @@ -1,4 +1,4 @@ -package forestry.api.apiculture; +package forestry.api.apiculture.bee; /** * Used in {@link IActivityType} to determine whether a bee prefers high light levels or low light levels. diff --git a/src/main/java/forestry/core/gui/buttons/package-info.java b/src/main/java/forestry/api/apiculture/bee/package-info.java similarity index 53% rename from src/main/java/forestry/core/gui/buttons/package-info.java rename to src/main/java/forestry/api/apiculture/bee/package-info.java index 4395437d7b..e391bd090e 100644 --- a/src/main/java/forestry/core/gui/buttons/package-info.java +++ b/src/main/java/forestry/api/apiculture/bee/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault -package forestry.core.gui.buttons; +package forestry.api.apiculture.bee; diff --git a/src/main/java/forestry/api/apiculture/genetics/package-info.java b/src/main/java/forestry/api/apiculture/genetics/package-info.java deleted file mode 100644 index 908857db21..0000000000 --- a/src/main/java/forestry/api/apiculture/genetics/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -package forestry.api.apiculture.genetics; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveDefinition.java b/src/main/java/forestry/api/apiculture/hives/IHiveDefinition.java index 59994ea0d8..7409ce7779 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveDefinition.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveDefinition.java @@ -17,7 +17,7 @@ public interface IHiveDefinition { /** * The hive generator for this hive. */ - IHiveGen getHiveGen(); + IHivePlacement getHiveGen(); /** * The hive block to be placed in the world. diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveDrop.java b/src/main/java/forestry/api/apiculture/hives/IHiveDrop.java index 23fcfee127..fe4f589d3a 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveDrop.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveDrop.java @@ -1,6 +1,6 @@ package forestry.api.apiculture.hives; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; @@ -8,7 +8,7 @@ import java.util.List; /** - * Represents an + * Represents a drop from a wild bee hive. */ public interface IHiveDrop { IBee createIndividual(BlockGetter level, BlockPos pos); diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveFrame.java b/src/main/java/forestry/api/apiculture/hives/IHiveFrame.java index a61e6ed5fa..506d068ba0 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveFrame.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveFrame.java @@ -2,11 +2,10 @@ import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import net.minecraft.world.item.ItemStack; public interface IHiveFrame { - /** * Wears out a frame. * @@ -21,7 +20,6 @@ public interface IHiveFrame { /** * @param frame ItemStack containing the actual frame. * @return the {@link IBeeModifier} for this frame. - * @since Forestry 5.5.1 */ IBeeModifier getBeeModifier(ItemStack frame); } diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveManager.java b/src/main/java/forestry/api/apiculture/hives/IHiveManager.java index ece4209ba7..bc2c07f6a7 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveManager.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveManager.java @@ -1,6 +1,7 @@ package forestry.api.apiculture.hives; import com.google.common.collect.ImmutableList; +import forestry.api.IForestryApi; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -11,6 +12,9 @@ import java.util.List; +/** + * Contains data and factory methods related to bee hives. Obtain from {@link IForestryApi#getHiveManager()}. + */ public interface IHiveManager { /** * @return List of all registered hives. diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveGen.java b/src/main/java/forestry/api/apiculture/hives/IHivePlacement.java similarity index 96% rename from src/main/java/forestry/api/apiculture/hives/IHiveGen.java rename to src/main/java/forestry/api/apiculture/hives/IHivePlacement.java index 2c9c7c068e..e29a8471ae 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveGen.java +++ b/src/main/java/forestry/api/apiculture/hives/IHivePlacement.java @@ -10,9 +10,8 @@ /** * Determines placement conditions for a naturally generated wild beehive. - * todo 1.21.1 rename to IHivePlacement */ -public interface IHiveGen { +public interface IHivePlacement { /** * @deprecated Use {@link #getPosForHive(WorldGenLevel, RandomSource, int, int)} with a world gen random instead. */ diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveTile.java b/src/main/java/forestry/api/apiculture/hives/IHiveTile.java deleted file mode 100644 index 7e855f5292..0000000000 --- a/src/main/java/forestry/api/apiculture/hives/IHiveTile.java +++ /dev/null @@ -1,25 +0,0 @@ -package forestry.api.apiculture.hives; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.Level; - -public interface IHiveTile { - /** - * Call to calm agitated bees. Used by the smoker to stop wild bees from attacking as much. - * Bees will not stay calm for very long. - */ - void calmBees(); - - boolean isAngry(); - - /** - * Called when the hive is attacked. - */ - void onAttack(Level world, BlockPos pos, Player player); - - /** - * Called when the hive is broken. - */ - void onBroken(Level world, BlockPos pos, Player player, boolean canHarvest); -} diff --git a/src/main/java/forestry/api/apiculture/hives/package-info.java b/src/main/java/forestry/api/apiculture/hives/package-info.java index 4dc73792c9..6c120e6cb0 100644 --- a/src/main/java/forestry/api/apiculture/hives/package-info.java +++ b/src/main/java/forestry/api/apiculture/hives/package-info.java @@ -1,7 +1,7 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +/** + * Contains classes relating to wild bee hives and their generation. + */ +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.apiculture.hives; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/apiculture/package-info.java b/src/main/java/forestry/api/apiculture/package-info.java index 5b2f403cbd..a5a0b37340 100644 --- a/src/main/java/forestry/api/apiculture/package-info.java +++ b/src/main/java/forestry/api/apiculture/package-info.java @@ -1,7 +1,7 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +/** + * Contains all bee-related API, including bee species, beekeeping, wild bee hives, and more. + */ +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.apiculture; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/arboriculture/ICharcoalManager.java b/src/main/java/forestry/api/arboriculture/ICharcoalManager.java deleted file mode 100644 index e324c52e79..0000000000 --- a/src/main/java/forestry/api/arboriculture/ICharcoalManager.java +++ /dev/null @@ -1,71 +0,0 @@ -package forestry.api.arboriculture; - -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import javax.annotation.Nullable; -import java.util.List; - -/** - * Provides functions that are related to the forestry charcoal pile. - */ -@Deprecated -public interface ICharcoalManager { - /** - * Registers the given block as a valid block for the charcoal pile wall and adds the given charcoal amount to it. - *

- * This method unlike {@link #registerWall(BlockState, int)} ignores the metadata of the actual block and - * only compares the world block with the given block. - * - * @deprecated Use {@link forestry.api.plugin.IArboricultureRegistration#registerCharcoalPitWall} - */ - @Deprecated(forRemoval = true) - void registerWall(Block block, int amount); - - /** - * Registers the given block as a valid block for the charcoal pile wall and adds the given charcoal amount to it. - *

- * This method unlike {@link #registerWall(Block, int)} compares the world state with the given state and not - * only the block. - * - * @deprecated Use {@link forestry.api.plugin.IArboricultureRegistration#registerCharcoalPitWall} - */ - @Deprecated(forRemoval = true) - void registerWall(BlockState blockState, int amount); - - /** - * Registers your implementation of the {@link ICharcoalPileWall} interface. - * - * @deprecated Use {@link forestry.api.plugin.IArboricultureRegistration#registerCharcoalPitWall} - */ - @Deprecated(forRemoval = true) - void registerWall(ICharcoalPileWall wall); - - @Nullable - ICharcoalPileWall getWall(BlockState state); - - /** - * Remove a wall associated with the given block. Not guaranteed to work depending on how {@link ICharcoalPileWall} is implemented. - * {@link #removeWall(BlockState)} is preferred. - * - * @return true if the wall was removed. - * @deprecated Use {@link forestry.api.plugin.IArboricultureRegistration#registerCharcoalPitWall} and set to 0 - */ - @Deprecated(forRemoval = true) - boolean removeWall(Block block); - - /** - * Remove a wall that {@link ICharcoalPileWall#matches(BlockState)} the given blockstate. - * - * @param state the blockstate to remove. - * @return true if the wall was removed. - * @deprecated Use {@link forestry.api.plugin.IArboricultureRegistration#registerCharcoalPitWall} and set to 0 - */ - @Deprecated(forRemoval = true) - boolean removeWall(BlockState state); - - /** - * @return A collection with all registered charcoal pile walls. - */ - List getWalls(); -} diff --git a/src/main/java/forestry/api/arboriculture/ICharcoalPileWall.java b/src/main/java/forestry/api/arboriculture/ICharcoalPileWall.java index b14197bf1e..4cfd8a088e 100644 --- a/src/main/java/forestry/api/arboriculture/ICharcoalPileWall.java +++ b/src/main/java/forestry/api/arboriculture/ICharcoalPileWall.java @@ -1,16 +1,14 @@ package forestry.api.arboriculture; -import net.minecraft.core.NonNullList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -@Deprecated -public interface ICharcoalPileWall { +import java.util.List; +public interface ICharcoalPileWall { int getCharcoalAmount(); boolean matches(BlockState state); - NonNullList getDisplayItems(); - + List getDisplayItems(); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeGenData.java b/src/main/java/forestry/api/arboriculture/ITreeGenData.java deleted file mode 100644 index 367e61f96b..0000000000 --- a/src/main/java/forestry/api/arboriculture/ITreeGenData.java +++ /dev/null @@ -1,41 +0,0 @@ -package forestry.api.arboriculture; - -import forestry.api.genetics.IGenome; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.LevelAccessor; - -import javax.annotation.Nullable; - -public interface ITreeGenData { - int getGirth(IGenome genome); - - float getHeightModifier(IGenome genome); - - /** - * @return Position that this tree can grow, or {@code null} if it cannot grow. May be different from pos if there are multiple saplings. - */ - @Nullable - BlockPos getGrowthPos(IGenome genome, LevelAccessor level, BlockPos pos, int expectedGirth, int expectedHeight); - - /** - * Places a leaf block for this species with genetic data included. - * - * @param genome The genome to use for the leaves. - * @param level The level. - * @param pos The position to set the leaves at. - * @param random Random number generation. - * @param convertBlockEntity If {@code true}, ALWAYS use a block entity even if a "default" block can be used. - * @return {@code true} if the leaf block was placed. - */ - boolean setLeaves(IGenome genome, LevelAccessor level, BlockPos pos, RandomSource random, boolean convertBlockEntity); - - boolean setLogBlock(IGenome genome, LevelAccessor level, BlockPos pos, Direction facing); - - boolean allowsFruitBlocks(IGenome genome); - - boolean trySpawnFruitBlock(LevelAccessor level, RandomSource rand, BlockPos pos); - - IGenome getDefaultGenome(); -} diff --git a/src/main/java/forestry/api/arboriculture/ITreeGenerator.java b/src/main/java/forestry/api/arboriculture/ITreeGenerator.java index cfb30a0207..5a3cec4328 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeGenerator.java +++ b/src/main/java/forestry/api/arboriculture/ITreeGenerator.java @@ -1,5 +1,6 @@ package forestry.api.arboriculture; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -12,7 +13,7 @@ * Implements the tree generation for a tree species. */ public interface ITreeGenerator { - Feature getTreeFeature(ITreeGenData tree); + Feature getTreeFeature(ITreeSpecies tree); boolean setLogBlock(IGenome genome, LevelAccessor level, BlockPos pos, Direction facing); diff --git a/src/main/java/forestry/api/arboriculture/ITreeManager.java b/src/main/java/forestry/api/arboriculture/ITreeManager.java index 72c5de4df3..c492fc0515 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeManager.java +++ b/src/main/java/forestry/api/arboriculture/ITreeManager.java @@ -1,8 +1,11 @@ package forestry.api.arboriculture; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nullable; +import java.util.Collection; +import java.util.List; /** * @since 2.6.0 @@ -17,9 +20,15 @@ public interface ITreeManager { Block getRefractoryWaxed(Block block); /** - * This getter will be replaced by separate methods in 1.21, as ICharcoalManager will be removed + * @return Read-only view of all registered charcoal pit wall types. */ - ICharcoalManager getCharcoalManager(); + List getWalls(); + + /** + * @return Information about the block in a charcoal pit wall, {@code null} if not a valid charcoal pit wall. + */ + @Nullable + ICharcoalPileWall getWall(BlockState state); IWoodAccess getWoodAccess(); } diff --git a/src/main/java/forestry/api/arboriculture/IWoodAccess.java b/src/main/java/forestry/api/arboriculture/IWoodAccess.java index beae910376..21024f0894 100644 --- a/src/main/java/forestry/api/arboriculture/IWoodAccess.java +++ b/src/main/java/forestry/api/arboriculture/IWoodAccess.java @@ -26,14 +26,8 @@ public interface IWoodAccess { BlockState getBlock(IWoodType woodType, WoodBlockKind kind, boolean fireproof); - /** - * @since 2.6.0 - */ - TagKey getLogBlockTag(IWoodType kind, boolean fireproof); + TagKey getLogBlockTag(IWoodType type, boolean fireproof); - /** - * @since 2.6.0 - */ TagKey getLogItemTag(IWoodType kind, boolean fireproof); List getRegisteredWoodTypes(); diff --git a/src/main/java/forestry/api/arboriculture/TreeManager.java b/src/main/java/forestry/api/arboriculture/TreeManager.java deleted file mode 100644 index 150c0a8958..0000000000 --- a/src/main/java/forestry/api/arboriculture/TreeManager.java +++ /dev/null @@ -1,25 +0,0 @@ -package forestry.api.arboriculture; - -import forestry.api.IForestryApi; - -/** - * @deprecated Use {@link IForestryApi#getTreeManager} - */ -@Deprecated(forRemoval = true) -public class TreeManager { - /** - * Convenient access to wood items. - * - * @deprecated Use {@link ITreeManager#getWoodAccess} - */ - @Deprecated(forRemoval = true) - public static IWoodAccess woodAccess; - - /** - * Can be used to add new charcoal pile walls. - * - * @deprecated Use {@link ITreeManager#getCharcoalManager} - */ - @Deprecated(forRemoval = true) - public static ICharcoalManager charcoalManager; -} diff --git a/src/main/java/forestry/api/arboriculture/genetics/IFruit.java b/src/main/java/forestry/api/arboriculture/genetics/IFruit.java index 1a899532f6..f3af498710 100644 --- a/src/main/java/forestry/api/arboriculture/genetics/IFruit.java +++ b/src/main/java/forestry/api/arboriculture/genetics/IFruit.java @@ -8,20 +8,18 @@ import forestry.api.genetics.alleles.TreeChromosomes; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.TagKey; import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.Block; import javax.annotation.Nullable; import java.util.List; /** - * Provides all information that is needed to spawn a fruit leaves / pod block in the world. + * Provides all information that is needed to spawn a fruit leaves in the world. + * If your fruit is a pod fruit, like Cocoa, Dates, or Papaya, use the more sensitive {@link IPodFruit}. */ public interface IFruit extends IRegistryAlleleValue, IProductProducer, ISpecialtyProducer { /** @@ -30,7 +28,7 @@ public interface IFruit extends IRegistryAlleleValue, IProductProducer, ISpecial * @param genome The genome of the tree of the pod / leaves block. * @param ripeningTime The ripening time of the leaves / pod block. From 0 to {@link #getRipeningPeriod()}. */ - int getColour(IGenome genome, BlockGetter world, BlockPos pos, int ripeningTime); + int getColour(IGenome genome, BlockGetter level, BlockPos pos, int ripeningTime); /** * return the color to use for decorative leaves. Usually the ripe color. @@ -85,34 +83,10 @@ default List getSpecialties() { * @return ResourceLocation of the texture to overlay on the leaf block. */ @Nullable - ResourceLocation getSprite(IGenome genome, BlockGetter world, BlockPos pos, int ripeningTime); + ResourceLocation getSprite(IGenome genome, BlockGetter level, BlockPos pos, int ripeningTime); @Nullable default ResourceLocation getDecorativeSprite() { return null; } - - /** - * @return true if this fruit provider requires fruit blocks to spawn, false otherwise. - */ - boolean requiresFruitBlocks(); - - /** - * Tries to spawn a fruit block at the potential position when the tree generates. - * Spawning a fruit has a random chance of success based on {@link TreeChromosomes#SAPPINESS}. - * - * @return true if a fruit block was spawned, false otherwise. - */ - boolean trySpawnFruitBlock(IGenome genome, LevelAccessor world, RandomSource rand, BlockPos pos); - - // Replaced with atlas JSONs pointing to the BLOCK atlas. - //default void registerSprites(TextureStitchEvent.Pre event) { - //} - - /** - * Tag for the log that a pod fruit is placed on - */ - default TagKey getLogTag() { - return BlockTags.JUNGLE_LOGS; - } } diff --git a/src/main/java/forestry/api/arboriculture/genetics/IPodFruit.java b/src/main/java/forestry/api/arboriculture/genetics/IPodFruit.java new file mode 100644 index 0000000000..71c3897277 --- /dev/null +++ b/src/main/java/forestry/api/arboriculture/genetics/IPodFruit.java @@ -0,0 +1,26 @@ +package forestry.api.arboriculture.genetics; + +import forestry.api.genetics.IGenome; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.state.BlockState; + +/** + * Use this interface if your fruit is a pod, like Cocoa, Dates, or Papaya. + */ +public interface IPodFruit extends IFruit { + /** + * @return Whether this pod fruit can hang off of the given block, ex. Cocoa can only hang off of Jungle logs + */ + boolean canSurviveOn(BlockState state); + + /** + * Attempts to place the pod fruit into the world. + * + * @param level The world to place the pod fruit in. + * @param pos The position to place the pod fruit at. + * @param genome The genome of the tree whose fruit is being placed. + * @return {@code true} if the placement was successful, {@code false} if the position was not valid for the pod. + */ + boolean tryPlace(LevelAccessor level, BlockPos pos, IGenome genome); +} diff --git a/src/main/java/forestry/api/arboriculture/genetics/ITree.java b/src/main/java/forestry/api/arboriculture/genetics/ITree.java index 3a919f93c1..d951a14e5f 100644 --- a/src/main/java/forestry/api/arboriculture/genetics/ITree.java +++ b/src/main/java/forestry/api/arboriculture/genetics/ITree.java @@ -1,7 +1,6 @@ package forestry.api.arboriculture.genetics; import com.mojang.authlib.GameProfile; -import forestry.api.arboriculture.ITreeSpecies; import forestry.api.core.IProductProducer; import forestry.api.core.ISpecialtyProducer; import forestry.api.genetics.IEffectData; diff --git a/src/main/java/forestry/api/arboriculture/genetics/ITreeEffect.java b/src/main/java/forestry/api/arboriculture/genetics/ITreeEffect.java index 844c87a209..56f52a0c1c 100644 --- a/src/main/java/forestry/api/arboriculture/genetics/ITreeEffect.java +++ b/src/main/java/forestry/api/arboriculture/genetics/ITreeEffect.java @@ -1,6 +1,6 @@ package forestry.api.arboriculture.genetics; -import forestry.api.apiculture.genetics.IEffect; +import forestry.api.core.IEffect; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.IRegistryAlleleValue; diff --git a/src/main/java/forestry/api/arboriculture/ITreeSpecies.java b/src/main/java/forestry/api/arboriculture/genetics/ITreeSpecies.java similarity index 56% rename from src/main/java/forestry/api/arboriculture/ITreeSpecies.java rename to src/main/java/forestry/api/arboriculture/genetics/ITreeSpecies.java index f4b376abb9..2095e08abb 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeSpecies.java +++ b/src/main/java/forestry/api/arboriculture/genetics/ITreeSpecies.java @@ -1,22 +1,27 @@ -package forestry.api.arboriculture; +package forestry.api.arboriculture.genetics; +import forestry.api.arboriculture.ITreeGenerator; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.core.HumidityType; import forestry.api.core.IProductProducer; import forestry.api.core.ISpecialtyProducer; import forestry.api.core.TemperatureType; +import forestry.api.genetics.IGenome; import forestry.api.genetics.ILifeStage; import forestry.api.genetics.ISpecies; import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.util.RandomSource; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.state.BlockState; +import javax.annotation.Nullable; import java.util.List; -public interface ITreeSpecies extends ISpecies, ITreeGenData, IProductProducer, ISpecialtyProducer { +public interface ITreeSpecies extends ISpecies, IProductProducer, ISpecialtyProducer { @Override ITreeSpeciesType getType(); @@ -62,4 +67,30 @@ public interface ITreeSpecies extends ISpecies, ITreeGenData, IProductPro * @return {@code true} if this is a leaves block with fruit on it, false otherwise. */ boolean isFruitLeaf(LevelAccessor level, BlockPos pos); + + int getGirth(IGenome genome); + + float getHeightModifier(IGenome genome); + + /** + * @return Position that this tree can grow, or {@code null} if it cannot grow. May be different from pos if there are multiple saplings. + */ + @Nullable + BlockPos getGrowthPos(IGenome genome, LevelAccessor level, BlockPos pos, int expectedGirth, int expectedHeight); + + /** + * Places a leaf block for this species with genetic data included. + * + * @param genome The genome to use for the leaves. + * @param level The level. + * @param pos The position to set the leaves at. + * @param random Random number generation. + * @param convertBlockEntity If {@code true}, ALWAYS use a block entity even if a "default" block can be used. + * @return {@code true} if the leaf block was placed. + */ + boolean setLeaves(IGenome genome, LevelAccessor level, BlockPos pos, RandomSource random, boolean convertBlockEntity); + + boolean setLogBlock(IGenome genome, LevelAccessor level, BlockPos pos, Direction facing); + + void trySpawnFruitPod(LevelAccessor level, RandomSource rand, BlockPos pos); } diff --git a/src/main/java/forestry/api/arboriculture/genetics/ITreeSpeciesType.java b/src/main/java/forestry/api/arboriculture/genetics/ITreeSpeciesType.java index 347f5f27f9..be185ab4d6 100644 --- a/src/main/java/forestry/api/arboriculture/genetics/ITreeSpeciesType.java +++ b/src/main/java/forestry/api/arboriculture/genetics/ITreeSpeciesType.java @@ -3,11 +3,11 @@ import com.mojang.authlib.GameProfile; import forestry.api.arboriculture.IArboristTracker; import forestry.api.arboriculture.ILeafTickHandler; -import forestry.api.arboriculture.ITreeSpecies; import forestry.api.genetics.IGenome; import forestry.api.genetics.ISpeciesType; import net.minecraft.core.BlockPos; import net.minecraft.world.item.Item; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.entity.BlockEntity; @@ -15,10 +15,11 @@ import javax.annotation.Nullable; import java.util.Collection; +import java.util.Map; public interface ITreeSpeciesType extends ISpeciesType { @Override - IArboristTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile); + IArboristTracker getBreedingTracker(LevelAccessor level, @Nullable @Nullable ResolvableProfile profile); /** * Register a leaf random tick handler. Used for butterfly spawner. @@ -37,8 +38,6 @@ public interface ITreeSpeciesType extends ISpeciesType { boolean plantSapling(Level level, ITree tree, GameProfile owner, BlockPos pos); - boolean setFruitBlock(LevelAccessor level, IGenome genome, IFruit fruit, float yield, BlockPos pos); - /** * Tries to get genetic information of a species from a mundane/vanilla block, like from Oak Leaves to Apple Oak Leaves. * Does not affect the block in the world, just returns an individual. @@ -58,4 +57,6 @@ public interface ITreeSpeciesType extends ISpeciesType { */ @Nullable ITree getVanillaIndividual(Item item); + + Map getAllVanillaIndividuals(); } diff --git a/src/main/java/forestry/api/arboriculture/genetics/package-info.java b/src/main/java/forestry/api/arboriculture/genetics/package-info.java index b0d8a2b58b..c3f56c0ce4 100644 --- a/src/main/java/forestry/api/arboriculture/genetics/package-info.java +++ b/src/main/java/forestry/api/arboriculture/genetics/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.arboriculture.genetics; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/arboriculture/package-info.java b/src/main/java/forestry/api/arboriculture/package-info.java index aafff0133a..299bacb21d 100644 --- a/src/main/java/forestry/api/arboriculture/package-info.java +++ b/src/main/java/forestry/api/arboriculture/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.arboriculture; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/circuits/CircuitLayout.java b/src/main/java/forestry/api/circuits/CircuitLayout.java new file mode 100644 index 0000000000..4683551700 --- /dev/null +++ b/src/main/java/forestry/api/circuits/CircuitLayout.java @@ -0,0 +1,32 @@ +package forestry.api.circuits; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; + +/** + * @param id Unique ID for this circuit layout + * @param socketType Specifies where a circuit layout is used + */ +public record CircuitLayout(String id, ResourceLocation socketType) { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + Codec.STRING.fieldOf("id").forGetter(CircuitLayout::id), + ResourceLocation.CODEC.fieldOf("socket_type").forGetter(CircuitLayout::socketType) + ).apply(inst, CircuitLayout::new)); + + /** + * @return localized name for this circuit layout + */ + public MutableComponent getName() { + return Component.translatable("circuit.layout." + this.id); + } + + /** + * @return localized string for how this circuit layout is used + */ + public MutableComponent getUsage() { + return Component.translatable("circuit.layout." + this.id + ".usage"); + } +} diff --git a/src/main/java/forestry/api/circuits/ICircuit.java b/src/main/java/forestry/api/circuits/ICircuit.java index a81240766c..20e6c37df2 100644 --- a/src/main/java/forestry/api/circuits/ICircuit.java +++ b/src/main/java/forestry/api/circuits/ICircuit.java @@ -1,10 +1,14 @@ package forestry.api.circuits; +import com.mojang.serialization.Codec; +import forestry.api.ForestryRegistries; import net.minecraft.network.chat.Component; import java.util.List; public interface ICircuit { + Codec CODEC = ForestryRegistries.CIRCUIT.byNameCodec(); + String getId(); String getTranslationKey(); diff --git a/src/main/java/forestry/api/circuits/ICircuitBoard.java b/src/main/java/forestry/api/circuits/ICircuitBoard.java index 920a2dfae8..c39f54f25d 100644 --- a/src/main/java/forestry/api/circuits/ICircuitBoard.java +++ b/src/main/java/forestry/api/circuits/ICircuitBoard.java @@ -1,15 +1,14 @@ package forestry.api.circuits; -import forestry.api.core.INbtWritable; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.List; -public interface ICircuitBoard extends INbtWritable { +public interface ICircuitBoard { @OnlyIn(Dist.CLIENT) int getPrimaryColor(); @@ -27,7 +26,7 @@ public interface ICircuitBoard extends INbtWritable { void onTick(Object tile); - ICircuit[] getCircuits(); + List getCircuits(); /** * Specifies where a circuit can be used. diff --git a/src/main/java/forestry/api/circuits/ICircuitLayout.java b/src/main/java/forestry/api/circuits/ICircuitLayout.java deleted file mode 100644 index 0eac697205..0000000000 --- a/src/main/java/forestry/api/circuits/ICircuitLayout.java +++ /dev/null @@ -1,27 +0,0 @@ -package forestry.api.circuits; - -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; - -public interface ICircuitLayout { - /** - * unique ID for this circuit layout - */ - String getId(); - - /** - * localized name for this circuit layout - */ - Component getName(); - - /** - * localized string for how this circuit layout is used - */ - MutableComponent getUsage(); - - /** - * Specifies where a circuit layout is used. - */ - ResourceLocation getSocketType(); -} diff --git a/src/main/java/forestry/api/circuits/ICircuitLibrary.java b/src/main/java/forestry/api/circuits/ICircuitLibrary.java deleted file mode 100644 index 1f38d6ccea..0000000000 --- a/src/main/java/forestry/api/circuits/ICircuitLibrary.java +++ /dev/null @@ -1,5 +0,0 @@ -package forestry.api.circuits; - -public interface ICircuitLibrary { - -} diff --git a/src/main/java/forestry/api/circuits/ICircuitManager.java b/src/main/java/forestry/api/circuits/ICircuitManager.java index a101c00c60..886134134a 100644 --- a/src/main/java/forestry/api/circuits/ICircuitManager.java +++ b/src/main/java/forestry/api/circuits/ICircuitManager.java @@ -14,7 +14,7 @@ public interface ICircuitManager { /** * @return A collection of all registered circuit layouts. */ - List getLayouts(); + List getLayouts(); /** * Retrieves the item's circuit for the given circuit layout, or null if this item is not applicable for the layout. @@ -24,22 +24,13 @@ public interface ICircuitManager { * @return The circuit associated with the circuit layout and item, or {@code null} if this item doesn't work for the circuit layout. */ @Nullable - ICircuit getCircuit(ICircuitLayout layout, ItemStack stack); - - @Nullable - ICircuit getCircuit(String circuitId); + ICircuit getCircuit(CircuitLayout layout, ItemStack stack); /** * @return The circuit layout with the given ID, or {@code null} if none was registered with that ID. */ @Nullable - ICircuitLayout getLayout(String layoutId); - - /** - * @return The circuit board stored in this item's NBT, {@code null} if this item has no NBT or is not a chipset. - */ - @Nullable - ICircuitBoard getCircuitBoard(ItemStack stack); + CircuitLayout getLayout(String layoutId); /** * Note: Currently hardcoded to Forestry circuit board. diff --git a/src/main/java/forestry/api/circuits/package-info.java b/src/main/java/forestry/api/circuits/package-info.java index 321b3e0c78..3ebef8e512 100644 --- a/src/main/java/forestry/api/circuits/package-info.java +++ b/src/main/java/forestry/api/circuits/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.circuits; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/client/IClientModuleHandler.java b/src/main/java/forestry/api/client/IClientModuleHandler.java index 554e417b0b..05ca81e413 100644 --- a/src/main/java/forestry/api/client/IClientModuleHandler.java +++ b/src/main/java/forestry/api/client/IClientModuleHandler.java @@ -1,6 +1,6 @@ package forestry.api.client; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; /** * Used to separate client-only code and events from a {@link forestry.api.modules.IForestryModule}. diff --git a/src/main/java/forestry/api/client/apiculture/IBeeClientManager.java b/src/main/java/forestry/api/client/apiculture/IBeeClientManager.java index 6d52cc1042..f1a34aa5eb 100644 --- a/src/main/java/forestry/api/client/apiculture/IBeeClientManager.java +++ b/src/main/java/forestry/api/client/apiculture/IBeeClientManager.java @@ -1,6 +1,6 @@ package forestry.api.client.apiculture; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.ILifeStage; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/forestry/api/client/apiculture/package-info.java b/src/main/java/forestry/api/client/apiculture/package-info.java index 8ed743928c..26cb74f8e4 100644 --- a/src/main/java/forestry/api/client/apiculture/package-info.java +++ b/src/main/java/forestry/api/client/apiculture/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.client.apiculture; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/client/arboriculture/ITreeClientManager.java b/src/main/java/forestry/api/client/arboriculture/ITreeClientManager.java index aec2b7ef60..79c4eea8c6 100644 --- a/src/main/java/forestry/api/client/arboriculture/ITreeClientManager.java +++ b/src/main/java/forestry/api/client/arboriculture/ITreeClientManager.java @@ -1,7 +1,7 @@ package forestry.api.client.arboriculture; import com.mojang.datafixers.util.Pair; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/forestry/api/client/arboriculture/package-info.java b/src/main/java/forestry/api/client/arboriculture/package-info.java index 2da3d1e1b4..83111062ff 100644 --- a/src/main/java/forestry/api/client/arboriculture/package-info.java +++ b/src/main/java/forestry/api/client/arboriculture/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.client.arboriculture; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/client/lepidopterology/package-info.java b/src/main/java/forestry/api/client/lepidopterology/package-info.java index 24c8f63391..54f680ba2f 100644 --- a/src/main/java/forestry/api/client/lepidopterology/package-info.java +++ b/src/main/java/forestry/api/client/lepidopterology/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.client.lepidopterology; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/client/package-info.java b/src/main/java/forestry/api/client/package-info.java index e2918d0da8..c34970a062 100644 --- a/src/main/java/forestry/api/client/package-info.java +++ b/src/main/java/forestry/api/client/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.client; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/client/plugin/package-info.java b/src/main/java/forestry/api/client/plugin/package-info.java index ee3c432072..b45eb0c5e1 100644 --- a/src/main/java/forestry/api/client/plugin/package-info.java +++ b/src/main/java/forestry/api/client/plugin/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.client.plugin; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/climate/IBiomeProvider.java b/src/main/java/forestry/api/climate/IBiomeProvider.java index 339c546849..806f4cb1d4 100644 --- a/src/main/java/forestry/api/climate/IBiomeProvider.java +++ b/src/main/java/forestry/api/climate/IBiomeProvider.java @@ -1,6 +1,7 @@ package forestry.api.climate; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.world.level.biome.Biome; /** @@ -10,5 +11,5 @@ public interface IBiomeProvider { /** * @return The biome the object that implements this interface is located in. */ - Holder getBiome(); + Holder getBiome(HolderLookup.Provider registries); } diff --git a/src/main/java/forestry/api/climate/package-info.java b/src/main/java/forestry/api/climate/package-info.java index 3f86197bf8..d1dfb4bf73 100644 --- a/src/main/java/forestry/api/climate/package-info.java +++ b/src/main/java/forestry/api/climate/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.climate; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/core/utils/FieldsAreNonnullByDefault.java b/src/main/java/forestry/api/core/FieldsAreNonnullByDefault.java similarity index 92% rename from src/main/java/forestry/core/utils/FieldsAreNonnullByDefault.java rename to src/main/java/forestry/api/core/FieldsAreNonnullByDefault.java index bd12f6ef25..6f98302b75 100644 --- a/src/main/java/forestry/core/utils/FieldsAreNonnullByDefault.java +++ b/src/main/java/forestry/api/core/FieldsAreNonnullByDefault.java @@ -1,4 +1,4 @@ -package forestry.core.utils; +package forestry.api.core; import javax.annotation.Nonnull; import javax.annotation.meta.TypeQualifierDefault; diff --git a/src/main/java/forestry/api/core/ForestryEvent.java b/src/main/java/forestry/api/core/ForestryEvent.java deleted file mode 100644 index 772fd2f7f6..0000000000 --- a/src/main/java/forestry/api/core/ForestryEvent.java +++ /dev/null @@ -1,99 +0,0 @@ -package forestry.api.core; - -import com.mojang.authlib.GameProfile; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.genetics.IBreedingTracker; -import forestry.api.genetics.IMutation; -import forestry.api.genetics.ISpecies; -import forestry.api.genetics.ISpeciesType; -import net.minecraft.world.entity.player.Player; -import net.minecraftforge.eventbus.api.Cancelable; -import net.minecraftforge.eventbus.api.Event; -import org.jetbrains.annotations.ApiStatus; - -// todo move to forestry.api.event -public abstract class ForestryEvent extends Event { - /** - * Supertype for events concerning breeding and mutation. - */ - @ApiStatus.Internal - private static abstract class BreedingEvent extends ForestryEvent { - public final ISpeciesType root; - public final IBreedingTracker tracker; - public final GameProfile username; - - private BreedingEvent(ISpeciesType root, GameProfile username, IBreedingTracker tracker) { - this.root = root; - this.username = username; - this.tracker = tracker; - } - } - - /** - * Fired before a queen is created as a result of breeding a princess and a drone. - * - * @since 2.4.4 - */ - @Cancelable - public static class BeeMatingEvent extends ForestryEvent { - private final IBeeHousing housing; - private IBee princess; - private final IBee drone; - - public BeeMatingEvent(IBeeHousing housing, IBee princess, IBee drone) { - this.housing = housing; - this.princess = princess; - this.drone = drone; - } - - public IBeeHousing getHousing() { - return this.housing; - } - - public IBee getPrincess() { - return this.princess; - } - - /** - * Used to override the princess individual, which will become the queen individual. - * - * @param princess The new princess individual to replace the queen with. - */ - public void setPrincess(IBee princess) { - this.princess = princess; - } - - public IBee getDrone() { - return this.drone; - } - } - - public static class SpeciesDiscovered extends BreedingEvent { - public final ISpecies species; - - public SpeciesDiscovered(ISpeciesType root, GameProfile username, ISpecies species, IBreedingTracker tracker) { - super(root, username, tracker); - this.species = species; - } - } - - public static class MutationDiscovered extends BreedingEvent { - public final IMutation allele; - - public MutationDiscovered(ISpeciesType root, GameProfile username, IMutation allele, IBreedingTracker tracker) { - super(root, username, tracker); - this.allele = allele; - } - } - - public static class SyncedBreedingTracker extends ForestryEvent { - public final IBreedingTracker tracker; - public final Player player; - - public SyncedBreedingTracker(IBreedingTracker tracker, Player player) { - this.tracker = tracker; - this.player = player; - } - } -} diff --git a/src/main/java/forestry/api/apiculture/genetics/IEffect.java b/src/main/java/forestry/api/core/IEffect.java similarity index 92% rename from src/main/java/forestry/api/apiculture/genetics/IEffect.java rename to src/main/java/forestry/api/core/IEffect.java index 91b58e8599..0c64b9df4e 100644 --- a/src/main/java/forestry/api/apiculture/genetics/IEffect.java +++ b/src/main/java/forestry/api/core/IEffect.java @@ -1,4 +1,4 @@ -package forestry.api.apiculture.genetics; +package forestry.api.core; import forestry.api.genetics.IEffectData; diff --git a/src/main/java/forestry/api/core/IFeatureSubtype.java b/src/main/java/forestry/api/core/IFeatureSubtype.java index 8f9b969bc7..4d83fdc719 100644 --- a/src/main/java/forestry/api/core/IFeatureSubtype.java +++ b/src/main/java/forestry/api/core/IFeatureSubtype.java @@ -1,6 +1,8 @@ package forestry.api.core; -import net.minecraft.util.StringRepresentable; - -public interface IFeatureSubtype extends StringRepresentable { +public interface IFeatureSubtype { + /** + * @return The identifier associated with this subtype, without any group prefix or suffix (ex. vintage for comb_vintage) + */ + String identifier(); } diff --git a/src/main/java/forestry/api/core/ILocationProvider.java b/src/main/java/forestry/api/core/ILocationProvider.java index 65af8c5d6b..aca7cdda31 100644 --- a/src/main/java/forestry/api/core/ILocationProvider.java +++ b/src/main/java/forestry/api/core/ILocationProvider.java @@ -7,13 +7,10 @@ /** * Interface for things, that have a location. - * Must not be named "getWorld" and "getPos" to avoid - * SpecialSource issue https://github.com/md-5/SpecialSource/issues/12 - * TODO rename to getBlockPos, getLevel in 1.21 */ public interface ILocationProvider { - BlockPos getCoordinates(); + BlockPos getBlockPos(); @Nullable - Level getWorldObj(); + Level getLevel(); } diff --git a/src/main/java/forestry/api/core/INbtReadable.java b/src/main/java/forestry/api/core/INbtReadable.java index 6a382c08d0..f9d0b35097 100644 --- a/src/main/java/forestry/api/core/INbtReadable.java +++ b/src/main/java/forestry/api/core/INbtReadable.java @@ -1,7 +1,8 @@ package forestry.api.core; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public interface INbtReadable { - void read(CompoundTag nbt); + void read(CompoundTag nbt, HolderLookup.Provider registries); } diff --git a/src/main/java/forestry/api/core/INbtWritable.java b/src/main/java/forestry/api/core/INbtWritable.java index 4c4c5290d4..80654e5323 100644 --- a/src/main/java/forestry/api/core/INbtWritable.java +++ b/src/main/java/forestry/api/core/INbtWritable.java @@ -1,7 +1,8 @@ package forestry.api.core; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public interface INbtWritable { - CompoundTag write(CompoundTag nbt); + CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries); } diff --git a/src/main/java/forestry/api/core/IProduct.java b/src/main/java/forestry/api/core/IProduct.java index 5c5fe0ffc1..3506395df4 100644 --- a/src/main/java/forestry/api/core/IProduct.java +++ b/src/main/java/forestry/api/core/IProduct.java @@ -1,6 +1,7 @@ package forestry.api.core; import it.unimi.dsi.fastutil.Hash; +import net.minecraft.core.Holder; import net.minecraft.util.RandomSource; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -29,8 +30,6 @@ public boolean equals(@Nullable IProduct a, @Nullable IProduct b) { } }; - // todo should this be replaced with is(ItemStack) and getIconStack() methods instead? - /** * Gets the item this product contains. In the case of a dynamic product, return an item that might * be used to display it in a screen or for equality purposes in {@link #ITEM_ONLY_STRATEGY}. @@ -39,6 +38,13 @@ public boolean equals(@Nullable IProduct a, @Nullable IProduct b) { */ Item item(); + /** + * @return The holder if the item this product contains, just like {@link #item}. + */ + default Holder itemHolder() { + return item().builtInRegistryHolder(); + } + /** * @return The set chance of this product being produced. */ diff --git a/src/main/java/forestry/api/core/ISpecialtyProducer.java b/src/main/java/forestry/api/core/ISpecialtyProducer.java index 2ded217004..fe648da06e 100644 --- a/src/main/java/forestry/api/core/ISpecialtyProducer.java +++ b/src/main/java/forestry/api/core/ISpecialtyProducer.java @@ -1,10 +1,12 @@ package forestry.api.core; +import forestry.api.apiculture.bee.IBeeJubilance; + import java.util.List; /** * Denotes a species that can produce "specialty" products when in a jubilant state, - * as described by {@link forestry.api.apiculture.IBeeJubilance} or something similar. + * as described by {@link IBeeJubilance} or something similar. */ public interface ISpecialtyProducer { /** diff --git a/src/main/java/forestry/api/core/IArmorNaturalist.java b/src/main/java/forestry/api/core/ISpectacleVision.java similarity index 88% rename from src/main/java/forestry/api/core/IArmorNaturalist.java rename to src/main/java/forestry/api/core/ISpectacleVision.java index bccabc353b..01842d6c0b 100644 --- a/src/main/java/forestry/api/core/IArmorNaturalist.java +++ b/src/main/java/forestry/api/core/ISpectacleVision.java @@ -7,9 +7,9 @@ /** * Naturalist armor allows players to see pollinated tree leaves. * - * @see ForestryCapabilities#ARMOR_NATURALIST + * @see ForestryCapabilities#SPECTACLE_VISION */ -public interface IArmorNaturalist { +public interface ISpectacleVision { /** * Called to see if this naturalist's armor allows for seeing pollinated tree leaves/flowers. diff --git a/src/main/java/forestry/api/core/IToolPipette.java b/src/main/java/forestry/api/core/IToolPipette.java index ef4201ff05..578ab6a1b1 100644 --- a/src/main/java/forestry/api/core/IToolPipette.java +++ b/src/main/java/forestry/api/core/IToolPipette.java @@ -2,9 +2,6 @@ import net.minecraft.world.item.ItemStack; -/** - * Taken from BuildCraft 5.0.x - */ public interface IToolPipette { /** * @return true if the pipette can pipette. diff --git a/src/main/java/forestry/api/core/ItemGroups.java b/src/main/java/forestry/api/core/ItemGroups.java deleted file mode 100644 index a2c82a5cb7..0000000000 --- a/src/main/java/forestry/api/core/ItemGroups.java +++ /dev/null @@ -1,14 +0,0 @@ -package forestry.api.core; - -import net.minecraft.world.item.CreativeModeTab; - -/** - * References to the specialised tabs added by Forestry to creative inventory. - */ -public class ItemGroups { - public static CreativeModeTab tabForestry; - public static CreativeModeTab tabStorage; - public static CreativeModeTab tabApiculture; - public static CreativeModeTab tabArboriculture; - public static CreativeModeTab tabLepidopterology; -} diff --git a/src/main/java/forestry/api/core/Product.java b/src/main/java/forestry/api/core/Product.java index 47a73050c8..c486952490 100644 --- a/src/main/java/forestry/api/core/Product.java +++ b/src/main/java/forestry/api/core/Product.java @@ -2,13 +2,14 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; -import javax.annotation.Nullable; import java.util.Optional; /** @@ -16,53 +17,52 @@ * * @param item The item this product represents. * @param count The count the produced stack should have. - * @param tag The NBT tag + * @param data The item's data components, if any, otherwise {@link DataComponentPatch#EMPTY}. * @param chance */ -public record Product(Item item, int count, @Nullable CompoundTag tag, float chance) implements IProduct { +public record Product(Item item, int count, DataComponentPatch data, float chance) implements IProduct { public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( BuiltInRegistries.ITEM.byNameCodec().fieldOf("item").forGetter(Product::item), Codec.intRange(1, 64).optionalFieldOf("count", 1).forGetter(Product::count), - CompoundTag.CODEC.optionalFieldOf("tag").forGetter(product -> Optional.ofNullable(product.tag)), + DataComponentPatch.CODEC.optionalFieldOf("data").forGetter(product -> Optional.ofNullable(product.data)), Codec.floatRange(0f, 1f).fieldOf("chance").forGetter(Product::chance) ).apply(instance, (item, count, tag, chance) -> new Product(item, count, tag.orElse(null), chance))); - // todo StreamCodec in 1.21 + public static final StreamCodec STREAM_CODEC = StreamCodec.of(Product::toNetwork, Product::fromNetwork); @Override public ItemStack createStack() { - ItemStack stack = new ItemStack(this.item, this.count); - if (this.tag != null) { - // defensive copy - stack.setTag(this.tag.copy()); - } - return stack; + return new ItemStack(this.item.builtInRegistryHolder(), this.count, this.data); } public static Product of(Item item) { - return new Product(item, 1, null, 1f); + return new Product(item, 1, DataComponentPatch.EMPTY, 1f); + } + + public static Product of(Item item, float chance) { + return new Product(item, 1, DataComponentPatch.EMPTY, chance); } public static Product of(Item item, int amount, float chance) { - return new Product(item, amount, null, chance); + return new Product(item, amount, DataComponentPatch.EMPTY, chance); } - public static void toNetwork(FriendlyByteBuf buffer, Product product) { - buffer.writeId(BuiltInRegistries.ITEM, product.item); + public static void toNetwork(RegistryFriendlyByteBuf buffer, Product product) { + buffer.writeById(BuiltInRegistries.ITEM::getId, product.item); buffer.writeByte(product.count); - buffer.writeNbt(product.tag); + DataComponentPatch.STREAM_CODEC.encode(buffer, product.data); buffer.writeFloat(product.chance); } - public static Product fromNetwork(FriendlyByteBuf buffer) { - Item item = buffer.readById(BuiltInRegistries.ITEM); + public static Product fromNetwork(RegistryFriendlyByteBuf buffer) { + Item item = buffer.readById(BuiltInRegistries.ITEM::byId); int count = buffer.readByte(); - CompoundTag tag = buffer.readNbt(); + DataComponentPatch data = DataComponentPatch.STREAM_CODEC.decode(buffer); float chance = buffer.readFloat(); - if (item == null) { + if (item == Items.AIR) { throw new IllegalStateException("Received invalid item ID"); } - return new Product(item, count, tag, chance); + return new Product(item, count, data, chance); } } diff --git a/src/main/java/forestry/api/core/package-info.java b/src/main/java/forestry/api/core/package-info.java index 62b4f89a14..ad5af87869 100644 --- a/src/main/java/forestry/api/core/package-info.java +++ b/src/main/java/forestry/api/core/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.core; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/core/tooltips/ITextInstance.java b/src/main/java/forestry/api/core/tooltips/ITextInstance.java index cb2e6895a9..a6942b17ce 100644 --- a/src/main/java/forestry/api/core/tooltips/ITextInstance.java +++ b/src/main/java/forestry/api/core/tooltips/ITextInstance.java @@ -10,6 +10,7 @@ import java.util.function.Consumer; import java.util.function.UnaryOperator; +// todo remove this from existence public interface ITextInstance, S, R> { default I text(String text) { return add(Component.literal(text)); diff --git a/src/main/java/forestry/api/core/tooltips/ToolTip.java b/src/main/java/forestry/api/core/tooltips/ToolTip.java index 627d0515aa..ade84ef1c6 100644 --- a/src/main/java/forestry/api/core/tooltips/ToolTip.java +++ b/src/main/java/forestry/api/core/tooltips/ToolTip.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.api.core.tooltips; public class ToolTip extends TextCollection { diff --git a/src/main/java/forestry/api/core/tooltips/package-info.java b/src/main/java/forestry/api/core/tooltips/package-info.java index c9ded9e447..e256e2520e 100644 --- a/src/main/java/forestry/api/core/tooltips/package-info.java +++ b/src/main/java/forestry/api/core/tooltips/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.core.tooltips; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/event/BackpackEvent.java b/src/main/java/forestry/api/event/BackpackEvent.java new file mode 100644 index 0000000000..192d0fbefb --- /dev/null +++ b/src/main/java/forestry/api/event/BackpackEvent.java @@ -0,0 +1,44 @@ +package forestry.api.event; + +import forestry.api.storage.BackpackDefinition; +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.neoforged.bus.api.Event; +import net.neoforged.bus.api.ICancellableEvent; + +public abstract class BackpackEvent extends Event { + public final Player player; + public final BackpackDefinition definition; + public final Container backpackInventory; + + public BackpackEvent(Player player, BackpackDefinition definition, Container backpackInventory) { + this.player = player; + this.definition = definition; + this.backpackInventory = backpackInventory; + } + + /** + * Will fire whenever a backpack tries to store an item. Processing will stop if the stack size + * of stackToStow drops to 0 or less or the event is canceled. + */ + public static class Stow extends BackpackEvent implements ICancellableEvent { + public final ItemStack stackToStow; + + public Stow(Player player, BackpackDefinition backpackDefinition, Container backpackInventory, ItemStack stackToStow) { + super(player, backpackDefinition, backpackInventory); + + this.stackToStow = stackToStow; + } + } + + /** + * Use @SubscribeEvent on a method taking this event as an argument. Will fire whenever a backpack tries to resupply to a player inventory. Processing will stop + * if the event is canceled. + */ + public static class Resupply extends BackpackEvent implements ICancellableEvent { + public Resupply(Player player, BackpackDefinition backpackDefinition, Container backpackInventory) { + super(player, backpackDefinition, backpackInventory); + } + } +} diff --git a/src/main/java/forestry/api/event/BeeMatingEvent.java b/src/main/java/forestry/api/event/BeeMatingEvent.java new file mode 100644 index 0000000000..c90c8c90e7 --- /dev/null +++ b/src/main/java/forestry/api/event/BeeMatingEvent.java @@ -0,0 +1,43 @@ +package forestry.api.event; + +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.bee.IBee; +import net.neoforged.bus.api.Event; +import net.neoforged.bus.api.ICancellableEvent; + +/** + * Fired before a queen is created as a result of breeding a princess and a drone. + * For example, this can be used to cancel the breeding or change the resultant queen's genome (ex. to make Zombified). + */ +public class BeeMatingEvent extends Event implements ICancellableEvent { + private final IBeeHousing housing; + private IBee princess; + private final IBee drone; + + public BeeMatingEvent(IBeeHousing housing, IBee princess, IBee drone) { + this.housing = housing; + this.princess = princess; + this.drone = drone; + } + + public IBeeHousing getHousing() { + return this.housing; + } + + public IBee getPrincess() { + return this.princess; + } + + /** + * Used to override the princess individual, which will become the queen individual. + * + * @param princess The new princess individual to replace the queen with. + */ + public void setPrincess(IBee princess) { + this.princess = princess; + } + + public IBee getDrone() { + return this.drone; + } +} diff --git a/src/main/java/forestry/api/event/BreedingTrackerEvent.java b/src/main/java/forestry/api/event/BreedingTrackerEvent.java new file mode 100644 index 0000000000..455592ffd0 --- /dev/null +++ b/src/main/java/forestry/api/event/BreedingTrackerEvent.java @@ -0,0 +1,73 @@ +package forestry.api.event; + +import com.mojang.authlib.GameProfile; +import forestry.api.genetics.IBreedingTracker; +import forestry.api.genetics.IMutation; +import forestry.api.genetics.ISpecies; +import forestry.api.genetics.ISpeciesType; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.component.ResolvableProfile; +import net.neoforged.bus.api.Event; +import org.jetbrains.annotations.ApiStatus; + +/** + * Supertype for events concerning breeding and mutation. + */ +@ApiStatus.Internal +public abstract class BreedingTrackerEvent extends Event { + public final ISpeciesType root; + public final IBreedingTracker tracker; + public final ResolvableProfile username; + + private BreedingTrackerEvent(ISpeciesType root, ResolvableProfile username, IBreedingTracker tracker) { + this.root = root; + this.username = username; + this.tracker = tracker; + } + + /** + * Fired when a player first discovers a mutation, such as: + *

+ */ + public static class MutationDiscovered extends BreedingTrackerEvent { + public final IMutation allele; + + public MutationDiscovered(ISpeciesType root, ResolvableProfile username, IMutation allele, IBreedingTracker tracker) { + super(root, username, tracker); + this.allele = allele; + } + } + + /** + * Fired when a player first discovers a species, such as: + * + */ + public static class SpeciesDiscovered extends BreedingTrackerEvent { + public final ISpecies species; + + public SpeciesDiscovered(ISpeciesType root, ResolvableProfile username, ISpecies species, IBreedingTracker tracker) { + super(root, username, tracker); + this.species = species; + } + } + + /** + * Fired when a player's breeding tracker is synced to the client. + */ + public static class Synced extends BreedingTrackerEvent { + public final Player player; + + public Synced(ISpeciesType type, IBreedingTracker tracker, Player player) { + super(type, new ResolvableProfile(player.getGameProfile()), tracker); + + this.player = player; + } + } +} diff --git a/src/main/java/forestry/energy/render/package-info.java b/src/main/java/forestry/api/event/package-info.java similarity index 54% rename from src/main/java/forestry/energy/render/package-info.java rename to src/main/java/forestry/api/event/package-info.java index 7364ae5004..73301464dd 100644 --- a/src/main/java/forestry/energy/render/package-info.java +++ b/src/main/java/forestry/api/event/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault -package forestry.energy.render; +package forestry.api.event; diff --git a/src/main/java/forestry/api/farming/IFarmHousing.java b/src/main/java/forestry/api/farming/IFarmHousing.java index 5558ef4d13..b389173e29 100644 --- a/src/main/java/forestry/api/farming/IFarmHousing.java +++ b/src/main/java/forestry/api/farming/IFarmHousing.java @@ -6,7 +6,7 @@ import net.minecraft.core.Vec3i; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import java.util.Collection; diff --git a/src/main/java/forestry/api/farming/IFarmListener.java b/src/main/java/forestry/api/farming/IFarmListener.java deleted file mode 100644 index 7ad3de8aa3..0000000000 --- a/src/main/java/forestry/api/farming/IFarmListener.java +++ /dev/null @@ -1,58 +0,0 @@ -package forestry.api.farming; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; - -import java.util.Collection; -import java.util.List; - -public interface IFarmListener { - /** - * Called before a crop is harvested. - * - * @param crop ICrop about to be harvested. - * @return true to cancel further processing of this crop. - */ - default boolean beforeCropHarvest(ICrop crop) { - return false; - } - - /** - * Called after a crop has been harvested, but before harvested items are stowed in the farms inventory. - * - * @param harvested Collection of harvested stacks. May be manipulated. Ensure removal of stacks with 0 or less items! - * @param crop Harvested {@link ICrop} - */ - default void afterCropHarvest(List harvested, ICrop crop) { - } - - /** - * Called after the stack of collected items has been returned by the farm logic, but before it is added to the farm's pending queue. - * - * @param collected Collection of collected stacks. May be manipulated. Ensure removal of stacks with 0 or less items! - */ - default void hasCollected(List collected, IFarmLogic logic) { - } - - /** - * Called after farmland has successfully been cultivated by a farm logic. - */ - default void hasCultivated(IFarmLogic logic, BlockPos pos, Direction direction, int extent) { - } - - /** - * Called after the stack of harvested crops has been returned by the farm logic, but before it is added to the farm's pending queue. - */ - default void hasScheduledHarvest(Collection harvested, IFarmLogic logic, BlockPos pos, Direction direction, int extent) { - } - - /** - * Can be used to cancel farm task on a per side/{@link IFarmLogic} basis. - * - * @return true to skip any work action on the given logic and direction for this work cycle. - */ - default boolean cancelTask(IFarmLogic logic, Direction direction) { - return false; - } -} diff --git a/src/main/java/forestry/api/farming/package-info.java b/src/main/java/forestry/api/farming/package-info.java index 92a34c9b55..e44b2e3792 100644 --- a/src/main/java/forestry/api/farming/package-info.java +++ b/src/main/java/forestry/api/farming/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.farming; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/fuels/BiogasEngineFuel.java b/src/main/java/forestry/api/fuels/BiogasEngineFuel.java new file mode 100644 index 0000000000..ec48bcd999 --- /dev/null +++ b/src/main/java/forestry/api/fuels/BiogasEngineFuel.java @@ -0,0 +1,17 @@ +package forestry.api.fuels; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +/** + * @param powerPerCycle Power produced by this fuel per work cycle of the engine. + * @param burnDuration How many work cycles a single "stack" of this type lasts. + * @param dissipationMultiplier By how much the normal heat dissipation rate of 1 is multiplied when using this fuel type. + */ +public record BiogasEngineFuel(int powerPerCycle, int burnDuration, int dissipationMultiplier) { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + Codec.INT.fieldOf("power_per_cycle").forGetter(BiogasEngineFuel::powerPerCycle), + Codec.INT.fieldOf("burn_duration").forGetter(BiogasEngineFuel::burnDuration), + Codec.INT.fieldOf("dissipation_multiplier").forGetter(BiogasEngineFuel::dissipationMultiplier) + ).apply(inst, BiogasEngineFuel::new)); +} diff --git a/src/main/java/forestry/api/fuels/EngineBronzeFuel.java b/src/main/java/forestry/api/fuels/EngineBronzeFuel.java deleted file mode 100644 index 10b101c22c..0000000000 --- a/src/main/java/forestry/api/fuels/EngineBronzeFuel.java +++ /dev/null @@ -1,14 +0,0 @@ -package forestry.api.fuels; - -import net.minecraft.world.level.material.Fluid; - -/** - * todo data driven - * - * @param liquid Fluid that is valid fuel for a biogas engine. - * @param powerPerCycle Power produced by this fuel per work cycle of the engine. - * @param burnDuration How many work cycles a single "stack" of this type lasts. - * @param dissipationMultiplier By how much the normal heat dissipation rate of 1 is multiplied when using this fuel type. - */ -public record EngineBronzeFuel(Fluid liquid, int powerPerCycle, int burnDuration, int dissipationMultiplier) { -} diff --git a/src/main/java/forestry/api/fuels/EngineCopperFuel.java b/src/main/java/forestry/api/fuels/EngineCopperFuel.java deleted file mode 100644 index b8c4041a91..0000000000 --- a/src/main/java/forestry/api/fuels/EngineCopperFuel.java +++ /dev/null @@ -1,13 +0,0 @@ -package forestry.api.fuels; - -import net.minecraft.world.item.ItemStack; - -/** - * todo data driven - * - * @param fuel Item that is valid fuel for a peat-fired engine. - * @param powerPerCycle Power produced by this fuel per work cycle. - * @param burnDuration Amount of work cycles this item lasts before being consumed. - */ -public record EngineCopperFuel(ItemStack fuel, int powerPerCycle, int burnDuration) { -} diff --git a/src/main/java/forestry/api/fuels/FermenterFuel.java b/src/main/java/forestry/api/fuels/FermenterFuel.java index 13e630faef..1c6a05622a 100644 --- a/src/main/java/forestry/api/fuels/FermenterFuel.java +++ b/src/main/java/forestry/api/fuels/FermenterFuel.java @@ -1,13 +1,15 @@ package forestry.api.fuels; -import net.minecraft.world.item.ItemStack; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; /** - * todo data driven - * - * @param item Item that is a valid fuel for the fermenter (i.e. fertilizer). * @param fermentPerCycle How much is fermented per work cycle, i.e. how much biomass is produced per cycle. * @param burnDuration Amount of work cycles a single item of this fuel lasts before expiring. */ -public record FermenterFuel(ItemStack item, int fermentPerCycle, int burnDuration) { +public record FermenterFuel(int fermentPerCycle, int burnDuration) { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + Codec.INT.fieldOf("ferment_per_cycle").forGetter(FermenterFuel::fermentPerCycle), + Codec.INT.fieldOf("burn_duration").forGetter(FermenterFuel::burnDuration) + ).apply(inst, FermenterFuel::new)); } diff --git a/src/main/java/forestry/api/fuels/FuelManager.java b/src/main/java/forestry/api/fuels/FuelManager.java index 1bb571c5b8..d05e78405d 100644 --- a/src/main/java/forestry/api/fuels/FuelManager.java +++ b/src/main/java/forestry/api/fuels/FuelManager.java @@ -5,27 +5,18 @@ import java.util.Map; -// todo get rid of the ItemStack maps +@Deprecated(forRemoval = true) public class FuelManager { - /** - * Add new fuels for the fermenter here (i.e. fertilizer). - */ public static Map fermenterFuel; - /** - * Add new resources for the moistener here (i.e. wheat) - */ public static Map moistenerResource; - /** - * Add new substrates for the rainmaker here - */ - public static Map rainSubstrate; + public static Map rainSubstrate; /** * Add new fuels for EngineBronze (= biogas engine) here */ - public static Map biogasEngineFuel; + public static Map biogasEngineFuel; /** * Add new fuels for EngineCopper (= peat-fired engine) here */ - public static Map peatEngineFuel; + public static Map peatEngineFuel; } diff --git a/src/main/java/forestry/api/fuels/MoistenerFuel.java b/src/main/java/forestry/api/fuels/MoistenerFuel.java index 268c2a9dfa..2a038b73b0 100644 --- a/src/main/java/forestry/api/fuels/MoistenerFuel.java +++ b/src/main/java/forestry/api/fuels/MoistenerFuel.java @@ -1,19 +1,19 @@ package forestry.api.fuels; -import com.google.common.base.Preconditions; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.world.item.ItemStack; /** - * todo data driven - * - * @param resource The item to use. * @param product The item that leaves the moistener's working slot (i.e. mouldy wheat, decayed wheat, mulch) * @param stage How much this item contributes to the final product of the moistener (i.e. mycelium) * @param moistenerValue What stage this product represents. Resources with lower stage value will be consumed first. */ -public record MoistenerFuel(ItemStack resource, ItemStack product, int stage, int moistenerValue) { - public MoistenerFuel { - Preconditions.checkArgument(!resource.isEmpty()); - Preconditions.checkArgument(!product.isEmpty()); - } +public record MoistenerFuel(ItemStack product, int stage, int moistenerValue) { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + ItemStack.CODEC.fieldOf("product").forGetter(MoistenerFuel::product), + Codec.INT.fieldOf("stage").forGetter(MoistenerFuel::stage), + Codec.INT.fieldOf("moistener_value").forGetter(MoistenerFuel::moistenerValue) + ).apply(inst, MoistenerFuel::new)); } diff --git a/src/main/java/forestry/api/fuels/PeatEngineFuel.java b/src/main/java/forestry/api/fuels/PeatEngineFuel.java new file mode 100644 index 0000000000..c31bd0c571 --- /dev/null +++ b/src/main/java/forestry/api/fuels/PeatEngineFuel.java @@ -0,0 +1,15 @@ +package forestry.api.fuels; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +/** + * @param powerPerCycle Power produced by this fuel per work cycle. + * @param burnDuration Amount of work cycles this item lasts before being consumed. + */ +public record PeatEngineFuel(int powerPerCycle, int burnDuration) { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + Codec.INT.fieldOf("power_per_cycle").forGetter(PeatEngineFuel::powerPerCycle), + Codec.INT.fieldOf("burn_duration").forGetter(PeatEngineFuel::burnDuration) + ).apply(inst, PeatEngineFuel::new)); +} diff --git a/src/main/java/forestry/api/fuels/RainSubstrate.java b/src/main/java/forestry/api/fuels/RainSubstrate.java deleted file mode 100644 index 995be05333..0000000000 --- a/src/main/java/forestry/api/fuels/RainSubstrate.java +++ /dev/null @@ -1,21 +0,0 @@ -package forestry.api.fuels; - -import net.minecraft.world.item.ItemStack; - -/** - * todo data driven - * - * @param item Rain substrate capable of activating the rainmaker. - * @param duration Duration of the rain shower triggered by this substrate in Minecraft ticks. - * @param speed Speed of activation sequence triggered. - * @param reverse Whether the substrate stops rain instead of creating rain. - */ -public record RainSubstrate(ItemStack item, int duration, float speed, boolean reverse) { - public RainSubstrate(ItemStack item, float speed) { - this(item, 0, speed, true); - } - - public RainSubstrate(ItemStack item, int duration, float speed) { - this(item, duration, speed, false); - } -} diff --git a/src/main/java/forestry/api/fuels/RainmakerFuel.java b/src/main/java/forestry/api/fuels/RainmakerFuel.java new file mode 100644 index 0000000000..331052df86 --- /dev/null +++ b/src/main/java/forestry/api/fuels/RainmakerFuel.java @@ -0,0 +1,27 @@ +package forestry.api.fuels; + +import com.google.common.base.Preconditions; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; + +/** + * Data map value for items usable by the Rainmaker machine. + * + * @param duration Duration of the rain shower triggered by this substrate in Minecraft ticks. Must be 0 for clear weather. + * @param speed Speed of activation sequence triggered. + * @param reverse Whether the substrate stops rain instead of creating rain. + */ +public record RainmakerFuel(int duration, float speed, boolean reverse) { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + Codec.INT.fieldOf("duration").forGetter(RainmakerFuel::duration), + Codec.FLOAT.fieldOf("speed").forGetter(RainmakerFuel::speed), + Codec.BOOL.fieldOf("reverse").forGetter(RainmakerFuel::reverse) + ).apply(inst, RainmakerFuel::new)); + + public RainmakerFuel { + if (reverse) { + Preconditions.checkArgument(duration == 0); + } + } +} diff --git a/src/main/java/forestry/api/fuels/package-info.java b/src/main/java/forestry/api/fuels/package-info.java index 94357fd6fe..72ab5afc8e 100644 --- a/src/main/java/forestry/api/fuels/package-info.java +++ b/src/main/java/forestry/api/fuels/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.fuels; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/genetics/ForestrySpeciesTypes.java b/src/main/java/forestry/api/genetics/ForestrySpeciesTypes.java index 18e4fbadf0..1282c59041 100644 --- a/src/main/java/forestry/api/genetics/ForestrySpeciesTypes.java +++ b/src/main/java/forestry/api/genetics/ForestrySpeciesTypes.java @@ -8,7 +8,7 @@ */ public class ForestrySpeciesTypes { /** - * @see forestry.api.apiculture.genetics.IBeeSpeciesType + * @see forestry.api.apiculture.bee.IBeeSpeciesType */ public static final ResourceLocation BEE = ForestryConstants.forestry("bee_species"); /** diff --git a/src/main/java/forestry/api/genetics/IBreedingTracker.java b/src/main/java/forestry/api/genetics/IBreedingTracker.java index a0b07e26f4..bb3618cea2 100644 --- a/src/main/java/forestry/api/genetics/IBreedingTracker.java +++ b/src/main/java/forestry/api/genetics/IBreedingTracker.java @@ -1,6 +1,7 @@ package forestry.api.genetics; import forestry.api.genetics.alleles.IAllele; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; @@ -76,8 +77,7 @@ public interface IBreedingTracker { void syncToPlayer(Player player); // todo replace these with "save" and "load" in 1.21 - void readFromNbt(CompoundTag nbt); + void readFromNbt(CompoundTag nbt, HolderLookup.Provider registries); void writeToNbt(CompoundTag nbt); - } diff --git a/src/main/java/forestry/api/genetics/IBreedingTrackerManager.java b/src/main/java/forestry/api/genetics/IBreedingTrackerManager.java index 7da2f823bd..2df3744b75 100644 --- a/src/main/java/forestry/api/genetics/IBreedingTrackerManager.java +++ b/src/main/java/forestry/api/genetics/IBreedingTrackerManager.java @@ -1,6 +1,6 @@ package forestry.api.genetics; -import com.mojang.authlib.GameProfile; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.LevelAccessor; import javax.annotation.Nullable; @@ -13,5 +13,5 @@ public interface IBreedingTrackerManager { * @param profile The profile of the player whose breeding tracker should be queried. * @return The player-specific species tracker for the species type with the given ID. */ - T getTracker(ISpeciesType type, LevelAccessor level, @Nullable GameProfile profile); + T getTracker(ISpeciesType type, LevelAccessor level, @Nullable ResolvableProfile profile); } diff --git a/src/main/java/forestry/api/genetics/IFruitBearer.java b/src/main/java/forestry/api/genetics/IFruitBearer.java index 29c6aded68..dfd8656010 100644 --- a/src/main/java/forestry/api/genetics/IFruitBearer.java +++ b/src/main/java/forestry/api/genetics/IFruitBearer.java @@ -16,10 +16,9 @@ public interface IFruitBearer { /** * Picks the fruits of this tile, resetting it to unripe fruits. * - * @param tool Tool used in picking the fruits. May be empty. * @return Picked fruits. The returned list is immutable. */ - List pickFruit(ItemStack tool); + List pickFruit(); /** * @return float indicating the ripeness of the fruit with >= 1.0f indicating full ripeness. diff --git a/src/main/java/forestry/api/genetics/IGenome.java b/src/main/java/forestry/api/genetics/IGenome.java index a478184ddd..0bee3e05b9 100644 --- a/src/main/java/forestry/api/genetics/IGenome.java +++ b/src/main/java/forestry/api/genetics/IGenome.java @@ -19,7 +19,6 @@ public interface IGenome { /** * Returns the allele pair containing the active and inactive alleles of the given chromosome. - * Uses an unchecked cast. * * @return The allele pair for the given chromosome. */ @@ -155,7 +154,7 @@ default MutableComponent getInactiveName(IValueChromosome chromosome) { * @return The active species of the individual. */ default > S getActiveSpecies() { - return (S) getActiveValue(getKaryotype().getSpeciesChromosome()); + return getActiveValue(getKaryotype().getSpeciesChromosome()).cast(); } /** @@ -164,6 +163,6 @@ default > S getActiveSpecies() { * @return The inactive species of the individual. */ default > S getInactiveSpecies() { - return (S) getInactiveValue(getKaryotype().getSpeciesChromosome()); + return getInactiveValue(getKaryotype().getSpeciesChromosome()).cast(); } } diff --git a/src/main/java/forestry/api/genetics/IIndividual.java b/src/main/java/forestry/api/genetics/IIndividual.java index d212cbfeb7..602381e8e0 100644 --- a/src/main/java/forestry/api/genetics/IIndividual.java +++ b/src/main/java/forestry/api/genetics/IIndividual.java @@ -1,7 +1,7 @@ package forestry.api.genetics; -import forestry.api.ForestryConstants; -import net.minecraft.resources.ResourceLocation; +import com.mojang.serialization.Codec; +import forestry.api.ForestryRegistries; import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; @@ -12,15 +12,7 @@ * It can be mated with another individual to produce offspring. */ public interface IIndividual { - ResourceLocation CAPABILITY_ID = new ResourceLocation(ForestryConstants.MOD_ID, "individual") { - // Used for AttachCapabilitiesEvent. Hashcode is cached for performance. - private final int hashCode = super.hashCode(); - - @Override - public int hashCode() { - return this.hashCode; - } - }; + Codec CODEC = ForestryRegistries.SPECIES_TYPE.byNameCodec().dispatch(IIndividual::getType, ISpeciesType::getIndividualCodec); /** * @return The genome of this individual. diff --git a/src/main/java/forestry/api/genetics/ILifeStage.java b/src/main/java/forestry/api/genetics/ILifeStage.java index 39d35cb790..f0db53f3c5 100644 --- a/src/main/java/forestry/api/genetics/ILifeStage.java +++ b/src/main/java/forestry/api/genetics/ILifeStage.java @@ -8,7 +8,7 @@ /** * The replacement for the old ISpeciesType class. Denotes different forms of the same species (ex. larvae, princess, queen, drone) * - * @see forestry.api.apiculture.genetics.BeeLifeStage + * @see forestry.api.apiculture.bee.BeeLifeStage * @see forestry.api.arboriculture.genetics.TreeLifeStage * @see forestry.api.lepidopterology.genetics.ButterflyLifeStage */ diff --git a/src/main/java/forestry/api/genetics/IMutation.java b/src/main/java/forestry/api/genetics/IMutation.java index 64c99048ee..c26ee87bcf 100644 --- a/src/main/java/forestry/api/genetics/IMutation.java +++ b/src/main/java/forestry/api/genetics/IMutation.java @@ -5,6 +5,7 @@ import forestry.api.genetics.alleles.AllelePair; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import java.util.List; @@ -71,5 +72,5 @@ public interface IMutation> { */ boolean isSecret(); - ItemStack getMutationNote(GameProfile researcher); + ItemStack getMutationNote(ResolvableProfile researcher); } diff --git a/src/main/java/forestry/api/genetics/ISpecies.java b/src/main/java/forestry/api/genetics/ISpecies.java index cd99cecbde..0cc57c8b2c 100644 --- a/src/main/java/forestry/api/genetics/ISpecies.java +++ b/src/main/java/forestry/api/genetics/ISpecies.java @@ -22,6 +22,14 @@ default MutableComponent getDisplayName() { return Component.translatable(getTranslationKey()); } + /** + * Returns the display name used for the item form of this species. + * + * @param stage The life stage of the item (ex. Drone, Pollen, Caterpillar) + * @return The display name of this species's item form. + */ + Component getItemDisplayName(ILifeStage stage); + /** * @return The translation key for the description of this species used by the Portable Analyzer. */ @@ -126,6 +134,7 @@ default IKaryotype getKaryotype() { */ int getEscritoireColor(); + @SuppressWarnings("unchecked") default > S cast() { return (S) this; } diff --git a/src/main/java/forestry/api/genetics/ISpeciesType.java b/src/main/java/forestry/api/genetics/ISpeciesType.java index 2436442ef1..453dac0728 100644 --- a/src/main/java/forestry/api/genetics/ISpeciesType.java +++ b/src/main/java/forestry/api/genetics/ISpeciesType.java @@ -2,20 +2,21 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.mojang.authlib.GameProfile; import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import forestry.api.ForestryCapabilities; import forestry.api.genetics.alleles.IKaryotype; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.plugin.IApicultureRegistration; import forestry.api.plugin.IForestryPlugin; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; @@ -71,7 +72,7 @@ public interface ISpeciesType, I extends IIndividual> exte * @throws IllegalStateException If not all species have been registered yet. */ @Nullable - S getSpeciesSafe(ResourceLocation id); + S getSpeciesSafe(@Nullable ResourceLocation id); /** * @return A random species from all registered species of this type. @@ -101,13 +102,11 @@ public interface ISpeciesType, I extends IIndividual> exte /** * @return The translation key for this species type. Ex. "species_type.forestry.bee" -> "Bee" - * @since 2.2.0 */ String getTranslationKey(); /** * @return The display name for this species type. Ex. "Bee" or "Butterfly" - * @since 2.2.0 */ default MutableComponent getDisplayName() { return Component.translatable(getTranslationKey()); @@ -132,7 +131,7 @@ default ItemStack createDefaultStack() { * @param profile The player whose breeding tracker should be returned. * @return The breeding tracker for species of this type. */ - IBreedingTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile); + IBreedingTracker getBreedingTracker(LevelAccessor level, @Nullable ResolvableProfile profile); /** * The type of the species that will be displayed at the given position of the mutation recipe in the gui. @@ -155,7 +154,7 @@ default ILifeStage getTypeForMutation(int position) { /** * @return The codec used to serialize/deserialize individuals of this species. */ - Codec getIndividualCodec(); + MapCodec getIndividualCodec(); /** * Used to check whether the given {@link IIndividual} is member of this class. @@ -165,9 +164,8 @@ default ILifeStage getTypeForMutation(int position) { */ boolean isMember(IIndividual individual); - @SuppressWarnings({"DataFlowIssue", "ConstantValue"}) default boolean isMember(ItemStack stack) { - IIndividualHandlerItem individual = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM).orElse(null); + IIndividualHandlerItem individual = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM); return individual != null && isMember(individual.getIndividual()); } @@ -193,12 +191,12 @@ default boolean isMember(ItemStack stack) { * The lowest level is 1. Rewards players for memorizing the tiles and using good research material. * @return A list of reward items granted upon researching a specimen in the Escritoire. Might be empty. */ - List getResearchBounty(S species, Level level, GameProfile researcher, I individual, int bountyLevel); + List getResearchBounty(S species, Level level, ResolvableProfile researcher, I individual, int bountyLevel); /** * @return The name of the breeding tracker save file for the given player. */ - String getBreedingTrackerFile(@Nullable GameProfile profile); + String getBreedingTrackerFile(@Nullable ResolvableProfile profile); /** * @return A new breeding tracker. @@ -208,7 +206,7 @@ default boolean isMember(ItemStack stack) { /** * @return A breeding tracker with data loaded from a previous save file. */ - IBreedingTracker createBreedingTracker(CompoundTag nbt); + IBreedingTracker createBreedingTracker(CompoundTag nbt, HolderLookup.Provider registries); /** * @return A new individual of a random species using the default genome of the chosen species. @@ -219,10 +217,10 @@ default boolean isMember(ItemStack stack) { * Used to initialize a breeding tracker with additional information. * * @param tracker The tracker to add information to. - * @param world The world this tracker is saved to. Always the overworld dimension. + * @param level The world this tracker is saved to. Always the overworld dimension. * @param profile The player to whom the breeding tracker belongs to. */ - void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level world, @Nullable GameProfile profile); + void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level level, @Nullable ResolvableProfile profile); /** * Used to register species and related data for this species type from an {@link IForestryPlugin}. @@ -251,6 +249,7 @@ default boolean isMember(ItemStack stack) { /** * @return This species type casted to a subclass of ISpeciesType. */ + @SuppressWarnings("unchecked") default > T cast() { return (T) this; } diff --git a/src/main/java/forestry/api/genetics/alleles/BeeChromosomes.java b/src/main/java/forestry/api/genetics/alleles/BeeChromosomes.java index a795023841..5cd3daeb55 100644 --- a/src/main/java/forestry/api/genetics/alleles/BeeChromosomes.java +++ b/src/main/java/forestry/api/genetics/alleles/BeeChromosomes.java @@ -1,9 +1,9 @@ package forestry.api.genetics.alleles; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.IFlowerType; -import forestry.api.apiculture.genetics.IBeeEffect; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.IFlowerType; +import forestry.api.apiculture.bee.IBeeEffect; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.core.ToleranceType; import forestry.api.genetics.ForestrySpeciesTypes; import net.minecraft.core.Vec3i; diff --git a/src/main/java/forestry/api/genetics/alleles/ButterflyChromosomes.java b/src/main/java/forestry/api/genetics/alleles/ButterflyChromosomes.java index 7110cbfbf1..c4a97286df 100644 --- a/src/main/java/forestry/api/genetics/alleles/ButterflyChromosomes.java +++ b/src/main/java/forestry/api/genetics/alleles/ButterflyChromosomes.java @@ -1,6 +1,6 @@ package forestry.api.genetics.alleles; -import forestry.api.apiculture.IFlowerType; +import forestry.api.apiculture.bee.IFlowerType; import forestry.api.core.ToleranceType; import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.lepidopterology.IButterflyCocoon; diff --git a/src/main/java/forestry/api/genetics/alleles/ForestryAlleles.java b/src/main/java/forestry/api/genetics/alleles/ForestryAlleles.java index 8ca9eb986b..66313d5c13 100644 --- a/src/main/java/forestry/api/genetics/alleles/ForestryAlleles.java +++ b/src/main/java/forestry/api/genetics/alleles/ForestryAlleles.java @@ -3,9 +3,12 @@ import forestry.api.ForestryConstants; import forestry.api.IForestryApi; import forestry.api.apiculture.*; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.IBeeEffect; +import forestry.api.apiculture.bee.IFlowerType; import forestry.api.arboriculture.ForestryFruits; import forestry.api.arboriculture.genetics.IFruit; +import forestry.api.arboriculture.genetics.IPodFruit; import forestry.api.arboriculture.genetics.ITreeEffect; import forestry.api.core.ToleranceType; import forestry.api.lepidopterology.ForestryButterflyEffects; @@ -227,12 +230,12 @@ public class ForestryAlleles { // Fruits public static final IRegistryAllele FRUIT_NONE = REGISTRY.registryAllele(ForestryFruits.NONE, TreeChromosomes.FRUIT); public static final IRegistryAllele FRUIT_APPLE = REGISTRY.registryAllele(ForestryFruits.APPLE, TreeChromosomes.FRUIT); - public static final IRegistryAllele FRUIT_COCOA = REGISTRY.registryAllele(ForestryFruits.COCOA, TreeChromosomes.FRUIT); + public static final IRegistryAllele FRUIT_COCOA = REGISTRY.registryAllele(ForestryFruits.COCOA, TreeChromosomes.FRUIT); public static final IRegistryAllele FRUIT_CHESTNUT = REGISTRY.registryAllele(ForestryFruits.CHESTNUT, TreeChromosomes.FRUIT); public static final IRegistryAllele FRUIT_WALNUT = REGISTRY.registryAllele(ForestryFruits.WALNUT, TreeChromosomes.FRUIT); public static final IRegistryAllele FRUIT_CHERRY = REGISTRY.registryAllele(ForestryFruits.CHERRY, TreeChromosomes.FRUIT); - public static final IRegistryAllele FRUIT_DATES = REGISTRY.registryAllele(ForestryFruits.DATES, TreeChromosomes.FRUIT); - public static final IRegistryAllele FRUIT_PAPAYA = REGISTRY.registryAllele(ForestryFruits.PAPAYA, TreeChromosomes.FRUIT); + public static final IRegistryAllele FRUIT_DATES = REGISTRY.registryAllele(ForestryFruits.DATES, TreeChromosomes.FRUIT); + public static final IRegistryAllele FRUIT_PAPAYA = REGISTRY.registryAllele(ForestryFruits.PAPAYA, TreeChromosomes.FRUIT); public static final IRegistryAllele FRUIT_LEMON = REGISTRY.registryAllele(ForestryFruits.LEMON, TreeChromosomes.FRUIT); public static final IRegistryAllele FRUIT_PLUM = REGISTRY.registryAllele(ForestryFruits.PLUM, TreeChromosomes.FRUIT); diff --git a/src/main/java/forestry/api/genetics/alleles/IAlleleManager.java b/src/main/java/forestry/api/genetics/alleles/IAlleleManager.java index 74f8520777..48516dc142 100644 --- a/src/main/java/forestry/api/genetics/alleles/IAlleleManager.java +++ b/src/main/java/forestry/api/genetics/alleles/IAlleleManager.java @@ -46,7 +46,10 @@ default IValueAllele valueAllele(V value, IAlleleNaming naming) { */ IBooleanAllele booleanAllele(boolean value, boolean dominant); - IRegistryAllele registryAllele(ResourceLocation id, IRegistryChromosome chromosome); + /** + * @return A new registry allele. Value must be set elsewhere depending on which chromosome this allele belongs to. + */ + IRegistryAllele registryAllele(ResourceLocation id, IRegistryChromosome chromosome); /** * @return The allele codec, which serializes/deserializes using the allele's ID. diff --git a/src/main/java/forestry/api/genetics/alleles/IKaryotype.java b/src/main/java/forestry/api/genetics/alleles/IKaryotype.java index 05a47a0f5d..3127520135 100644 --- a/src/main/java/forestry/api/genetics/alleles/IKaryotype.java +++ b/src/main/java/forestry/api/genetics/alleles/IKaryotype.java @@ -65,7 +65,7 @@ public interface IKaryotype { /** * @return {@code true} if the given allele can be set for this chromosome. */ - boolean isAlleleValid(IChromosome chromosome, A allele); + boolean isAlleleValid(IChromosome chromosome, B allele); Codec getGenomeCodec(); diff --git a/src/main/java/forestry/api/genetics/alleles/IRegistryChromosome.java b/src/main/java/forestry/api/genetics/alleles/IRegistryChromosome.java index 88b4113c9b..ef86c87437 100644 --- a/src/main/java/forestry/api/genetics/alleles/IRegistryChromosome.java +++ b/src/main/java/forestry/api/genetics/alleles/IRegistryChromosome.java @@ -31,7 +31,7 @@ public interface IRegistryChromosome extends IVa * @throws IllegalStateException If the registry is not yet populated. */ @Nullable - V getSafe(ResourceLocation id); + V getSafe(@Nullable ResourceLocation id); /** * @return An immutable collection of all values in this chromosome. diff --git a/src/main/java/forestry/api/genetics/alleles/IValueChromosome.java b/src/main/java/forestry/api/genetics/alleles/IValueChromosome.java index 5055c5d4be..759afb2c73 100644 --- a/src/main/java/forestry/api/genetics/alleles/IValueChromosome.java +++ b/src/main/java/forestry/api/genetics/alleles/IValueChromosome.java @@ -8,5 +8,5 @@ * * @param The type of value held by the alleles of this chromosome. */ -public interface IValueChromosome extends IChromosome> { +public interface IValueChromosome extends IChromosome> { } diff --git a/src/main/java/forestry/api/genetics/alleles/TreeChromosomes.java b/src/main/java/forestry/api/genetics/alleles/TreeChromosomes.java index 62e6836f97..138d947fd2 100644 --- a/src/main/java/forestry/api/genetics/alleles/TreeChromosomes.java +++ b/src/main/java/forestry/api/genetics/alleles/TreeChromosomes.java @@ -1,6 +1,6 @@ package forestry.api.genetics.alleles; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.ITreeEffect; import forestry.api.genetics.ForestrySpeciesTypes; diff --git a/src/main/java/forestry/api/genetics/alleles/package-info.java b/src/main/java/forestry/api/genetics/alleles/package-info.java index 3081a85400..6a80f1be5c 100644 --- a/src/main/java/forestry/api/genetics/alleles/package-info.java +++ b/src/main/java/forestry/api/genetics/alleles/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.genetics.alleles; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/genetics/alyzer/IAlleleDisplayHelper.java b/src/main/java/forestry/api/genetics/alyzer/IAlleleDisplayHelper.java deleted file mode 100644 index bb30a0df2b..0000000000 --- a/src/main/java/forestry/api/genetics/alyzer/IAlleleDisplayHelper.java +++ /dev/null @@ -1,17 +0,0 @@ -package forestry.api.genetics.alyzer; - -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ILifeStage; -import forestry.apiculture.genetics.IGeneticTooltipProvider; -import net.minecraft.resources.ResourceLocation; - -import java.util.function.Predicate; - -public interface IAlleleDisplayHelper { - void addTooltip(IGeneticTooltipProvider provider, ResourceLocation id, int orderingInfo); - - void addTooltip(IGeneticTooltipProvider provider, ResourceLocation id, int orderingInfo, Predicate typeFilter); - - void addAlyzer(IGeneticTooltipProvider provider, ResourceLocation id, int orderingInfo); - -} diff --git a/src/main/java/forestry/api/genetics/alyzer/package-info.java b/src/main/java/forestry/api/genetics/alyzer/package-info.java index bc6fa873ca..4addd2bd0d 100644 --- a/src/main/java/forestry/api/genetics/alyzer/package-info.java +++ b/src/main/java/forestry/api/genetics/alyzer/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.genetics.alyzer; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/genetics/capability/IIndividualHandlerItem.java b/src/main/java/forestry/api/genetics/capability/IIndividualHandlerItem.java index 2ff194e718..3f447e6566 100644 --- a/src/main/java/forestry/api/genetics/capability/IIndividualHandlerItem.java +++ b/src/main/java/forestry/api/genetics/capability/IIndividualHandlerItem.java @@ -17,7 +17,6 @@ * The individual handler manages an item's genetic information. * It contains the {@link IIndividual} and {@link ILifeStage} of the item. * This class can be thought of as the {@link IIndividual} analog of IFluidItemHandler. - * In 1.21, this will be replaced by Components. */ public interface IIndividualHandlerItem { /** @@ -46,22 +45,24 @@ public interface IIndividualHandlerItem { boolean isGeneticForm(); static void ifPresent(ItemStack stack, BiConsumer action) { - if (!stack.isEmpty()) { - stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null).ifPresent(handler -> action.accept(handler.getIndividual(), handler.getStage())); + IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null); + if (handler != null) { + action.accept(handler.getIndividual(), handler.getStage()); } } static void ifPresent(ItemStack stack, Consumer action) { - if (!stack.isEmpty()) { - stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null).ifPresent(handler -> action.accept(handler.getIndividual())); + IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null); + if (handler != null) { + action.accept(handler.getIndividual()); } } /** - * @return Whether the given item has an individual capability. (Vanilla saplings have a capability too) + * @return Whether the given item has genetic data. (Vanilla saplings will return true too) */ static boolean isIndividual(ItemStack stack) { - return !stack.isEmpty() && stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM).isPresent(); + return stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM) != null; } /** @@ -69,23 +70,15 @@ static boolean isIndividual(ItemStack stack) { * * @param stack The item to retrieve the individual from. * @param predicate The predicate to test on the individual. - * @return {@code true} if the individual was present and the predicate returned true, false otherwise. + * @return {@code true} if the individual was present and the predicate returned true, {@code false} otherwise. */ - @SuppressWarnings({"ConstantValue", "DataFlowIssue"}) static boolean filter(ItemStack stack, Predicate predicate) { - if (stack.isEmpty()) { - return false; - } - IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null).orElse(null); + IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null); return handler != null && predicate.test(handler.getIndividual()); } - @SuppressWarnings({"ConstantValue", "DataFlowIssue"}) static boolean filter(ItemStack stack, BiPredicate predicate) { - if (stack.isEmpty()) { - return false; - } - IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null).orElse(null); + IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null); return handler != null && predicate.test(handler.getIndividual(), handler.getStage()); } @@ -96,26 +89,20 @@ static boolean filter(ItemStack stack, BiPredicate pred * @return The individual handler for this item, or null if none was found. */ @Nullable - @SuppressWarnings("DataFlowIssue") static IIndividualHandlerItem get(ItemStack stack) { - return stack.isEmpty() ? null : stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null).orElse(null); + return stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null); } @Nullable - @SuppressWarnings({"ConstantValue", "DataFlowIssue"}) static IIndividual getIndividual(ItemStack stack) { - if (stack.isEmpty()) { - return null; - } - // hack fix for creative tabs - stack.reviveCaps(); - IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null).orElse(null); + IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, null); return handler != null ? handler.getIndividual() : null; } /** * Gets the species of the current item stack, or returns the default species for the species type. */ + @SuppressWarnings("unchecked") static > S getSpecies(ItemStack stack, ISpeciesType type) { IIndividual individual = getIndividual(stack); return individual != null ? (S) individual.getSpecies() : type.getDefaultSpecies(); diff --git a/src/main/java/forestry/api/genetics/capability/package-info.java b/src/main/java/forestry/api/genetics/capability/package-info.java index b0def9d3fe..99dfee7011 100644 --- a/src/main/java/forestry/api/genetics/capability/package-info.java +++ b/src/main/java/forestry/api/genetics/capability/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.genetics.capability; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/genetics/filter/package-info.java b/src/main/java/forestry/api/genetics/filter/package-info.java index fc724e1b34..0caf4a50fc 100644 --- a/src/main/java/forestry/api/genetics/filter/package-info.java +++ b/src/main/java/forestry/api/genetics/filter/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.genetics.filter; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/genetics/package-info.java b/src/main/java/forestry/api/genetics/package-info.java index 73d52e1b44..e19d3c029c 100644 --- a/src/main/java/forestry/api/genetics/package-info.java +++ b/src/main/java/forestry/api/genetics/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.genetics; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/genetics/pollen/package-info.java b/src/main/java/forestry/api/genetics/pollen/package-info.java index 915f195305..ea2e84bc1a 100644 --- a/src/main/java/forestry/api/genetics/pollen/package-info.java +++ b/src/main/java/forestry/api/genetics/pollen/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.genetics.pollen; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/lepidopterology/genetics/ButterflyLifeStage.java b/src/main/java/forestry/api/lepidopterology/genetics/ButterflyLifeStage.java index d02c864167..863af99f7b 100644 --- a/src/main/java/forestry/api/lepidopterology/genetics/ButterflyLifeStage.java +++ b/src/main/java/forestry/api/lepidopterology/genetics/ButterflyLifeStage.java @@ -9,8 +9,8 @@ public enum ButterflyLifeStage implements ILifeStage { BUTTERFLY(LepidopterologyItems.BUTTERFLY_GE), - SERUM(LepidopterologyItems.SERUM_GE), - CATERPILLAR(LepidopterologyItems.CATERPILLAR_GE), + SERUM(LepidopterologyItems.SERUM), + CATERPILLAR(LepidopterologyItems.CATERPILLAR), COCOON(LepidopterologyItems.COCOON_GE); private final String name; diff --git a/src/main/java/forestry/api/lepidopterology/genetics/IButterflySpeciesType.java b/src/main/java/forestry/api/lepidopterology/genetics/IButterflySpeciesType.java index 6a54622c7f..6a07ff93ac 100644 --- a/src/main/java/forestry/api/lepidopterology/genetics/IButterflySpeciesType.java +++ b/src/main/java/forestry/api/lepidopterology/genetics/IButterflySpeciesType.java @@ -1,11 +1,11 @@ package forestry.api.lepidopterology.genetics; -import com.mojang.authlib.GameProfile; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesType; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Mob; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; @@ -13,7 +13,7 @@ public interface IButterflySpeciesType extends ISpeciesType { @Override - IBreedingTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile); + IBreedingTracker getBreedingTracker(LevelAccessor level, @Nullable @Nullable ResolvableProfile profile); /** * Spawns the given butterfly in the world. diff --git a/src/main/java/forestry/api/lepidopterology/genetics/package-info.java b/src/main/java/forestry/api/lepidopterology/genetics/package-info.java index 21f247a85f..9ef98c9706 100644 --- a/src/main/java/forestry/api/lepidopterology/genetics/package-info.java +++ b/src/main/java/forestry/api/lepidopterology/genetics/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.lepidopterology.genetics; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/lepidopterology/package-info.java b/src/main/java/forestry/api/lepidopterology/package-info.java index 47ee2aee91..efb84792ae 100644 --- a/src/main/java/forestry/api/lepidopterology/package-info.java +++ b/src/main/java/forestry/api/lepidopterology/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.lepidopterology; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/mail/ILetter.java b/src/main/java/forestry/api/mail/ILetter.java index 1e04d9fc8e..72f88848a5 100644 --- a/src/main/java/forestry/api/mail/ILetter.java +++ b/src/main/java/forestry/api/mail/ILetter.java @@ -10,7 +10,6 @@ import java.util.List; public interface ILetter extends Container, INbtWritable { - NonNullList getPostage(); void setProcessed(boolean flag); diff --git a/src/main/java/forestry/api/mail/ILetterHandler.java b/src/main/java/forestry/api/mail/ILetterHandler.java index 3edd3c0e15..6a1798f7e0 100644 --- a/src/main/java/forestry/api/mail/ILetterHandler.java +++ b/src/main/java/forestry/api/mail/ILetterHandler.java @@ -4,5 +4,5 @@ import net.minecraft.world.item.ItemStack; public interface ILetterHandler { - IPostalState handleLetter(ServerLevel world, IMailAddress recipient, ItemStack letterStack, boolean doLodge); + IPostalState handleLetter(ServerLevel level, IMailAddress recipient, ItemStack letterStack, boolean doLodge); } diff --git a/src/main/java/forestry/api/mail/IMailAddress.java b/src/main/java/forestry/api/mail/IMailAddress.java index 259e61fd3e..10f919e58b 100644 --- a/src/main/java/forestry/api/mail/IMailAddress.java +++ b/src/main/java/forestry/api/mail/IMailAddress.java @@ -4,7 +4,6 @@ import forestry.api.core.INbtWritable; public interface IMailAddress extends INbtWritable { - IPostalCarrier getCarrier(); String getName(); diff --git a/src/main/java/forestry/api/mail/IPostOffice.java b/src/main/java/forestry/api/mail/IPostOffice.java index 7e553d2f37..5e4445b01f 100644 --- a/src/main/java/forestry/api/mail/IPostOffice.java +++ b/src/main/java/forestry/api/mail/IPostOffice.java @@ -5,7 +5,6 @@ import net.minecraft.world.item.ItemStack; public interface IPostOffice { - void collectPostage(NonNullList stamps); IPostalState lodgeLetter(ServerLevel world, ItemStack itemstack, boolean doLodge); diff --git a/src/main/java/forestry/api/mail/IPostalCarrier.java b/src/main/java/forestry/api/mail/IPostalCarrier.java index 0f9c3bfe6f..bb3e97fe9f 100644 --- a/src/main/java/forestry/api/mail/IPostalCarrier.java +++ b/src/main/java/forestry/api/mail/IPostalCarrier.java @@ -6,8 +6,8 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; /** * Postal Carriers are systems which can be hooked into Forestry's mail system to handle mail delivery. @@ -17,7 +17,6 @@ * "trader" - Handles mail addressed to trade stations. */ public interface IPostalCarrier { - /** * @return The translation key for the human-readable name for this carrier. */ @@ -33,14 +32,14 @@ public interface IPostalCarrier { /** * Handle delivery of a letter addressed to this carrier. * - * @param world The world the {@link IPostOffice} handles. + * @param level The world the {@link IPostOffice} handles. * @param office {link @IPostOffice} which received this letter and handed it to the carrier. * @param recipient An identifier for the recipient as typed by the player into the address field. * @param letterstack ItemStack representing the letter. See {@link LetterUtils} for helper functions to validate and extract it. * @param doDeliver Whether or not the letter is supposed to actually be delivered or if delivery is only to be simulated. * @return {link IPostalState} holding information on success or failure for delivery. */ - IPostalState deliverLetter(ServerLevel world, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doDeliver); + IPostalState deliverLetter(ServerLevel level, IPostOffice office, IMailAddress recipient, ItemStack letterstack, boolean doDeliver); IMailAddress getRecipient(MinecraftServer minecraftServer, String recipientName); } diff --git a/src/main/java/forestry/api/mail/IStampItem.java b/src/main/java/forestry/api/mail/IStampItem.java new file mode 100644 index 0000000000..6f19356749 --- /dev/null +++ b/src/main/java/forestry/api/mail/IStampItem.java @@ -0,0 +1,7 @@ +package forestry.api.mail; + +import net.minecraft.world.item.ItemStack; + +public interface IStampItem { + EnumPostage getPostage(ItemStack stack); +} diff --git a/src/main/java/forestry/api/mail/IStamps.java b/src/main/java/forestry/api/mail/IStamps.java deleted file mode 100644 index 7613da5bfc..0000000000 --- a/src/main/java/forestry/api/mail/IStamps.java +++ /dev/null @@ -1,9 +0,0 @@ -package forestry.api.mail; - -import net.minecraft.world.item.ItemStack; - -public interface IStamps { - - EnumPostage getPostage(ItemStack itemstack); - -} diff --git a/src/main/java/forestry/api/mail/ITradeStation.java b/src/main/java/forestry/api/mail/ITradeStation.java index 35d06a7634..d756558d8d 100644 --- a/src/main/java/forestry/api/mail/ITradeStation.java +++ b/src/main/java/forestry/api/mail/ITradeStation.java @@ -7,7 +7,6 @@ import javax.annotation.Nullable; public interface ITradeStation extends ILetterHandler, Container, IWatchable, IInventoryAdapter { - @Nullable IMailAddress getAddress(); @@ -19,6 +18,5 @@ public interface ITradeStation extends ILetterHandler, Container, IWatchable, II boolean isVirtual(); - ITradeStationInfo getTradeInfo(); - + TradeStationInfo getTradeInfo(); } diff --git a/src/main/java/forestry/api/mail/ITradeStationInfo.java b/src/main/java/forestry/api/mail/ITradeStationInfo.java deleted file mode 100644 index 2d41e66555..0000000000 --- a/src/main/java/forestry/api/mail/ITradeStationInfo.java +++ /dev/null @@ -1,18 +0,0 @@ -package forestry.api.mail; - -import com.mojang.authlib.GameProfile; -import net.minecraft.world.item.ItemStack; - -import java.util.List; - -public interface ITradeStationInfo { - IMailAddress address(); - - GameProfile owner(); - - ItemStack tradegood(); - - List required(); - - EnumTradeStationState state(); -} diff --git a/src/main/java/forestry/api/mail/TradeStationInfo.java b/src/main/java/forestry/api/mail/TradeStationInfo.java new file mode 100644 index 0000000000..9eacdbeca6 --- /dev/null +++ b/src/main/java/forestry/api/mail/TradeStationInfo.java @@ -0,0 +1,20 @@ +package forestry.api.mail; + +import com.google.common.base.Preconditions; +import com.mojang.authlib.GameProfile; +import forestry.mail.features.PostalCarriers; +import net.minecraft.world.item.ItemStack; + +import java.util.List; + +public record TradeStationInfo( + IMailAddress address, + GameProfile owner, + ItemStack tradegood, + List required, + EnumTradeStationState state +) { + public TradeStationInfo { + Preconditions.checkArgument(address.getCarrier().equals(PostalCarriers.TRADER.value()), "TradeStation address must be a trader"); + } +} diff --git a/src/main/java/forestry/api/mail/package-info.java b/src/main/java/forestry/api/mail/package-info.java index 80ee36d9c2..aa75ba6dd5 100644 --- a/src/main/java/forestry/api/mail/package-info.java +++ b/src/main/java/forestry/api/mail/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.mail; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/modules/ForestryModuleIds.java b/src/main/java/forestry/api/modules/ForestryModuleIds.java index c438741b00..4ef9ca41c9 100644 --- a/src/main/java/forestry/api/modules/ForestryModuleIds.java +++ b/src/main/java/forestry/api/modules/ForestryModuleIds.java @@ -9,12 +9,10 @@ public class ForestryModuleIds { public static final ResourceLocation APICULTURE = ForestryConstants.forestry("apiculture"); public static final ResourceLocation ARBORICULTURE = ForestryConstants.forestry("arboriculture"); - public static final ResourceLocation CHARCOAL = ForestryConstants.forestry("charcoal"); public static final ResourceLocation CORE = ForestryConstants.forestry("core"); public static final ResourceLocation ENERGY = ForestryConstants.forestry("energy"); public static final ResourceLocation FACTORY = ForestryConstants.forestry("factory"); public static final ResourceLocation FARMING = ForestryConstants.forestry("farming"); - public static final ResourceLocation FLUIDS = ForestryConstants.forestry("fluids"); public static final ResourceLocation LEPIDOPTEROLOGY = ForestryConstants.forestry("lepidopterology"); public static final ResourceLocation MAIL = ForestryConstants.forestry("mail"); public static final ResourceLocation STORAGE = ForestryConstants.forestry("storage"); diff --git a/src/main/java/forestry/api/modules/IForestryModule.java b/src/main/java/forestry/api/modules/IForestryModule.java index 7089c9f90d..a48518cfaa 100644 --- a/src/main/java/forestry/api/modules/IForestryModule.java +++ b/src/main/java/forestry/api/modules/IForestryModule.java @@ -2,7 +2,8 @@ import forestry.api.client.IClientModuleHandler; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.List; import java.util.function.Consumer; @@ -48,15 +49,7 @@ default void registerEvents(IEventBus modBus) { default void registerClientHandler(Consumer registrar) { } - /** - * Note: this is generally not recommended to use. - * Called during Forestry's common phase. Initialize any static API. - */ - @Deprecated - default void setupApi() { - } - - default void registerPackets(IPacketRegistry registry) { + default void registerPackets(PayloadRegistrar registrar) { } /** diff --git a/src/main/java/forestry/api/modules/IForestryPacket.java b/src/main/java/forestry/api/modules/IForestryPacket.java deleted file mode 100644 index b199478074..0000000000 --- a/src/main/java/forestry/api/modules/IForestryPacket.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.api.modules; - -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; - -public interface IForestryPacket { - // Useless until 1.21 - ResourceLocation id(); - - void write(FriendlyByteBuf buffer); -} diff --git a/src/main/java/forestry/api/modules/IForestryPacketClient.java b/src/main/java/forestry/api/modules/IForestryPacketClient.java index c3e145ad78..4110d40531 100644 --- a/src/main/java/forestry/api/modules/IForestryPacketClient.java +++ b/src/main/java/forestry/api/modules/IForestryPacketClient.java @@ -1,17 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.api.modules; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + /** * A packet sent from the server to the client */ -public interface IForestryPacketClient extends IForestryPacket { +public interface IForestryPacketClient extends CustomPacketPayload { } diff --git a/src/main/java/forestry/api/modules/IForestryPacketServer.java b/src/main/java/forestry/api/modules/IForestryPacketServer.java index 2f27340c96..2ad812c7ec 100644 --- a/src/main/java/forestry/api/modules/IForestryPacketServer.java +++ b/src/main/java/forestry/api/modules/IForestryPacketServer.java @@ -1,14 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.api.modules; -public interface IForestryPacketServer extends IForestryPacket { +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public interface IForestryPacketServer extends CustomPacketPayload { } diff --git a/src/main/java/forestry/api/modules/IPacketRegistry.java b/src/main/java/forestry/api/modules/IPacketRegistry.java index 54b9eb004a..ffa5d04fb1 100644 --- a/src/main/java/forestry/api/modules/IPacketRegistry.java +++ b/src/main/java/forestry/api/modules/IPacketRegistry.java @@ -10,22 +10,22 @@ ******************************************************************************/ package forestry.api.modules; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import java.util.function.BiConsumer; -import java.util.function.Function; public interface IPacketRegistry { /** * Register a packet during the play phase that is handled on the main server thread when the sender is not null. */ -

void serverbound(ResourceLocation id, Class

packetClass, Function decoder, BiConsumer packetHandler); +

void serverbound(CustomPacketPayload.Type

type, StreamDecoder decoder, BiConsumer packetHandler); /** * Register a packet during the play phase that is handled on the main render thread on the client. */ -

void clientbound(ResourceLocation id, Class

packetClass, Function decoder, BiConsumer packetHandler); +

void clientbound(CustomPacketPayload.Type

- * For Backpack Implementers: you can create a new filter with - * {@link IBackpackInterface#createBackpackFilter()} or - * {@link IBackpackInterface#createNaturalistBackpackFilter(String)} - * or implement your own. - * - * @return the backpack's item filter. - */ - Predicate getFilter(); -} diff --git a/src/main/java/forestry/api/storage/IBackpackInterface.java b/src/main/java/forestry/api/storage/IBackpackInterface.java deleted file mode 100755 index 025bd7434f..0000000000 --- a/src/main/java/forestry/api/storage/IBackpackInterface.java +++ /dev/null @@ -1,55 +0,0 @@ - -package forestry.api.storage; - -import forestry.api.genetics.ISpeciesType; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import java.util.function.Predicate; - -/** - * The Backpack Interface allows you to add items to Forestry backpacks or create your own backpacks. - *

- * To create your own backpack, create an {@link IBackpackDefinition}. - * Backpack definitions have a filter, which you can create here with - * {@link #createNaturalistBackpackFilter(String)} - * or create your own. - *

- * After you've created your backpack definition, create the item with - * {@link #createBackpack(IBackpackDefinition, EnumBackpackType)} - * or {@link #createNaturalistBackpack(IBackpackDefinition, ResourceLocation, CreativeModeTab)} - * and then register the returned item like any other item. - */ -public interface IBackpackInterface { - - /** - * Creates a backpack with the given UID and type, returning the item. - * - * @param definition The backpack definition. - * @param type Type of backpack. - * @return Created backpack item. - */ - Item createBackpack(IBackpackDefinition definition, EnumBackpackType type); - - /** - * Create a backpack that can hold items from a specific {@link ISpeciesType}. - * - * @param definition The backpack definition. - * @param speciesTypeId The species root. - * @param tab - * @return Created backpack item. - */ - Item createNaturalistBackpack(IBackpackDefinition definition, ResourceLocation speciesTypeId, CreativeModeTab tab); - - /** - * Makes a new naturalist backpack filter. Only accepts items from a specific {@link ISpeciesType}. - * Useful for implementing {@link IBackpackDefinition} for naturalist's backpacks. - * - * @param speciesTypeId The species root's unique ID. - * @return a new backpack filter for the specified species root - * @see #createNaturalistBackpack(IBackpackDefinition, ResourceLocation, CreativeModeTab) - */ - Predicate createNaturalistBackpackFilter(ResourceLocation speciesTypeId); -} diff --git a/src/main/java/forestry/api/storage/package-info.java b/src/main/java/forestry/api/storage/package-info.java index c549a75f46..1ac38d4001 100644 --- a/src/main/java/forestry/api/storage/package-info.java +++ b/src/main/java/forestry/api/storage/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.storage; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/util/package-info.java b/src/main/java/forestry/api/util/package-info.java index 8e32e17655..ed2f1069ba 100644 --- a/src/main/java/forestry/api/util/package-info.java +++ b/src/main/java/forestry/api/util/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.util; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/apiculture/AlvearyBeeModifier.java b/src/main/java/forestry/apiculture/AlvearyBeeModifier.java index 474abc0882..0d7e70de65 100644 --- a/src/main/java/forestry/apiculture/AlvearyBeeModifier.java +++ b/src/main/java/forestry/apiculture/AlvearyBeeModifier.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeModifier; diff --git a/src/main/java/forestry/apiculture/ApiaristAI.java b/src/main/java/forestry/apiculture/ApiaristAI.java index f42b1b430c..6114723363 100644 --- a/src/main/java/forestry/apiculture/ApiaristAI.java +++ b/src/main/java/forestry/apiculture/ApiaristAI.java @@ -1,6 +1,6 @@ package forestry.apiculture; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.apiculture.blocks.BlockApiculture; import forestry.apiculture.items.ItemBeeGE; import forestry.apiculture.tiles.TileBeeHouse; @@ -41,7 +41,6 @@ public boolean canUse() { return super.canUse(); } - //TODO - now tick? @Override public void tick() { super.tick(); diff --git a/src/main/java/forestry/apiculture/ApiaryBeeListener.java b/src/main/java/forestry/apiculture/ApiaryBeeListener.java index 65dffa191f..694c761ca9 100644 --- a/src/main/java/forestry/apiculture/ApiaryBeeListener.java +++ b/src/main/java/forestry/apiculture/ApiaryBeeListener.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeListener; diff --git a/src/main/java/forestry/apiculture/ApiaryBeeModifier.java b/src/main/java/forestry/apiculture/ApiaryBeeModifier.java index 37b3d428fb..ff08383888 100644 --- a/src/main/java/forestry/apiculture/ApiaryBeeModifier.java +++ b/src/main/java/forestry/apiculture/ApiaryBeeModifier.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeModifier; diff --git a/src/main/java/forestry/apiculture/ApicultureFilterRule.java b/src/main/java/forestry/apiculture/ApicultureFilterRule.java index fbdbfcf5ae..6cc9ea56b8 100644 --- a/src/main/java/forestry/apiculture/ApicultureFilterRule.java +++ b/src/main/java/forestry/apiculture/ApicultureFilterRule.java @@ -1,7 +1,7 @@ package forestry.apiculture; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.IBee; import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.genetics.IIndividual; import forestry.api.genetics.alleles.BeeChromosomes; diff --git a/src/main/java/forestry/apiculture/ApicultureFilterRuleType.java b/src/main/java/forestry/apiculture/ApicultureFilterRuleType.java index 995c5a4dfb..3bed876113 100644 --- a/src/main/java/forestry/apiculture/ApicultureFilterRuleType.java +++ b/src/main/java/forestry/apiculture/ApicultureFilterRuleType.java @@ -1,6 +1,6 @@ package forestry.apiculture; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.client.ForestrySprites; import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.genetics.filter.FilterData; diff --git a/src/main/java/forestry/apiculture/ArmorApiaristHelper.java b/src/main/java/forestry/apiculture/ArmorApiaristHelper.java deleted file mode 100644 index 83c019e3df..0000000000 --- a/src/main/java/forestry/apiculture/ArmorApiaristHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.ForestryCapabilities; -import forestry.api.apiculture.IArmorApiaristHelper; -import forestry.api.apiculture.genetics.IBeeEffect; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nullable; - -public class ArmorApiaristHelper implements IArmorApiaristHelper { - @Override - public boolean isArmorApiarist(ItemStack stack, LivingEntity entity, IBeeEffect cause, boolean doProtect) { - if (stack.isEmpty()) { - return false; - } - - return stack.getCapability(ForestryCapabilities.ARMOR_APIARIST) - .map(armorApiarist -> armorApiarist.protectEntity(entity, stack, cause, doProtect)) - .orElse(false); - } - - @Override - public int wearsItems(LivingEntity entity, @Nullable IBeeEffect cause, boolean doProtect) { - int count = 0; - - for (ItemStack armorItem : entity.getAllSlots()) { - if (isArmorApiarist(armorItem, entity, cause, doProtect)) { - count++; - } - } - - return count; - } -} diff --git a/src/main/java/forestry/apiculture/BeeHousingListener.java b/src/main/java/forestry/apiculture/BeeHousingListener.java index a05c66dfdf..f59b2ffb73 100644 --- a/src/main/java/forestry/apiculture/BeeHousingListener.java +++ b/src/main/java/forestry/apiculture/BeeHousingListener.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeHousing; diff --git a/src/main/java/forestry/apiculture/BeeHousingModifier.java b/src/main/java/forestry/apiculture/BeeHousingModifier.java index ae6cad78f0..1c49d4312c 100644 --- a/src/main/java/forestry/apiculture/BeeHousingModifier.java +++ b/src/main/java/forestry/apiculture/BeeHousingModifier.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutation; import net.minecraft.core.Vec3i; diff --git a/src/main/java/forestry/apiculture/BeeSpecies.java b/src/main/java/forestry/apiculture/BeeSpecies.java index fee69e621e..be6e9285fa 100644 --- a/src/main/java/forestry/apiculture/BeeSpecies.java +++ b/src/main/java/forestry/apiculture/BeeSpecies.java @@ -1,17 +1,18 @@ package forestry.apiculture; import com.google.common.base.Preconditions; -import forestry.api.apiculture.IActivityType; +import forestry.api.apiculture.bee.IActivityType; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.IBeeJubilance; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.api.core.HumidityType; import forestry.api.core.IProduct; import forestry.api.core.TemperatureType; import forestry.api.genetics.ClimateHelper; import forestry.api.genetics.IGenome; +import forestry.api.genetics.ILifeStage; import forestry.api.genetics.alleles.BeeChromosomes; import forestry.api.genetics.alleles.ForestryAlleles; import forestry.api.genetics.alleles.IValueAllele; @@ -100,6 +101,13 @@ public int getEscritoireColor() { return this.escritoireColor == -1 ? this.outline : this.escritoireColor; } + @Override + public Component getItemDisplayName(ILifeStage stage) { + Component speciesName = getDisplayName(); + Component typeName = Component.translatable("for.bees.grammar." + stage.getSerializedName() + ".type"); + return Component.translatable("for.bees.grammar." + stage.getSerializedName(), speciesName, typeName); + } + @Override public void addTooltip(IBee individual, List tooltip) { // No info 4 u! @@ -141,7 +149,7 @@ public void addTooltip(IBee individual, List tooltip) { tooltip.add(genome.getActiveName(BeeChromosomes.FLOWER_TYPE).withStyle(ChatFormatting.GRAY)); - IValueAllele activityAllele = genome.getActiveAllele(BeeChromosomes.ACTIVITY); + IValueAllele activityAllele = genome.getActiveAllele(BeeChromosomes.ACTIVITY); if (activityAllele != ForestryAlleles.ACTIVITY_DIURNAL) { tooltip.add(BeeChromosomes.ACTIVITY.getDisplayName(activityAllele).withStyle(ChatFormatting.GOLD)); } diff --git a/src/main/java/forestry/apiculture/BeehouseBeeModifier.java b/src/main/java/forestry/apiculture/BeehouseBeeModifier.java deleted file mode 100644 index f296cbdf72..0000000000 --- a/src/main/java/forestry/apiculture/BeehouseBeeModifier.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture; - -import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IMutation; - -import javax.annotation.Nullable; - -// no mutations/ignoble decay, 300% aging and flowering, 25% production -public class BeehouseBeeModifier implements IBeeModifier { - @Override - public float modifyProductionSpeed(IGenome genome, float currentSpeed) { - return 0.25f * currentSpeed; - } - - @Override - public float modifyMutationChance(IGenome genome, IGenome mate, IMutation mutation, float currentChance) { - return 0.0f; - } - - @Override - public float modifyAging(IGenome genome, @Nullable IGenome mate, float currentAging) { - return currentAging / 3f; - } - - @Override - public float modifyPollination(IGenome genome, float currentPollination) { - return 3.0f * currentPollination; - } - - @Override - public float modifyGeneticDecay(IGenome genome, float currentDecay) { - return 0.0f; - } -} diff --git a/src/main/java/forestry/apiculture/BeekeepingLogic.java b/src/main/java/forestry/apiculture/BeekeepingLogic.java index 6f453c914e..dc8ba0ad99 100644 --- a/src/main/java/forestry/apiculture/BeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/BeekeepingLogic.java @@ -1,44 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.IForestryApi; import forestry.api.apiculture.*; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; import forestry.api.core.ForestryError; -import forestry.api.core.ForestryEvent; import forestry.api.core.IError; import forestry.api.core.IErrorLogic; +import forestry.api.event.BeeMatingEvent; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.api.genetics.ILifeStage; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.genetics.pollen.IPollen; +import forestry.api.modules.IForestryPacketClient; import forestry.apiculture.network.packets.PacketBeeLogicActive; import forestry.core.config.Constants; +import forestry.core.config.ForestryConfig; import forestry.core.utils.NetworkUtil; import forestry.core.utils.SpeciesUtil; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.MinecraftForge; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.*; @@ -77,7 +70,7 @@ public BeekeepingLogic(IBeeHousing housing) { // / SAVING & LOADING @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { compoundNBT.putInt("BreedingTime", this.beeProgress); compoundNBT.putInt("Throttle", this.workThrottleCounter); @@ -89,7 +82,7 @@ public CompoundTag write(CompoundTag compoundNBT) { compoundNBT.putBoolean("Active", this.active); - this.hasFlowersCache.write(compoundNBT); + this.hasFlowersCache.write(compoundNBT, registries); ArrayDeque spawnCopy = new ArrayDeque<>(this.spawn); ListTag nbttaglist = new ListTag(); @@ -103,14 +96,14 @@ public CompoundTag write(CompoundTag compoundNBT) { } @Override - public void read(CompoundTag compoundNBT) { + public void read(CompoundTag compoundNBT, HolderLookup.Provider registries) { this.beeProgress = compoundNBT.getInt("BreedingTime"); this.workThrottleCounter = compoundNBT.getInt("Throttle"); // sadly this means duplicated NBT if (compoundNBT.contains("queen")) { CompoundTag queenNBT = compoundNBT.getCompound("queen"); - this.queenStack = ItemStack.of(queenNBT); + this.queenStack = ItemStack.parseOptional(registries, queenNBT); this.queen = (IBee) IIndividualHandlerItem.getIndividual(this.queenStack); if (this.queen != null) { this.beeProgressMax = this.queen.getMaxHealth(); @@ -119,33 +112,33 @@ public void read(CompoundTag compoundNBT) { setActive(compoundNBT.getBoolean("Active")); - this.hasFlowersCache.read(compoundNBT); + this.hasFlowersCache.read(compoundNBT, registries); ListTag list = compoundNBT.getList("Offspring", 10); for (int i = 0; i < list.size(); i++) { - this.spawn.add(ItemStack.of(list.getCompound(i))); + this.spawn.add(ItemStack.parseOptional(registries, list.getCompound(i))); } } @Override - public void writeData(FriendlyByteBuf data) { - data.writeBoolean(this.active); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeBoolean(this.active); if (this.active) { - data.writeItem(this.queenStack); - this.hasFlowersCache.writeData(data); + buffer.writeItem(this.queenStack); + this.hasFlowersCache.writeData(buffer); } } @Override - public void readData(FriendlyByteBuf data) { - boolean active = data.readBoolean(); + public void readData(RegistryFriendlyByteBuf buffer) { + boolean active = buffer.readBoolean(); setActive(active); if (active) { - this.queenStack = data.readItem(); + this.queenStack = buffer.readItem(); this.queen = (IBee) IIndividualHandlerItem.getIndividual(this.queenStack); - this.hasFlowersCache.readData(data); + this.hasFlowersCache.readData(buffer); } } @@ -249,7 +242,7 @@ public void doWork() { @Override public void clearCachedValues() { - if (!this.housing.getWorldObj().isClientSide) { + if (!this.housing.getLevel().isClientSide) { this.queenCanWorkCache.clear(); canWork(); if (this.queen != null) { @@ -274,9 +267,9 @@ private void queenWorkTick(@Nullable IBee queen, ItemStack queenStack) { this.workThrottleCounter = 0; doProduction(queen, this.housing, this.beeListener); - Level world = this.housing.getWorldObj(); + Level world = this.housing.getLevel(); List flowers = this.hasFlowersCache.getFlowers(world); - if (flowers.size() < ModuleApiculture.maxFlowersSpawnedPerHive) { + if (flowers.size() < ForestryConfig.SERVER.maxFlowersSpawnedPerHive.get()) { BlockPos blockPos = queen.plantFlowerRandom(this.housing, flowers); if (blockPos != null) { this.hasFlowersCache.addFlowerPos(blockPos); @@ -355,7 +348,7 @@ private void tickBreed() { IGenome originalMate = princess.getMate(); princess.setMate(drone.getGenome()); - ForestryEvent.BeeMatingEvent event = new ForestryEvent.BeeMatingEvent(this.housing, princess, drone); + BeeMatingEvent event = new BeeMatingEvent(this.housing, princess, drone); if (MinecraftForge.EVENT_BUS.post(event)) { princess.setMate(originalMate); @@ -369,7 +362,7 @@ private void tickBreed() { beeInventory.setQueen(this.queenStack); // Register the new queen with the breeding tracker - SpeciesUtil.BEE_TYPE.get().getBreedingTracker(this.housing.getWorldObj(), this.housing.getOwner()).registerQueen(princess); + SpeciesUtil.BEE_TYPE.get().getBreedingTracker(this.housing.getLevel(), this.housing.getOwner()).registerQueen(princess); // Remove drone droneStack.shrink(1); @@ -404,12 +397,12 @@ private static Collection killQueen(IBee queen, IBeeHousing beeHousin * Creates the succeeding princess and between one and three drones. */ private static Collection spawnOffspring(IBee queen, IBeeHousing beeHousing) { - Level level = beeHousing.getWorldObj(); + Level level = beeHousing.getLevel(); ArrayDeque offspring = new ArrayDeque<>(); IApiaristTracker breedingTracker = SpeciesUtil.BEE_TYPE.get().getBreedingTracker(level, beeHousing.getOwner()); // Princess - boolean secondPrincess = level.random.nextInt(10000) < ModuleApiculture.getSecondPrincessChance() * 100; + boolean secondPrincess = level.random.nextInt(10000) < ForestryConfig.SERVER.secondPrincessChance.get() * 100; int count = secondPrincess ? 2 : 1; while (count > 0) { count--; @@ -447,17 +440,18 @@ private static Collection spawnOffspring(IBee queen, IBeeHousing beeH /* CLIENT */ @Override public void syncToClient() { - Level level = this.housing.getWorldObj(); + Level level = this.housing.getLevel(); if (level != null && !level.isClientSide) { - NetworkUtil.sendNetworkPacket(new PacketBeeLogicActive(this.housing), this.housing.getCoordinates(), level); + NetworkUtil.sendToPlayersTrackingPos(new PacketBeeLogicActive(this.housing), this.housing.getBlockPos(), level); } } @Override public void syncToClient(ServerPlayer player) { - Level level = this.housing.getWorldObj(); + Level level = this.housing.getLevel(); if (level != null && !level.isClientSide) { - NetworkUtil.sendToPlayer(new PacketBeeLogicActive(this.housing), player); + IForestryPacketClient packet = new PacketBeeLogicActive(this.housing); + PacketDistributor.sendToPlayer(player, packet); } } diff --git a/src/main/java/forestry/apiculture/CathemeralActivityType.java b/src/main/java/forestry/apiculture/CathemeralActivityType.java index 36e2b1a592..cac1010b40 100644 --- a/src/main/java/forestry/apiculture/CathemeralActivityType.java +++ b/src/main/java/forestry/apiculture/CathemeralActivityType.java @@ -1,7 +1,7 @@ package forestry.apiculture; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.LightPreference; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.LightPreference; import forestry.api.core.ForestryError; import forestry.api.core.IError; import net.minecraft.core.BlockPos; diff --git a/src/main/java/forestry/apiculture/CrepuscularActivityType.java b/src/main/java/forestry/apiculture/CrepuscularActivityType.java index f8b74888c3..220d21c923 100644 --- a/src/main/java/forestry/apiculture/CrepuscularActivityType.java +++ b/src/main/java/forestry/apiculture/CrepuscularActivityType.java @@ -1,7 +1,7 @@ package forestry.apiculture; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.LightPreference; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.LightPreference; import forestry.api.core.ForestryError; import forestry.api.core.IError; import net.minecraft.core.BlockPos; diff --git a/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java b/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java index 1199c9721c..549fe55d6f 100644 --- a/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java @@ -1,17 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeekeepingLogic; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerPlayer; @@ -62,11 +53,11 @@ public List getFlowerPositions() { } @Override - public void read(CompoundTag nbt) { + public void read(CompoundTag nbt, HolderLookup.Provider registries) { } @Override - public CompoundTag write(CompoundTag nbt) { + public CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries) { return nbt; } } diff --git a/src/main/java/forestry/apiculture/FlowerType.java b/src/main/java/forestry/apiculture/FlowerType.java index da6eca05f3..f6a34e9053 100644 --- a/src/main/java/forestry/apiculture/FlowerType.java +++ b/src/main/java/forestry/apiculture/FlowerType.java @@ -1,7 +1,7 @@ package forestry.apiculture; import forestry.api.ForestryTags; -import forestry.api.apiculture.IFlowerType; +import forestry.api.apiculture.bee.IFlowerType; import net.minecraft.core.BlockPos; import net.minecraft.tags.TagKey; import net.minecraft.world.level.Level; diff --git a/src/main/java/forestry/apiculture/HasFlowersCache.java b/src/main/java/forestry/apiculture/HasFlowersCache.java index a0d14bccdb..2fc7e01993 100644 --- a/src/main/java/forestry/apiculture/HasFlowersCache.java +++ b/src/main/java/forestry/apiculture/HasFlowersCache.java @@ -1,24 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IFlowerType; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IFlowerType; +import forestry.api.apiculture.bee.IBee; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.BeeChromosomes; import forestry.api.util.TickHelper; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; @@ -78,7 +69,7 @@ public void update(IBee queen, IBeeHousing beeHousing) { this.flowerCoords.clear(); this.flowers.clear(); } - Level level = beeHousing.getWorldObj(); + Level level = beeHousing.getLevel(); this.tickHelper.onTick(); if (!this.flowerCoords.isEmpty() && this.tickHelper.updateOnInterval(this.flowerCheckInterval)) { @@ -155,7 +146,7 @@ public void forceLookForFlowers(IBee queen, IBeeHousing housing) { this.flowerCoords.clear(); this.flowers.clear(); this.flowerData.resetIterator(queen, housing); - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); while (this.flowerData.areaIterator.hasNext()) { BlockPos.MutableBlockPos blockPos = this.flowerData.areaIterator.next(); if (this.flowerData.flowerType.isAcceptableFlower(level, blockPos)) { @@ -166,7 +157,7 @@ public void forceLookForFlowers(IBee queen, IBeeHousing housing) { } @Override - public void read(CompoundTag compoundNBT) { + public void read(CompoundTag compoundNBT, HolderLookup.Provider registries) { if (!compoundNBT.contains(NBT_KEY)) { return; } @@ -192,7 +183,7 @@ public void read(CompoundTag compoundNBT) { } @Override - public CompoundTag write(CompoundTag CompoundNBT) { + public CompoundTag write(CompoundTag CompoundNBT, HolderLookup.Provider registries) { CompoundTag hasFlowerCacheNBT = new CompoundTag(); if (!this.flowerCoords.isEmpty()) { diff --git a/src/main/java/forestry/apiculture/IApiary.java b/src/main/java/forestry/apiculture/IApiary.java index a4a4b83df5..05b22d7917 100644 --- a/src/main/java/forestry/apiculture/IApiary.java +++ b/src/main/java/forestry/apiculture/IApiary.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeHousing; diff --git a/src/main/java/forestry/apiculture/InventoryBeeHousing.java b/src/main/java/forestry/apiculture/InventoryBeeHousing.java index 9dcc99526b..b1a2f457c9 100644 --- a/src/main/java/forestry/apiculture/InventoryBeeHousing.java +++ b/src/main/java/forestry/apiculture/InventoryBeeHousing.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; import forestry.api.apiculture.IBeeHousingInventory; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.genetics.ILifeStage; import forestry.core.inventory.InventoryAdapterRestricted; import forestry.core.utils.InventoryUtil; diff --git a/src/main/java/forestry/apiculture/ModuleApiculture.java b/src/main/java/forestry/apiculture/ModuleApiculture.java index ad2d430ab3..32033c3677 100644 --- a/src/main/java/forestry/apiculture/ModuleApiculture.java +++ b/src/main/java/forestry/apiculture/ModuleApiculture.java @@ -1,32 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; +import com.google.common.collect.ImmutableList; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import forestry.api.apiculture.BeeManager; +import forestry.api.ForestryCapabilities; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.IArmorApiarist; import forestry.api.client.IClientModuleHandler; -import forestry.api.core.ForestryEvent; import forestry.api.core.TemperatureType; +import forestry.api.event.BeeMatingEvent; import forestry.api.genetics.ForestryTaxa; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.api.modules.IPacketRegistry; import forestry.apiculture.commands.CommandBee; import forestry.apiculture.features.ApicultureItems; import forestry.apiculture.items.EnumPollenCluster; -import forestry.apiculture.network.packets.PacketAlvearyChange; +import forestry.apiculture.items.ItemArmorApiarist; +import forestry.apiculture.network.packets.PacketAlvearyControllerChange; import forestry.apiculture.network.packets.PacketBeeLogicActive; -import forestry.apiculture.network.packets.PacketHabitatBiomePointer; import forestry.apiculture.proxy.ApicultureClientHandler; import forestry.apiculture.villagers.ApicultureVillagers; import forestry.core.data.LootTableHelper; @@ -34,34 +23,24 @@ import forestry.core.utils.SpeciesUtil; import forestry.modules.BlankForestryModule; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.PotionBrewing; import net.minecraft.world.item.alchemy.Potions; -import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.storage.loot.BuiltInLootTables; import net.minecraft.world.level.storage.loot.LootPool; import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.brewing.BrewingRecipeRegistry; -import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; -import net.minecraftforge.event.LootTableLoadEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.LootTableLoadEvent; +import net.neoforged.neoforge.event.brewing.RegisterBrewingRecipesEvent; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.function.Consumer; @ForestryModule public class ModuleApiculture extends BlankForestryModule { - public static int ticksPerBeeWorkCycle = 550; - public static boolean hivesDamageOnPeaceful = false; - public static boolean hivesDamageUnderwater = true; - public static boolean hivesDamageOnlyPlayers = false; - public static boolean hiveDamageOnAttack = true; - public static boolean doSelfPollination = false; - public static int maxFlowersSpawnedPerHive = 20; - @Override public ResourceLocation getId() { return ForestryModuleIds.APICULTURE; @@ -70,44 +49,40 @@ public ResourceLocation getId() { @Override public void registerEvents(IEventBus modBus) { modBus.addListener(ModuleApiculture::registerCapabilities); - modBus.addListener(ModuleApiculture::onCommonSetup); + modBus.addListener(ModuleApiculture::registerBrewingRecipes); - MinecraftForge.EVENT_BUS.addListener(ApicultureVillagers::villagerTrades); - MinecraftForge.EVENT_BUS.addListener(ModuleApiculture::onNetherBeeMate); - MinecraftForge.EVENT_BUS.addListener(ModuleApiculture::modifySnifferLoot); + NeoForge.EVENT_BUS.addListener(ApicultureVillagers::villagerTrades); + NeoForge.EVENT_BUS.addListener(ModuleApiculture::onNetherBeeMate); + NeoForge.EVENT_BUS.addListener(ModuleApiculture::modifySnifferLoot); } - private static void onCommonSetup(FMLCommonSetupEvent event) { + private static void registerBrewingRecipes(RegisterBrewingRecipesEvent event) { // BREWING RECIPES - BrewingRecipeRegistry.addRecipe( - Ingredient.of(PotionUtils.setPotion(new ItemStack(Items.POTION), Potions.AWKWARD)), - Ingredient.of(ApicultureItems.POLLEN_CLUSTER.stack(EnumPollenCluster.NORMAL, 1)), - PotionUtils.setPotion(new ItemStack(Items.POTION), Potions.HEALING)); - BrewingRecipeRegistry.addRecipe( - Ingredient.of(PotionUtils.setPotion(new ItemStack(Items.POTION), Potions.AWKWARD)), - Ingredient.of(ApicultureItems.POLLEN_CLUSTER.stack(EnumPollenCluster.CRYSTALLINE, 1)), - PotionUtils.setPotion(new ItemStack(Items.POTION), Potions.REGENERATION)); + PotionBrewing.Builder builder = event.getBuilder(); + + builder.addMix(Potions.AWKWARD, ApicultureItems.POLLEN_CLUSTER.item(EnumPollenCluster.NORMAL), Potions.HEALING); + builder.addMix(Potions.AWKWARD, ApicultureItems.POLLEN_CLUSTER.item(EnumPollenCluster.CRYSTALLINE), Potions.REGENERATION); } private static void registerCapabilities(RegisterCapabilitiesEvent event) { - event.register(IArmorApiarist.class); + event.registerItem(ForestryCapabilities.BEE_PROTECTION, (stack, v) -> ItemArmorApiarist.PROTECTION, ApicultureItems.APIARIST_HELMET, ApicultureItems.APIARIST_CHEST, ApicultureItems.APIARIST_LEGS, ApicultureItems.APIARIST_BOOTS); } - private static void onNetherBeeMate(ForestryEvent.BeeMatingEvent event) { + private static void onNetherBeeMate(BeeMatingEvent event) { if (event.getPrincess().getSpecies().getGenusName().equals(ForestryTaxa.GENUS_EMBITTERED) && event.getHousing().temperature() != TemperatureType.HELLISH) { event.setPrincess(SpeciesUtil.getBeeSpecies(ForestryBeeSpecies.ZOMBIFIED).createIndividual()); } } private static void modifySnifferLoot(LootTableLoadEvent event) { - if (event.getName().equals(BuiltInLootTables.SNIFFER_DIGGING)) { + if (event.getName().equals(BuiltInLootTables.SNIFFER_DIGGING.location())) { LootPool main = event.getTable().getPool("main"); if (main != null) { - LootPoolEntryContainer[] entries = new LootPoolEntryContainer[main.entries.length + 1]; - System.arraycopy(main.entries, 0, entries, 0, main.entries.length); - entries[main.entries.length] = LootTableHelper.beeLoot(ForestryBeeSpecies.RELIC).build(); - main.entries = entries; + ImmutableList.Builder entries = ImmutableList.builderWithExpectedSize(main.entries.size() + 1); + entries.addAll(main.entries); + entries.add(LootTableHelper.beeLoot(ForestryBeeSpecies.RELIC).build()); + main.entries = entries.build(); } } } @@ -118,20 +93,9 @@ public void addToRootCommand(LiteralArgumentBuilder command) } @Override - public void setupApi() { - BeeManager.armorApiaristHelper = new ArmorApiaristHelper(); - } - - @Override - public void registerPackets(IPacketRegistry registry) { - registry.clientbound(PacketIdClient.BEE_LOGIC_ACTIVE, PacketBeeLogicActive.class, PacketBeeLogicActive::decode, PacketBeeLogicActive::handle); - registry.clientbound(PacketIdClient.HABITAT_BIOME_POINTER, PacketHabitatBiomePointer.class, PacketHabitatBiomePointer::decode, PacketHabitatBiomePointer::handle); - registry.clientbound(PacketIdClient.ALVERAY_CONTROLLER_CHANGE, PacketAlvearyChange.class, PacketAlvearyChange::decode, PacketAlvearyChange::handle); - } - - // todo config - public static double getSecondPrincessChance() { - return (float) 0; + public void registerPackets(PayloadRegistrar registrar) { + registrar.playToClient(PacketIdClient.BEE_LOGIC_ACTIVE, StreamCodec.of(PacketBeeLogicActive::encode, PacketBeeLogicActive::decode), PacketBeeLogicActive::handle); + registrar.playToClient(PacketIdClient.ALVEARY_CONTROLLER_CHANGE, StreamCodec.of(PacketAlvearyControllerChange::encode, PacketAlvearyControllerChange::decode), PacketAlvearyControllerChange::handle); } @Override diff --git a/src/main/java/forestry/apiculture/PhotosynthesisFlowerType.java b/src/main/java/forestry/apiculture/PhotosynthesisFlowerType.java index 3ef8fce5f9..c1efc1c3f2 100644 --- a/src/main/java/forestry/apiculture/PhotosynthesisFlowerType.java +++ b/src/main/java/forestry/apiculture/PhotosynthesisFlowerType.java @@ -1,6 +1,6 @@ package forestry.apiculture; -import forestry.api.apiculture.IFlowerType; +import forestry.api.apiculture.bee.IFlowerType; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer; diff --git a/src/main/java/forestry/apiculture/SingleActivityType.java b/src/main/java/forestry/apiculture/SingleActivityType.java index f10436fde5..1b89b3224f 100644 --- a/src/main/java/forestry/apiculture/SingleActivityType.java +++ b/src/main/java/forestry/apiculture/SingleActivityType.java @@ -1,7 +1,7 @@ package forestry.apiculture; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.LightPreference; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.LightPreference; import forestry.api.core.IError; import net.minecraft.core.BlockPos; diff --git a/src/main/java/forestry/apiculture/WaterFlowerType.java b/src/main/java/forestry/apiculture/WaterFlowerType.java index 8ff5cc0149..df51d058ce 100644 --- a/src/main/java/forestry/apiculture/WaterFlowerType.java +++ b/src/main/java/forestry/apiculture/WaterFlowerType.java @@ -1,7 +1,7 @@ package forestry.apiculture; import forestry.api.ForestryTags; -import forestry.api.apiculture.IFlowerType; +import forestry.api.apiculture.bee.IFlowerType; import net.minecraft.core.BlockPos; import net.minecraft.tags.TagKey; import net.minecraft.world.level.Level; diff --git a/src/main/java/forestry/apiculture/WorldgenBeekeepingLogic.java b/src/main/java/forestry/apiculture/WorldgenBeekeepingLogic.java index a403b502a0..3b62ea43e3 100644 --- a/src/main/java/forestry/apiculture/WorldgenBeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/WorldgenBeekeepingLogic.java @@ -1,33 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture; -import forestry.api.apiculture.IActivityType; +import forestry.api.apiculture.bee.IActivityType; import forestry.api.apiculture.IBeekeepingLogic; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.BeeChromosomes; +import forestry.api.modules.IForestryPacketClient; import forestry.api.util.TickHelper; import forestry.apiculture.network.packets.PacketBeeLogicActive; import forestry.apiculture.tiles.TileHive; import forestry.core.utils.NetworkUtil; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.PacketDistributor; import java.util.List; @@ -47,33 +41,33 @@ public WorldgenBeekeepingLogic(TileHive housing) { // / SAVING & LOADING @Override - public void read(CompoundTag CompoundNBT) { + public void read(CompoundTag CompoundNBT, HolderLookup.Provider registries) { setActive(CompoundNBT.getBoolean("Active")); - this.hasFlowersCache.read(CompoundNBT); + this.hasFlowersCache.read(CompoundNBT, registries); } @Override - public CompoundTag write(CompoundTag CompoundNBT) { + public CompoundTag write(CompoundTag CompoundNBT, HolderLookup.Provider registries) { CompoundNBT.putBoolean("Active", this.active); - this.hasFlowersCache.write(CompoundNBT); + this.hasFlowersCache.write(CompoundNBT, registries); return CompoundNBT; } @Override - public void writeData(FriendlyByteBuf data) { - data.writeBoolean(this.active); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeBoolean(this.active); if (this.active) { - this.hasFlowersCache.writeData(data); + this.hasFlowersCache.writeData(buffer); } } @Override - public void readData(FriendlyByteBuf data) { - boolean active = data.readBoolean(); + public void readData(RegistryFriendlyByteBuf buffer) { + boolean active = buffer.readBoolean(); setActive(active); if (active) { - this.hasFlowersCache.readData(data); + this.hasFlowersCache.readData(buffer); } } @@ -96,7 +90,7 @@ public boolean canWork() { if (this.tickHelper.updateOnInterval(200)) { IBee queen = this.housing.getContainedBee(); this.hasFlowersCache.update(queen, this.housing); - Level level = this.housing.getWorldObj(); + Level level = this.housing.getLevel(); IGenome genome = queen.getGenome(); boolean canWork = genome.getActiveValue(BeeChromosomes.ACTIVITY).isActive(level.getGameTime(), IActivityType.getBeeDayTime(level), this.housing.getBlockPos()) && (!this.housing.isRaining() || genome.getActiveValue(BeeChromosomes.TOLERATES_RAIN)); @@ -126,17 +120,17 @@ public void clearCachedValues() { @Override public void syncToClient() { - Level world = this.housing.getWorldObj(); - if (world != null && !world.isClientSide) { - NetworkUtil.sendNetworkPacket(new PacketBeeLogicActive(this.housing), this.housing.getCoordinates(), world); + if (this.housing.getLevel() instanceof ServerLevel level) { + NetworkUtil.sendToPlayersTrackingPos(new PacketBeeLogicActive(this.housing), this.housing.getBlockPos(), level); } } @Override public void syncToClient(ServerPlayer player) { - Level world = this.housing.getWorldObj(); + Level world = this.housing.getLevel(); if (world != null && !world.isClientSide) { - NetworkUtil.sendToPlayer(new PacketBeeLogicActive(this.housing), player); + IForestryPacketClient packet = new PacketBeeLogicActive(this.housing); + PacketDistributor.sendToPlayer(player, packet); } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java index 4dfd21db5a..771570d2ae 100755 --- a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java +++ b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java @@ -1,28 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.blocks; +import forestry.api.core.IBlockSubtype; +import forestry.apiculture.features.ApicultureTiles; import forestry.apiculture.multiblock.*; -import forestry.apiculture.network.packets.PacketAlvearyChange; +import forestry.apiculture.network.packets.PacketAlvearyControllerChange; import forestry.core.blocks.BlockStructure; import forestry.core.tiles.IActivatable; import forestry.core.tiles.TileUtil; import forestry.core.utils.ItemTooltipUtil; import forestry.core.utils.NetworkUtil; +import forestry.modules.features.FeatureTileType; import net.minecraft.client.gui.screens.Screen; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.BlockTags; import net.minecraft.util.StringRepresentable; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; @@ -34,8 +29,6 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.EnumProperty; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.ArrayList; @@ -64,15 +57,15 @@ public String getSerializedName() { } } - private final BlockAlvearyType type; + private final Type type; - public BlockAlveary(BlockAlvearyType type) { + public BlockAlveary(Type type) { super(Block.Properties.of().strength(1f).sound(SoundType.WOOD)); this.type = type; BlockState defaultState = this.getStateDefinition().any(); - if (type == BlockAlvearyType.PLAIN) { + if (type == Type.PLAIN) { defaultState = defaultState.setValue(PLAIN_TYPE, AlvearyPlainType.NORMAL); - } else if (type.activatable) { + } else if (type.activatable()) { defaultState = defaultState.setValue(STATE, State.OFF); } registerDefaultState(defaultState); @@ -83,22 +76,14 @@ protected void createBlockStateDefinition(StateDefinition.Builder new TileAlvearySwarmer(pos, state); - case FAN -> new TileAlvearyFan(pos, state); - case HEATER -> new TileAlvearyHeater(pos, state); - case HYGRO -> new TileAlvearyHygroregulator(pos, state); - case STABILISER -> new TileAlvearyStabiliser(pos, state); - case SIEVE -> new TileAlvearySieve(pos, state); - default -> new TileAlvearyPlain(pos, state); - }; + return this.type.tileFeature.tileType().create(pos, state); } public BlockState getNewState(TileAlveary tile) { @@ -106,7 +91,7 @@ public BlockState getNewState(TileAlveary tile) { if (tile instanceof IActivatable activatable) { state = state.setValue(STATE, activatable.isActive() ? State.ON : State.OFF); - } else if (getType() == BlockAlvearyType.PLAIN) { + } else if (getType() == Type.PLAIN) { Level level = tile.getLevel(); BlockPos pos = tile.getBlockPos(); @@ -152,24 +137,34 @@ private static List getBlocksTouching(BlockGetter world, BlockPos blo } @Override - public void neighborChanged(BlockState state, Level worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean p_220069_6_) { - TileUtil.actOnTile(worldIn, pos, TileAlveary.class, tileAlveary -> { + public void neighborChanged(BlockState state, Level level, BlockPos pos, Block blockIn, BlockPos fromPos, boolean movedByPiston) { + TileUtil.actOnTile(level, pos, TileAlveary.class, tileAlveary -> { // We must check that the slabs on top were not removed IAlvearyControllerInternal alveary = tileAlveary.getMultiblockLogic().getController(); alveary.reassemble(); BlockPos referenceCoord = alveary.getReferenceCoord(); - NetworkUtil.sendNetworkPacket(new PacketAlvearyChange(referenceCoord), referenceCoord, worldIn); + if (level instanceof ServerLevel serverLevel) { + NetworkUtil.sendToPlayersTrackingPos(new PacketAlvearyControllerChange(referenceCoord), referenceCoord, serverLevel); + } }); } - // todo this method isn't client only - @OnlyIn(Dist.CLIENT) @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter world, List tooltip, TooltipFlag flag) { + public void appendHoverText(ItemStack stack, Item.TooltipContext level, List tooltip, TooltipFlag flag) { if (Screen.hasShiftDown()) { tooltip.add(Component.translatable("block.forestry.alveary_tooltip")); } else { - ItemTooltipUtil.addShiftInformation(stack, world, tooltip, flag); + ItemTooltipUtil.addShiftInformation(tooltip); } } + + public record Type(String identifier, boolean activatable, FeatureTileType tileFeature) implements IBlockSubtype { + public static final Type PLAIN = new Type("plain", false, ApicultureTiles.ALVEARY_PLAIN); + public static final Type SWARMER = new Type("swarmer", true, ApicultureTiles.ALVEARY_SWARMER); + public static final Type FAN = new Type("fan", true, ApicultureTiles.ALVEARY_FAN); + public static final Type HEATER = new Type("heater", true, ApicultureTiles.ALVEARY_HEATER); + public static final Type HYGRO = new Type("hygro", false, ApicultureTiles.ALVEARY_HYGROREGULATOR); + public static final Type STABILISER = new Type("stabiliser", false, ApicultureTiles.ALVEARY_STABILISER); + public static final Type SIEVE = new Type("sieve", false, ApicultureTiles.ALVEARY_SIEVE); + } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockAlvearyType.java b/src/main/java/forestry/apiculture/blocks/BlockAlvearyType.java deleted file mode 100644 index 4bb41e2299..0000000000 --- a/src/main/java/forestry/apiculture/blocks/BlockAlvearyType.java +++ /dev/null @@ -1,47 +0,0 @@ -package forestry.apiculture.blocks; - -import forestry.api.core.IBlockSubtype; -import forestry.apiculture.features.ApicultureTiles; -import forestry.modules.features.FeatureTileType; - -import java.util.Locale; - -public enum BlockAlvearyType implements IBlockSubtype { - PLAIN(false), - SWARMER(true), - FAN(true), - HEATER(true), - HYGRO(false), - STABILISER(false), - SIEVE(false); - - public static final BlockAlvearyType[] VALUES = values(); - - public final boolean activatable; - - BlockAlvearyType(boolean activatable) { - this.activatable = activatable; - } - - @Override - public String toString() { - return super.toString().toLowerCase(Locale.ENGLISH); - } - - @Override - public String getSerializedName() { - return super.toString().toLowerCase(Locale.ENGLISH); - } - - public FeatureTileType getTileType() { - return switch (this) { - case PLAIN -> ApicultureTiles.ALVEARY_PLAIN; - case SWARMER -> ApicultureTiles.ALVEARY_SWARMER; - case FAN -> ApicultureTiles.ALVEARY_FAN; - case HEATER -> ApicultureTiles.ALVEARY_HEATER; - case HYGRO -> ApicultureTiles.ALVEARY_HYGROREGULATOR; - case STABILISER -> ApicultureTiles.ALVEARY_STABILISER; - case SIEVE -> ApicultureTiles.ALVEARY_SIEVE; - }; - } -} diff --git a/src/main/java/forestry/apiculture/blocks/BlockApiculture.java b/src/main/java/forestry/apiculture/blocks/BlockApiculture.java index 44a436d280..879325d211 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockApiculture.java +++ b/src/main/java/forestry/apiculture/blocks/BlockApiculture.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.blocks; import forestry.core.blocks.BlockBase; diff --git a/src/main/java/forestry/apiculture/blocks/BlockBeeHive.java b/src/main/java/forestry/apiculture/blocks/BlockBeeHive.java index 4983b7eaf1..bd169735e6 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockBeeHive.java +++ b/src/main/java/forestry/apiculture/blocks/BlockBeeHive.java @@ -1,21 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.blocks; import forestry.api.ForestryTags; import forestry.api.IForestryApi; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; import forestry.api.apiculture.hives.IHiveDrop; -import forestry.api.apiculture.hives.IHiveTile; import forestry.apiculture.features.ApicultureTiles; import forestry.apiculture.tiles.TileHive; import forestry.core.tiles.TileUtil; @@ -23,12 +12,12 @@ import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; @@ -72,14 +61,14 @@ public BlockEntityTicker getTicker(Level level, Block @Override public void attack(BlockState state, Level world, BlockPos pos, Player player) { - TileUtil.actOnTile(world, pos, IHiveTile.class, tile -> tile.onAttack(world, pos, player)); + TileUtil.actOnTile(world, pos, TileHive.class, tile -> tile.onAttack(world, pos, player)); } @Override - public void playerWillDestroy(Level world, BlockPos pos, BlockState state, Player player) { - super.playerWillDestroy(world, pos, state, player); + public BlockState playerWillDestroy(Level world, BlockPos pos, BlockState state, Player player) { boolean canHarvest = canHarvestBlock(state, world, pos, player); - TileUtil.actOnTile(world, pos, IHiveTile.class, tile -> tile.onBroken(world, pos, player, canHarvest)); + TileUtil.actOnTile(world, pos, TileHive.class, tile -> tile.onBroken(world, pos, player, canHarvest)); + return super.playerWillDestroy(world, pos, state, player); } @Nullable @@ -99,7 +88,7 @@ public List getDrops(BlockState state, LootParams.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool.is(ForestryTags.Items.SCOOPS)) { - int fortune = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); + int fortune = tool.getEnchantmentLevel(builder.getLevel().holderLookup(Registries.ENCHANTMENT).getOrThrow(Enchantments.FORTUNE)); return getDrops(builder.getLevel(), pos, fortune); } return List.of(); diff --git a/src/main/java/forestry/apiculture/blocks/BlockHiveType.java b/src/main/java/forestry/apiculture/blocks/BlockHiveType.java index 983a16f0f1..f66eeb2464 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockHiveType.java +++ b/src/main/java/forestry/apiculture/blocks/BlockHiveType.java @@ -32,7 +32,7 @@ public ResourceLocation getSpeciesId() { } @Override - public String getSerializedName() { + public String identifier() { return name().toLowerCase(Locale.ENGLISH); } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockHoneyComb.java b/src/main/java/forestry/apiculture/blocks/BlockHoneyComb.java index ad1c8a7e6e..9e4aa7c254 100755 --- a/src/main/java/forestry/apiculture/blocks/BlockHoneyComb.java +++ b/src/main/java/forestry/apiculture/blocks/BlockHoneyComb.java @@ -7,8 +7,8 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; diff --git a/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java b/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java index 4d4a8b0540..c9b77eb31b 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java +++ b/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.blocks; import forestry.apiculture.features.ApicultureTiles; @@ -36,7 +26,7 @@ public IMachineProperties getMachineProperties() { } @Override - public String getSerializedName() { - return getMachineProperties().getSerializedName(); + public String identifier() { + return getMachineProperties().identifier(); } } diff --git a/src/main/java/forestry/apiculture/blocks/NaturalistChestBlockType.java b/src/main/java/forestry/apiculture/blocks/NaturalistChestBlockType.java index b90447afc5..44440bbb85 100644 --- a/src/main/java/forestry/apiculture/blocks/NaturalistChestBlockType.java +++ b/src/main/java/forestry/apiculture/blocks/NaturalistChestBlockType.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.blocks; import forestry.core.blocks.IBlockType; @@ -37,7 +27,7 @@ public IMachineProperties getMachineProperties() { } @Override - public String getSerializedName() { - return getMachineProperties().getSerializedName(); + public String identifier() { + return getMachineProperties().identifier(); } } diff --git a/src/main/java/forestry/apiculture/blocks/package-info.java b/src/main/java/forestry/apiculture/blocks/package-info.java index 338722e0ed..84024eebc4 100644 --- a/src/main/java/forestry/apiculture/blocks/package-info.java +++ b/src/main/java/forestry/apiculture/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.blocks; diff --git a/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java b/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java index 4e2f3c6e20..de5913c221 100644 --- a/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java +++ b/src/main/java/forestry/apiculture/commands/BeeStatsSaveHelper.java @@ -1,23 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.commands; import com.mojang.authlib.GameProfile; import forestry.api.apiculture.IApiaristTracker; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IBreedingTracker; import forestry.core.commands.IStatsSaveHelper; import forestry.core.utils.SpeciesUtil; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import java.util.Collection; @@ -58,7 +49,7 @@ public String getFileSuffix() { @Override public IBreedingTracker getBreedingTracker(Level level, GameProfile gameProfile) { - return SpeciesUtil.BEE_TYPE.get().getBreedingTracker(level, gameProfile); + return SpeciesUtil.BEE_TYPE.get().getBreedingTracker(level, new ResolvableProfile(gameProfile)); } } diff --git a/src/main/java/forestry/apiculture/commands/CommandBee.java b/src/main/java/forestry/apiculture/commands/CommandBee.java index 9b3ab3dc69..8e881f3cdd 100644 --- a/src/main/java/forestry/apiculture/commands/CommandBee.java +++ b/src/main/java/forestry/apiculture/commands/CommandBee.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.commands; import com.mojang.brigadier.builder.ArgumentBuilder; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.core.commands.CommandSaveStats; import forestry.core.commands.GiveSpeciesCommand; import forestry.core.commands.IStatsSaveHelper; diff --git a/src/main/java/forestry/apiculture/commands/package-info.java b/src/main/java/forestry/apiculture/commands/package-info.java index 7c25e0c704..196a5465cf 100644 --- a/src/main/java/forestry/apiculture/commands/package-info.java +++ b/src/main/java/forestry/apiculture/commands/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.commands; diff --git a/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java b/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java index c882e62604..4f408e4e4a 100644 --- a/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java +++ b/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java @@ -8,8 +8,7 @@ import forestry.api.genetics.alleles.BeeChromosomes; import forestry.api.modules.ForestryModuleIds; import forestry.apiculture.features.ApicultureItems; -import forestry.apiculture.items.ItemCreativeHiveFrame; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.core.utils.SpeciesUtil; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; @@ -58,9 +57,7 @@ public void registerCategories(IRecipeCategoryRegistration registration) { @Override public void registerItemSubtypes(ISubtypeRegistration registry) { - JeiUtil.registerItemSubtypes(registry, BeeChromosomes.SPECIES, SpeciesUtil.BEE_TYPE.get()); - // show both creative frames in JEI - registry.registerSubtypeInterpreter(ApicultureItems.FRAME_CREATIVE.item(), (stack, context) -> String.valueOf(ItemCreativeHiveFrame.hasForceMutations(stack))); + JeiUtil.registerItemSubtypes(registry, SpeciesUtil.BEE_TYPE.get()); } @Override diff --git a/src/main/java/forestry/apiculture/compat/MutationsRecipeCategory.java b/src/main/java/forestry/apiculture/compat/MutationsRecipeCategory.java index 4f539b86ff..5129b8363e 100644 --- a/src/main/java/forestry/apiculture/compat/MutationsRecipeCategory.java +++ b/src/main/java/forestry/apiculture/compat/MutationsRecipeCategory.java @@ -2,7 +2,7 @@ import forestry.api.genetics.*; import forestry.api.genetics.capability.IIndividualHandlerItem; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.core.utils.ModUtil; import mezz.jei.api.gui.builder.IIngredientAcceptor; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; diff --git a/src/main/java/forestry/apiculture/compat/ProductsRecipeCategory.java b/src/main/java/forestry/apiculture/compat/ProductsRecipeCategory.java index 69ded2b6f6..536aee2f3d 100644 --- a/src/main/java/forestry/apiculture/compat/ProductsRecipeCategory.java +++ b/src/main/java/forestry/apiculture/compat/ProductsRecipeCategory.java @@ -2,7 +2,7 @@ import forestry.api.genetics.ISpecies; import forestry.api.genetics.ISpeciesType; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.core.utils.ModUtil; import it.unimi.dsi.fastutil.objects.Object2FloatOpenCustomHashMap; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; diff --git a/src/main/java/forestry/apiculture/compat/package-info.java b/src/main/java/forestry/apiculture/compat/package-info.java index 167bc395e3..64cd378f8d 100644 --- a/src/main/java/forestry/apiculture/compat/package-info.java +++ b/src/main/java/forestry/apiculture/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.compat; diff --git a/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java b/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java index c7eb5d5426..ee2aa07d86 100755 --- a/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java +++ b/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.entities; import net.minecraft.world.entity.PathfinderMob; diff --git a/src/main/java/forestry/apiculture/entities/package-info.java b/src/main/java/forestry/apiculture/entities/package-info.java index ef5eab9624..da112f31d3 100644 --- a/src/main/java/forestry/apiculture/entities/package-info.java +++ b/src/main/java/forestry/apiculture/entities/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.entities; diff --git a/src/main/java/forestry/apiculture/features/ApicultureArmorMaterials.java b/src/main/java/forestry/apiculture/features/ApicultureArmorMaterials.java new file mode 100644 index 0000000000..9176cde394 --- /dev/null +++ b/src/main/java/forestry/apiculture/features/ApicultureArmorMaterials.java @@ -0,0 +1,37 @@ +package forestry.apiculture.features; + +import forestry.api.modules.ForestryModuleIds; +import forestry.core.features.CoreItems; +import forestry.core.items.definitions.EnumCraftingMaterial; +import forestry.modules.features.FeatureProvider; +import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.world.item.ArmorItem; +import net.minecraft.world.item.ArmorMaterial; +import net.minecraft.world.item.crafting.Ingredient; +import net.neoforged.neoforge.registries.DeferredRegister; + +import java.util.Map; + +@FeatureProvider +public class ApicultureArmorMaterials { + public static final DeferredRegister REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.APICULTURE).getRegistry(Registries.ARMOR_MATERIAL); + + public static final Holder APIARIST = REGISTRY.register("apiarist", () -> new ArmorMaterial( + Map.of( + ArmorItem.Type.HELMET, 1, + ArmorItem.Type.CHESTPLATE, 3, + ArmorItem.Type.LEGGINGS, 2, + ArmorItem.Type.BOOTS, 1 + // todo doggy armor + ), + 15, + SoundEvents.ARMOR_EQUIP_LEATHER, + () -> Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK).get()), + IDK, + 0.0f, + 0.0f + )); +} diff --git a/src/main/java/forestry/apiculture/features/ApicultureBlocks.java b/src/main/java/forestry/apiculture/features/ApicultureBlocks.java index 037c7dbf9d..a084a2cbda 100644 --- a/src/main/java/forestry/apiculture/features/ApicultureBlocks.java +++ b/src/main/java/forestry/apiculture/features/ApicultureBlocks.java @@ -11,6 +11,8 @@ import forestry.modules.features.ModFeatureRegistry; import net.minecraft.world.item.Item; +import java.util.List; + @FeatureProvider public class ApicultureBlocks { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.APICULTURE); @@ -19,6 +21,14 @@ public class ApicultureBlocks { public static final FeatureBlockGroup BEEHIVE = REGISTRY.blockGroup(BlockBeeHive::new, BlockHiveType.values()).itemWithType((block, type) -> new ItemBlockForestry<>(block, new Item.Properties())).identifier("beehive").create(); - public static final FeatureBlockGroup BEE_COMB = REGISTRY.blockGroup(BlockHoneyComb::new, EnumHoneyComb.VALUES).item(ItemBlockHoneyComb::new).identifier("block_bee_comb").create(); - public static final FeatureBlockGroup ALVEARY = REGISTRY.blockGroup(BlockAlveary::new, BlockAlvearyType.VALUES).item(blockAlveary -> new ItemBlockForestry<>(blockAlveary, new Item.Properties())).identifier("alveary").create(); + public static final FeatureBlockGroup BEE_COMB = REGISTRY.blockGroup(BlockHoneyComb::new, EnumHoneyComb.values()).item(ItemBlockHoneyComb::new).identifier("block_bee_comb").create(); + public static final FeatureBlockGroup ALVEARY = REGISTRY.blockGroup(BlockAlveary::new, List.of( + BlockAlveary.Type.PLAIN, + BlockAlveary.Type.SWARMER, + BlockAlveary.Type.FAN, + BlockAlveary.Type.HEATER, + BlockAlveary.Type.HYGRO, + BlockAlveary.Type.STABILISER, + BlockAlveary.Type.SIEVE + )).item(blockAlveary -> new ItemBlockForestry<>(blockAlveary, new Item.Properties())).identifier("alveary").create(); } diff --git a/src/main/java/forestry/apiculture/features/ApicultureEffects.java b/src/main/java/forestry/apiculture/features/ApicultureEffects.java index 6328c2e00e..d9cf17cfcf 100644 --- a/src/main/java/forestry/apiculture/features/ApicultureEffects.java +++ b/src/main/java/forestry/apiculture/features/ApicultureEffects.java @@ -1,16 +1,17 @@ package forestry.apiculture.features; +import forestry.api.ForestryConstants; import forestry.api.modules.ForestryModuleIds; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class ApicultureEffects { @@ -18,11 +19,11 @@ public class ApicultureEffects { private static final DeferredRegister MOB_EFFECTS = REGISTRY.getRegistry(Registries.MOB_EFFECT); - public static final RegistryObject HAKUNA_MATATA = MOB_EFFECTS.register("hakuna_matata", () -> { + public static final Holder HAKUNA_MATATA = MOB_EFFECTS.register("hakuna_matata", () -> { return new ForestryMobEffect(MobEffectCategory.BENEFICIAL, 0x069af3) - .addAttributeModifier(Attributes.FOLLOW_RANGE, "07FB7192-49C7-4f77-BE0B-D182BD391AFD", 0, AttributeModifier.Operation.MULTIPLY_TOTAL); + .addAttributeModifier(Attributes.FOLLOW_RANGE, ForestryConstants.forestry("effect.hakuna_matata"), 0, AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL); }); - public static final RegistryObject MATATA = MOB_EFFECTS.register("matata", () -> { + public static final Holder MATATA = MOB_EFFECTS.register("matata", () -> { return new ForestryMobEffect(MobEffectCategory.NEUTRAL, 0x380835); }); @@ -33,7 +34,7 @@ protected ForestryMobEffect(MobEffectCategory category, int color) { // we have no ongoing effects @Override - public boolean isDurationEffectTick(int duration, int amplifier) { + public boolean shouldApplyEffectTickThisTick(int duration, int amplifier) { return false; } } diff --git a/src/main/java/forestry/apiculture/features/ApicultureFeatures.java b/src/main/java/forestry/apiculture/features/ApicultureFeatures.java index e106f4d1e5..6b16e37f47 100644 --- a/src/main/java/forestry/apiculture/features/ApicultureFeatures.java +++ b/src/main/java/forestry/apiculture/features/ApicultureFeatures.java @@ -11,10 +11,11 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElementType; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class ApicultureFeatures { @@ -23,8 +24,8 @@ public class ApicultureFeatures { public static final DeferredRegister> FEATURES = REGISTRY.getRegistry(Registries.FEATURE); public static final DeferredRegister> POOL_ELEMENT_TYPES = REGISTRY.getRegistry(Registries.STRUCTURE_POOL_ELEMENT); - public static final RegistryObject HIVE = FEATURES.register("hive", HiveDecorator::new); - public static final RegistryObject> APIARIST_POOL_ELEMENT_TYPE = POOL_ELEMENT_TYPES.register("apiarist", () -> () -> ApiaristPoolElement.CODEC); + public static final DeferredHolder, Feature> HIVE = FEATURES.register("hive", HiveDecorator::new); + public static final DeferredHolder, StructurePoolElementType> APIARIST_POOL_ELEMENT_TYPE = POOL_ELEMENT_TYPES.register("apiarist", () -> () -> ApiaristPoolElement.CODEC); public static final ResourceKey> CONFIGURED_HIVE = ResourceKey.create(Registries.CONFIGURED_FEATURE, ForestryConstants.forestry("hive")); public static final ResourceKey PLACED_HIVE = ResourceKey.create(Registries.PLACED_FEATURE, ForestryConstants.forestry("hive")); diff --git a/src/main/java/forestry/apiculture/features/ApicultureItems.java b/src/main/java/forestry/apiculture/features/ApicultureItems.java index fa4c27f32a..3cd26ee078 100644 --- a/src/main/java/forestry/apiculture/features/ApicultureItems.java +++ b/src/main/java/forestry/apiculture/features/ApicultureItems.java @@ -1,16 +1,17 @@ package forestry.apiculture.features; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.modules.ForestryModuleIds; import forestry.apiculture.items.*; import forestry.core.items.ItemForestryFood; +import forestry.core.items.ItemOverlay; import forestry.modules.features.*; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.Item; @FeatureProvider public class ApicultureItems { - // / BEES + // BEES public static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.APICULTURE); public static final FeatureItem BEE_QUEEN = REGISTRY.item(() -> new ItemBeeGE(BeeLifeStage.QUEEN), "bee_queen_ge"); @@ -18,29 +19,28 @@ public class ApicultureItems { public static final FeatureItem BEE_PRINCESS = REGISTRY.item(() -> new ItemBeeGE(BeeLifeStage.PRINCESS), "bee_princess_ge"); public static final FeatureItem BEE_LARVAE = REGISTRY.item(() -> new ItemBeeGE(BeeLifeStage.LARVAE), "bee_larvae_ge"); - // / COMB FRAMES + // COMB FRAMES public static final FeatureItem FRAME_UNTREATED = REGISTRY.item(() -> new ItemHiveFrame(80, 0.9f), "frame_untreated"); public static final FeatureItem FRAME_IMPREGNATED = REGISTRY.item(() -> new ItemHiveFrame(240, 0.4f), "frame_impregnated"); public static final FeatureItem FRAME_PROVEN = REGISTRY.item(() -> new ItemHiveFrame(720, 0.3f), "frame_proven"); - public static final FeatureItem FRAME_CREATIVE = REGISTRY.item(ItemCreativeHiveFrame::new, "frame_creative"); + public static final FeatureItemGroup FRAME_CREATIVE = REGISTRY.itemGroup(ItemCreativeHiveFrame::new, ItemCreativeHiveFrame.Variant.values()).create(); // BEE RESOURCES public static final FeatureItem HONEY_DROP = REGISTRY.item("honey_drop"); public static final FeatureItem HONEYDEW = REGISTRY.item("honeydew"); public static final FeatureItem EXPERIENCE_DROP = REGISTRY.item("experience_drop"); - public static final FeatureItemGroup PROPOLIS = REGISTRY.itemGroup(ItemPropolis::new, "propolis", EnumPropolis.values()); + public static final FeatureItemGroup PROPOLIS = REGISTRY.itemGroup(ItemOverlay::new, "propolis", EnumPropolis.values()); public static final FeatureItem ROYAL_JELLY = REGISTRY.item("royal_jelly"); - public static final FeatureItemGroup POLLEN_CLUSTER = REGISTRY.itemGroup(ItemPollenCluster::new, "pollen_cluster", EnumPollenCluster.values()); - public static final FeatureItemGroup BEE_COMBS = REGISTRY.itemGroup(ItemHoneyComb::new, "bee_comb", EnumHoneyComb.VALUES); + public static final FeatureItemGroup POLLEN_CLUSTER = REGISTRY.itemGroup(ItemOverlay::new, "pollen_cluster", EnumPollenCluster.values()); + public static final FeatureItemGroup BEE_COMBS = REGISTRY.itemGroup(ItemHoneyComb::new, "bee_comb", EnumHoneyComb.values()); - // / BEE FOOD PRODUCTS + // BEE FOOD PRODUCTS public static final FeatureItem HONEYED_SLICE = REGISTRY.item(() -> new ItemForestryFood(8, 0.6f), "honeyed_slice"); public static final FeatureItem AMBROSIA = REGISTRY.item(() -> new ItemAmbrosia().setIsDrink(), "ambrosia"); - public static final FeatureItem HONEY_POT = REGISTRY.item(() -> new ItemForestryFood(2, 0.2f).setIsDrink(), "honey_pot"); - // / APIARIST'S CLOTHES + // APIARIST'S CLOTHES public static final FeatureItem APIARIST_HELMET = REGISTRY.item(() -> new ItemArmorApiarist(ArmorItem.Type.HELMET), "apiarist_helmet"); public static final FeatureItem APIARIST_CHEST = REGISTRY.item(() -> new ItemArmorApiarist(ArmorItem.Type.CHESTPLATE), "apiarist_chest"); public static final FeatureItem APIARIST_LEGS = REGISTRY.item(() -> new ItemArmorApiarist(ArmorItem.Type.LEGGINGS), "apiarist_legs"); diff --git a/src/main/java/forestry/apiculture/features/ApicultureMenuTypes.java b/src/main/java/forestry/apiculture/features/ApicultureMenuTypes.java index 544b55aae2..c6411024e8 100644 --- a/src/main/java/forestry/apiculture/features/ApicultureMenuTypes.java +++ b/src/main/java/forestry/apiculture/features/ApicultureMenuTypes.java @@ -11,9 +11,9 @@ public class ApicultureMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.APICULTURE); - public static final FeatureMenuType ALVEARY = REGISTRY.menuType(ContainerAlveary::fromNetwork, "alveary"); - public static final FeatureMenuType ALVEARY_HYGROREGULATOR = REGISTRY.menuType(ContainerAlvearyHygroregulator::fromNetwork, "alveary_hygroregulator"); - public static final FeatureMenuType ALVEARY_SIEVE = REGISTRY.menuType(ContainerAlvearySieve::fromNetwork, "alveary_sieve"); - public static final FeatureMenuType ALVEARY_SWARMER = REGISTRY.menuType(ContainerAlvearySwarmer::fromNetwork, "alveary_swarmer"); - public static final FeatureMenuType BEE_HOUSING = REGISTRY.menuType(ContainerBeeHousing::fromNetwork, "bee_housing"); + public static final FeatureMenuType ALVEARY = REGISTRY.menuType(AlvearyMenu::fromNetwork, "alveary"); + public static final FeatureMenuType ALVEARY_HYGROREGULATOR = REGISTRY.menuType(AlvearyHygroregulatorMenu::fromNetwork, "alveary_hygroregulator"); + public static final FeatureMenuType ALVEARY_SIEVE = REGISTRY.menuType(AlvearySieveMenu::fromNetwork, "alveary_sieve"); + public static final FeatureMenuType ALVEARY_SWARMER = REGISTRY.menuType(AlvearySwarmerMenu::fromNetwork, "alveary_swarmer"); + public static final FeatureMenuType BEE_HOUSING = REGISTRY.menuType(BeeHousingMenu::fromNetwork, "bee_housing"); } diff --git a/src/main/java/forestry/apiculture/features/ApicultureTiles.java b/src/main/java/forestry/apiculture/features/ApicultureTiles.java index aa8921aa30..e7f8fe7c5d 100644 --- a/src/main/java/forestry/apiculture/features/ApicultureTiles.java +++ b/src/main/java/forestry/apiculture/features/ApicultureTiles.java @@ -1,7 +1,7 @@ package forestry.apiculture.features; import forestry.api.modules.ForestryModuleIds; -import forestry.apiculture.blocks.BlockAlvearyType; +import forestry.apiculture.blocks.BlockAlveary; import forestry.apiculture.blocks.BlockTypeApiculture; import forestry.apiculture.multiblock.*; import forestry.apiculture.tiles.TileApiary; @@ -20,12 +20,12 @@ public class ApicultureTiles { public static final FeatureTileType HIVE = REGISTRY.tile(TileHive::new, "hive", () -> ApicultureBlocks.BEEHIVE.getBlocks()); public static final FeatureTileType APIARY = REGISTRY.tile(TileApiary::new, "apiary", () -> ApicultureBlocks.BASE.get(BlockTypeApiculture.APIARY).collect()); public static final FeatureTileType BEE_HOUSE = REGISTRY.tile(TileBeeHouse::new, "bee_house", () -> ApicultureBlocks.BASE.get(BlockTypeApiculture.BEE_HOUSE).collect()); - public static final FeatureTileType ALVEARY_PLAIN = REGISTRY.tile(TileAlvearyPlain::new, "alveary", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.PLAIN).collect()); - public static final FeatureTileType ALVEARY_SIEVE = REGISTRY.tile(TileAlvearySieve::new, "alveary_sieve", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.SIEVE).collect()); - public static final FeatureTileType ALVEARY_SWARMER = REGISTRY.tile(TileAlvearySwarmer::new, "alveary_swarmer", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.SWARMER).collect()); - public static final FeatureTileType ALVEARY_HYGROREGULATOR = REGISTRY.tile(TileAlvearyHygroregulator::new, "alveary_hygroregulator", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.HYGRO).collect()); - public static final FeatureTileType ALVEARY_STABILISER = REGISTRY.tile(TileAlvearyStabiliser::new, "alveary_stabiliser", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.STABILISER).collect()); - public static final FeatureTileType ALVEARY_FAN = REGISTRY.tile(TileAlvearyFan::new, "alveary_fan", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.FAN).collect()); - public static final FeatureTileType ALVEARY_HEATER = REGISTRY.tile(TileAlvearyHeater::new, "alveary_heater", () -> ApicultureBlocks.ALVEARY.get(BlockAlvearyType.HEATER).collect()); + public static final FeatureTileType ALVEARY_PLAIN = REGISTRY.tile(TileAlvearyPlain::new, "alveary", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.PLAIN).collect()); + public static final FeatureTileType ALVEARY_SIEVE = REGISTRY.tile(TileAlvearySieve::new, "alveary_sieve", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.SIEVE).collect()); + public static final FeatureTileType ALVEARY_SWARMER = REGISTRY.tile(TileAlvearySwarmer::new, "alveary_swarmer", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.SWARMER).collect()); + public static final FeatureTileType ALVEARY_HYGROREGULATOR = REGISTRY.tile(TileAlvearyHygroregulator::new, "alveary_hygroregulator", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.HYGRO).collect()); + public static final FeatureTileType ALVEARY_STABILISER = REGISTRY.tile(TileAlvearyStabiliser::new, "alveary_stabiliser", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.STABILISER).collect()); + public static final FeatureTileType ALVEARY_FAN = REGISTRY.tile(TileAlvearyFan::new, "alveary_fan", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.FAN).collect()); + public static final FeatureTileType ALVEARY_HEATER = REGISTRY.tile(TileAlvearyHeater::new, "alveary_heater", () -> ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.HEATER).collect()); } diff --git a/src/main/java/forestry/apiculture/features/package-info.java b/src/main/java/forestry/apiculture/features/package-info.java index 7bd463fdcd..4e76571662 100644 --- a/src/main/java/forestry/apiculture/features/package-info.java +++ b/src/main/java/forestry/apiculture/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.features; diff --git a/src/main/java/forestry/apiculture/genetics/AlyzerManager.java b/src/main/java/forestry/apiculture/genetics/AlyzerManager.java deleted file mode 100644 index 4daeace9cf..0000000000 --- a/src/main/java/forestry/apiculture/genetics/AlyzerManager.java +++ /dev/null @@ -1,5 +0,0 @@ -package forestry.apiculture.genetics; - -public class AlyzerManager { - -} diff --git a/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java b/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java index 9a09478b62..ead35a8a02 100755 --- a/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java +++ b/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java @@ -1,23 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; import forestry.api.IForestryApi; import forestry.api.apiculture.IApiaristTracker; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.genetics.IMutationManager; import forestry.api.genetics.ISpecies; import forestry.core.genetics.BreedingTracker; import forestry.core.utils.SpeciesUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public class ApiaristTracker extends BreedingTracker implements IApiaristTracker { @@ -44,8 +35,8 @@ protected void writeUpdateData(CompoundTag nbt) { } @Override - public void readFromNbt(CompoundTag nbt) { - super.readFromNbt(nbt); + public void readFromNbt(CompoundTag nbt, HolderLookup.Provider registries) { + super.readFromNbt(nbt, registries); this.queensTotal = nbt.getInt("QueensTotal"); this.princessesTotal = nbt.getInt("PrincessesTotal"); diff --git a/src/main/java/forestry/apiculture/genetics/Bee.java b/src/main/java/forestry/apiculture/genetics/Bee.java index 8c6404a100..14f0ae1b49 100755 --- a/src/main/java/forestry/apiculture/genetics/Bee.java +++ b/src/main/java/forestry/apiculture/genetics/Bee.java @@ -1,24 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; import com.google.common.collect.ImmutableList; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.IForestryApi; import forestry.api.apiculture.*; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeEffect; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.*; import forestry.api.climate.IClimateManager; import forestry.api.core.*; import forestry.api.genetics.ClimateHelper; @@ -40,7 +28,6 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; import net.minecraft.core.Vec3i; import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; @@ -52,7 +39,7 @@ import java.util.*; public class Bee extends IndividualLiving implements IBee { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> { Codec genomeCodec = SpeciesUtil.BEE_TYPE.get().getKaryotype().getGenomeCodec(); return IndividualLiving.livingFields(instance, genomeCodec).and(instance.group( @@ -150,7 +137,7 @@ private IEffectData doFX(IBeeEffect effect, IEffectData storedData, IBeeHousing @Override public Set getCanWork(IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); Set errorStates = new HashSet<>(); IBeeModifier beeModifier = IForestryApi.INSTANCE.getHiveManager().createBeeHousingModifier(housing); @@ -165,7 +152,7 @@ public Set getCanWork(IBeeHousing housing) { if (!beeModifier.isAlwaysActive(this.genome)) { long gameTime = level.getGameTime(); long dayTime = IActivityType.getBeeDayTime(level); - BlockPos pos = housing.getCoordinates(); + BlockPos pos = housing.getBlockPos(); if (!type.isActive(gameTime, dayTime, pos)) { errorStates.add(type.getInactiveError(gameTime, dayTime, pos)); @@ -244,21 +231,6 @@ private boolean isSuitableClimate(TemperatureType temperature, HumidityType humi ); } - // todo this can be optimized in a cache somewhere - @Override - public List> getSuitableBiomes(Registry registry) { - return registry.holders().filter(this::isSuitableBiome).toList(); - } -/* - @Override - public void age(Level world, float housingLifespanModifier) { - IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); - IBeeModifier beeModifier = mode.getBeeModifier(); - float finalModifier = housingLifespanModifier * beeModifier.modifyAging(genome, mate, housingLifespanModifier); - - super.age(world, finalModifier); - }*/ - // / PRODUCTION @Override public List getProduceList() { @@ -306,7 +278,7 @@ public List getSpecialtyList() { @Override public List produceStacks(IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); //IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); ArrayList stacks = new ArrayList<>(); @@ -343,7 +315,7 @@ public List produceStacks(IBeeHousing housing) { } } - BlockPos housingCoordinates = housing.getCoordinates(); + BlockPos housingCoordinates = housing.getBlockPos(); return this.genome.getActiveValue(BeeChromosomes.FLOWER_TYPE).affectProducts(level, housingCoordinates, this, stacks); } @@ -363,7 +335,7 @@ public IBee spawnPrincess(IBeeHousing housing) { // Fatigued (dead ignoble) queens do not produce princesses. if (!this.pristine) { IBeeModifier beeModifier = IForestryApi.INSTANCE.getHiveManager().createBeeHousingModifier(housing); - RandomSource rand = housing.getWorldObj().random; + RandomSource rand = housing.getLevel().random; if (checkIgnobleDecay(rand, this.generation, beeModifier.modifyGeneticDecay(this.genome, 1f))) { return null; @@ -389,8 +361,8 @@ public List spawnDrones(IBeeHousing housing) { } List bees = new ArrayList<>(); - //Level level = housing.getWorldObj(); - //BlockPos housingPos = housing.getCoordinates(); + //Level level = housing.getLevel(); + //BlockPos housingPos = housing.getBlockPos(); int toCreate = this.genome.getActiveValue(BeeChromosomes.FERTILITY);//BeeManager.beeRoot.getBeekeepingMode(level).getFinalFertility(this, level, housingPos); @@ -412,7 +384,7 @@ private IBee createOffspring(IBeeHousing housing, IGenome mate, int generation) // drones are always generation 0 boolean haploid = generation == 0 && ForestryConfig.SERVER.useHaploidDrones.get(); - return SpeciesUtil.createOffspring(housing.getWorldObj().random, this.genome, mate, mutator, genome -> { + return SpeciesUtil.createOffspring(housing.getLevel().random, this.genome, mate, mutator, genome -> { //IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(level); int maxHealth = genome.getActiveValue(BeeChromosomes.LIFESPAN); return new Bee(genome, Optional.empty(), false, maxHealth, maxHealth, this.pristine, generation); /*mode.isOffspringPristine(this)*/ @@ -422,14 +394,14 @@ private IBee createOffspring(IBeeHousing housing, IGenome mate, int generation) @Nullable @SuppressWarnings("CodeBlock2Expr") private static ImmutableList> mutateSpecies(IBeeHousing housing, IGenome parent1, IGenome parent2) { - return SpeciesUtil.mutateSpecies(housing.getWorldObj(), housing.getCoordinates(), housing.getOwner(), parent1, parent2, BeeChromosomes.SPECIES, (mutation, level, pos, firstGenome, secondGenome, climate) -> { + return SpeciesUtil.mutateSpecies(housing.getLevel(), housing.getBlockPos(), housing.getOwner(), parent1, parent2, BeeChromosomes.SPECIES, (mutation, level, pos, firstGenome, secondGenome, climate) -> { return getChance(mutation, housing, firstGenome, secondGenome); }); } private static float getChance(IMutation mutation, IBeeHousing housing, IGenome genome0, IGenome genome1) { - Level level = housing.getWorldObj(); - BlockPos housingPos = housing.getCoordinates(); + Level level = housing.getLevel(); + BlockPos housingPos = housing.getBlockPos(); float currentChance = Mutation.getChance(mutation, level, housingPos, genome0, genome1, housing); if (currentChance <= 0) { @@ -453,7 +425,7 @@ public IPollen retrievePollen(IBeeHousing housing) { int chance = getAdjustedPollination(this.genome, beeModifier); - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); RandomSource random = level.random; if (random.nextInt(100) >= chance) { @@ -462,7 +434,7 @@ public IPollen retrievePollen(IBeeHousing housing) { Vec3i area = getAdjustedTerritory(this.genome, beeModifier); Vec3i offset = new Vec3i(-area.getX() / 2, -area.getY() / 4, -area.getZ() / 2); - BlockPos housingPos = housing.getCoordinates(); + BlockPos housingPos = housing.getBlockPos(); IPollenManager pollens = IForestryApi.INSTANCE.getPollenManager(); for (int i = 0; i < 20; i++) { @@ -486,7 +458,7 @@ public boolean pollinateRandom(IBeeHousing housing, IPollen pollen) { int chance = getAdjustedPollination(this.genome, beeModifier); - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); RandomSource random = level.random; // Correct speed @@ -496,7 +468,7 @@ public boolean pollinateRandom(IBeeHousing housing, IPollen pollen) { Vec3i area = getAdjustedTerritory(this.genome, beeModifier); Vec3i offset = new Vec3i(-area.getX() / 2, -area.getY() / 4, -area.getZ() / 2); - BlockPos housingPos = housing.getCoordinates(); + BlockPos housingPos = housing.getBlockPos(); IPollenType type = pollen.getType(); for (int i = 0; i < 30; i++) { @@ -519,7 +491,7 @@ public BlockPos plantFlowerRandom(IBeeHousing housing, List potentia int chance = getAdjustedPollination(this.genome, beeModifier); - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); RandomSource random = level.random; // Correct speed @@ -530,7 +502,7 @@ public BlockPos plantFlowerRandom(IBeeHousing housing, List potentia IFlowerType flowerType = this.genome.getActiveValue(BeeChromosomes.FLOWER_TYPE); Vec3i area = getAdjustedTerritory(this.genome, beeModifier); Vec3i offset = new Vec3i(-area.getX() / 2, -area.getY() / 4, -area.getZ() / 2); - BlockPos housingPos = housing.getCoordinates(); + BlockPos housingPos = housing.getBlockPos(); for (int i = 0; i < 10; i++) { BlockPos randomPos = VecUtil.getRandomPositionInArea(random, area); @@ -547,10 +519,10 @@ public BlockPos plantFlowerRandom(IBeeHousing housing, List potentia public Iterator getAreaIterator(IBeeHousing housing) { IBeeModifier beeModifier = IForestryApi.INSTANCE.getHiveManager().createBeeHousingModifier(housing); Vec3i area = getAdjustedTerritory(this.genome, beeModifier); - BlockPos housingPos = housing.getCoordinates(); + BlockPos housingPos = housing.getBlockPos(); BlockPos minPos = housingPos.offset(-area.getX() / 2, -area.getY() / 2, -area.getZ() / 2); BlockPos maxPos = minPos.offset(area); - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); return VecUtil.getAllInBoxFromCenterMutable(level, minPos, housingPos, maxPos); } diff --git a/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java b/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java index a05ca88fa6..354f771ffe 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java +++ b/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java @@ -1,8 +1,8 @@ package forestry.apiculture.genetics; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.core.ToleranceType; import forestry.api.genetics.ClimateHelper; import forestry.api.genetics.IAlyzerPlugin; @@ -13,7 +13,7 @@ import forestry.api.genetics.alleles.IValueAllele; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.core.config.ForestryConfig; -import forestry.core.gui.GuiAlyzer; +import forestry.core.gui.PortableAnalyzerScreen; import forestry.core.gui.GuiForestry; import forestry.core.gui.TextLayoutHelper; import forestry.core.gui.widgets.ItemStackWidget; @@ -37,15 +37,15 @@ public enum BeeAlyzerPlugin implements IAlyzerPlugin { @Override public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, (individual, stage) -> { if (individual instanceof IBee bee) { if (ForestryConfig.SERVER.useHaploidDrones.get() && stage == BeeLifeStage.DRONE) { TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); textLayout.newLine(); textLayout.newLine(); @@ -62,9 +62,9 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack guiAlyzer.drawHaploidChromosomeRow(graphics, bee, BeeChromosomes.FLOWER_TYPE); textLayout.newLine(); - textLayout.drawLine(graphics, BeeChromosomes.FERTILITY.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, BeeChromosomes.FERTILITY.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); IIntegerAllele primaryFertility = bee.getGenome().getActiveAllele(BeeChromosomes.FERTILITY); - guiAlyzer.drawFertilityInfo(graphics, primaryFertility.value(), GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(primaryFertility.dominant()), 0); + guiAlyzer.drawFertilityInfo(graphics, primaryFertility.value(), PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(primaryFertility.dominant()), 0); textLayout.newLine(); guiAlyzer.drawHaploidChromosomeRow(graphics, bee, BeeChromosomes.TERRITORY); @@ -77,10 +77,10 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack } else { TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); - textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); textLayout.newLine(); @@ -97,11 +97,11 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack guiAlyzer.drawChromosomeRow(graphics, bee, BeeChromosomes.FLOWER_TYPE); textLayout.newLine(); - textLayout.drawLine(graphics, BeeChromosomes.FERTILITY.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, BeeChromosomes.FERTILITY.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); IIntegerAllele primaryFertility = bee.getGenome().getActiveAllele(BeeChromosomes.FERTILITY); IIntegerAllele secondaryFertility = bee.getGenome().getInactiveAllele(BeeChromosomes.FERTILITY); - guiAlyzer.drawFertilityInfo(graphics, primaryFertility.value(), GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(primaryFertility.dominant()), 0); - guiAlyzer.drawFertilityInfo(graphics, secondaryFertility.value(), GuiAlyzer.COLUMN_2, GuiAlyzer.getColorCoding(secondaryFertility.dominant()), 0); + guiAlyzer.drawFertilityInfo(graphics, primaryFertility.value(), PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(primaryFertility.dominant()), 0); + guiAlyzer.drawFertilityInfo(graphics, secondaryFertility.value(), PortableAnalyzerScreen.COLUMN_2, PortableAnalyzerScreen.getColorCoding(secondaryFertility.dominant()), 0); textLayout.newLine(); guiAlyzer.drawChromosomeRow(graphics, bee, BeeChromosomes.TERRITORY); @@ -119,7 +119,7 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack @Override public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, (individual, type) -> { if (individual instanceof IBee bee) { if (ForestryConfig.SERVER.useHaploidDrones.get() && type == BeeLifeStage.DRONE) { @@ -128,31 +128,31 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); textLayout.newLine(); textLayout.drawRow(graphics, Component.translatable("for.gui.climate"), ClimateHelper.toDisplay(primaryAllele.getTemperature()), - ColourProperties.INSTANCE.get("gui.screen"), GuiAlyzer.getColorCoding(genome.getActiveAllele(BeeChromosomes.SPECIES).dominant())); + ColourProperties.INSTANCE.get("gui.screen"), PortableAnalyzerScreen.getColorCoding(genome.getActiveAllele(BeeChromosomes.SPECIES).dominant())); textLayout.newLine(); IValueAllele tempToleranceActive = genome.getActiveAllele(BeeChromosomes.TEMPERATURE_TOLERANCE); - textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), GuiAlyzer.COLUMN_0); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceActive, GuiAlyzer.COLUMN_1); + textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceActive, PortableAnalyzerScreen.COLUMN_1); textLayout.newLine(16); textLayout.drawRow(graphics, Component.translatable("for.gui.humidity"), ClimateHelper.toDisplay(primaryAllele.getHumidity()), - ColourProperties.INSTANCE.get("gui.screen"), GuiAlyzer.getColorCoding(individual.getGenome().getActiveAllele(BeeChromosomes.SPECIES).dominant())); + ColourProperties.INSTANCE.get("gui.screen"), PortableAnalyzerScreen.getColorCoding(individual.getGenome().getActiveAllele(BeeChromosomes.SPECIES).dominant())); textLayout.newLine(); IValueAllele humidToleranceActive = genome.getActiveAllele(BeeChromosomes.HUMIDITY_TOLERANCE); - textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), GuiAlyzer.COLUMN_0); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.HUMIDITY_TOLERANCE, humidToleranceActive, GuiAlyzer.COLUMN_1); + textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.HUMIDITY_TOLERANCE, humidToleranceActive, PortableAnalyzerScreen.COLUMN_1); textLayout.newLine(16); @@ -164,14 +164,14 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack Component primary = genome.getActiveValue(BeeChromosomes.TOLERATES_RAIN) ? yes : no; - textLayout.drawLine(graphics, BeeChromosomes.TOLERATES_RAIN.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); - textLayout.drawLine(graphics, primary, GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(false)); + textLayout.drawLine(graphics, BeeChromosomes.TOLERATES_RAIN.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); + textLayout.drawLine(graphics, primary, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(false)); textLayout.newLineCompressed(); primary = genome.getActiveValue(BeeChromosomes.CAVE_DWELLING) ? yes : no; - textLayout.drawLine(graphics, BeeChromosomes.CAVE_DWELLING.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); - textLayout.drawLine(graphics, primary, GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(false)); + textLayout.drawLine(graphics, BeeChromosomes.CAVE_DWELLING.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); + textLayout.drawLine(graphics, primary, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(false)); textLayout.newLine(); @@ -183,10 +183,10 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); - textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); @@ -197,9 +197,9 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack IValueAllele tempToleranceActive = genome.getActiveAllele(BeeChromosomes.TEMPERATURE_TOLERANCE); IValueAllele tempToleranceInactive = genome.getInactiveAllele(BeeChromosomes.TEMPERATURE_TOLERANCE); - textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), GuiAlyzer.COLUMN_0); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceActive, GuiAlyzer.COLUMN_1); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceInactive, GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceActive, PortableAnalyzerScreen.COLUMN_1); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceInactive, PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(16); @@ -210,9 +210,9 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack IValueAllele humidToleranceActive = genome.getActiveAllele(BeeChromosomes.HUMIDITY_TOLERANCE); IValueAllele humidToleranceInactive = genome.getInactiveAllele(BeeChromosomes.HUMIDITY_TOLERANCE); - textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), GuiAlyzer.COLUMN_0); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceActive, GuiAlyzer.COLUMN_1); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceInactive, GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.literal(" ").append(Component.translatable("for.gui.tolerance")), PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceActive, PortableAnalyzerScreen.COLUMN_1); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceInactive, PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(16); @@ -225,18 +225,18 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack Component primary = genome.getActiveValue(BeeChromosomes.TOLERATES_RAIN) ? yes : no; Component secondary = genome.getInactiveValue(BeeChromosomes.TOLERATES_RAIN) ? yes : no; - textLayout.drawLine(graphics, BeeChromosomes.TOLERATES_RAIN.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); - textLayout.drawLine(graphics, primary, GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(false)); - textLayout.drawLine(graphics, secondary, GuiAlyzer.COLUMN_2, GuiAlyzer.getColorCoding(false)); + textLayout.drawLine(graphics, BeeChromosomes.TOLERATES_RAIN.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); + textLayout.drawLine(graphics, primary, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(false)); + textLayout.drawLine(graphics, secondary, PortableAnalyzerScreen.COLUMN_2, PortableAnalyzerScreen.getColorCoding(false)); textLayout.newLineCompressed(); primary = genome.getActiveValue(BeeChromosomes.CAVE_DWELLING) ? yes : no; secondary = genome.getInactiveValue(BeeChromosomes.CAVE_DWELLING) ? yes : no; - textLayout.drawLine(graphics, BeeChromosomes.CAVE_DWELLING.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); - textLayout.drawLine(graphics, primary, GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(false)); - textLayout.drawLine(graphics, secondary, GuiAlyzer.COLUMN_2, GuiAlyzer.getColorCoding(false)); + textLayout.drawLine(graphics, BeeChromosomes.CAVE_DWELLING.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); + textLayout.drawLine(graphics, primary, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(false)); + textLayout.drawLine(graphics, secondary, PortableAnalyzerScreen.COLUMN_2, PortableAnalyzerScreen.getColorCoding(false)); textLayout.newLine(); @@ -264,25 +264,25 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack @Override public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack itemStack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(itemStack, individual -> { if (individual instanceof IBee bee) { TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); WidgetManager widgetManager = guiAlyzer.getWidgetManager(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.produce").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.produce").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - int x = GuiAlyzer.COLUMN_0; + int x = PortableAnalyzerScreen.COLUMN_0; for (ItemStack stack : bee.getProduceList()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), stack)); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } @@ -292,16 +292,16 @@ public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack itemS textLayout.newLine(); textLayout.newLine(); - textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.specialty").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.specialty").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; for (ItemStack stack : bee.getSpecialtyList()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), stack)); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } diff --git a/src/main/java/forestry/apiculture/genetics/BeeSpeciesType.java b/src/main/java/forestry/apiculture/genetics/BeeSpeciesType.java index 16543cc206..661ba6adaf 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeSpeciesType.java +++ b/src/main/java/forestry/apiculture/genetics/BeeSpeciesType.java @@ -1,25 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; import com.google.common.collect.ImmutableMap; -import com.mojang.authlib.GameProfile; import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import forestry.api.IForestryApi; import forestry.api.apiculture.IApiaristTracker; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.api.core.IProduct; import forestry.api.genetics.*; import forestry.api.genetics.alleles.BeeChromosomes; @@ -35,6 +24,7 @@ import forestry.core.utils.ItemStackUtil; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; @@ -69,13 +59,13 @@ public boolean isMated(ItemStack stack) { } @Override - public IApiaristTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile) { + public IApiaristTracker getBreedingTracker(LevelAccessor level, @Nullable ResolvableProfile profile) { return BreedingTrackerManager.INSTANCE.getTracker(this, level, profile); } @Override - public String getBreedingTrackerFile(@Nullable GameProfile profile) { - return "ApiaristTracker." + (profile == null ? "common" : profile.getId()); + public String getBreedingTrackerFile(@Nullable ResolvableProfile profile) { + return "ApiaristTracker." + ((profile == null || profile.id().isEmpty()) ? "common" : profile.id().get()); } @Override @@ -84,9 +74,9 @@ public IBreedingTracker createBreedingTracker() { } @Override - public void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level world, @Nullable GameProfile profile) { + public void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level level, @Nullable ResolvableProfile profile) { if (tracker instanceof BreedingTracker apiaristTracker) { - apiaristTracker.setLevel(world); + apiaristTracker.setLevel(level); apiaristTracker.setUsername(profile); } } @@ -102,7 +92,7 @@ public IAlyzerPlugin getAlyzerPlugin() { } @Override - public Codec getIndividualCodec() { + public MapCodec getIndividualCodec() { return Bee.CODEC; } @@ -122,7 +112,7 @@ public float getResearchSuitability(IBeeSpecies species, ItemStack stack) { } @Override - public List getResearchBounty(IBeeSpecies species, Level level, GameProfile researcher, IBee individual, int bountyLevel) { + public List getResearchBounty(IBeeSpecies species, Level level, ResolvableProfile researcher, IBee individual, int bountyLevel) { List bounty = super.getResearchBounty(species, level, researcher, individual, bountyLevel); if (bountyLevel > 10) { for (IProduct stack : species.getSpecialties()) { diff --git a/src/main/java/forestry/apiculture/genetics/DefaultBeeJubilance.java b/src/main/java/forestry/apiculture/genetics/DefaultBeeJubilance.java index 300fb27c63..c57b6fcaff 100644 --- a/src/main/java/forestry/apiculture/genetics/DefaultBeeJubilance.java +++ b/src/main/java/forestry/apiculture/genetics/DefaultBeeJubilance.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeJubilance; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IGenome; public enum DefaultBeeJubilance implements IBeeJubilance { diff --git a/src/main/java/forestry/apiculture/genetics/DefaultBeeSpriteColourProvider.java b/src/main/java/forestry/apiculture/genetics/DefaultBeeSpriteColourProvider.java deleted file mode 100644 index c5b18e409e..0000000000 --- a/src/main/java/forestry/apiculture/genetics/DefaultBeeSpriteColourProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import forestry.api.apiculture.IBeeSpriteColourProvider; - -public class DefaultBeeSpriteColourProvider implements IBeeSpriteColourProvider { - private final int primaryColour; - private final int secondaryColour; - - public DefaultBeeSpriteColourProvider(int primaryColour, int secondaryColour) { - this.primaryColour = primaryColour; - this.secondaryColour = secondaryColour; - } - - @Override - public int getSpriteColour(int renderPass) { - if (renderPass == 0) { - return this.primaryColour; - } - if (renderPass == 1) { - return this.secondaryColour; - } - return 0xffffff; - } -} diff --git a/src/main/java/forestry/apiculture/genetics/HermitBeeJubilance.java b/src/main/java/forestry/apiculture/genetics/HermitBeeJubilance.java index df1e3a0ed6..4a3bfd70d7 100644 --- a/src/main/java/forestry/apiculture/genetics/HermitBeeJubilance.java +++ b/src/main/java/forestry/apiculture/genetics/HermitBeeJubilance.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeJubilance; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IGenome; import forestry.apiculture.genetics.effects.ThrottledBeeEffect; import net.minecraft.world.entity.Mob; diff --git a/src/main/java/forestry/apiculture/genetics/HiveDrop.java b/src/main/java/forestry/apiculture/genetics/HiveDrop.java index 0f568b9401..e9665a76e5 100755 --- a/src/main/java/forestry/apiculture/genetics/HiveDrop.java +++ b/src/main/java/forestry/apiculture/genetics/HiveDrop.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.apiculture.hives.IHiveDrop; import forestry.api.genetics.alleles.IAllele; import forestry.api.genetics.alleles.IChromosome; diff --git a/src/main/java/forestry/apiculture/genetics/IGeneticTooltipProvider.java b/src/main/java/forestry/apiculture/genetics/IGeneticTooltipProvider.java deleted file mode 100644 index c36fd1f912..0000000000 --- a/src/main/java/forestry/apiculture/genetics/IGeneticTooltipProvider.java +++ /dev/null @@ -1,15 +0,0 @@ -package forestry.apiculture.genetics; - -import forestry.api.core.tooltips.ToolTip; -import forestry.api.genetics.IGenome; -import forestry.api.genetics.IIndividual; - -public interface IGeneticTooltipProvider { - /** - * Adds the handled allele to the tooltip of the individual. - * - * @param toolTip The instance of the tooltip helper class. - * @param genome The genome of the individual - */ - void addTooltip(ToolTip toolTip, IGenome genome, I individual); -} diff --git a/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java b/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java deleted file mode 100644 index a7952ea0d3..0000000000 --- a/src/main/java/forestry/apiculture/genetics/JubilanceFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.genetics; - -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.IJubilanceFactory; -import net.minecraft.world.level.block.state.BlockState; - -public class JubilanceFactory implements IJubilanceFactory { - @Override - public IBeeJubilance getDefault() { - return DefaultBeeJubilance.INSTANCE; - } - - @Override - public IBeeJubilance getHermit() { - return HermitBeeJubilance.INSTANCE; - } - - @Override - public IBeeJubilance getRequiresResource(BlockState... acceptedBlockStates) { - return new RequiresResourceBeeJubilance(acceptedBlockStates); - } -} diff --git a/src/main/java/forestry/apiculture/genetics/RequiresResourceBeeJubilance.java b/src/main/java/forestry/apiculture/genetics/RequiresResourceBeeJubilance.java index 0af1112824..7f3a9d062e 100644 --- a/src/main/java/forestry/apiculture/genetics/RequiresResourceBeeJubilance.java +++ b/src/main/java/forestry/apiculture/genetics/RequiresResourceBeeJubilance.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeJubilance; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IGenome; import forestry.core.tiles.TileUtil; import net.minecraft.core.BlockPos; @@ -23,6 +13,7 @@ import java.util.Collections; import java.util.HashSet; +// todo expose in IForestryApi public class RequiresResourceBeeJubilance implements IBeeJubilance { private final HashSet acceptedBlockStates = new HashSet<>(); @@ -32,17 +23,16 @@ public RequiresResourceBeeJubilance(BlockState... acceptedBlockStates) { @Override public boolean isJubilant(IBeeSpecies species, IGenome genome, IBeeHousing housing) { - Level level = housing.getWorldObj(); - BlockPos pos = housing.getCoordinates(); + Level level = housing.getLevel(); + BlockPos pos = housing.getBlockPos(); BlockEntity tile; do { pos = pos.below(); tile = TileUtil.getTile(level, pos); - } while (tile instanceof IBeeHousing && pos.getY() > 0); + } while (tile instanceof IBeeHousing && pos.getY() > level.dimensionType().minY()); BlockState blockState = level.getBlockState(pos); return this.acceptedBlockStates.contains(blockState); } - } diff --git a/src/main/java/forestry/apiculture/genetics/effects/AggressiveBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/AggressiveBeeEffect.java index 5deefa9e26..978b2fb5cb 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/AggressiveBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/AggressiveBeeEffect.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.features.CoreDamageTypes; import net.minecraft.world.entity.LivingEntity; import java.util.List; @@ -31,13 +21,13 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe int damage = 4; // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, this, true); + int count = IBeeProtection.getBeeProtectionLevel(entity, this, true); damage -= count; if (damage <= 0) { continue; } - entity.hurt(CoreDamageTypes.source(housing.getWorldObj(), CoreDamageTypes.AGGRESSIVE), damage); + entity.hurt(CoreDamageTypes.source(housing.getLevel(), CoreDamageTypes.AGGRESSIVE), damage); } return storedData; diff --git a/src/main/java/forestry/apiculture/genetics/effects/AgingBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/AgingBeeEffect.java index 480d923c59..61f669985d 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/AgingBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/AgingBeeEffect.java @@ -1,7 +1,7 @@ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IIndividualLiving; import forestry.api.genetics.alleles.ForestryAlleles; diff --git a/src/main/java/forestry/apiculture/genetics/effects/AscensionBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/AscensionBeeEffect.java index fd7575f543..925e28db04 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/AscensionBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/AscensionBeeEffect.java @@ -19,10 +19,10 @@ public AscensionBeeEffect() { @Override public IEffectData doFX(IGenome genome, IEffectData storedData, IBeeHousing housing) { super.doFX(genome, storedData, housing); - RandomSource rand = housing.getWorldObj().random; + RandomSource rand = housing.getLevel().random; Vec3i area = Bee.getParticleArea(genome, housing); - BlockPos coordinates = housing.getCoordinates().offset(VecUtil.center(area)); - housing.getWorldObj().addParticle(ParticleTypes.END_ROD, coordinates.getX() + rand.nextFloat() * area.getX(), coordinates.getY() + rand.nextFloat() * area.getY(), coordinates.getZ() + rand.nextFloat() * area.getZ(), 0D, 0.5D * rand.nextFloat(), 0D); + BlockPos coordinates = housing.getBlockPos().offset(VecUtil.center(area)); + housing.getLevel().addParticle(ParticleTypes.END_ROD, coordinates.getX() + rand.nextFloat() * area.getX(), coordinates.getY() + rand.nextFloat() * area.getY(), coordinates.getZ() + rand.nextFloat() * area.getZ(), 0D, 0.5D * rand.nextFloat(), 0D); return storedData; } } diff --git a/src/main/java/forestry/apiculture/genetics/effects/CreeperBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/CreeperBeeEffect.java index b8941179e3..5c1cc40bce 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/CreeperBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/CreeperBeeEffect.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.core.genetics.EffectData; @@ -44,8 +34,8 @@ public IEffectData validateStorage(IEffectData storedData) { @Override public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level world = housing.getWorldObj(); - BlockPos housingCoords = housing.getCoordinates(); + Level world = housing.getLevel(); + BlockPos housingCoords = housing.getBlockPos(); // If we are already triggered, we continue the explosion sequence. if (storedData.getInteger(indexExplosionTimer) > 0) { @@ -59,7 +49,7 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe storedData.setInteger(indexExplosionForce, defaultForce); // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(player, this, true); + int count = IBeeProtection.getBeeProtectionLevel(player, this, true); if (count > 3) { continue; // Full set, no damage/effect } else if (count > 2) { diff --git a/src/main/java/forestry/apiculture/genetics/effects/DummyBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/DummyBeeEffect.java index 75e8921f8a..c371507590 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/DummyBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/DummyBeeEffect.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.bee.IBeeEffect; // A bee effect that does nothing. Used in the default "none" as well as for the Leporine bee's Easter effect. public class DummyBeeEffect implements IBeeEffect { diff --git a/src/main/java/forestry/apiculture/genetics/effects/ExplorationBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/ExplorationBeeEffect.java index 37eb9363ca..37e554669c 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/ExplorationBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/ExplorationBeeEffect.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; @@ -18,7 +8,6 @@ import java.util.List; public class ExplorationBeeEffect extends ThrottledBeeEffect { - public ExplorationBeeEffect() { super(false, 80, true, false); } diff --git a/src/main/java/forestry/apiculture/genetics/effects/FertileBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/FertileBeeEffect.java index b562b4a00b..59b852ae05 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/FertileBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/FertileBeeEffect.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; @@ -21,7 +11,6 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.IPlantable; public class FertileBeeEffect extends ThrottledBeeEffect { private static final int MAX_BLOCK_FIND_TRIES = 5; @@ -32,9 +21,8 @@ public FertileBeeEffect() { @Override public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - - Level level = housing.getWorldObj(); - BlockPos housingCoordinates = housing.getCoordinates(); + Level level = housing.getLevel(); + BlockPos housingCoordinates = housing.getBlockPos(); Vec3i area = Bee.getParticleArea(genome, housing); int blockX = getRandomOffset(level.random, housingCoordinates.getX(), area.getX()); @@ -60,15 +48,19 @@ private static int getRandomOffset(RandomSource random, int centrePos, int offse } private static boolean tryTickColumn(Level level, int x, int z, int maxY, int minY) { + BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(x, maxY, z); + for (int y = maxY; y >= minY; --y) { - BlockState state = level.getBlockState(new BlockPos(x, y, z)); + pos.setY(y); + + BlockState state = level.getBlockState(pos); Block block = state.getBlock(); - if (block.isRandomlyTicking(state) && (block instanceof BonemealableBlock || block instanceof IPlantable)) { - level.scheduleTick(new BlockPos(x, y, z), block, 5); + + if (state.isRandomlyTicking() && (block instanceof BonemealableBlock)) { + level.scheduleTick(pos, block, 5); return true; } } return false; } - } diff --git a/src/main/java/forestry/apiculture/genetics/effects/FungificationBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/FungificationBeeEffect.java index dd6b82975d..8586297bc7 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/FungificationBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/FungificationBeeEffect.java @@ -55,8 +55,8 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe } private void doBlockEffect(IGenome genome, IBeeHousing housing) { - Level world = housing.getWorldObj(); - BlockPos housingCoordinates = housing.getCoordinates(); + Level world = housing.getLevel(); + BlockPos housingCoordinates = housing.getBlockPos(); Vec3i area = Bee.getParticleArea(genome, housing); Vec3i halfArea = new Vec3i(area.getX() / 2, area.getY() / 2, area.getZ() / 2); diff --git a/src/main/java/forestry/apiculture/genetics/effects/GlacialBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/GlacialBeeEffect.java index 19c5c2611d..71cfc47045 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/GlacialBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/GlacialBeeEffect.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; @@ -29,14 +19,14 @@ public GlacialBeeEffect() { @Override public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); if (housing.temperature().isWarmerOrEqual(TemperatureType.WARM)) { return storedData; } Vec3i area = Bee.getParticleArea(genome, housing); - BlockPos centerPos = housing.getCoordinates().offset(VecUtil.center(area)); + BlockPos centerPos = housing.getBlockPos().offset(VecUtil.center(area)); for (int i = 0; i < 10; i++) { diff --git a/src/main/java/forestry/apiculture/genetics/effects/GlowBerryGrowEffect.java b/src/main/java/forestry/apiculture/genetics/effects/GlowBerryGrowEffect.java index c9e308f3fe..95b6a75bac 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/GlowBerryGrowEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/GlowBerryGrowEffect.java @@ -18,12 +18,12 @@ public GlowBerryGrowEffect() { @Override IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); Vec3i area = Bee.getParticleArea(genome, housing); BlockPos randomPos = VecUtil.getRandomPositionInArea(level.random, area); - BlockPos posBlock = randomPos.offset(housing.getCoordinates()).offset(VecUtil.center(area)); + BlockPos posBlock = randomPos.offset(housing.getBlockPos()).offset(VecUtil.center(area)); if (level.hasChunkAt(posBlock)) { BlockState state = level.getBlockState(posBlock); diff --git a/src/main/java/forestry/apiculture/genetics/effects/GuardianBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/GuardianBeeEffect.java index 73536bc46f..6288c9665c 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/GuardianBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/GuardianBeeEffect.java @@ -1,7 +1,7 @@ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import net.minecraft.network.protocol.game.ClientboundGameEventPacket; @@ -22,7 +22,7 @@ IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousin List list = getEntitiesInRange(genome, housing, Player.class); for (Player player : list) { if (!player.hasEffect(MobEffects.DIG_SLOWDOWN)) { - int count = BeeManager.armorApiaristHelper.wearsItems(player, this, true); + int count = IBeeProtection.getBeeProtectionLevel(player, this, true); if (count >= 4) { continue; } diff --git a/src/main/java/forestry/apiculture/genetics/effects/HeroicBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/HeroicBeeEffect.java index 5c67e2d392..d07e5b86e6 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/HeroicBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/HeroicBeeEffect.java @@ -1,19 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.features.CoreDamageTypes; import net.minecraft.world.entity.monster.Monster; import java.util.List; @@ -27,7 +17,7 @@ public HeroicBeeEffect() { public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { List mobs = ThrottledBeeEffect.getEntitiesInRange(genome, housing, Monster.class); for (Monster mob : mobs) { - mob.hurt(CoreDamageTypes.source(housing.getWorldObj(), CoreDamageTypes.HEROIC), 2); + mob.hurt(CoreDamageTypes.source(housing.getLevel(), CoreDamageTypes.HEROIC), 2); } return storedData; diff --git a/src/main/java/forestry/apiculture/genetics/effects/IgnitionBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/IgnitionBeeEffect.java index d135ec6ec9..9674cbd286 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/IgnitionBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/IgnitionBeeEffect.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.core.render.ParticleRender; @@ -19,8 +9,8 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.List; @@ -34,14 +24,14 @@ public IgnitionBeeEffect() { @Override public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); List entities = ThrottledBeeEffect.getEntitiesInRange(genome, housing, LivingEntity.class); for (LivingEntity entity : entities) { int chance = ignitionChance; int duration = fireDuration; // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, this, true); + int count = IBeeProtection.getBeeProtectionLevel(entity, this, true); if (count > 3) { continue; // Full set, no damage/effect } else if (count > 2) { @@ -59,7 +49,7 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe continue; } - entity.setSecondsOnFire(duration); + entity.igniteForSeconds(duration); } return storedData; @@ -68,7 +58,7 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe @Override @OnlyIn(Dist.CLIENT) public IEffectData doFX(IGenome genome, IEffectData storedData, IBeeHousing housing) { - ClientLevel level = (ClientLevel) housing.getWorldObj(); + ClientLevel level = (ClientLevel) housing.getLevel(); if (level.random.nextInt(2) != 0) { super.doFX(genome, storedData, housing); } else { diff --git a/src/main/java/forestry/apiculture/genetics/effects/MisanthropeBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/MisanthropeBeeEffect.java index 7114ac9c8e..a42bc22b37 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/MisanthropeBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/MisanthropeBeeEffect.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.features.CoreDamageTypes; import net.minecraft.world.entity.player.Player; import java.util.List; @@ -31,16 +21,15 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe int damage = 4; // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(player, this, true); + int count = IBeeProtection.getBeeProtectionLevel(player, this, true); damage -= count; if (damage <= 0) { continue; } - player.hurt(CoreDamageTypes.source(housing.getWorldObj(), CoreDamageTypes.MISANTHROPE), damage); + player.hurt(CoreDamageTypes.source(housing.getLevel(), CoreDamageTypes.MISANTHROPE), damage); } return storedData; } - } diff --git a/src/main/java/forestry/apiculture/genetics/effects/NonStackingBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/NonStackingBeeEffect.java index 3341c2e6db..98212c2462 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/NonStackingBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/NonStackingBeeEffect.java @@ -4,8 +4,8 @@ import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; import forestry.api.apiculture.IBeekeepingLogic; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBeeEffect; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.api.genetics.IIndividual; @@ -20,8 +20,8 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.TickEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.tick.LevelTickEvent; import java.util.HashMap; import java.util.HashSet; @@ -37,14 +37,14 @@ public NonStackingBeeEffect(boolean dominant) { this.dominant = dominant; this.trackedOwners = new HashMap<>(); - MinecraftForge.EVENT_BUS.addListener(this::performGlobalEffect); + NeoForge.EVENT_BUS.addListener(this::performGlobalEffect); } @Override public IEffectData doEffect(IGenome genome, IEffectData storedData, IBeeHousing housing) { // Don't spam adding to the set - if ((housing.getWorldObj().getGameTime() & 64L) == 0) { - this.trackedOwners.computeIfAbsent(housing.getWorldObj().dimension(), key -> new HashSet<>()).add(housing.getCoordinates()); + if ((housing.getLevel().getGameTime() & 64L) == 0) { + this.trackedOwners.computeIfAbsent(housing.getLevel().dimension(), key -> new HashSet<>()).add(housing.getBlockPos()); } return IBeeEffect.super.doEffect(genome, storedData, housing); } @@ -54,12 +54,8 @@ public boolean isDominant() { return this.dominant; } - private void performGlobalEffect(TickEvent.LevelTickEvent event) { - if (event.phase != TickEvent.Phase.START) { - return; - } - - Level level = event.level; + private void performGlobalEffect(LevelTickEvent.Pre event) { + Level level = event.getLevel(); if (level.isClientSide || level.getGameTime() % IBeekeepingLogic.DEFAULT_WORK_THROTTLE != 0) { return; diff --git a/src/main/java/forestry/apiculture/genetics/effects/PhasingBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/PhasingBeeEffect.java index 7a6ae5b278..54bb5a89c5 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/PhasingBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/PhasingBeeEffect.java @@ -1,7 +1,7 @@ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import net.minecraft.core.particles.ParticleTypes; @@ -16,8 +16,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.event.entity.EntityTeleportEvent.ChorusFruit; +import net.neoforged.neoforge.event.EventHooks; +import net.neoforged.neoforge.event.entity.EntityTeleportEvent; import java.util.List; @@ -28,12 +28,12 @@ public PhasingBeeEffect() { @Override IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - ServerLevel level = (ServerLevel) housing.getWorldObj(); + ServerLevel level = (ServerLevel) housing.getLevel(); RandomSource random = level.random; List list = getEntitiesInRange(genome, housing, LivingEntity.class); for (LivingEntity entity : list) { - int count = BeeManager.armorApiaristHelper.wearsItems(entity, this, true); + int count = IBeeProtection.getBeeProtectionLevel(entity, this, true); if (count >= 4) { continue; @@ -54,7 +54,7 @@ IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousin Vec3 vec3 = entity.position(); level.gameEvent(GameEvent.TELEPORT, vec3, GameEvent.Context.of(entity)); - ChorusFruit event = ForgeEventFactory.onChorusFruitTeleport(entity, targetX, targetY, targetZ); + EntityTeleportEvent.ChorusFruit event = EventHooks.onChorusFruitTeleport(entity, targetX, targetY, targetZ); if (event.isCanceled()) { break; @@ -73,8 +73,8 @@ IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousin @Override public IEffectData doFX(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); - level.addParticle(ParticleTypes.PORTAL, housing.getCoordinates().getX() + 0.5, housing.getCoordinates().getY() + 0.5 + level.random.nextDouble() * 2, housing.getCoordinates().getZ() + 0.5, level.random.nextGaussian(), 0, level.random.nextGaussian()); + Level level = housing.getLevel(); + level.addParticle(ParticleTypes.PORTAL, housing.getBlockPos().getX() + 0.5, housing.getBlockPos().getY() + 0.5 + level.random.nextDouble() * 2, housing.getBlockPos().getZ() + 0.5, level.random.nextGaussian(), 0, level.random.nextGaussian()); return storedData; } } diff --git a/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffect.java index da9f22140f..bcc054a237 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffect.java @@ -1,59 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.core.render.ParticleRender; +import net.minecraft.core.Holder; import net.minecraft.util.RandomSource; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectCategory; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.monster.Enemy; -import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.PotionContents; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.Collection; import java.util.Collections; import java.util.List; public class PotionBeeEffect extends ThrottledBeeEffect { - private final MobEffect potion; + private final Holder potion; private final int potionFXColor; private final int duration; private final float chance; - public PotionBeeEffect(boolean dominant, MobEffect potion, int duration) { + public PotionBeeEffect(boolean dominant, Holder potion, int duration) { this(dominant, potion, duration, 200, 1.0f); } - public PotionBeeEffect(boolean dominant, MobEffect potion, int duration, int throttle, float chance) { + public PotionBeeEffect(boolean dominant, Holder potion, int duration, int throttle, float chance) { super(dominant, throttle, true, false); this.potion = potion; this.duration = duration; this.chance = chance; Collection potionEffects = Collections.singleton(new MobEffectInstance(potion, 1, 0)); - this.potionFXColor = PotionUtils.getColor(potionEffects); + this.potionFXColor = PotionContents.getColor(potionEffects); } @Override public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - RandomSource rand = housing.getWorldObj().random; + RandomSource rand = housing.getLevel().random; List entities = ThrottledBeeEffect.getEntitiesInRange(genome, housing, LivingEntity.class); for (LivingEntity entity : entities) { @@ -66,9 +57,9 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe } int dur = this.duration; - if (this.potion.getCategory() == MobEffectCategory.HARMFUL) { + if (this.potion.value().getCategory() == MobEffectCategory.HARMFUL) { // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, this, true); + int count = IBeeProtection.getBeeProtectionLevel(entity, this, true); if (count >= 4) { continue; // Full set, no damage/effect } else if (count == 3) { @@ -81,7 +72,7 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe } else { // don't apply positive effects to mobs // but apply neutral ones - if (this.potion.getCategory() == MobEffectCategory.BENEFICIAL && entity instanceof Enemy) { + if (this.potion.value().getCategory() == MobEffectCategory.BENEFICIAL && entity instanceof Enemy) { continue; } } @@ -99,7 +90,7 @@ public boolean secondaryEntityCheck(LivingEntity entity) { @Override @OnlyIn(Dist.CLIENT) public IEffectData doFX(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); if (level.random.nextBoolean()) { super.doFX(genome, storedData, housing); } else { diff --git a/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffectExclusive.java b/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffectExclusive.java index f26ce1bc3f..f559050a83 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffectExclusive.java +++ b/src/main/java/forestry/apiculture/genetics/effects/PotionBeeEffectExclusive.java @@ -1,12 +1,13 @@ package forestry.apiculture.genetics.effects; +import net.minecraft.core.Holder; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.LivingEntity; public class PotionBeeEffectExclusive extends PotionBeeEffect { - private final MobEffect exclude; + private final Holder exclude; - public PotionBeeEffectExclusive(boolean dominant, MobEffect potion, int duration, int throttle, float chance, MobEffect exclude) { + public PotionBeeEffectExclusive(boolean dominant, Holder potion, int duration, int throttle, float chance, Holder exclude) { super(dominant, potion, duration, throttle, chance); this.exclude = exclude; } diff --git a/src/main/java/forestry/apiculture/genetics/effects/RadioactiveBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/RadioactiveBeeEffect.java index 50ef865317..00127e7ef9 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/RadioactiveBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/RadioactiveBeeEffect.java @@ -1,22 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; -import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeeProtection; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.BeeChromosomes; import forestry.apiculture.blocks.BlockAlveary; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.features.CoreDamageTypes; import forestry.core.tiles.TileUtil; import forestry.core.utils.BlockUtil; import forestry.core.utils.VecUtil; @@ -48,22 +38,22 @@ private void harmEntities(IGenome genome, IBeeHousing housing) { int damage = 8; // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, this, true); + int count = IBeeProtection.getBeeProtectionLevel(entity, this, true); damage -= count * 2; if (damage <= 0) { continue; } - entity.hurt(CoreDamageTypes.source(housing.getWorldObj(), CoreDamageTypes.RADIOACTIVE), damage); + entity.hurt(CoreDamageTypes.source(housing.getLevel(), CoreDamageTypes.RADIOACTIVE), damage); } } private static IEffectData destroyEnvironment(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); RandomSource rand = level.random; Vec3i area = VecUtil.scale(genome.getActiveValue(BeeChromosomes.TERRITORY), 2); - BlockPos posHousing = housing.getCoordinates(); + BlockPos posHousing = housing.getBlockPos(); for (int i = 0; i < 20; i++) { BlockPos randomPos = VecUtil.getRandomPositionInArea(rand, area); diff --git a/src/main/java/forestry/apiculture/genetics/effects/RepulsionBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/RepulsionBeeEffect.java index 28383ac825..917979b82b 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/RepulsionBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/RepulsionBeeEffect.java @@ -1,19 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.apiculture.entities.AIAvoidPlayers; +import net.minecraft.world.entity.ai.goal.WrappedGoal; import net.minecraft.world.entity.monster.Monster; import java.util.List; @@ -37,6 +28,11 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe } private boolean isMobAvoidingPlayers(Monster mob) { - return mob.goalSelector.getRunningGoals().anyMatch(task -> task.getGoal() instanceof AIAvoidPlayers); + for (WrappedGoal task : mob.goalSelector.getAvailableGoals()) { + if (task.isRunning() && task.getGoal() instanceof AIAvoidPlayers) { + return true; + } + } + return false; } } diff --git a/src/main/java/forestry/apiculture/genetics/effects/ResurrectionBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/ResurrectionBeeEffect.java index 241b304d9b..5e1d29ce8b 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/ResurrectionBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/ResurrectionBeeEffect.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; diff --git a/src/main/java/forestry/apiculture/genetics/effects/SculkSpreadBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/SculkSpreadBeeEffect.java index e8f9c59aec..cee99c901b 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/SculkSpreadBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/SculkSpreadBeeEffect.java @@ -21,7 +21,7 @@ public SculkSpreadBeeEffect() { @Override IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); if (level.isClientSide) { return storedData; } @@ -30,7 +30,7 @@ IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousin BlockPos randomPos = VecUtil.getRandomPositionInArea(random, area); - BlockPos posBlock = randomPos.offset(housing.getCoordinates()).offset(VecUtil.center(area)); + BlockPos posBlock = randomPos.offset(housing.getBlockPos()).offset(VecUtil.center(area)); if (level.hasChunkAt(posBlock)) { BlockState state = level.getBlockState(posBlock); @@ -38,11 +38,11 @@ IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousin if (state.isAir() && !level.getBlockState(posBlock.below()).isAir()) { SculkSpreader spreader = SculkSpreader.createLevelSpreader(); spreader.addCursors(posBlock, random.nextInt(5) + 1); - spreader.updateCursors(level, housing.getCoordinates(), random, true); - spreader.updateCursors(level, housing.getCoordinates(), random, true); - spreader.updateCursors(level, housing.getCoordinates(), random, true); - spreader.updateCursors(level, housing.getCoordinates(), random, true); - spreader.updateCursors(level, housing.getCoordinates(), random, true); + spreader.updateCursors(level, housing.getBlockPos(), random, true); + spreader.updateCursors(level, housing.getBlockPos(), random, true); + spreader.updateCursors(level, housing.getBlockPos(), random, true); + spreader.updateCursors(level, housing.getBlockPos(), random, true); + spreader.updateCursors(level, housing.getBlockPos(), random, true); } else if (state.getBlock() == Blocks.SCULK_SHRIEKER) { level.setBlockAndUpdate(posBlock.above(), Blocks.SCULK_SHRIEKER.defaultBlockState().setValue(SculkShriekerBlock.CAN_SUMMON, true)); } diff --git a/src/main/java/forestry/apiculture/genetics/effects/SifterBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/SifterBeeEffect.java index 33881dc9ce..9ae70be953 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/SifterBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/SifterBeeEffect.java @@ -20,12 +20,12 @@ public SifterBeeEffect() { @Override IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); Vec3i area = Bee.getParticleArea(genome, housing); BlockPos randomPos = VecUtil.getRandomPositionInArea(level.random, area); - BlockPos posBlock = randomPos.offset(housing.getCoordinates()).offset(VecUtil.center(area)); + BlockPos posBlock = randomPos.offset(housing.getBlockPos()).offset(VecUtil.center(area)); if (level.hasChunkAt(posBlock)) { BlockState state = level.getBlockState(posBlock); diff --git a/src/main/java/forestry/apiculture/genetics/effects/SnowingBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/SnowingBeeEffect.java index b761976d64..19b97d9510 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/SnowingBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/SnowingBeeEffect.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.apiculture.IBeeHousing; @@ -32,7 +22,7 @@ public SnowingBeeEffect() { @Override public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); if (housing.temperature().isWarmerOrEqual(TemperatureType.WARM)) { return storedData; @@ -41,7 +31,7 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe Vec3i area = Bee.getParticleArea(genome, housing); BlockPos randomPos = VecUtil.getRandomPositionInArea(level.random, area); - BlockPos posBlock = randomPos.offset(housing.getCoordinates()).offset(VecUtil.center(area)); + BlockPos posBlock = randomPos.offset(housing.getBlockPos()).offset(VecUtil.center(area)); // Put snow on the ground if (level.hasChunkAt(posBlock)) { @@ -69,12 +59,12 @@ public IEffectData doEffectThrottled(IGenome genome, IEffectData storedData, IBe @Override public IEffectData doFX(IGenome genome, IEffectData storedData, IBeeHousing housing) { - Level level = housing.getWorldObj(); + Level level = housing.getLevel(); if (level.random.nextInt(3) == 0) { Vec3i area = Bee.getParticleArea(genome, housing); - BlockPos coordinates = housing.getCoordinates(); + BlockPos coordinates = housing.getBlockPos(); BlockPos spawn = VecUtil.getRandomPositionInArea(level.random, area).offset(coordinates).offset(VecUtil.center(area)); ParticleRender.addEntitySnowFX(level, spawn.getX(), spawn.getY(), spawn.getZ()); diff --git a/src/main/java/forestry/apiculture/genetics/effects/ThrottledBeeEffect.java b/src/main/java/forestry/apiculture/genetics/effects/ThrottledBeeEffect.java index 163c4f3595..deb87c67be 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/ThrottledBeeEffect.java +++ b/src/main/java/forestry/apiculture/genetics/effects/ThrottledBeeEffect.java @@ -1,19 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.genetics.effects; import forestry.api.IForestryApi; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.bee.IBeeEffect; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; import forestry.apiculture.genetics.Bee; @@ -42,7 +32,7 @@ public static AABB getBounding(IBeeHousing housing, IGenome genome) { IBeeModifier beeModifier = IForestryApi.INSTANCE.getHiveManager().createBeeHousingModifier(housing); Vec3i territory = Bee.getAdjustedTerritory(genome, beeModifier); - BlockPos min = housing.getCoordinates().offset(VecUtil.center(territory)); + BlockPos min = housing.getBlockPos().offset(VecUtil.center(territory)); BlockPos max = min.offset(territory); return new AABB(min.getX(), min.getY(), min.getZ(), max.getX(), max.getY(), max.getZ()); @@ -50,7 +40,7 @@ public static AABB getBounding(IBeeHousing housing, IGenome genome) { public static List getEntitiesInRange(IGenome genome, IBeeHousing housing, Class entityClass) { AABB boundingBox = getBounding(housing, genome); - return housing.getWorldObj().getEntitiesOfClass(entityClass, boundingBox); + return housing.getLevel().getEntitiesOfClass(entityClass, boundingBox); } @Override diff --git a/src/main/java/forestry/apiculture/genetics/effects/package-info.java b/src/main/java/forestry/apiculture/genetics/effects/package-info.java index a2f7bd371b..c0372662fb 100644 --- a/src/main/java/forestry/apiculture/genetics/effects/package-info.java +++ b/src/main/java/forestry/apiculture/genetics/effects/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.genetics.effects; diff --git a/src/main/java/forestry/apiculture/genetics/package-info.java b/src/main/java/forestry/apiculture/genetics/package-info.java index e901b7ce5a..3e094bfb8c 100644 --- a/src/main/java/forestry/apiculture/genetics/package-info.java +++ b/src/main/java/forestry/apiculture/genetics/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.genetics; diff --git a/src/main/java/forestry/apiculture/gui/AlvearyHygroregulatorMenu.java b/src/main/java/forestry/apiculture/gui/AlvearyHygroregulatorMenu.java new file mode 100644 index 0000000000..b8ec345dce --- /dev/null +++ b/src/main/java/forestry/apiculture/gui/AlvearyHygroregulatorMenu.java @@ -0,0 +1,23 @@ +package forestry.apiculture.gui; + +import forestry.apiculture.features.ApicultureMenuTypes; +import forestry.apiculture.inventory.InventoryHygroregulator; +import forestry.apiculture.multiblock.TileAlvearyHygroregulator; +import forestry.core.gui.LiquidTanksMenu; +import forestry.core.gui.slots.SlotLiquidIn; +import forestry.core.tiles.TileUtil; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Inventory; + +public class AlvearyHygroregulatorMenu extends LiquidTanksMenu { + public static AlvearyHygroregulatorMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + TileAlvearyHygroregulator tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileAlvearyHygroregulator.class); + return new AlvearyHygroregulatorMenu(windowId, inv, tile); + } + + public AlvearyHygroregulatorMenu(int windowId, Inventory playerInventory, TileAlvearyHygroregulator tile) { + super(windowId, ApicultureMenuTypes.ALVEARY_HYGROREGULATOR.menuType(), playerInventory, tile, 8, 84); + + addSlot(new SlotLiquidIn(tile, InventoryHygroregulator.SLOT_INPUT, 56, 38)); + } +} diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlveary.java b/src/main/java/forestry/apiculture/gui/AlvearyMenu.java old mode 100755 new mode 100644 similarity index 53% rename from src/main/java/forestry/apiculture/gui/ContainerAlveary.java rename to src/main/java/forestry/apiculture/gui/AlvearyMenu.java index b34bbeda47..d038396052 --- a/src/main/java/forestry/apiculture/gui/ContainerAlveary.java +++ b/src/main/java/forestry/apiculture/gui/AlvearyMenu.java @@ -1,31 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.api.modules.IForestryPacketClient; import forestry.apiculture.features.ApicultureMenuTypes; import forestry.apiculture.multiblock.TileAlveary; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.network.packets.PacketGuiStream; import forestry.core.tiles.TileUtil; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerAlveary extends ContainerTile { - public static ContainerAlveary fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class AlvearyMenu extends TileMenu { + public static AlvearyMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileAlveary tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileAlveary.class); - return new ContainerAlveary(windowId, inv, tile); + return new AlvearyMenu(windowId, inv, tile); } - public ContainerAlveary(int windowid, Inventory playerInv, TileAlveary tile) { + public AlvearyMenu(int windowid, Inventory playerInv, TileAlveary tile) { super(windowid, ApicultureMenuTypes.ALVEARY.menuType(), playerInv, tile, 8, 108); ContainerBeeHelper.addSlots(this, tile, false); diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java b/src/main/java/forestry/apiculture/gui/AlvearySieveMenu.java old mode 100755 new mode 100644 similarity index 53% rename from src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java rename to src/main/java/forestry/apiculture/gui/AlvearySieveMenu.java index 0a71a1081c..453d7967df --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearySieve.java +++ b/src/main/java/forestry/apiculture/gui/AlvearySieveMenu.java @@ -1,19 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.apiculture.features.ApicultureMenuTypes; import forestry.apiculture.inventory.InventoryAlvearySieve; import forestry.apiculture.multiblock.TileAlvearySieve; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.inventory.watchers.ISlotPickupWatcher; @@ -21,13 +11,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerAlvearySieve extends ContainerTile { - public static ContainerAlvearySieve fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class AlvearySieveMenu extends TileMenu { + public static AlvearySieveMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileAlvearySieve tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileAlvearySieve.class); - return new ContainerAlvearySieve(windowId, inv, tile); //TODO nullability. + return new AlvearySieveMenu(windowId, inv, tile); //TODO nullability. } - public ContainerAlvearySieve(int windowId, Inventory player, TileAlvearySieve tile) { + public AlvearySieveMenu(int windowId, Inventory player, TileAlvearySieve tile) { super(windowId, ApicultureMenuTypes.ALVEARY_SIEVE.menuType(), player, tile, 8, 87); ISlotPickupWatcher crafter = tile.getCrafter(); diff --git a/src/main/java/forestry/apiculture/gui/AlvearySwarmerMenu.java b/src/main/java/forestry/apiculture/gui/AlvearySwarmerMenu.java new file mode 100644 index 0000000000..483d7491d9 --- /dev/null +++ b/src/main/java/forestry/apiculture/gui/AlvearySwarmerMenu.java @@ -0,0 +1,25 @@ +package forestry.apiculture.gui; + +import forestry.apiculture.features.ApicultureMenuTypes; +import forestry.apiculture.multiblock.TileAlvearySwarmer; +import forestry.core.gui.TileMenu; +import forestry.core.gui.slots.SlotFiltered; +import forestry.core.tiles.TileUtil; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Inventory; + +public class AlvearySwarmerMenu extends TileMenu { + public static AlvearySwarmerMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + TileAlvearySwarmer tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileAlvearySwarmer.class); + return new AlvearySwarmerMenu(windowId, inv, tile); + } + + public AlvearySwarmerMenu(int windowId, Inventory player, TileAlvearySwarmer tile) { + super(windowId, ApicultureMenuTypes.ALVEARY_SWARMER.menuType(), player, tile, 8, 87); + + this.addSlot(new SlotFiltered(tile, 0, 79, 52)); + this.addSlot(new SlotFiltered(tile, 1, 100, 39)); + this.addSlot(new SlotFiltered(tile, 2, 58, 39)); + this.addSlot(new SlotFiltered(tile, 3, 79, 26)); + } +} diff --git a/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java b/src/main/java/forestry/apiculture/gui/BeeHousingMenu.java similarity index 59% rename from src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java rename to src/main/java/forestry/apiculture/gui/BeeHousingMenu.java index 8633cb4bdf..efb370bd0c 100644 --- a/src/main/java/forestry/apiculture/gui/ContainerBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/BeeHousingMenu.java @@ -1,19 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.api.modules.IForestryPacketClient; import forestry.apiculture.features.ApicultureMenuTypes; import forestry.apiculture.tiles.TileBeeHousingBase; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.network.packets.PacketGuiStream; import forestry.core.tiles.TileUtil; import forestry.core.utils.NetworkUtil; @@ -22,18 +12,18 @@ import java.util.Objects; -public class ContainerBeeHousing extends ContainerTile implements IContainerBeeHousing { +public class BeeHousingMenu extends TileMenu implements IContainerBeeHousing { private final IGuiBeeHousingDelegate delegate; private final GuiBeeHousing.Icon icon; - public static ContainerBeeHousing fromNetwork(int windowId, Inventory inv, FriendlyByteBuf buffer) { + public static BeeHousingMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf buffer) { TileBeeHousingBase tile = TileUtil.getTile(inv.player.level(), buffer.readBlockPos(), TileBeeHousingBase.class); boolean hasFrames = buffer.readBoolean(); GuiBeeHousing.Icon icon = NetworkUtil.readEnum(buffer, GuiBeeHousing.Icon.VALUES); - return new ContainerBeeHousing(windowId, inv, Objects.requireNonNull(tile), hasFrames, icon); + return new BeeHousingMenu(windowId, inv, Objects.requireNonNull(tile), hasFrames, icon); } - public ContainerBeeHousing(int windowId, Inventory playerInv, TileBeeHousingBase tile, boolean hasFrames, GuiBeeHousing.Icon icon) { + public BeeHousingMenu(int windowId, Inventory playerInv, TileBeeHousingBase tile, boolean hasFrames, GuiBeeHousing.Icon icon) { super(windowId, ApicultureMenuTypes.BEE_HOUSING.menuType(), playerInv, tile, 8, 108); ContainerBeeHelper.addSlots(this, tile, hasFrames); diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java deleted file mode 100755 index ccc570b37a..0000000000 --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearyHygroregulator.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui; - -import forestry.apiculture.features.ApicultureMenuTypes; -import forestry.apiculture.inventory.InventoryHygroregulator; -import forestry.apiculture.multiblock.TileAlvearyHygroregulator; -import forestry.core.gui.ContainerLiquidTanks; -import forestry.core.gui.slots.SlotLiquidIn; -import forestry.core.tiles.TileUtil; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.entity.player.Inventory; - -public class ContainerAlvearyHygroregulator extends ContainerLiquidTanks { - public static ContainerAlvearyHygroregulator fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { - TileAlvearyHygroregulator tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileAlvearyHygroregulator.class); - return new ContainerAlvearyHygroregulator(windowId, inv, tile); - } - - public ContainerAlvearyHygroregulator(int windowId, Inventory playerInventory, TileAlvearyHygroregulator tile) { - super(windowId, ApicultureMenuTypes.ALVEARY_HYGROREGULATOR.menuType(), playerInventory, tile, 8, 84); - - addSlot(new SlotLiquidIn(tile, InventoryHygroregulator.SLOT_INPUT, 56, 38)); - } -} diff --git a/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java b/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java deleted file mode 100755 index 5b305ca7f8..0000000000 --- a/src/main/java/forestry/apiculture/gui/ContainerAlvearySwarmer.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui; - -import forestry.apiculture.features.ApicultureMenuTypes; -import forestry.apiculture.multiblock.TileAlvearySwarmer; -import forestry.core.gui.ContainerTile; -import forestry.core.gui.slots.SlotFiltered; -import forestry.core.tiles.TileUtil; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.entity.player.Inventory; - -public class ContainerAlvearySwarmer extends ContainerTile { - public static ContainerAlvearySwarmer fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { - TileAlvearySwarmer tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileAlvearySwarmer.class); - return new ContainerAlvearySwarmer(windowId, inv, tile); - } - - public ContainerAlvearySwarmer(int windowId, Inventory player, TileAlvearySwarmer tile) { - super(windowId, ApicultureMenuTypes.ALVEARY_SWARMER.menuType(), player, tile, 8, 87); - - this.addSlot(new SlotFiltered(tile, 0, 79, 52)); - this.addSlot(new SlotFiltered(tile, 1, 100, 39)); - this.addSlot(new SlotFiltered(tile, 2, 58, 39)); - this.addSlot(new SlotFiltered(tile, 3, 79, 26)); - } -} diff --git a/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java b/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java index 9db6feb4fc..38a3454252 100644 --- a/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java +++ b/src/main/java/forestry/apiculture/gui/ContainerBeeHelper.java @@ -1,25 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.apiculture.InventoryBeeHousing; import forestry.apiculture.inventory.InventoryApiary; -import forestry.core.gui.ContainerForestry; +import forestry.core.gui.ForestryMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.tiles.IFilterSlotDelegate; import net.minecraft.world.Container; public abstract class ContainerBeeHelper { - public static void addSlots(ContainerForestry container, T inventory, boolean hasFrames) { + public static void addSlots(ForestryMenu container, T inventory, boolean hasFrames) { // Queen/Princess container.addSlot(new SlotFiltered(inventory, InventoryBeeHousing.SLOT_QUEEN, 29, 39)); diff --git a/src/main/java/forestry/apiculture/gui/GuiAlveary.java b/src/main/java/forestry/apiculture/gui/GuiAlveary.java index b55bac79a0..46cb6e3028 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlveary.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlveary.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.apiculture.multiblock.IAlvearyControllerInternal; @@ -19,10 +9,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiAlveary extends GuiForestryTitled { +public class GuiAlveary extends GuiForestryTitled { private final TileAlveary tile; - public GuiAlveary(ContainerAlveary container, Inventory inventory, Component title) { + public GuiAlveary(AlvearyMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/alveary.png", container, inventory, title); this.tile = container.getTile(); this.imageHeight = 190; diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java index 1547b3f558..b7201015fe 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearyHygroregulator.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.apiculture.multiblock.TileAlvearyHygroregulator; @@ -17,10 +7,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiAlvearyHygroregulator extends GuiForestryTitled { +public class GuiAlvearyHygroregulator extends GuiForestryTitled { private final TileAlvearyHygroregulator tile; - public GuiAlvearyHygroregulator(ContainerAlvearyHygroregulator container, Inventory inventory, Component title) { + public GuiAlvearyHygroregulator(AlvearyHygroregulatorMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/hygroregulator.png", container, inventory, title); this.tile = container.getTile(); diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java b/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java index e791e09224..1f8f117662 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearySieve.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.apiculture.multiblock.TileAlvearySieve; @@ -16,10 +6,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiAlvearySieve extends GuiForestryTitled { +public class GuiAlvearySieve extends GuiForestryTitled { private final TileAlvearySieve tile; - public GuiAlvearySieve(ContainerAlvearySieve container, Inventory inventory, Component title) { + public GuiAlvearySieve(AlvearySieveMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/sieve.png", container, inventory, title); this.tile = container.getTile(); } diff --git a/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java b/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java index 610ec10406..1800fc6959 100755 --- a/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/gui/GuiAlvearySwarmer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.apiculture.multiblock.TileAlvearySwarmer; @@ -16,10 +6,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiAlvearySwarmer extends GuiForestryTitled { +public class GuiAlvearySwarmer extends GuiForestryTitled { private final TileAlvearySwarmer tile; - public GuiAlvearySwarmer(ContainerAlvearySwarmer container, Inventory inventory, Component title) { + public GuiAlvearySwarmer(AlvearySwarmerMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/swarmer.png", container, inventory, title); this.tile = container.getTile(); } diff --git a/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java b/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java index 443424f06e..52f0cc0fe8 100644 --- a/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/GuiBeeHousing.java @@ -1,24 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.core.config.Constants; -import forestry.core.gui.ContainerForestry; +import forestry.core.gui.ForestryMenu; import forestry.core.gui.GuiForestryTitled; import forestry.core.render.EnumTankLevel; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiBeeHousing extends GuiForestryTitled { +public class GuiBeeHousing extends GuiForestryTitled { private final IGuiBeeHousingDelegate delegate; public enum Icon { diff --git a/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java b/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java index 4df3e23605..679a764dc9 100644 --- a/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java +++ b/src/main/java/forestry/apiculture/gui/IContainerBeeHousing.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; public interface IContainerBeeHousing { diff --git a/src/main/java/forestry/apiculture/gui/IGuiBeeHousingDelegate.java b/src/main/java/forestry/apiculture/gui/IGuiBeeHousingDelegate.java index ebc3ba8713..dc3edee57e 100644 --- a/src/main/java/forestry/apiculture/gui/IGuiBeeHousingDelegate.java +++ b/src/main/java/forestry/apiculture/gui/IGuiBeeHousingDelegate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.gui; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/apiculture/gui/package-info.java b/src/main/java/forestry/apiculture/gui/package-info.java index 2510c8911c..576a9a36fb 100644 --- a/src/main/java/forestry/apiculture/gui/package-info.java +++ b/src/main/java/forestry/apiculture/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.gui; diff --git a/src/main/java/forestry/apiculture/hives/Hive.java b/src/main/java/forestry/apiculture/hives/Hive.java index 45724ddc06..fd75ad9f4e 100644 --- a/src/main/java/forestry/apiculture/hives/Hive.java +++ b/src/main/java/forestry/apiculture/hives/Hive.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.hives; import forestry.api.apiculture.hives.IHive; diff --git a/src/main/java/forestry/apiculture/hives/HiveDecorator.java b/src/main/java/forestry/apiculture/hives/HiveDecorator.java index 3e4226326f..8d6b4076e8 100644 --- a/src/main/java/forestry/apiculture/hives/HiveDecorator.java +++ b/src/main/java/forestry/apiculture/hives/HiveDecorator.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.hives; import forestry.api.IForestryApi; @@ -47,11 +37,6 @@ public static boolean tryGenHive(WorldGenLevel world, RandomSource rand, int pos Holder biome = world.getBiome(hivePos); TemperatureType temperature = IForestryApi.INSTANCE.getClimateManager().getTemperature(biome); HumidityType humidity = IForestryApi.INSTANCE.getClimateManager().getHumidity(biome); - if (temperature == null) { - System.out.println(biome.getClass()); - System.out.println(biome.unwrapKey()); - System.out.println(biome.get()); - } // check if the biome is valid if (!hive.isGoodBiome(biome) || !hive.isGoodTemperature(temperature) || !hive.isGoodHumidity(humidity)) { return false; diff --git a/src/main/java/forestry/apiculture/hives/HiveDefinition.java b/src/main/java/forestry/apiculture/hives/HiveDefinition.java index 94458b65a0..58ad60bb41 100644 --- a/src/main/java/forestry/apiculture/hives/HiveDefinition.java +++ b/src/main/java/forestry/apiculture/hives/HiveDefinition.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.hives; import forestry.api.ForestryTags; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.apiculture.hives.IHiveDefinition; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.api.core.HumidityType; import forestry.api.core.TemperatureType; import forestry.api.core.ToleranceType; @@ -38,7 +28,7 @@ import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; import java.util.ArrayList; import java.util.Collections; @@ -46,7 +36,7 @@ // todo this should be data driven public enum HiveDefinition implements IHiveDefinition { - FOREST(ApicultureBlocks.BEEHIVE.get(BlockHiveType.FOREST).defaultState(), 6.0f, ForestryBeeSpecies.FOREST, HiveGenTree.INSTANCE) { + FOREST(ApicultureBlocks.BEEHIVE.get(BlockHiveType.FOREST).defaultState(), 6.0f, ForestryBeeSpecies.FOREST, HivePlacementTree.INSTANCE) { @Override public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { postGenFlowers(level, rand, pos, flowerStates); @@ -58,7 +48,7 @@ public boolean isGoodBiome(Holder biome) { return super.isGoodBiome(biome) && !biome.is(Tags.Biomes.IS_SNOWY); } }, - MEADOWS(ApicultureBlocks.BEEHIVE.get(BlockHiveType.MEADOWS).defaultState(), 1.0f, ForestryBeeSpecies.MEADOWS, new HiveGenGround(BlockTags.DIRT)) { + MEADOWS(ApicultureBlocks.BEEHIVE.get(BlockHiveType.MEADOWS).defaultState(), 1.0f, ForestryBeeSpecies.MEADOWS, new HivePlacementGround(BlockTags.DIRT)) { @Override public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { postGenFlowers(level, rand, pos, flowerStates); @@ -70,20 +60,20 @@ public boolean isGoodBiome(Holder biome) { return super.isGoodBiome(biome) && !biome.is(BiomeTags.IS_FOREST); } }, - DESERT(ApicultureBlocks.BEEHIVE.get(BlockHiveType.DESERT).defaultState(), 1.0f, ForestryBeeSpecies.MODEST, new HiveGenGround(ForestryTags.Blocks.MODEST_BEE_GROUND)) { + DESERT(ApicultureBlocks.BEEHIVE.get(BlockHiveType.DESERT).defaultState(), 1.0f, ForestryBeeSpecies.MODEST, new HivePlacementGround(ForestryTags.Blocks.MODEST_BEE_GROUND)) { @Override public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { postGenFlowers(level, rand, pos, cactusStates); } }, - JUNGLE(ApicultureBlocks.BEEHIVE.get(BlockHiveType.JUNGLE).defaultState(), 6.0f, ForestryBeeSpecies.TROPICAL, HiveGenTree.INSTANCE), - END(ApicultureBlocks.BEEHIVE.get(BlockHiveType.END).defaultState(), 2.0f, ForestryBeeSpecies.ENDED, new HiveGenGround(ForestryTags.Blocks.ENDED_BEE_GROUND)) { + JUNGLE(ApicultureBlocks.BEEHIVE.get(BlockHiveType.JUNGLE).defaultState(), 6.0f, ForestryBeeSpecies.TROPICAL, HivePlacementTree.INSTANCE), + END(ApicultureBlocks.BEEHIVE.get(BlockHiveType.END).defaultState(), 2.0f, ForestryBeeSpecies.ENDED, new HivePlacementGround(ForestryTags.Blocks.ENDED_BEE_GROUND)) { @Override public boolean isGoodBiome(Holder biome) { return biome.is(BiomeTags.IS_END); } }, - SNOW(ApicultureBlocks.BEEHIVE.get(BlockHiveType.SNOW).defaultState(), 2.0f, ForestryBeeSpecies.WINTRY, new HiveGenGround(ForestryTags.Blocks.WINTRY_BEE_GROUND)) { + SNOW(ApicultureBlocks.BEEHIVE.get(BlockHiveType.SNOW).defaultState(), 2.0f, ForestryBeeSpecies.WINTRY, new HivePlacementGround(ForestryTags.Blocks.WINTRY_BEE_GROUND)) { @Override public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { BlockPos posAbove = pos.above(); @@ -94,7 +84,7 @@ public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { postGenFlowers(level, rand, pos, flowerStates); } }, - SWAMP(ApicultureBlocks.BEEHIVE.get(BlockHiveType.SWAMP).defaultState(), 2.0f, ForestryBeeSpecies.MARSHY, new HiveGenGround(BlockTags.DIRT)) { + SWAMP(ApicultureBlocks.BEEHIVE.get(BlockHiveType.SWAMP).defaultState(), 2.0f, ForestryBeeSpecies.MARSHY, new HivePlacementGround(BlockTags.DIRT)) { @Override public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { postGenFlowers(level, rand, pos, mushroomStates); @@ -106,14 +96,14 @@ public boolean isGoodBiome(Holder biome) { return super.isGoodBiome(biome) && !biome.is(Tags.Biomes.IS_SNOWY); } }, - SAVANNA(ApicultureBlocks.BEEHIVE.get(BlockHiveType.SAVANNA).defaultState(), 1.0f, ForestryBeeSpecies.SAVANNA, new HiveGenGround(BlockTags.DIRT)) { + SAVANNA(ApicultureBlocks.BEEHIVE.get(BlockHiveType.SAVANNA).defaultState(), 1.0f, ForestryBeeSpecies.SAVANNA, new HivePlacementGround(BlockTags.DIRT)) { @Override public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { //TODO: generate pumpkins in dry biomes and melons in normal ones //postGenFlowers(world,rand,pos,flowerStates); } }, - LUSH(ApicultureBlocks.BEEHIVE.get(BlockHiveType.LUSH).defaultState(), 2.0F, ForestryBeeSpecies.LUSH, new HiveGenCaveCeiling(ForestryTags.Blocks.LUSH_BEE_CEILING, ForestryTags.Blocks.CAVE_EXTRA_REPLACEABLES)) { + LUSH(ApicultureBlocks.BEEHIVE.get(BlockHiveType.LUSH).defaultState(), 2.0F, ForestryBeeSpecies.LUSH, new HivePlacementCaveCeiling(ForestryTags.Blocks.LUSH_BEE_CEILING, ForestryTags.Blocks.CAVE_EXTRA_REPLACEABLES)) { @Override public boolean isGoodBiome(Holder biome) { return super.isGoodBiome(biome) && biome.is(Tags.Biomes.IS_CAVE); @@ -126,7 +116,7 @@ public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { } } }, - AQUATIC(ApicultureBlocks.BEEHIVE.get(BlockHiveType.AQUATIC).defaultState(), 1.0F, ForestryBeeSpecies.AQUATIC, new HiveGenOcean(BlockTags.SAND)) { + AQUATIC(ApicultureBlocks.BEEHIVE.get(BlockHiveType.AQUATIC).defaultState(), 1.0F, ForestryBeeSpecies.AQUATIC, new HivePlacementOcean(BlockTags.SAND)) { @Override public boolean isGoodBiome(Holder biome) { return biome.is(Biomes.WARM_OCEAN); @@ -148,7 +138,7 @@ public void postGen(WorldGenLevel level, RandomSource rand, BlockPos pos) { } } }, - NETHER(ApicultureBlocks.BEEHIVE.get(BlockHiveType.NETHER).defaultState(), 4.0F, ForestryBeeSpecies.EMBITTERED, new HiveGenCaveCeiling(BlockTags.WART_BLOCKS, ForestryTags.Blocks.NETHER_EXTRA_REPLACEABLES)) { + NETHER(ApicultureBlocks.BEEHIVE.get(BlockHiveType.NETHER).defaultState(), 4.0F, ForestryBeeSpecies.EMBITTERED, new HivePlacementCaveCeiling(BlockTags.WART_BLOCKS, ForestryTags.Blocks.NETHER_EXTRA_REPLACEABLES)) { @Override public boolean isGoodBiome(Holder biome) { return biome.is(BiomeTags.IS_NETHER); @@ -156,7 +146,7 @@ public boolean isGoodBiome(Holder biome) { }, ; - private static final IHiveGen FLOWER_GROUND = new HiveGenGround(ForestryTags.Blocks.PLANTABLE_FLOWERS_GROUND); + private static final IHivePlacement FLOWER_GROUND = new HivePlacementGround(ForestryTags.Blocks.PLANTABLE_FLOWERS_GROUND); private static final List flowerStates = new ArrayList<>(); private static final List mushroomStates = new ArrayList<>(); private static final List cactusStates = Collections.singletonList(Blocks.CACTUS.defaultBlockState()); @@ -171,9 +161,9 @@ public boolean isGoodBiome(Holder biome) { private final BlockState blockState; private final float genChance; private final ResourceLocation speciesId; - private final IHiveGen hiveGen; + private final IHivePlacement hiveGen; - HiveDefinition(BlockState hiveState, float genChance, ResourceLocation beeTemplate, IHiveGen hiveGen) { + HiveDefinition(BlockState hiveState, float genChance, ResourceLocation beeTemplate, IHivePlacement hiveGen) { this.blockState = hiveState; this.genChance = genChance; this.speciesId = beeTemplate; @@ -181,7 +171,7 @@ public boolean isGoodBiome(Holder biome) { } @Override - public IHiveGen getHiveGen() { + public IHivePlacement getHiveGen() { return this.hiveGen; } diff --git a/src/main/java/forestry/apiculture/hives/HiveDefinitionSwarmer.java b/src/main/java/forestry/apiculture/hives/HiveDefinitionSwarmer.java index 34ade24f23..e1ce84e222 100644 --- a/src/main/java/forestry/apiculture/hives/HiveDefinitionSwarmer.java +++ b/src/main/java/forestry/apiculture/hives/HiveDefinitionSwarmer.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.hives; import forestry.api.ForestryTags; import forestry.api.apiculture.hives.IHiveDefinition; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.api.core.HumidityType; import forestry.api.core.TemperatureType; import forestry.apiculture.blocks.BlockHiveType; @@ -38,8 +28,8 @@ public HiveDefinitionSwarmer(ItemStack... bees) { } @Override - public IHiveGen getHiveGen() { - return new HiveGenGround(ForestryTags.Blocks.SWARM_BEE_GROUND); + public IHivePlacement getHiveGen() { + return new HivePlacementGround(ForestryTags.Blocks.SWARM_BEE_GROUND); } @Override diff --git a/src/main/java/forestry/apiculture/hives/HiveGenCaveCeiling.java b/src/main/java/forestry/apiculture/hives/HivePlacementCaveCeiling.java similarity index 90% rename from src/main/java/forestry/apiculture/hives/HiveGenCaveCeiling.java rename to src/main/java/forestry/apiculture/hives/HivePlacementCaveCeiling.java index ec6216cc8c..d2a8324f08 100644 --- a/src/main/java/forestry/apiculture/hives/HiveGenCaveCeiling.java +++ b/src/main/java/forestry/apiculture/hives/HivePlacementCaveCeiling.java @@ -1,6 +1,6 @@ package forestry.apiculture.hives; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.core.utils.BlockUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -14,11 +14,11 @@ import javax.annotation.Nullable; import java.util.ArrayList; -public class HiveGenCaveCeiling implements IHiveGen { +public class HivePlacementCaveCeiling implements IHivePlacement { private final TagKey blocks; private final TagKey extraReplaceable; - public HiveGenCaveCeiling(TagKey blocks, TagKey extraReplaceable) { + public HivePlacementCaveCeiling(TagKey blocks, TagKey extraReplaceable) { this.blocks = blocks; this.extraReplaceable = extraReplaceable; } diff --git a/src/main/java/forestry/apiculture/hives/HiveGenGround.java b/src/main/java/forestry/apiculture/hives/HivePlacementGround.java similarity index 84% rename from src/main/java/forestry/apiculture/hives/HiveGenGround.java rename to src/main/java/forestry/apiculture/hives/HivePlacementGround.java index e454283d37..145c1ba439 100644 --- a/src/main/java/forestry/apiculture/hives/HiveGenGround.java +++ b/src/main/java/forestry/apiculture/hives/HivePlacementGround.java @@ -1,6 +1,6 @@ package forestry.apiculture.hives; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.core.utils.BlockUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -10,10 +10,10 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.Heightmap; -public class HiveGenGround implements IHiveGen { +public class HivePlacementGround implements IHivePlacement { private final TagKey blocks; - public HiveGenGround(TagKey blocks) { + public HivePlacementGround(TagKey blocks) { this.blocks = blocks; } @@ -47,7 +47,7 @@ public Heightmap.Types getHeightmapType() { @Override public boolean canReplace(BlockState blockState, WorldGenLevel world, BlockPos pos) { - return IHiveGen.isTreeBlock(blockState) || BlockUtil.canReplace(blockState, world, pos); + return IHivePlacement.isTreeBlock(blockState) || BlockUtil.canReplace(blockState, world, pos); } @Override diff --git a/src/main/java/forestry/apiculture/hives/HiveGenOcean.java b/src/main/java/forestry/apiculture/hives/HivePlacementOcean.java similarity index 84% rename from src/main/java/forestry/apiculture/hives/HiveGenOcean.java rename to src/main/java/forestry/apiculture/hives/HivePlacementOcean.java index 6ce0fcb299..01bb9c36a6 100644 --- a/src/main/java/forestry/apiculture/hives/HiveGenOcean.java +++ b/src/main/java/forestry/apiculture/hives/HivePlacementOcean.java @@ -8,8 +8,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.Heightmap; -public class HiveGenOcean extends HiveGenGround { - public HiveGenOcean(TagKey blocks) { +public class HivePlacementOcean extends HivePlacementGround { + public HivePlacementOcean(TagKey blocks) { super(blocks); } diff --git a/src/main/java/forestry/apiculture/hives/HiveGenTree.java b/src/main/java/forestry/apiculture/hives/HivePlacementTree.java similarity index 66% rename from src/main/java/forestry/apiculture/hives/HiveGenTree.java rename to src/main/java/forestry/apiculture/hives/HivePlacementTree.java index 31ddef0eb8..0344252aed 100644 --- a/src/main/java/forestry/apiculture/hives/HiveGenTree.java +++ b/src/main/java/forestry/apiculture/hives/HivePlacementTree.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.hives; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.core.utils.BlockUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -19,7 +9,7 @@ import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.levelgen.Heightmap; -public enum HiveGenTree implements IHiveGen { +public enum HivePlacementTree implements IHivePlacement { INSTANCE; @Override @@ -31,7 +21,7 @@ public boolean canReplace(BlockState blockState, WorldGenLevel world, BlockPos p public boolean isValidLocation(WorldGenLevel world, BlockPos pos) { BlockPos posAbove = pos.above(); BlockState blockStateAbove = world.getBlockState(posAbove); - if (!IHiveGen.isTreeBlock(blockStateAbove)) { + if (!IHivePlacement.isTreeBlock(blockStateAbove)) { return false; } @@ -56,7 +46,7 @@ public BlockPos getPosForHive(WorldGenLevel level, int posX, int posZ) { BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(posX, height, posZ); BlockState state = chunk.getBlockState(pos); - if (!IHiveGen.isTreeBlock(state)) { + if (!IHivePlacement.isTreeBlock(state)) { return null; } @@ -64,7 +54,7 @@ public BlockPos getPosForHive(WorldGenLevel level, int posX, int posZ) { do { pos.move(Direction.DOWN); state = chunk.getBlockState(pos); - } while (IHiveGen.isTreeBlock(state)); + } while (IHivePlacement.isTreeBlock(state)); return pos.immutable(); } diff --git a/src/main/java/forestry/apiculture/hives/package-info.java b/src/main/java/forestry/apiculture/hives/package-info.java index d33dc7c09b..f948a3e475 100644 --- a/src/main/java/forestry/apiculture/hives/package-info.java +++ b/src/main/java/forestry/apiculture/hives/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.hives; diff --git a/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java b/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java index babac89b32..8c4b4ae55d 100644 --- a/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java +++ b/src/main/java/forestry/apiculture/inventory/IApiaryInventory.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.inventory; import forestry.api.apiculture.IBeeHousing; diff --git a/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java b/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java index 3a8fc04dfa..a16651b431 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.inventory; import forestry.apiculture.multiblock.TileAlvearySieve; diff --git a/src/main/java/forestry/apiculture/inventory/InventoryApiary.java b/src/main/java/forestry/apiculture/inventory/InventoryApiary.java index 580a3c92c7..d9b6e29b33 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryApiary.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryApiary.java @@ -1,28 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.inventory; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import forestry.api.apiculture.hives.IHiveFrame; -import forestry.api.genetics.IIndividual; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.apiculture.InventoryBeeHousing; import forestry.core.utils.SlotUtil; -import net.minecraft.util.Tuple; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import java.util.ArrayList; -import java.util.Collection; +import java.util.function.BiConsumer; public class InventoryApiary extends InventoryBeeHousing implements IApiaryInventory { public static final int SLOT_FRAMES_1 = 9; @@ -48,34 +35,26 @@ public boolean canPlaceItem(int slotIndex, ItemStack itemStack) { super.canPlaceItem(slotIndex, itemStack); } - public Collection> getFrames() { - Collection> hiveFrames = new ArrayList<>(SLOT_FRAMES_COUNT); - + public void forEachFrame(BiConsumer action) { for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { ItemStack stackInSlot = getItem(i); Item itemInSlot = stackInSlot.getItem(); + if (itemInSlot instanceof IHiveFrame frame) { - hiveFrames.add(new Tuple<>(frame, stackInSlot.copy())); + action.accept(frame, stackInSlot); } } - - return hiveFrames; } @Override public void wearOutFrames(IBeeHousing beeHousing, int amount) { - //IBeekeepingMode beekeepingMode = SpeciesUtil.BEE_TYPE.get().getBeekeepingMode(beeHousing.getWorldObj()); - int wear = amount; /* Math.round(amount * beekeepingMode.getWearModifier())*/ - - for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { - ItemStack hiveFrameStack = getItem(i); - Item hiveFrameItem = hiveFrameStack.getItem(); - - if (hiveFrameItem instanceof IHiveFrame hiveFrame) { - IIndividual queen = IIndividualHandlerItem.getIndividual(getQueen()); + if (IIndividualHandlerItem.getIndividual(getQueen()) instanceof IBee queen) { + for (int i = SLOT_FRAMES_1; i < SLOT_FRAMES_1 + SLOT_FRAMES_COUNT; i++) { + ItemStack hiveFrameStack = getItem(i); + Item hiveFrameItem = hiveFrameStack.getItem(); - if (queen != null) { - ItemStack usedFrame = hiveFrame.frameUsed(beeHousing, hiveFrameStack, (IBee) queen, wear); + if (hiveFrameItem instanceof IHiveFrame hiveFrame) { + ItemStack usedFrame = hiveFrame.frameUsed(beeHousing, hiveFrameStack, queen, amount); setItem(i, usedFrame); } } diff --git a/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java b/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java index 5d5678b46c..d27358263d 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryHygroregulator.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.inventory; import forestry.apiculture.multiblock.TileAlvearyHygroregulator; import forestry.core.inventory.InventoryAdapterTile; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.Optional; diff --git a/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java b/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java index f4877d83e4..c6de33eed9 100644 --- a/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java +++ b/src/main/java/forestry/apiculture/inventory/InventorySwarmer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.inventory; import forestry.api.IForestryApi; diff --git a/src/main/java/forestry/apiculture/inventory/package-info.java b/src/main/java/forestry/apiculture/inventory/package-info.java index 249e52b611..625bb1706b 100644 --- a/src/main/java/forestry/apiculture/inventory/package-info.java +++ b/src/main/java/forestry/apiculture/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.inventory; diff --git a/src/main/java/forestry/apiculture/items/EnumHoneyComb.java b/src/main/java/forestry/apiculture/items/EnumHoneyComb.java index 57ae90ba99..e65f4ad2c9 100644 --- a/src/main/java/forestry/apiculture/items/EnumHoneyComb.java +++ b/src/main/java/forestry/apiculture/items/EnumHoneyComb.java @@ -1,23 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; import forestry.api.core.IBlockSubtype; import forestry.api.core.IItemSubtype; -import net.minecraft.util.StringRepresentable; import java.awt.*; import java.util.Locale; -public enum EnumHoneyComb implements StringRepresentable, IItemSubtype, IBlockSubtype { +public enum EnumHoneyComb implements IItemSubtype, IBlockSubtype { HONEY(new Color(0xe8d56a), new Color(0xffa12b)), COCOA(new Color(0x674016), new Color(0xffb62b)), SIMMERING(new Color(0x981919), new Color(0xFE8738)), @@ -35,37 +24,20 @@ public enum EnumHoneyComb implements StringRepresentable, IItemSubtype, IBlockSu VINTAGE(new Color(0xDEB887), new Color(0xCD853F)), SPONGE(new Color(0x9D8F39), new Color(0xe1e351)), SCULKEN(new Color(0x111B21), new Color(0x05625d)), - //LUMINOUS(new Color(0x495E27), new Color(0xF7CE46)); ; - //""(new Color(0xd7bee5), new Color(0xfd58ab)); // kindof pinkish - - public static final EnumHoneyComb[] VALUES = values(); public final String name; public final int primaryColor; public final int secondaryColor; - private final boolean unused; EnumHoneyComb(Color primary, Color secondary) { - this(primary, secondary, false); - } - - EnumHoneyComb(Color primary, Color secondary, boolean unused) { - this.unused = unused; this.name = toString().toLowerCase(Locale.ENGLISH); this.primaryColor = primary.getRGB(); this.secondaryColor = secondary.getRGB(); } @Override - public String getSerializedName() { + public String identifier() { return this.name; } - - public static EnumHoneyComb get(int meta) { - if (meta >= VALUES.length) { - meta = 0; - } - return VALUES[meta]; - } } diff --git a/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java b/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java deleted file mode 100644 index 699b55df27..0000000000 --- a/src/main/java/forestry/apiculture/items/EnumHoneyDrop.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import forestry.core.items.ItemOverlay; - -import java.awt.*; -import java.util.Locale; - -public enum EnumHoneyDrop implements ItemOverlay.IOverlayInfo { - HONEY(new Color(0xecb42d), new Color(0xe8c814)); - - private final String name; - private final int primaryColor; - private final int secondaryColor; - - EnumHoneyDrop(Color primary, Color secondary) { - this.name = toString().toLowerCase(Locale.ENGLISH); - this.primaryColor = primary.getRGB(); - this.secondaryColor = secondary.getRGB(); - } - - @Override - public String getSerializedName() { - return this.name; - } - - @Override - public int getPrimaryColor() { - return this.primaryColor; - } - - @Override - public int getSecondaryColor() { - return this.secondaryColor; - } -} diff --git a/src/main/java/forestry/apiculture/items/EnumPollenCluster.java b/src/main/java/forestry/apiculture/items/EnumPollenCluster.java index c1e6df26ee..942bdb04c4 100644 --- a/src/main/java/forestry/apiculture/items/EnumPollenCluster.java +++ b/src/main/java/forestry/apiculture/items/EnumPollenCluster.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; import forestry.core.items.ItemOverlay; diff --git a/src/main/java/forestry/apiculture/items/EnumPropolis.java b/src/main/java/forestry/apiculture/items/EnumPropolis.java index d01064a601..600fbf65d8 100644 --- a/src/main/java/forestry/apiculture/items/EnumPropolis.java +++ b/src/main/java/forestry/apiculture/items/EnumPropolis.java @@ -1,44 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; import forestry.core.items.ItemOverlay; -import java.awt.*; import java.util.Locale; public enum EnumPropolis implements ItemOverlay.IOverlayInfo { - NORMAL(new Color(0xc5b24e)), - PULSATING(new Color(0x2ccdb1)), - SILKY(new Color(0xddff00)), - VOLCANIC(new Color(0xE84528)); - - public static final EnumPropolis[] VALUES = values(); + NORMAL(0xc5b24e), + PULSATING(0x2ccdb1), + SILKY(0xddff00), + VOLCANIC(0xE84528); private final String name; - private final int primaryColor; + private final int color; - EnumPropolis(Color color) { + EnumPropolis(int color) { this.name = toString().toLowerCase(Locale.ENGLISH); - this.primaryColor = color.getRGB(); + this.color = color; } @Override - public String getSerializedName() { + public String identifier() { return this.name; } @Override public int getPrimaryColor() { - return this.primaryColor; + return this.color; } @Override diff --git a/src/main/java/forestry/apiculture/items/ItemAmbrosia.java b/src/main/java/forestry/apiculture/items/ItemAmbrosia.java index 83a2c51780..80440670a7 100644 --- a/src/main/java/forestry/apiculture/items/ItemAmbrosia.java +++ b/src/main/java/forestry/apiculture/items/ItemAmbrosia.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; import forestry.core.config.Constants; @@ -19,20 +9,18 @@ import net.minecraft.world.item.ItemStack; public class ItemAmbrosia extends ItemForestryFood { - public ItemAmbrosia() { super(new Item.Properties() .food(new FoodProperties.Builder() - .alwaysEat() + .alwaysEdible() .nutrition(Constants.FOOD_AMBROSIA_HEAL) - .saturationMod(0.6f) - .effect(new MobEffectInstance(MobEffects.REGENERATION, 40, 0), 1.0F) + .saturationModifier(0.6f) + .effect(() -> new MobEffectInstance(MobEffects.REGENERATION, 40, 0), 1f) .build())); } @Override - public boolean isFoil(ItemStack itemstack) { + public boolean isFoil(ItemStack stack) { return true; } - } diff --git a/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java b/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java index 9bec266f0f..97b69cd9da 100755 --- a/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java +++ b/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java @@ -1,100 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; -import forestry.api.ForestryCapabilities; import forestry.api.ForestryConstants; -import forestry.api.apiculture.IArmorApiarist; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.IBeeProtection; +import forestry.apiculture.features.ApicultureArmorMaterials; import forestry.apiculture.features.ApicultureItems; import forestry.core.config.Constants; -import forestry.core.features.CoreItems; -import forestry.core.items.definitions.EnumCraftingMaterial; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ArmorItem; -import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; -import org.jetbrains.annotations.Nullable; public class ItemArmorApiarist extends ArmorItem { public static final String TEXTURE_APIARIST_ARMOR_PRIMARY = ForestryConstants.MOD_ID + ":" + Constants.TEXTURE_PATH_ITEM + "/apiarist_armor_1.png"; public static final String TEXTURE_APIARIST_ARMOR_SECONDARY = ForestryConstants.MOD_ID + ":" + Constants.TEXTURE_PATH_ITEM + "/apiarist_armor_2.png"; - - public static final class ApiaristArmorMaterial implements ArmorMaterial { - private static final int[] reductions = new int[]{1, 3, 2, 1}; - private static final int[] DURABILITY = new int[]{11 * 3, 16 * 3, 15 * 3, 13 * 3}; - - @Override - public int getDurabilityForType(ArmorItem.Type type) { - return DURABILITY[type.ordinal()]; - } - - @Override - public int getDefenseForType(ArmorItem.Type type) { - return reductions[type.ordinal()]; - } - - @Override - public int getEnchantmentValue() { - return 15; - } - - @Override - public SoundEvent getEquipSound() { - return SoundEvents.ARMOR_EQUIP_LEATHER; - } - - @Override - public Ingredient getRepairIngredient() { - return Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK).get()); - } - - @Override - public String getName() { - return "APIARIST_ARMOR"; - } - - @Override - public float getToughness() { - return 0.0F; - } - - @Override - public float getKnockbackResistance() { - return 0.0F; - } - } - - public enum ArmorApiarist implements IArmorApiarist { - INSTANCE; - - @Override - public boolean protectEntity(LivingEntity entity, ItemStack armor, @Nullable IBeeEffect cause, boolean doProtect) { - return true; - } - } + public static final IBeeProtection PROTECTION = (entity, armor, cause, execute) -> true; public ItemArmorApiarist(ArmorItem.Type type) { - super(new ApiaristArmorMaterial(), type, new Item.Properties()); + super(ApicultureArmorMaterials.APIARIST, type, new Item.Properties().durability(type.getDurability(3))); } @Override @@ -105,14 +28,4 @@ public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot return TEXTURE_APIARIST_ARMOR_PRIMARY; } } - - @Override - public @Nullable ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) { - return new ICapabilityProvider() { - @Override - public LazyOptional getCapability(Capability cap, @Nullable Direction side) { - return cap == ForestryCapabilities.ARMOR_APIARIST ? LazyOptional.of(() -> ArmorApiarist.INSTANCE).cast() : LazyOptional.empty(); - } - }; - } } diff --git a/src/main/java/forestry/apiculture/items/ItemBeeGE.java b/src/main/java/forestry/apiculture/items/ItemBeeGE.java index 2c810ac95e..bf8e3f7874 100755 --- a/src/main/java/forestry/apiculture/items/ItemBeeGE.java +++ b/src/main/java/forestry/apiculture/items/ItemBeeGE.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.core.genetics.ItemGE; @@ -45,18 +35,12 @@ protected IBeeSpecies getSpecies(ItemStack stack) { @Override public void appendHoverText(ItemStack stack, @Nullable Level level, List list, TooltipFlag flag) { - if (!stack.hasTag()) { - return; - } - - if (this.stage != BeeLifeStage.DRONE) { - IIndividualHandlerItem.ifPresent(stack, individual -> { - if (((IBee) individual).isPristine()) { - list.add(Component.translatable("for.bees.stock.pristine").withStyle(ChatFormatting.YELLOW, ChatFormatting.ITALIC)); - } else { - list.add(Component.translatable("for.bees.stock.ignoble").withStyle(ChatFormatting.YELLOW)); - } - }); + if (this.stage != BeeLifeStage.DRONE && IIndividualHandlerItem.getIndividual(stack) instanceof IBee bee) { + if (bee.isPristine()) { + list.add(Component.translatable("for.bees.stock.pristine").withStyle(ChatFormatting.YELLOW, ChatFormatting.ITALIC)); + } else { + list.add(Component.translatable("for.bees.stock.ignoble").withStyle(ChatFormatting.YELLOW)); + } } super.appendHoverText(stack, level, list, flag); @@ -64,27 +48,14 @@ public void appendHoverText(ItemStack stack, @Nullable Level level, List species.getStripes(); - case 1 -> species.getBody(); - case 0 -> species.getOutline(); - default -> 0xffffff; - }; - } + return switch (tintIndex) { + case 2 -> species.getStripes(); + case 1 -> species.getBody(); + case 0 -> species.getOutline(); + default -> 0xffffff; + }; } public final BeeLifeStage getStage() { diff --git a/src/main/java/forestry/apiculture/items/ItemBeesWax.java b/src/main/java/forestry/apiculture/items/ItemBeesWax.java deleted file mode 100644 index 50a2460301..0000000000 --- a/src/main/java/forestry/apiculture/items/ItemBeesWax.java +++ /dev/null @@ -1,10 +0,0 @@ -package forestry.apiculture.items; - -import net.minecraft.world.item.HoneycombItem; - -// Reuse the behavior from HoneycombItem -public class ItemBeesWax extends HoneycombItem { - public ItemBeesWax() { - super(new Properties()); - } -} diff --git a/src/main/java/forestry/apiculture/items/ItemBlockHoneyComb.java b/src/main/java/forestry/apiculture/items/ItemBlockHoneyComb.java index 3f71b9f1f8..231cb443d4 100644 --- a/src/main/java/forestry/apiculture/items/ItemBlockHoneyComb.java +++ b/src/main/java/forestry/apiculture/items/ItemBlockHoneyComb.java @@ -14,10 +14,6 @@ public ItemBlockHoneyComb(BlockHoneyComb block) { @Override public int getColorFromItemStack(ItemStack stack, int tintIndex) { EnumHoneyComb honeyComb = getBlock().getType(); - if (tintIndex == 1) { - return honeyComb.primaryColor; - } else { - return honeyComb.secondaryColor; - } + return tintIndex == 1 ? honeyComb.primaryColor : honeyComb.secondaryColor; } } diff --git a/src/main/java/forestry/apiculture/items/ItemCreativeHiveFrame.java b/src/main/java/forestry/apiculture/items/ItemCreativeHiveFrame.java index 2f80875f06..aad05eadc5 100644 --- a/src/main/java/forestry/apiculture/items/ItemCreativeHiveFrame.java +++ b/src/main/java/forestry/apiculture/items/ItemCreativeHiveFrame.java @@ -1,32 +1,43 @@ package forestry.apiculture.items; -import java.util.List; - -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Rarity; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; - import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.apiculture.hives.IHiveFrame; +import forestry.api.core.IItemSubtype; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutation; import forestry.core.items.ItemForestry; - +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Rarity; +import net.minecraft.world.item.TooltipFlag; import org.jetbrains.annotations.Nullable; +import java.util.List; +import java.util.Locale; + // 100% mutation chance. 100% production chance. 0% lifespan. public class ItemCreativeHiveFrame extends ItemForestry implements IHiveFrame { - public static final String NBT_FORCE_MUTATIONS = "force_mutations"; + private final Variant variant; - public ItemCreativeHiveFrame() { + public enum Variant implements IItemSubtype { + FRAME_CREATIVE, + FRAME_CREATIVE_FORCE_MUTATIONS; + + @Override + public String identifier() { + return name().toLowerCase(Locale.ENGLISH); + } + } + + public ItemCreativeHiveFrame(Variant variant) { super(new Item.Properties().rarity(Rarity.EPIC)); + + this.variant = variant; } @Override @@ -35,13 +46,13 @@ public ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int } @Override - public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag advanced) { - super.appendHoverText(stack, world, tooltip, advanced); + public void appendHoverText(ItemStack stack, TooltipContext ctx, List tooltip, TooltipFlag advanced) { + super.appendHoverText(stack, ctx, tooltip, advanced); tooltip.add(Component.translatable("item.forestry.bee.modifier.production", Modifier.PRODUCTION)); tooltip.add(Component.translatable("item.forestry.bee.modifier.genetic.decay", Modifier.GENETIC_DECAY)); - if (hasForceMutations(stack)) { + if (hasForceMutations()) { tooltip.add(Component.literal("Maximum mutation chances").withStyle(ChatFormatting.LIGHT_PURPLE)); } else { tooltip.add(Component.literal("Base mutation chances").withStyle(ChatFormatting.GRAY)); @@ -50,11 +61,11 @@ public void appendHoverText(ItemStack stack, @Nullable Level world, List broken.setTrue()); + + if (broken.isTrue()) { return ItemStack.EMPTY; } else { return frame; @@ -50,39 +47,28 @@ public ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int @Override public IBeeModifier getBeeModifier(ItemStack frame) { - return this.beeModifier; + return this; } @Override public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag advanced) { super.appendHoverText(stack, world, tooltip, advanced); - this.beeModifier.addInformation(tooltip); + + tooltip.add(Component.translatable("item.forestry.bee.modifier.production", PRODUCTION_MODIFIER)); + tooltip.add(Component.translatable("item.forestry.bee.modifier.genetic.decay", this.geneticDecay)); + if (!stack.isDamaged()) { tooltip.add(Component.translatable("item.forestry.durability", stack.getMaxDamage())); } } - private static class HiveFrameBeeModifier implements IBeeModifier { - private static final float production = 2f; - private final float geneticDecay; - - public HiveFrameBeeModifier(float geneticDecay) { - this.geneticDecay = geneticDecay; - } - - @Override - public float modifyProductionSpeed(IGenome genome, float currentSpeed) { - return currentSpeed < 10f ? currentSpeed * production : 1f; - } - - @Override - public float modifyGeneticDecay(IGenome genome, float currentDecay) { - return this.geneticDecay; - } + @Override + public float modifyProductionSpeed(IGenome genome, float currentSpeed) { + return currentSpeed < 10f ? currentSpeed * PRODUCTION_MODIFIER : 1f; + } - public void addInformation(List tooltip) { - tooltip.add(Component.translatable("item.forestry.bee.modifier.production", production)); - tooltip.add(Component.translatable("item.forestry.bee.modifier.genetic.decay", this.geneticDecay)); - } + @Override + public float modifyGeneticDecay(IGenome genome, float currentDecay) { + return currentDecay * this.geneticDecay; } } diff --git a/src/main/java/forestry/apiculture/items/ItemHoneyComb.java b/src/main/java/forestry/apiculture/items/ItemHoneyComb.java index b827d7bf9a..e2654ca752 100755 --- a/src/main/java/forestry/apiculture/items/ItemHoneyComb.java +++ b/src/main/java/forestry/apiculture/items/ItemHoneyComb.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; import forestry.core.items.ItemForestry; diff --git a/src/main/java/forestry/apiculture/items/ItemPollenCluster.java b/src/main/java/forestry/apiculture/items/ItemPollenCluster.java deleted file mode 100644 index eb62c46b4a..0000000000 --- a/src/main/java/forestry/apiculture/items/ItemPollenCluster.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import forestry.api.core.ItemGroups; -import forestry.core.items.ItemOverlay; - -public class ItemPollenCluster extends ItemOverlay { - public ItemPollenCluster(EnumPollenCluster type) { - super(ItemGroups.tabApiculture, type); - } -} diff --git a/src/main/java/forestry/apiculture/items/ItemPropolis.java b/src/main/java/forestry/apiculture/items/ItemPropolis.java deleted file mode 100644 index c312ee2e3a..0000000000 --- a/src/main/java/forestry/apiculture/items/ItemPropolis.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import forestry.api.core.ItemGroups; -import forestry.core.items.ItemOverlay; - -//TODO - create common superclass for items/blocks defined by an enum. -//Will help with automatic creation of stuff too. -public class ItemPropolis extends ItemOverlay { - - private final EnumPropolis type; - - public ItemPropolis(EnumPropolis type) { - super(ItemGroups.tabApiculture, type); - this.type = type; - } -} diff --git a/src/main/java/forestry/apiculture/items/ItemRefractoryWax.java b/src/main/java/forestry/apiculture/items/ItemRefractoryWax.java index a881a7e8cb..cfe854f464 100644 --- a/src/main/java/forestry/apiculture/items/ItemRefractoryWax.java +++ b/src/main/java/forestry/apiculture/items/ItemRefractoryWax.java @@ -6,6 +6,7 @@ import forestry.core.utils.NetworkUtil; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; @@ -35,8 +36,8 @@ public InteractionResult useOn(UseOnContext context) { stack.shrink(1); level.setBlock(pos, waxedState, 11); level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(player, waxedState)); - if (!level.isClientSide) { - NetworkUtil.sendNetworkPacket(new PacketRefractoryWax(pos), pos, level); + if (level instanceof ServerLevel serverLevel) { + NetworkUtil.sendToPlayersTrackingPos(new PacketRefractoryWax(pos), pos, serverLevel); } return InteractionResult.sidedSuccess(level.isClientSide); diff --git a/src/main/java/forestry/apiculture/items/ItemScoop.java b/src/main/java/forestry/apiculture/items/ItemScoop.java index f487301bc1..8636b9a48e 100644 --- a/src/main/java/forestry/apiculture/items/ItemScoop.java +++ b/src/main/java/forestry/apiculture/items/ItemScoop.java @@ -1,21 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.items; import forestry.api.ForestryTags; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.core.items.ItemForestry; import forestry.core.utils.SpeciesUtil; -import net.minecraft.core.BlockPos; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; @@ -47,17 +36,12 @@ public float getDestroySpeed(ItemStack itemstack, BlockState state) { @Override public boolean hurtEnemy(ItemStack stack, LivingEntity entity, LivingEntity player) { - stack.hurtAndBreak(2, player, (living) -> living.broadcastBreakEvent(EquipmentSlot.MAINHAND)); return true; } @Override - public boolean mineBlock(ItemStack stack, Level world, BlockState blockState, BlockPos pos, LivingEntity player) { - if (!world.isClientSide && blockState.getDestroySpeed(world, pos) != 0.0F) { - stack.hurtAndBreak(1, player, (living) -> living.broadcastBreakEvent(EquipmentSlot.MAINHAND)); - } - - return true; + public void postHurtEnemy(ItemStack stack, LivingEntity target, LivingEntity attacker) { + stack.hurtAndBreak(2, attacker, EquipmentSlot.MAINHAND); } @Override @@ -70,7 +54,7 @@ public InteractionResult interactLivingEntity(ItemStack stack, Player player, Li level.addFreshEntity(bee); level.playSound(null, interactionTarget.blockPosition(), SoundEvents.BEE_HURT, SoundSource.PLAYERS, 1f, 1f); interactionTarget.setRemoved(Entity.RemovalReason.DISCARDED); - stack.hurtAndBreak(1, player, living -> living.broadcastBreakEvent(usedHand)); + stack.hurtAndBreak(1, player, LivingEntity.getSlotForHand(usedHand)); } return InteractionResult.sidedSuccess(player.level().isClientSide()); } diff --git a/src/main/java/forestry/apiculture/items/ItemSmoker.java b/src/main/java/forestry/apiculture/items/ItemSmoker.java index ced5420595..becc08204a 100755 --- a/src/main/java/forestry/apiculture/items/ItemSmoker.java +++ b/src/main/java/forestry/apiculture/items/ItemSmoker.java @@ -1,6 +1,6 @@ package forestry.apiculture.items; -import forestry.api.apiculture.hives.IHiveTile; +import forestry.apiculture.tiles.TileHive; import forestry.core.items.ItemForestry; import forestry.core.render.ParticleRender; import forestry.core.tiles.TileUtil; @@ -69,7 +69,7 @@ private static void addSmoke(Level level, Entity entity, int distance) { } BlockPos blockPos = BlockPos.containing(smokePos.x, smokePos.y + 1, smokePos.z); - TileUtil.actOnTile(level, blockPos, IHiveTile.class, IHiveTile::calmBees); + TileUtil.actOnTile(level, blockPos, TileHive.class, TileHive::calmBees); } @Override @@ -81,12 +81,12 @@ public InteractionResultHolder use(Level level, Player player, Intera @Override public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) { - TileUtil.actOnTile(context.getLevel(), context.getClickedPos(), IHiveTile.class, IHiveTile::calmBees); + TileUtil.actOnTile(context.getLevel(), context.getClickedPos(), TileHive.class, TileHive::calmBees); return super.onItemUseFirst(stack, context); } @Override - public int getUseDuration(ItemStack stack) { + public int getUseDuration(ItemStack stack, LivingEntity entity) { return 32; } } diff --git a/src/main/java/forestry/apiculture/items/ItemWaxCast.java b/src/main/java/forestry/apiculture/items/ItemWaxCast.java deleted file mode 100755 index 991489f464..0000000000 --- a/src/main/java/forestry/apiculture/items/ItemWaxCast.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.items; - -import forestry.core.items.ItemForestry; -import forestry.core.items.definitions.ICraftingPlan; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -// todo figure out what this is supposed to be used for -public class ItemWaxCast extends ItemForestry implements ICraftingPlan { - public ItemWaxCast() { - super(new Item.Properties().durability(16).setNoRepair()); - } - - @Override - public ItemStack planUsed(ItemStack plan, ItemStack result) { - plan.setDamageValue(plan.getDamageValue() + result.getCount()); - if (plan.getDamageValue() >= plan.getMaxDamage()) { - return ItemStack.EMPTY; - } else { - return plan; - } - } -} diff --git a/src/main/java/forestry/apiculture/items/package-info.java b/src/main/java/forestry/apiculture/items/package-info.java index 45bb1f3cce..e78be061fa 100644 --- a/src/main/java/forestry/apiculture/items/package-info.java +++ b/src/main/java/forestry/apiculture/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.items; diff --git a/src/main/java/forestry/apiculture/models/ModelBee.java b/src/main/java/forestry/apiculture/models/ModelBee.java index d8b82b806b..182b2b4321 100644 --- a/src/main/java/forestry/apiculture/models/ModelBee.java +++ b/src/main/java/forestry/apiculture/models/ModelBee.java @@ -3,8 +3,8 @@ import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.client.IForestryClientApi; import forestry.api.client.apiculture.IBeeClientManager; import forestry.api.genetics.IIndividual; @@ -23,9 +23,9 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.geometry.IGeometryBakingContext; -import net.minecraftforge.client.model.geometry.IGeometryLoader; -import net.minecraftforge.client.model.geometry.IUnbakedGeometry; +import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; +import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; +import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; import javax.annotation.Nullable; import java.util.IdentityHashMap; @@ -45,7 +45,7 @@ public ModelBee(ILifeStage stage) { } @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { IBeeClientManager manager = IForestryClientApi.INSTANCE.getBeeManager(); Map models = manager.getBeeModels(this.stage); IdentityHashMap itemModels = new IdentityHashMap<>(); diff --git a/src/main/java/forestry/apiculture/models/package-info.java b/src/main/java/forestry/apiculture/models/package-info.java index afc438d7f9..72862a34f4 100644 --- a/src/main/java/forestry/apiculture/models/package-info.java +++ b/src/main/java/forestry/apiculture/models/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.models; diff --git a/src/main/java/forestry/apiculture/multiblock/AlvearyController.java b/src/main/java/forestry/apiculture/multiblock/AlvearyController.java index 08d870b79e..0548bda780 100644 --- a/src/main/java/forestry/apiculture/multiblock/AlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/AlvearyController.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; -import com.mojang.authlib.GameProfile; import forestry.api.IForestryApi; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -27,29 +16,35 @@ import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.IMultiblockControllerInternal; +import forestry.core.multiblock.MultiblockSizeLimits; import forestry.core.multiblock.MultiblockValidationException; import forestry.core.multiblock.RectangularMultiblockControllerBase; import forestry.core.render.ParticleRender; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.tags.BiomeTags; import net.minecraft.tags.BlockTags; import net.minecraft.world.Containers; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import javax.annotation.Nullable; import java.util.HashSet; import java.util.Set; public class AlvearyController extends RectangularMultiblockControllerBase implements IAlvearyControllerInternal, IClimateControlled { + private static final MultiblockSizeLimits ALVEARY_LIMITS = new MultiblockSizeLimits(27, 3, 3, 3, 3, 3, 3); + private final InventoryBeeHousing inventory; private final IBeekeepingLogic beekeepingLogic; private IClimateProvider climate = IForestryApi.INSTANCE.getClimateManager().createDummyClimateProvider(); @@ -60,14 +55,14 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple // PARTS private final Set beeModifiers = new HashSet<>(); private final Set beeListeners = new HashSet<>(); - private final Set climatisers = new HashSet<>(); - private final Set activeComponents = new HashSet<>(); + private final Set> climatisers = new HashSet<>(); + private final Set> activeComponents = new HashSet<>(); // CLIENT private int breedingProgressPercent = 0; public AlvearyController(Level world) { - super(world, AlvearyMultiblockSizeLimits.instance); + super(world, ALVEARY_LIMITS); this.inventory = new InventoryBeeHousing(9); this.beekeepingLogic = IForestryApi.INSTANCE.getHiveManager().createBeekeepingLogic(this); @@ -105,28 +100,28 @@ public Iterable getBeeModifiers() { @Override public void onAttachedPartWithMultiblockData(IMultiblockComponent part, CompoundTag data) { - this.read(data); + read(data, this.level.registryAccess()); } @Override protected void onBlockAdded(IMultiblockComponent newPart) { if (newPart instanceof IAlvearyComponent) { - if (newPart instanceof IAlvearyComponent.BeeModifier alvearyBeeModifier) { + if (newPart instanceof IAlvearyComponent.BeeModifier alvearyBeeModifier) { IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); - this.beeModifiers.add(beeModifier); + this.beeModifiers.add(beeModifier); } - if (newPart instanceof IAlvearyComponent.BeeListener beeListenerSource) { + if (newPart instanceof IAlvearyComponent.BeeListener beeListenerSource) { IBeeListener beeListener = beeListenerSource.getBeeListener(); - this.beeListeners.add(beeListener); + this.beeListeners.add(beeListener); } - if (newPart instanceof IAlvearyComponent.Climatiser) { - this.climatisers.add((IAlvearyComponent.Climatiser) newPart); + if (newPart instanceof IAlvearyComponent.Climatiser climatiser) { + this.climatisers.add(climatiser); } - if (newPart instanceof IAlvearyComponent.Active) { - this.activeComponents.add((IAlvearyComponent.Active) newPart); + if (newPart instanceof IAlvearyComponent.Active active) { + this.activeComponents.add(active); } } } @@ -134,22 +129,22 @@ protected void onBlockAdded(IMultiblockComponent newPart) { @Override protected void onBlockRemoved(IMultiblockComponent oldPart) { if (oldPart instanceof IAlvearyComponent) { - if (oldPart instanceof IAlvearyComponent.BeeModifier alvearyBeeModifier) { + if (oldPart instanceof IAlvearyComponent.BeeModifier alvearyBeeModifier) { IBeeModifier beeModifier = alvearyBeeModifier.getBeeModifier(); - this.beeModifiers.remove(beeModifier); + this.beeModifiers.remove(beeModifier); } - if (oldPart instanceof IAlvearyComponent.BeeListener beeListenerSource) { + if (oldPart instanceof IAlvearyComponent.BeeListener beeListenerSource) { IBeeListener beeListener = beeListenerSource.getBeeListener(); - this.beeListeners.remove(beeListener); + this.beeListeners.remove(beeListener); } if (oldPart instanceof IAlvearyComponent.Climatiser) { - this.climatisers.remove(oldPart); + this.climatisers.remove(oldPart); } if (oldPart instanceof IAlvearyComponent.Active) { - this.activeComponents.remove(oldPart); + this.activeComponents.remove(oldPart); } } } @@ -227,20 +222,20 @@ public void onAssimilated(IMultiblockControllerInternal assimilator) { @Override protected boolean serverTick(int tickCount) { - for (IAlvearyComponent.Active activeComponent : this.activeComponents) { + for (IAlvearyComponent.Active activeComponent : this.activeComponents) { activeComponent.updateServer(tickCount); } final boolean canWork = this.beekeepingLogic.canWork(); if (canWork) { - this.beekeepingLogic.doWork(); + this.beekeepingLogic.doWork(); } // the old equalizeChange would cap out the climate increases from the climate blocks this.temperatureSteps = 0; this.humiditySteps = 0; // climate blocks will increase climate every tick and must go before the canWork check - for (IAlvearyComponent.Climatiser climatiser : this.climatisers) { + for (IAlvearyComponent.Climatiser climatiser : this.climatisers) { climatiser.changeClimate(tickCount, this); } @@ -255,12 +250,12 @@ protected boolean serverTick(int tickCount) { @Override @OnlyIn(Dist.CLIENT) protected void clientTick(int tickCount) { - for (IAlvearyComponent.Active activeComponent : this.activeComponents) { + for (IAlvearyComponent.Active activeComponent : this.activeComponents) { activeComponent.updateClient(tickCount); } if (this.beekeepingLogic.canDoBeeFX() && updateOnInterval(2)) { - this.beekeepingLogic.doBeeFX(); + this.beekeepingLogic.doBeeFX(); if (updateOnInterval(50)) { BlockPos center = getCenterCoord(); @@ -283,44 +278,44 @@ protected void clientTick(int tickCount) { } @Override - public CompoundTag write(CompoundTag data) { - data = super.write(data); + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { + data = super.write(data, registries); data.putByte("temperatureSteps", this.temperatureSteps); data.putByte("humiditySteps", this.humiditySteps); - this.beekeepingLogic.write(data); - this.inventory.write(data); + this.beekeepingLogic.write(data, registries); + this.inventory.write(data, registries); return data; } @Override - public void read(CompoundTag data) { - super.read(data); + public void read(CompoundTag data, HolderLookup.Provider registries) { + super.read(data, registries); this.temperatureSteps = data.getByte("temperatureSteps"); this.humiditySteps = data.getByte("humiditySteps"); - this.beekeepingLogic.read(data); - this.inventory.read(data); + this.beekeepingLogic.read(data, registries); + this.inventory.read(data, registries); } @Override - public void formatDescriptionPacket(CompoundTag data) { - this.write(data); - this.beekeepingLogic.write(data); + public void encodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries) { + write(data, registries); + this.beekeepingLogic.write(data, registries); } @Override - public void decodeDescriptionPacket(CompoundTag data) { - this.read(data); - this.beekeepingLogic.read(data); + public void decodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries) { + this.read(data, registries); + this.beekeepingLogic.read(data, registries); } /* IActivatable */ @Override - public BlockPos getCoordinates() { + public BlockPos getBlockPos() { BlockPos coord = getCenterCoord(); return coord.offset(0, 1, 0); } @@ -339,7 +334,7 @@ public HumidityType humidity() { @Override public TemperatureType temperature() { IBeeModifier beeModifier = IForestryApi.INSTANCE.getHiveManager().createBeeHousingModifier(this); - if (beeModifier.isHellish() || getBiome().is(BiomeTags.IS_NETHER)) { + if (beeModifier.isHellish() || getBiome(this.level.registryAccess()).is(BiomeTags.IS_NETHER)) { if (this.temperatureSteps >= 0) { return TemperatureType.HELLISH; } @@ -349,7 +344,7 @@ public TemperatureType temperature() { } @Override - public GameProfile getOwner() { + public @Nullable ResolvableProfile getOwner() { return getOwnerHandler().getOwner(); } @@ -359,7 +354,7 @@ public String getUnlocalizedType() { } @Override - public Holder getBiome() { + public Holder getBiome(HolderLookup.Provider registries) { return this.level.getBiome(getReferenceCoord()); } @@ -398,18 +393,18 @@ public int getHealthScaled(int i) { } @Override - public void writeGuiData(FriendlyByteBuf data) { - data.writeVarInt(this.beekeepingLogic.getBeeProgressPercent()); - NetworkUtil.writeClimateState(data, this.climate.temperature(), this.climate.humidity()); - data.writeByte(this.temperatureSteps); - data.writeByte(this.humiditySteps); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + buffer.writeVarInt(this.beekeepingLogic.getBeeProgressPercent()); + NetworkUtil.writeClimateState(buffer, this.climate.temperature(), this.climate.humidity()); + buffer.writeByte(this.temperatureSteps); + buffer.writeByte(this.humiditySteps); } @Override - public void readGuiData(FriendlyByteBuf data) { - this.breedingProgressPercent = data.readVarInt(); - this.climate = NetworkUtil.readClimateState(data); - this.temperatureSteps = data.readByte(); - this.humiditySteps = data.readByte(); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.breedingProgressPercent = buffer.readVarInt(); + this.climate = NetworkUtil.readClimateState(buffer); + this.temperatureSteps = buffer.readByte(); + this.humiditySteps = buffer.readByte(); } } diff --git a/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java b/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java deleted file mode 100644 index 81763e209b..0000000000 --- a/src/main/java/forestry/apiculture/multiblock/AlvearyMultiblockSizeLimits.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.multiblock; - -import forestry.core.multiblock.IMultiblockSizeLimits; - -class AlvearyMultiblockSizeLimits implements IMultiblockSizeLimits { - - public static final AlvearyMultiblockSizeLimits instance = new AlvearyMultiblockSizeLimits(); - - private AlvearyMultiblockSizeLimits() { - - } - - @Override - public int getMinimumNumberOfBlocksForAssembledMachine() { - return 27; - } - - @Override - public int getMaximumXSize() { - return 3; - } - - @Override - public int getMaximumZSize() { - return 3; - } - - @Override - public int getMaximumYSize() { - return 3; - } - - @Override - public int getMinimumXSize() { - return 3; - } - - @Override - public int getMinimumYSize() { - return 3; - } - - @Override - public int getMinimumZSize() { - return 3; - } -} diff --git a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java index 213b3b0068..9f30325e6d 100644 --- a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; -import com.mojang.authlib.GameProfile; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -22,25 +11,26 @@ import forestry.core.multiblock.FakeMultiblockController; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.registries.ForgeRegistries; import javax.annotation.Nullable; -import java.util.Collections; +import java.util.List; public enum FakeAlvearyController implements FakeMultiblockController, IAlvearyControllerInternal { INSTANCE; @Override public Iterable getBeeModifiers() { - return Collections.emptyList(); + return List.of(); } @Override public Iterable getBeeListeners() { - return Collections.emptyList(); + return List.of(); } @Override @@ -70,12 +60,12 @@ public boolean isRaining() { @Override @Nullable - public GameProfile getOwner() { + public ResolvableProfile getOwner() { return null; } @Override - public BlockPos getCoordinates() { + public BlockPos getBlockPos() { return BlockPos.ZERO; } @@ -85,8 +75,8 @@ public Vec3 getBeeFXCoordinates() { } @Override - public Holder getBiome() { - return ForgeRegistries.BIOMES.getDelegateOrThrow(Biomes.PLAINS); + public Holder getBiome(HolderLookup.Provider registries) { + return registries.holderOrThrow(Biomes.PLAINS); } @Override diff --git a/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java b/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java index a44d3d1629..ba28b0a827 100644 --- a/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java +++ b/src/main/java/forestry/apiculture/multiblock/IAlvearyControllerInternal.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java b/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java index ef9dcd3ca8..87fe011cf1 100644 --- a/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java +++ b/src/main/java/forestry/apiculture/multiblock/MultiblockLogicAlveary.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.multiblock.IMultiblockLogicAlveary; @@ -32,14 +22,4 @@ public IAlvearyControllerInternal getController() { public IAlvearyControllerInternal createNewController(Level level) { return new AlvearyController(level); } - - @Override - public void becomeMultiblockSaveDelegate() { - super.becomeMultiblockSaveDelegate(); - } - - @Override - public void forfeitMultiblockSaveDelegate() { - super.forfeitMultiblockSaveDelegate(); - } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java index e330417c3a..c20e294b8e 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.apiculture.*; @@ -18,9 +8,8 @@ import forestry.api.multiblock.IAlvearyComponent; import forestry.api.multiblock.IMultiblockController; import forestry.apiculture.blocks.BlockAlveary; -import forestry.apiculture.blocks.BlockAlvearyType; import forestry.apiculture.features.ApicultureBlocks; -import forestry.apiculture.gui.ContainerAlveary; +import forestry.apiculture.gui.AlvearyMenu; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.MultiblockTileEntityForestry; import forestry.core.network.IStreamableGui; @@ -28,9 +17,9 @@ import forestry.core.owner.IOwnerHandler; import forestry.core.tiles.ITitled; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.core.Holder; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -40,22 +29,15 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.wrapper.InvWrapper; -import net.minecraftforge.items.wrapper.SidedInvWrapper; - -import javax.annotation.Nullable; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class TileAlveary extends MultiblockTileEntityForestry implements IBeeHousing, IAlvearyComponent, IOwnedTile, IStreamableGui, ITitled, IClimateProvider { private final String translationKey; // For Forestry only - public TileAlveary(BlockAlvearyType type, BlockPos pos, BlockState state) { - this(type.getTileType().tileType(), ApicultureBlocks.ALVEARY.get(type).getTranslationKey(), pos, state); + public TileAlveary(BlockAlveary.Type type, BlockPos pos, BlockState state) { + this(type.tileFeature().tileType(), ApicultureBlocks.ALVEARY.get(type).getTranslationKey(), pos, state); } // For addons @@ -82,23 +64,10 @@ public void onMachineBroken() { setChanged(); } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.ITEM_HANDLER) { - if (facing != null) { - // TODO why is sided inventory used here? the side is actually ignored, see in InventoryAdapter - return LazyOptional.of(() -> new SidedInvWrapper(getInternalInventory(), facing)).cast(); - } else { - return LazyOptional.of(() -> new InvWrapper(getInternalInventory())).cast(); - } - } - return super.getCapability(capability, facing); - } - /* IHousing */ @Override - public Holder getBiome() { - return getMultiblockLogic().getController().getBiome(); + public Holder getBiome(HolderLookup.Provider registries) { + return getMultiblockLogic().getController().getBiome(registries); } /* IBeeHousing */ @@ -175,19 +144,19 @@ public Component getTitle() { /* IStreamableGui */ @Override - public void writeGuiData(FriendlyByteBuf data) { - getMultiblockLogic().getController().writeGuiData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + getMultiblockLogic().getController().writeGuiData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readGuiData(FriendlyByteBuf data) { - getMultiblockLogic().getController().readGuiData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + getMultiblockLogic().getController().readGuiData(buffer); } @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerAlveary(windowId, player.getInventory(), this); + return new AlvearyMenu(windowId, player.getInventory(), this); } @Override diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java index 33b330c181..719981bb17 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyClimatiser.java @@ -1,32 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.climate.IClimateControlled; import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlveary; -import forestry.apiculture.blocks.BlockAlvearyType; import forestry.core.tiles.IActivatable; import forestry.energy.EnergyHelper; import forestry.energy.EnergyTransferMode; import forestry.energy.ForestryEnergyStorage; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; - -import javax.annotation.Nullable; // Used by Heater and Fan, which increase and decrease Temperature, respectively public abstract class TileAlvearyClimatiser extends TileAlveary implements IActivatable, IAlvearyComponent.Climatiser { @@ -34,17 +18,15 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IActi private static final int FE_PER_OPERATION = 50; private final ForestryEnergyStorage energyStorage; - private final LazyOptional energyCap; private final byte temperatureSteps; private int workingTime = 0; - protected TileAlvearyClimatiser(BlockAlvearyType alvearyType, BlockPos pos, BlockState state, byte temperatureSteps) { + protected TileAlvearyClimatiser(BlockAlveary.Type alvearyType, BlockPos pos, BlockState state, byte temperatureSteps) { super(alvearyType, pos, state); this.temperatureSteps = temperatureSteps; this.energyStorage = new ForestryEnergyStorage(1000, 2000, EnergyTransferMode.RECEIVE); - this.energyCap = LazyOptional.of(() -> this.energyStorage); } /* UPDATING */ @@ -52,11 +34,11 @@ protected TileAlvearyClimatiser(BlockAlvearyType alvearyType, BlockPos pos, Bloc public void changeClimate(int tick, IClimateControlled climateControlled) { if (this.workingTime < 20 && EnergyHelper.consumeEnergyToDoWork(this.energyStorage, TICKS_PER_CYCLE, FE_PER_OPERATION)) { // one tick of work for every 10 RF - this.workingTime += FE_PER_OPERATION / 10; + this.workingTime += FE_PER_OPERATION / 10; } if (this.workingTime > 0) { - this.workingTime--; + this.workingTime--; climateControlled.addTemperatureChange(this.temperatureSteps); } @@ -65,17 +47,17 @@ public void changeClimate(int tick, IClimateControlled climateControlled) { /* LOADING & SAVING */ @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.energyStorage.read(compoundNBT); - this.workingTime = compoundNBT.getInt("Heating"); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.energyStorage.read(nbt, registries); + this.workingTime = nbt.getInt("Heating"); } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.energyStorage.write(compoundNBT); - compoundNBT.putInt("Heating", this.workingTime); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.energyStorage.write(nbt, registries); + nbt.putInt("Heating", this.workingTime); } /* Network */ @@ -101,12 +83,4 @@ public void setActive(boolean active) { this.level.setBlockAndUpdate(this.worldPosition, getBlockState().setValue(BlockAlveary.STATE, active ? BlockAlveary.State.ON : BlockAlveary.State.OFF)); } } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (!this.remove && capability == ForgeCapabilities.ENERGY) { - return this.energyCap.cast(); - } - return super.getCapability(capability, facing); - } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java index a3b0285f76..dd5f700bfa 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyFan.java @@ -1,21 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; -import forestry.apiculture.blocks.BlockAlvearyType; +import forestry.apiculture.blocks.BlockAlveary; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; public class TileAlvearyFan extends TileAlvearyClimatiser { public TileAlvearyFan(BlockPos pos, BlockState state) { - super(BlockAlvearyType.FAN, pos, state, (byte) -1); + super(BlockAlveary.Type.FAN, pos, state, (byte) -1); } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java index 7109418618..9b2d7506ae 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHeater.java @@ -1,21 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; -import forestry.apiculture.blocks.BlockAlvearyType; +import forestry.apiculture.blocks.BlockAlveary; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; public class TileAlvearyHeater extends TileAlvearyClimatiser { public TileAlvearyHeater(BlockPos pos, BlockState state) { - super(BlockAlvearyType.HEATER, pos, state, (byte) 1); + super(BlockAlveary.Type.HEATER, pos, state, (byte) 1); } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java index 3a24de4928..eb3de9656b 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.climate.IClimateControlled; import forestry.api.multiblock.IAlvearyComponent; import forestry.api.recipes.IHygroregulatorRecipe; -import forestry.apiculture.blocks.BlockAlvearyType; -import forestry.apiculture.gui.ContainerAlvearyHygroregulator; +import forestry.apiculture.blocks.BlockAlveary; +import forestry.apiculture.gui.AlvearyHygroregulatorMenu; import forestry.apiculture.inventory.InventoryHygroregulator; import forestry.core.config.Constants; import forestry.core.fluids.FilteredTank; @@ -23,20 +13,19 @@ import forestry.core.fluids.TankManager; import forestry.core.inventory.IInventoryAdapter; import forestry.core.tiles.ILiquidTankTile; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; @@ -46,12 +35,12 @@ public class TileAlvearyHygroregulator extends TileAlveary implements Container, private final IInventoryAdapter inventory; @Nullable - private IHygroregulatorRecipe currentRecipe; + private RecipeHolder currentRecipe; // number of ticks the current temperature change lasts for. private int heatTicks; public TileAlvearyHygroregulator(BlockPos pos, BlockState state) { - super(BlockAlvearyType.HYGRO, pos, state); + super(BlockAlveary.Type.HYGRO, pos, state); this.inventory = new InventoryHygroregulator(this); this.liquidTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilter(FluidRecipeFilter.HYGROREGULATOR_INPUT); @@ -75,10 +64,10 @@ public void changeClimate(int tickCount, IClimateControlled climateControlled) { FluidStack fluid = this.liquidTank.getFluid(); if (!fluid.isEmpty()) { - this.currentRecipe = RecipeUtils.getHygroRegulatorRecipe(this.level.getRecipeManager(), fluid); + this.currentRecipe = RecipeUtil.getHygroRegulatorRecipe(this.level.getRecipeManager(), fluid); if (this.currentRecipe != null) { - this.liquidTank.drainInternal(this.currentRecipe.getInputFluid().getAmount(), IFluidHandler.FluidAction.EXECUTE); + this.liquidTank.drainInternal(this.currentRecipe.value().getInputFluid().amount(), IFluidHandler.FluidAction.EXECUTE); this.heatTicks = 20; } } @@ -87,8 +76,8 @@ public void changeClimate(int tickCount, IClimateControlled climateControlled) { if (this.heatTicks > 0) { this.heatTicks--; if (this.currentRecipe != null) { - climateControlled.addHumidityChange(this.currentRecipe.getHumiditySteps()); - climateControlled.addTemperatureChange(this.currentRecipe.getTemperatureSteps()); + climateControlled.addHumidityChange(this.currentRecipe.value().getHumiditySteps()); + climateControlled.addTemperatureChange(this.currentRecipe.value().getTemperatureSteps()); } else { this.heatTicks = 0; } @@ -102,52 +91,36 @@ public void changeClimate(int tickCount, IClimateControlled climateControlled) { /* SAVING & LOADING */ @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.tankManager.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); - this.heatTicks = compoundNBT.getInt("TransferTime"); + this.heatTicks = nbt.getInt("TransferTime"); - if (compoundNBT.contains("CurrentLiquid")) { - FluidStack liquid = FluidStack.loadFluidStackFromNBT(compoundNBT.getCompound("CurrentLiquid")); - this.currentRecipe = RecipeUtils.getHygroRegulatorRecipe(RecipeUtils.getRecipeManager(), liquid); + if (nbt.contains("currentRecipe")) { + this.currentRecipe = RecipeUtil.getRecipe(ResourceLocation.tryParse(nbt.getString("currentRecipe"))); } } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.tankManager.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.tankManager.write(nbt, registries); - compoundNBT.putInt("TransferTime", this.heatTicks); + nbt.putInt("TransferTime", this.heatTicks); if (this.currentRecipe != null) { - CompoundTag subcompound = new CompoundTag(); - this.currentRecipe.getInputFluid().writeToNBT(subcompound); - compoundNBT.put("CurrentLiquid", subcompound); + nbt.putString("currentRecipe", this.currentRecipe.id().toString()); } } - /* ILIQUIDTANKCONTAINER */ @Override public TankManager getTankManager() { return this.tankManager; } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - LazyOptional superCap = super.getCapability(capability, facing); - if (superCap.isPresent()) { - return superCap; - } - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return LazyOptional.empty(); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerAlvearyHygroregulator(windowId, inv, this); + return new AlvearyHygroregulatorMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java index 32291a35db..744a281fd1 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyPlain.java @@ -1,23 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; -import forestry.apiculture.blocks.BlockAlvearyType; +import forestry.apiculture.blocks.BlockAlveary; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; public class TileAlvearyPlain extends TileAlveary { - public TileAlvearyPlain(BlockPos pos, BlockState state) { - super(BlockAlvearyType.PLAIN, pos, state); + super(BlockAlveary.Type.PLAIN, pos, state); } @Override diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java index 2645f597da..6fda890786 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearySieve.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.apiculture.IBeeListener; import forestry.api.genetics.pollen.IPollen; import forestry.api.multiblock.IAlvearyComponent; -import forestry.apiculture.blocks.BlockAlvearyType; -import forestry.apiculture.gui.ContainerAlvearySieve; +import forestry.apiculture.blocks.BlockAlveary; +import forestry.apiculture.gui.AlvearySieveMenu; import forestry.apiculture.inventory.InventoryAlvearySieve; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.watchers.ISlotPickupWatcher; @@ -30,7 +20,7 @@ public class TileAlvearySieve extends TileAlveary implements IAlvearyComponent.B private final InventoryAlvearySieve inventory; public TileAlvearySieve(BlockPos pos, BlockState state) { - super(BlockAlvearyType.SIEVE, pos, state); + super(BlockAlveary.Type.SIEVE, pos, state); this.inventory = new InventoryAlvearySieve(this); this.beeListener = new AlvearySieveBeeListener(this.inventory); } @@ -51,7 +41,7 @@ public IBeeListener getBeeListener() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerAlvearySieve(windowId, inv, this); + return new AlvearySieveMenu(windowId, inv, this); } static class AlvearySieveBeeListener implements IBeeListener { diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java index ba76a1aa87..e0aed1da3a 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyStabiliser.java @@ -1,21 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.multiblock; import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutation; import forestry.api.multiblock.IAlvearyComponent; -import forestry.apiculture.blocks.BlockAlvearyType; +import forestry.apiculture.blocks.BlockAlveary; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.state.BlockState; @@ -28,7 +18,7 @@ public float modifyMutationChance(IGenome genome, IGenome mate, IMutation pendingSpawns = new ArrayDeque<>(); public TileAlvearySwarmer(BlockPos pos, BlockState state) { - super(BlockAlvearyType.SWARMER, pos, state); + super(BlockAlveary.Type.SWARMER, pos, state); this.inventory = new InventorySwarmer(this); } @@ -144,19 +134,19 @@ private void trySpawnSwarm() { /* SAVING & LOADING */ @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); + public void load(CompoundTag compoundNBT, HolderLookup.Provider registries) { + super.load(compoundNBT, registries); ListTag nbttaglist = compoundNBT.getList("PendingSpawns", 10); for (int i = 0; i < nbttaglist.size(); i++) { CompoundTag compoundNBT1 = nbttaglist.getCompound(i); - this.pendingSpawns.add(ItemStack.of(compoundNBT1)); + this.pendingSpawns.add(ItemStack.parseOptional(registries, compoundNBT1)); } } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); ListTag nbttaglist = new ListTag(); ItemStack[] offspring = this.pendingSpawns.toArray(new ItemStack[0]); @@ -168,7 +158,7 @@ public void saveAdditional(CompoundTag compoundNBT) { nbttaglist.add(compoundNBT1); } } - compoundNBT.put("PendingSpawns", nbttaglist); + nbt.put("PendingSpawns", nbttaglist); } @Override @@ -185,6 +175,6 @@ public void setActive(boolean active) { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerAlvearySwarmer(windowId, inv, this); + return new AlvearySwarmerMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/apiculture/multiblock/package-info.java b/src/main/java/forestry/apiculture/multiblock/package-info.java index b8f6254a12..b36e2bbc0b 100644 --- a/src/main/java/forestry/apiculture/multiblock/package-info.java +++ b/src/main/java/forestry/apiculture/multiblock/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.multiblock; diff --git a/src/main/java/forestry/apiculture/network/packets/PacketAlvearyChange.java b/src/main/java/forestry/apiculture/network/packets/PacketAlvearyChange.java deleted file mode 100644 index a2b6f70e22..0000000000 --- a/src/main/java/forestry/apiculture/network/packets/PacketAlvearyChange.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import forestry.api.modules.IForestryPacketClient; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.network.PacketIdClient; -import forestry.core.tiles.TileUtil; -import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; - -public record PacketAlvearyChange(BlockPos pos) implements IForestryPacketClient { - @Override - public ResourceLocation id() { - return PacketIdClient.ALVERAY_CONTROLLER_CHANGE; - } - - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - } - - public static PacketAlvearyChange decode(FriendlyByteBuf buffer) { - return new PacketAlvearyChange(buffer.readBlockPos()); - } - - public static void handle(PacketAlvearyChange msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, IMultiblockComponent.class, tile -> tile.getMultiblockLogic().getController().reassemble()); - } -} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketAlvearyControllerChange.java b/src/main/java/forestry/apiculture/network/packets/PacketAlvearyControllerChange.java new file mode 100644 index 0000000000..774f454fde --- /dev/null +++ b/src/main/java/forestry/apiculture/network/packets/PacketAlvearyControllerChange.java @@ -0,0 +1,28 @@ +package forestry.apiculture.network.packets; + +import forestry.api.modules.IForestryPacketClient; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.network.PacketIdClient; +import forestry.core.tiles.TileUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; + +public record PacketAlvearyControllerChange(BlockPos pos) implements IForestryPacketClient { + @Override + public Type type() { + return PacketIdClient.ALVEARY_CONTROLLER_CHANGE; + } + + public static void encode(RegistryFriendlyByteBuf buffer, PacketAlvearyControllerChange msg) { + buffer.writeBlockPos(msg.pos); + } + + public static PacketAlvearyControllerChange decode(RegistryFriendlyByteBuf buffer) { + return new PacketAlvearyControllerChange(buffer.readBlockPos()); + } + + public static void handle(PacketAlvearyControllerChange msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, IMultiblockComponent.class, tile -> tile.getMultiblockLogic().getController().reassemble()); + } +} diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java index b4e28de276..4dfb712ce6 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.network.packets; import forestry.api.apiculture.IBeeHousing; @@ -18,8 +8,8 @@ import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; // Similar to PacketGuiStream public record PacketBeeLogicActive( @@ -30,26 +20,25 @@ public record PacketBeeLogicActive( FriendlyByteBuf payload ) implements IForestryPacketClient { public PacketBeeLogicActive(IBeeHousing tile) { - this(tile.getCoordinates(), tile.getBeekeepingLogic(), null); + this(tile.getBlockPos(), tile.getBeekeepingLogic(), null); } @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.BEE_LOGIC_ACTIVE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writePayloadBuffer(buffer, this.logic::writeData); + public static void encode(RegistryFriendlyByteBuf buffer, PacketBeeLogicActive msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writePayloadBuffer(buffer, msg.logic::writeData); } - public static PacketBeeLogicActive decode(FriendlyByteBuf buffer) { + public static PacketBeeLogicActive decode(RegistryFriendlyByteBuf buffer) { return new PacketBeeLogicActive(buffer.readBlockPos(), null, NetworkUtil.readPayloadBuffer(buffer)); } - public static void handle(PacketBeeLogicActive msg, Player player) { - IBeeHousing beeHousing = TileUtil.getTile(player.level(), msg.pos, IBeeHousing.class); + public static void handle(PacketBeeLogicActive msg, IPayloadContext ctx) { + IBeeHousing beeHousing = TileUtil.getTile(ctx.player().level(), msg.pos, IBeeHousing.class); if (beeHousing != null) { IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); beekeepingLogic.readData(msg.payload); diff --git a/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java b/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java deleted file mode 100644 index 7fd7fe6a53..0000000000 --- a/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.network.packets; - -import forestry.api.modules.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; - -public record PacketHabitatBiomePointer(BlockPos pos) implements IForestryPacketClient { - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - } - - @Override - public ResourceLocation id() { - return PacketIdClient.HABITAT_BIOME_POINTER; - } - - public static PacketHabitatBiomePointer decode(FriendlyByteBuf buffer) { - return new PacketHabitatBiomePointer(buffer.readBlockPos()); - } - - public static void handle(PacketHabitatBiomePointer msg, Player player) { - BlockPos pos = msg.pos(); - //TextureHabitatLocator.getInstance().setTargetCoordinates(pos);//TODO: TextureHabitatLocator - } -} diff --git a/src/main/java/forestry/apiculture/network/packets/package-info.java b/src/main/java/forestry/apiculture/network/packets/package-info.java index e0c8319473..58311ed070 100644 --- a/src/main/java/forestry/apiculture/network/packets/package-info.java +++ b/src/main/java/forestry/apiculture/network/packets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.network.packets; diff --git a/src/main/java/forestry/apiculture/package-info.java b/src/main/java/forestry/apiculture/package-info.java index 556fbd718a..0922e06a3b 100644 --- a/src/main/java/forestry/apiculture/package-info.java +++ b/src/main/java/forestry/apiculture/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture; diff --git a/src/main/java/forestry/apiculture/particles/ApicultureParticles.java b/src/main/java/forestry/apiculture/particles/ApicultureParticles.java index 635c759f12..3107e5814c 100644 --- a/src/main/java/forestry/apiculture/particles/ApicultureParticles.java +++ b/src/main/java/forestry/apiculture/particles/ApicultureParticles.java @@ -1,14 +1,13 @@ package forestry.apiculture.particles; -import com.mojang.serialization.Codec; import forestry.api.modules.ForestryModuleIds; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; import net.minecraft.core.particles.ParticleType; import net.minecraft.core.registries.Registries; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class ApicultureParticles { @@ -16,12 +15,7 @@ public class ApicultureParticles { private static final DeferredRegister> PARTICLE_TYPES = REGISTRY.getRegistry(Registries.PARTICLE_TYPE); - public static final RegistryObject> BEE_EXPLORER_PARTICLE = PARTICLE_TYPES.register("bee_explore_particle", BeeParticleType::new); - public static final RegistryObject> BEE_ROUND_TRIP_PARTICLE = PARTICLE_TYPES.register("bee_round_trip_particle", BeeParticleType::new); - public static final RegistryObject> BEE_TARGET_ENTITY_PARTICLE = PARTICLE_TYPES.register("bee_target_entity_particle", () -> new ParticleType<>(false, BeeTargetParticleData.DESERIALIZER) { - @Override - public Codec codec() { - return BeeTargetParticleData.CODEC; - } - }); + public static final DeferredHolder, BeeParticleData.Type> BEE_EXPLORER_PARTICLE = PARTICLE_TYPES.register("bee_explore_particle", BeeParticleData.Type::new); + public static final DeferredHolder, BeeParticleData.Type> BEE_ROUND_TRIP_PARTICLE = PARTICLE_TYPES.register("bee_round_trip_particle", BeeParticleData.Type::new); + public static final DeferredHolder, BeeTargetParticleData.Type> BEE_TARGET_ENTITY_PARTICLE = PARTICLE_TYPES.register("bee_target_entity_particle", BeeTargetParticleData.Type::new); } diff --git a/src/main/java/forestry/apiculture/particles/BeeExploreParticle.java b/src/main/java/forestry/apiculture/particles/BeeExploreParticle.java index a02f87cef1..521aa9a4ac 100644 --- a/src/main/java/forestry/apiculture/particles/BeeExploreParticle.java +++ b/src/main/java/forestry/apiculture/particles/BeeExploreParticle.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.particles; import net.minecraft.client.multiplayer.ClientLevel; diff --git a/src/main/java/forestry/apiculture/particles/BeeParticleData.java b/src/main/java/forestry/apiculture/particles/BeeParticleData.java index 39cfa239b4..bd5d1a6a6c 100644 --- a/src/main/java/forestry/apiculture/particles/BeeParticleData.java +++ b/src/main/java/forestry/apiculture/particles/BeeParticleData.java @@ -1,84 +1,51 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.particles; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import forestry.core.utils.ModUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; -import javax.annotation.Nonnull; -import java.util.Locale; +public record BeeParticleData(ParticleType type, BlockPos destination, int color) implements ParticleOptions { + @Override + public ParticleType getType() { + return this.type; + } -public class BeeParticleData implements ParticleOptions { + public static class Type extends ParticleType implements StreamCodec { + private final MapCodec codec; - public static final Deserializer DESERIALIZER = new Deserializer<>() { - @Nonnull - @Override - public BeeParticleData fromCommand(@Nonnull ParticleType type, @Nonnull StringReader reader) throws CommandSyntaxException { - reader.expect(' '); - long direction = reader.readLong(); - reader.expect(' '); - int color = reader.readInt(); - return new BeeParticleData(type, direction, color); + public Type() { + super(false); + + this.codec = RecordCodecBuilder.mapCodec(instance -> instance.group( + BlockPos.CODEC.fieldOf("destination").forGetter(BeeParticleData::destination), + Codec.INT.fieldOf("color").forGetter(BeeParticleData::color) + ).apply(instance, (destination, color) -> new BeeParticleData(this, destination, color))); } @Override - public BeeParticleData fromNetwork(@Nonnull ParticleType type, FriendlyByteBuf buf) { - return new BeeParticleData(type, buf.readLong(), buf.readInt()); + public MapCodec codec() { + return this.codec; } - }; - - public static Codec createCodec(ParticleType type) { - return RecordCodecBuilder.create(val -> val.group(Codec.LONG.fieldOf("direction").forGetter(data -> data.destination.asLong()), Codec.INT.fieldOf("color").forGetter(data -> data.color)).apply(val, (destination1, color1) -> new BeeParticleData(type, destination1, color1))); - } - - public final ParticleType type; - public final BlockPos destination; - public final int color; - - public BeeParticleData(ParticleType type, long destination, int color) { - this.type = type; - this.destination = BlockPos.of(destination); - this.color = color; - } - - public BeeParticleData(ParticleType type, BlockPos destination, int color) { - this.type = type; - this.destination = destination; - this.color = color; - } - @Nonnull - @Override - public ParticleType getType() { - return this.type; - } + @Override + public StreamCodec streamCodec() { + return this; + } - @Override - public void writeToNetwork(@Nonnull FriendlyByteBuf buffer) { - buffer.writeRegistryId(ForgeRegistries.PARTICLE_TYPES, this.type); - buffer.writeLong(this.destination.asLong()); - buffer.writeInt(this.color); - } + @Override + public void encode(RegistryFriendlyByteBuf buffer, BeeParticleData msg) { + buffer.writeBlockPos(msg.destination); + buffer.writeInt(msg.color); + } - @Nonnull - @Override - public String writeToString() { - return String.format(Locale.ROOT, "%s %d %d %d %d", ModUtil.getRegistryName(getType()), this.destination.getX(), this.destination.getY(), this.destination.getZ(), this.color); + @Override + public BeeParticleData decode(RegistryFriendlyByteBuf buffer) { + return new BeeParticleData(this, buffer.readBlockPos(), buffer.readInt()); + } } } diff --git a/src/main/java/forestry/apiculture/particles/BeeParticleType.java b/src/main/java/forestry/apiculture/particles/BeeParticleType.java deleted file mode 100644 index b9416f8250..0000000000 --- a/src/main/java/forestry/apiculture/particles/BeeParticleType.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.particles; - -import com.mojang.serialization.Codec; -import net.minecraft.core.particles.ParticleType; - -import javax.annotation.Nonnull; - -public class BeeParticleType extends ParticleType { - public BeeParticleType() { - super(false, BeeParticleData.DESERIALIZER); - } - - @Nonnull - @Override - public Codec codec() { - return BeeParticleData.createCodec(this); - } -} diff --git a/src/main/java/forestry/apiculture/particles/BeeRoundTripParticle.java b/src/main/java/forestry/apiculture/particles/BeeRoundTripParticle.java index 3f10cf91ca..5ada35d30e 100644 --- a/src/main/java/forestry/apiculture/particles/BeeRoundTripParticle.java +++ b/src/main/java/forestry/apiculture/particles/BeeRoundTripParticle.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.particles; import net.minecraft.client.multiplayer.ClientLevel; diff --git a/src/main/java/forestry/apiculture/particles/BeeTargetEntityParticle.java b/src/main/java/forestry/apiculture/particles/BeeTargetEntityParticle.java index 15a5fbcf05..5dcce78cf0 100644 --- a/src/main/java/forestry/apiculture/particles/BeeTargetEntityParticle.java +++ b/src/main/java/forestry/apiculture/particles/BeeTargetEntityParticle.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.particles; import net.minecraft.client.multiplayer.ClientLevel; diff --git a/src/main/java/forestry/apiculture/particles/BeeTargetParticleData.java b/src/main/java/forestry/apiculture/particles/BeeTargetParticleData.java index 66ad847ab5..ed9fe325e0 100644 --- a/src/main/java/forestry/apiculture/particles/BeeTargetParticleData.java +++ b/src/main/java/forestry/apiculture/particles/BeeTargetParticleData.java @@ -1,80 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.particles; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import forestry.core.utils.ModUtil; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.entity.Entity; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; -import javax.annotation.Nonnull; -import java.util.Locale; - -public class BeeTargetParticleData implements ParticleOptions { - - public static final Deserializer DESERIALIZER = new Deserializer<>() { - @Nonnull - @Override - public BeeTargetParticleData fromCommand(@Nonnull ParticleType type, @Nonnull StringReader reader) throws CommandSyntaxException { - reader.expect(' '); - int entityId = reader.readInt(); - reader.expect(' '); - int color = reader.readInt(); - return new BeeTargetParticleData(entityId, color); - } - - @Override - public BeeTargetParticleData fromNetwork(@Nonnull ParticleType type, FriendlyByteBuf buf) { - return new BeeTargetParticleData(buf.readInt(), buf.readInt()); - } - }; - - public static Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codec.INT.fieldOf("entity").forGetter(data -> data.entity), - Codec.INT.fieldOf("color").forGetter(data -> data.color) +public record BeeTargetParticleData(int entity, int color) implements ParticleOptions { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( + Codec.INT.fieldOf("entity").forGetter(BeeTargetParticleData::entity), + Codec.INT.fieldOf("color").forGetter(BeeTargetParticleData::color) ).apply(instance, BeeTargetParticleData::new)); - public final int entity; - public final int color; + public static final StreamCodec STREAM_CODEC = StreamCodec.of(BeeTargetParticleData::encode, BeeTargetParticleData::decode); - public BeeTargetParticleData(int entity, int color) { - this.entity = entity; - this.color = color; + @Override + public ParticleType getType() { + return ApicultureParticles.BEE_TARGET_ENTITY_PARTICLE.value(); } - public BeeTargetParticleData(Entity entity, int color) { - this.entity = entity.getId(); - this.color = color; + private static void encode(RegistryFriendlyByteBuf buffer, BeeTargetParticleData msg) { + buffer.writeInt(msg.entity); + buffer.writeInt(msg.color); } - @Nonnull - @Override - public ParticleType getType() { - return ApicultureParticles.BEE_TARGET_ENTITY_PARTICLE.get(); + private static BeeTargetParticleData decode(RegistryFriendlyByteBuf buffer) { + return new BeeTargetParticleData(buffer.readInt(), buffer.readInt()); } - @Override - public void writeToNetwork(@Nonnull FriendlyByteBuf buffer) { - buffer.writeLong(this.entity); - buffer.writeInt(this.color); - } + public static class Type extends ParticleType { + protected Type() { + super(false); + } - @Nonnull - @Override - public String writeToString() { - return String.format(Locale.ROOT, "%s %d %d", ModUtil.getRegistryName(getType()), this.entity, this.color); + @Override + public MapCodec codec() { + return CODEC; + } + + @Override + public StreamCodec streamCodec() { + return STREAM_CODEC; + } } } diff --git a/src/main/java/forestry/apiculture/particles/ParticleSnow.java b/src/main/java/forestry/apiculture/particles/ParticleSnow.java index f3a813e725..96cff8e589 100644 --- a/src/main/java/forestry/apiculture/particles/ParticleSnow.java +++ b/src/main/java/forestry/apiculture/particles/ParticleSnow.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.particles; import net.minecraft.client.multiplayer.ClientLevel; diff --git a/src/main/java/forestry/apiculture/particles/package-info.java b/src/main/java/forestry/apiculture/particles/package-info.java index 9d5b5a3272..f088a9bd2d 100644 --- a/src/main/java/forestry/apiculture/particles/package-info.java +++ b/src/main/java/forestry/apiculture/particles/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.particles; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/apiculture/proxy/ApicultureClientHandler.java b/src/main/java/forestry/apiculture/proxy/ApicultureClientHandler.java index b03648c792..275da55dea 100644 --- a/src/main/java/forestry/apiculture/proxy/ApicultureClientHandler.java +++ b/src/main/java/forestry/apiculture/proxy/ApicultureClientHandler.java @@ -1,73 +1,65 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.proxy; +import forestry.api.ForestryConstants; import forestry.api.client.IClientModuleHandler; import forestry.apiculture.features.ApicultureBlocks; import forestry.apiculture.features.ApicultureMenuTypes; import forestry.apiculture.gui.*; import forestry.apiculture.models.ModelBee; import forestry.apiculture.particles.*; -import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.event.RegisterParticleProvidersEvent; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.neoforge.client.event.ModelEvent; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; +import net.neoforged.neoforge.client.event.RegisterParticleProvidersEvent; +import net.neoforged.neoforge.client.event.TextureAtlasStitchedEvent; public class ApicultureClientHandler implements IClientModuleHandler { @Override public void registerEvents(IEventBus modBus) { modBus.addListener(ApicultureClientHandler::setupClient); + modBus.addListener(ApicultureClientHandler::registerMenus); modBus.addListener(ApicultureClientHandler::registerParticleFactory); modBus.addListener(ApicultureClientHandler::handleSprites); modBus.addListener(ApicultureClientHandler::registerModelLoaders); } private static void setupClient(FMLClientSetupEvent event) { - event.enqueueWork(() -> { - ApicultureBlocks.BEE_COMB.getBlocks().forEach((block) -> ItemBlockRenderTypes.setRenderLayer(block, RenderType.cutout())); + // todo use JSON render_type field + event.enqueueWork(() -> ApicultureBlocks.BEE_COMB.getBlocks().forEach((block) -> ItemBlockRenderTypes.setRenderLayer(block, RenderType.cutout()))); + } - MenuScreens.register(ApicultureMenuTypes.ALVEARY.menuType(), GuiAlveary::new); - MenuScreens.register(ApicultureMenuTypes.ALVEARY_HYGROREGULATOR.menuType(), GuiAlvearyHygroregulator::new); - MenuScreens.register(ApicultureMenuTypes.ALVEARY_SIEVE.menuType(), GuiAlvearySieve::new); - MenuScreens.register(ApicultureMenuTypes.ALVEARY_SWARMER.menuType(), GuiAlvearySwarmer::new); - MenuScreens.register(ApicultureMenuTypes.BEE_HOUSING.menuType(), GuiBeeHousing::new); - }); + private static void registerMenus(RegisterMenuScreensEvent event) { + event.register(ApicultureMenuTypes.ALVEARY.menuType(), GuiAlveary::new); + event.register(ApicultureMenuTypes.ALVEARY_HYGROREGULATOR.menuType(), GuiAlvearyHygroregulator::new); + event.register(ApicultureMenuTypes.ALVEARY_SIEVE.menuType(), GuiAlvearySieve::new); + event.register(ApicultureMenuTypes.ALVEARY_SWARMER.menuType(), GuiAlvearySwarmer::new); + event.register(ApicultureMenuTypes.BEE_HOUSING.menuType(), GuiBeeHousing::new); } private static void registerParticleFactory(RegisterParticleProvidersEvent event) { - event.registerSprite(ApicultureParticles.BEE_EXPLORER_PARTICLE.get(), (data, level, x, y, z, xSpeed, ySpeed, zSpeed) -> new BeeExploreParticle(level, x, y, z, data.destination, data.color)); - event.registerSprite(ApicultureParticles.BEE_ROUND_TRIP_PARTICLE.get(), (data, level, x, y, z, xSpeed, ySpeed, zSpeed) -> new BeeRoundTripParticle(level, x, y, z, data.destination, data.color)); - event.registerSprite(ApicultureParticles.BEE_TARGET_ENTITY_PARTICLE.get(), (data, level, x, y, z, xSpeed, ySpeed, zSpeed) -> { - Entity entity = level.getEntity(data.entity); - return entity == null ? null : new BeeTargetEntityParticle(level, x, y, z, entity, data.color); + event.registerSprite(ApicultureParticles.BEE_EXPLORER_PARTICLE.value(), (data, level, x, y, z, xSpeed, ySpeed, zSpeed) -> new BeeExploreParticle(level, x, y, z, data.destination(), data.color())); + event.registerSprite(ApicultureParticles.BEE_ROUND_TRIP_PARTICLE.value(), (data, level, x, y, z, xSpeed, ySpeed, zSpeed) -> new BeeRoundTripParticle(level, x, y, z, data.destination(), data.color())); + event.registerSprite(ApicultureParticles.BEE_TARGET_ENTITY_PARTICLE.value(), (data, level, x, y, z, xSpeed, ySpeed, zSpeed) -> { + Entity entity = level.getEntity(data.entity()); + return entity == null ? null : new BeeTargetEntityParticle(level, x, y, z, entity, data.color()); }); } - private static void handleSprites(TextureStitchEvent.Post event) { + private static void handleSprites(TextureAtlasStitchedEvent event) { TextureAtlas map = event.getAtlas(); if (map.location().equals(TextureAtlas.LOCATION_PARTICLES)) { for (int i = 0; i < ParticleSnow.SPRITES.length; i++) { - ParticleSnow.SPRITES[i] = map.getSprite(new ResourceLocation("forestry:snow." + (i + 1))); + ParticleSnow.SPRITES[i] = map.getSprite(ForestryConstants.forestry("snow." + (i + 1))); } } } private static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register("bee_ge", new ModelBee.Loader()); + event.register(ForestryConstants.forestry("bee_ge"), new ModelBee.Loader()); } } diff --git a/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java b/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java deleted file mode 100644 index 93f2406c07..0000000000 --- a/src/main/java/forestry/apiculture/proxy/ProxyApiculture.java +++ /dev/null @@ -1,14 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.proxy; - -public class ProxyApiculture { -} diff --git a/src/main/java/forestry/apiculture/proxy/package-info.java b/src/main/java/forestry/apiculture/proxy/package-info.java index 8287f38496..421dcda29c 100644 --- a/src/main/java/forestry/apiculture/proxy/package-info.java +++ b/src/main/java/forestry/apiculture/proxy/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.proxy; diff --git a/src/main/java/forestry/apiculture/recipes/HygroregulatorRecipe.java b/src/main/java/forestry/apiculture/recipes/HygroregulatorRecipe.java index a3113a733e..13b9f63997 100644 --- a/src/main/java/forestry/apiculture/recipes/HygroregulatorRecipe.java +++ b/src/main/java/forestry/apiculture/recipes/HygroregulatorRecipe.java @@ -1,41 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.IHygroregulatorRecipe; import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; // recipes used by Alveary Hygroregulator public class HygroregulatorRecipe implements IHygroregulatorRecipe { - private final ResourceLocation id; - private final FluidStack liquid; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + SizedFluidIngredient.FLAT_CODEC.fieldOf("input_fluid").forGetter(HygroregulatorRecipe::getInputFluid), + Codec.INT.fieldOf("retain_time").forGetter(HygroregulatorRecipe::getRetainTime), + Codec.BYTE.fieldOf("humidity_steps").forGetter(HygroregulatorRecipe::getHumiditySteps), + Codec.BYTE.fieldOf("temperature_steps").forGetter(HygroregulatorRecipe::getTemperatureSteps) + ).apply(inst, HygroregulatorRecipe::new)); + private static final StreamCodec STREAM_CODEC = StreamCodec.of(Serializer::encode, Serializer::decode); + + private final SizedFluidIngredient liquid; private final byte humiditySteps; private final byte temperatureSteps; private final int retainTime; - public HygroregulatorRecipe(ResourceLocation id, FluidStack liquid, int retainTime, byte humiditySteps, byte temperatureSteps) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(liquid); - this.id = id; + public HygroregulatorRecipe(SizedFluidIngredient liquid, int retainTime, byte humiditySteps, byte temperatureSteps) { this.liquid = liquid; this.retainTime = retainTime; this.humiditySteps = humiditySteps; @@ -43,7 +36,7 @@ public HygroregulatorRecipe(ResourceLocation id, FluidStack liquid, int retainTi } @Override - public FluidStack getInputFluid() { + public SizedFluidIngredient getInputFluid() { return this.liquid; } @@ -63,15 +56,10 @@ public byte getTemperatureSteps() { } @Override - public ItemStack getResultItem(RegistryAccess pRegistryAccess) { + public ItemStack getResultItem(HolderLookup.Provider registries) { return ItemStack.EMPTY; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.HYGROREGULATOR.serializer(); @@ -83,32 +71,30 @@ public RecipeType getType() { } public static class Serializer implements RecipeSerializer { - @Override - public HygroregulatorRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - FluidStack liquid = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "liquid")); - int transferTime = GsonHelper.getAsInt(json, "time"); - byte humiditySteps = GsonHelper.getAsByte(json, "humidity_steps"); - byte temperatureSteps = GsonHelper.getAsByte(json, "temperature_steps"); - - return new HygroregulatorRecipe(recipeId, liquid, transferTime, humiditySteps, temperatureSteps); + public static void encode(RegistryFriendlyByteBuf buffer, HygroregulatorRecipe recipe) { + SizedFluidIngredient.STREAM_CODEC.encode(buffer, recipe.liquid); + buffer.writeVarInt(recipe.retainTime); + buffer.writeByte(recipe.humiditySteps); + buffer.writeByte(recipe.temperatureSteps); } - @Override - public HygroregulatorRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - FluidStack liquid = FluidStack.readFromPacket(buffer); + public static HygroregulatorRecipe decode(RegistryFriendlyByteBuf buffer) { + SizedFluidIngredient liquid = SizedFluidIngredient.STREAM_CODEC.decode(buffer); int retainTime = buffer.readVarInt(); byte humiditySteps = buffer.readByte(); byte temperatureSteps = buffer.readByte(); - return new HygroregulatorRecipe(recipeId, liquid, retainTime, humiditySteps, temperatureSteps); + return new HygroregulatorRecipe(liquid, retainTime, humiditySteps, temperatureSteps); } @Override - public void toNetwork(FriendlyByteBuf buffer, HygroregulatorRecipe recipe) { - recipe.liquid.writeToPacket(buffer); - buffer.writeVarInt(recipe.retainTime); - buffer.writeByte(recipe.humiditySteps); - buffer.writeByte(recipe.temperatureSteps); + public MapCodec codec() { + return CODEC; + } + + @Override + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/apiculture/recipes/package-info.java b/src/main/java/forestry/apiculture/recipes/package-info.java index 9e8cee3c08..1e0542277c 100644 --- a/src/main/java/forestry/apiculture/recipes/package-info.java +++ b/src/main/java/forestry/apiculture/recipes/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.recipes; diff --git a/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java b/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java deleted file mode 100644 index fcfcdea484..0000000000 --- a/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.render; - -/*@OnlyIn(Dist.CLIENT) -public class TextureHabitatLocator extends TextureAtlasSprite { - - private static TextureHabitatLocator instance; - - public static TextureHabitatLocator getInstance() { - return instance; - } - - @Nullable - private BlockPos targetBiome; - private boolean targetBiomeFound; - - private double currentAngle; - private double angleDelta; - - public TextureHabitatLocator(String iconName) { - //TODO texture size - super(new ResourceLocation(iconName), 0, 0); - instance = this; - } - - public void setTargetCoordinates(@Nullable BlockPos coordinates) { - this.targetBiome = coordinates; - this.targetBiomeFound = false; - } - - @Override - public void updateAnimation() { - Minecraft minecraft = Minecraft.getInstance(); - - if (minecraft.world != null && minecraft.player != null) { - BlockPos pos = minecraft.player.getPosition(); - updateCompass(minecraft.world, pos.getX(), pos.getZ(), minecraft.player.rotationYaw); - } else { - updateCompass(null, 0.0d, 0.0d, 0.0d); - } - } - - private void updateCompass(@Nullable World world, double playerX, double playerZ, double playerYaw) { - - double targetAngle; - - if (world == null || targetBiome == null) { - // No target has the locator spinning wildly. - targetAngle = Math.random() * Math.PI * 2.0d; - } else { - double xPart = targetBiome.getX() - playerX; - double zPart = targetBiome.getZ() - playerZ; - - if (Math.abs(xPart) + Math.abs(zPart) < 10 || targetBiomeFound) { - // spin steadily when the biome is found - targetAngle = currentAngle + 1; - targetBiomeFound = true; - } else { - playerYaw %= 360.0D; - targetAngle = -((playerYaw - 90.0f) * Math.PI / 180.0d - Math.atan2(zPart, xPart)); - } - } - - double angleChange = targetAngle - currentAngle; - while (angleChange < -Math.PI) { - angleChange += Math.PI * 2D; - } - - while (angleChange >= Math.PI) { - angleChange -= Math.PI * 2D; - } - - if (angleChange < -1.0D) { - angleChange = -1.0D; - } - - if (angleChange > 1.0D) { - angleChange = 1.0D; - } - - this.angleDelta += angleChange * 0.1D; - this.angleDelta *= 0.8D; - this.currentAngle += this.angleDelta; - //TODO - check it is frames and not interpolatedframedata - int i = (int) ((this.currentAngle / (Math.PI * 2D) + 1.0d) * this.frames.length) % this.frames.length; - while (i < 0) { - i = (i + this.frames.length) % this.frames.length; - } - - if (i != this.frameCounter) { - this.frameCounter = i; - //TODO - check - this.frames[this.frameCounter].uploadTextureSub(0, this.x, this.y, false); - } - - } -}*/ diff --git a/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java b/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java index 6972030df0..58840d2904 100644 --- a/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java +++ b/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java @@ -1,20 +1,20 @@ package forestry.apiculture.tiles; import forestry.api.apiculture.IBeeHousingInventory; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; class HiveBeeHousingInventory implements IBeeHousingInventory { + private final TileHive hive; + @Nullable private ItemStack queen; @Nullable private ItemStack drone; - private final TileHive hive; - public HiveBeeHousingInventory(TileHive hive) { this.hive = hive; } diff --git a/src/main/java/forestry/apiculture/tiles/TileApiary.java b/src/main/java/forestry/apiculture/tiles/TileApiary.java index 22365067e9..9baf7135e3 100644 --- a/src/main/java/forestry/apiculture/tiles/TileApiary.java +++ b/src/main/java/forestry/apiculture/tiles/TileApiary.java @@ -1,43 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.tiles; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; -import forestry.api.apiculture.hives.IHiveFrame; import forestry.apiculture.ApiaryBeeListener; import forestry.apiculture.ApiaryBeeModifier; import forestry.apiculture.IApiary; import forestry.apiculture.features.ApicultureTiles; -import forestry.apiculture.gui.ContainerBeeHousing; +import forestry.apiculture.gui.BeeHousingMenu; import forestry.apiculture.gui.GuiBeeHousing; import forestry.apiculture.inventory.IApiaryInventory; import forestry.apiculture.inventory.InventoryApiary; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.Tuple; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkHooks; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.List; public class TileApiary extends TileBeeHousingBase implements IApiary { private final IBeeModifier beeModifier = new ApiaryBeeModifier(); @@ -61,16 +45,10 @@ public IApiaryInventory getApiaryInventory() { @Override public Collection getBeeModifiers() { - List beeModifiers = new ArrayList<>(); + ArrayList beeModifiers = new ArrayList<>(); beeModifiers.add(this.beeModifier); - - for (Tuple frame : this.inventory.getFrames()) { - IHiveFrame hiveFrame = frame.getA(); - ItemStack stack = frame.getB(); - IBeeModifier beeModifier = hiveFrame.getBeeModifier(stack); - beeModifiers.add(beeModifier); - } + this.inventory.forEachFrame((hiveFrame, stack) -> beeModifiers.add(hiveFrame.getBeeModifier(stack))); return beeModifiers; } @@ -82,15 +60,16 @@ public Iterable getBeeListeners() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerBeeHousing(windowId, player.getInventory(), this, true, GuiBeeHousing.Icon.APIARY); + return new BeeHousingMenu(windowId, player.getInventory(), this, true, GuiBeeHousing.Icon.APIARY); } @Override - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { - NetworkHooks.openScreen(player, this, buffer -> { + public boolean interactNoItem(Level level, Player player, BlockPos pos) { + player.openMenu(this, buffer -> { buffer.writeBlockPos(pos); buffer.writeBoolean(true); NetworkUtil.writeEnum(buffer, GuiBeeHousing.Icon.APIARY); }); + return false; } } diff --git a/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java b/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java index 761daf5482..53e3623075 100644 --- a/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java +++ b/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java @@ -1,45 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.tiles; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; -import forestry.apiculture.BeehouseBeeModifier; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.IMutation; import forestry.apiculture.InventoryBeeHousing; import forestry.apiculture.features.ApicultureTiles; -import forestry.apiculture.gui.ContainerBeeHousing; +import forestry.apiculture.gui.BeeHousingMenu; import forestry.apiculture.gui.GuiBeeHousing; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkHooks; +import javax.annotation.Nullable; +import java.util.Collections; import java.util.List; public class TileBeeHouse extends TileBeeHousingBase { - private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); + private static final Iterable MODIFIER = Collections.singleton(new Modifier()); private final InventoryBeeHousing beeInventory; public TileBeeHouse(BlockPos pos, BlockState state) { super(ApicultureTiles.BEE_HOUSE.tileType(), pos, state, "bee.house"); - this.beeInventory = new InventoryBeeHousing(12); - this.beeInventory.disableAutomation(); + this.beeInventory = new InventoryBeeHousing(12); + this.beeInventory.disableAutomation(); setInternalInventory(this.beeInventory); } @@ -50,7 +42,7 @@ public IBeeHousingInventory getBeeInventory() { @Override public Iterable getBeeModifiers() { - return List.of(beeModifier); + return MODIFIER; } @Override @@ -60,15 +52,44 @@ public Iterable getBeeListeners() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerBeeHousing(windowId, player.getInventory(), this, false, GuiBeeHousing.Icon.BEE_HOUSE); + return new BeeHousingMenu(windowId, player.getInventory(), this, false, GuiBeeHousing.Icon.BEE_HOUSE); } @Override - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { - NetworkHooks.openScreen(player, this, buffer -> { + public boolean interactNoItem(Level level, Player player, BlockPos pos) { + player.openMenu(this, buffer -> { buffer.writeBlockPos(pos); buffer.writeBoolean(false); NetworkUtil.writeEnum(buffer, GuiBeeHousing.Icon.BEE_HOUSE); }); + return false; + } + + // no mutations/ignoble decay, 300% aging and flowering, 25% production + private static class Modifier implements IBeeModifier { + @Override + public float modifyProductionSpeed(IGenome genome, float currentSpeed) { + return 0.25f * currentSpeed; + } + + @Override + public float modifyMutationChance(IGenome genome, IGenome mate, IMutation mutation, float currentChance) { + return 0.0f; + } + + @Override + public float modifyAging(IGenome genome, @Nullable IGenome mate, float currentAging) { + return currentAging / 3f; + } + + @Override + public float modifyPollination(IGenome genome, float currentPollination) { + return 3.0f * currentPollination; + } + + @Override + public float modifyGeneticDecay(IGenome genome, float currentDecay) { + return 0.0f; + } } } diff --git a/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java b/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java index 9c3601fd0e..3de1b11300 100644 --- a/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java +++ b/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.tiles; -import com.mojang.authlib.GameProfile; import forestry.api.IForestryApi; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeekeepingLogic; @@ -27,22 +16,24 @@ import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; + +import javax.annotation.Nullable; public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing, IOwnedTile, IClimateProvider, IGuiBeeHousingDelegate, IStreamableGui { private final String hintKey; private final OwnerHandler ownerHandler = new OwnerHandler(); private final IBeekeepingLogic beeLogic; - protected IClimateProvider climate = IForestryApi.INSTANCE.getClimateManager().createDummyClimateProvider(); + protected IClimateProvider climate = IForestryApi.INSTANCE.getClimateManager().createDummyClimateProvider(); // CLIENT private int breedingProgressPercent = 0; @@ -68,35 +59,33 @@ public IBeekeepingLogic getBeekeepingLogic() { return this.beeLogic; } - /* LOADING & SAVING */ @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.beeLogic.write(compoundNBT); - this.ownerHandler.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.beeLogic.write(nbt, registries); + this.ownerHandler.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.beeLogic.read(compoundNBT); - this.ownerHandler.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.beeLogic.read(nbt, registries); + this.ownerHandler.read(nbt, registries); } @Override - public CompoundTag getUpdateTag() { - CompoundTag updateTag = super.getUpdateTag(); - this.beeLogic.write(updateTag); - this.ownerHandler.write(updateTag); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag updateTag = super.getUpdateTag(registries); + this.beeLogic.write(updateTag, registries); + this.ownerHandler.write(updateTag, registries); return updateTag; } @Override - @OnlyIn(Dist.CLIENT) - public void handleUpdateTag(CompoundTag tag) { - super.handleUpdateTag(tag); - this.beeLogic.read(tag); - this.ownerHandler.read(tag); + public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider registries) { + super.handleUpdateTag(tag, registries); + this.beeLogic.read(tag, registries); + this.ownerHandler.read(tag, registries); } @Override @@ -119,7 +108,7 @@ public HumidityType humidity() { @Override public void clientTick(Level level, BlockPos pos, BlockState state) { if (this.beeLogic.canDoBeeFX() && updateOnInterval(4)) { - this.beeLogic.doBeeFX(); + this.beeLogic.doBeeFX(); if (updateOnInterval(50)) { doPollenFX(level, getBlockPos().getX(), getBlockPos().getY(), getBlockPos().getZ()); @@ -127,26 +116,25 @@ public void clientTick(Level level, BlockPos pos, BlockState state) { } } - @OnlyIn(Dist.CLIENT) - public static void doPollenFX(Level world, double xCoord, double yCoord, double zCoord) { + public static void doPollenFX(Level level, double xCoord, double yCoord, double zCoord) { double fxX = xCoord + 0.5F; double fxY = yCoord + 0.25F; double fxZ = zCoord + 0.5F; float distanceFromCenter = 0.6F; - float leftRightSpreadFromCenter = distanceFromCenter * (world.random.nextFloat() - 0.5F); - float upSpread = world.random.nextFloat() * 6F / 16F; + float leftRightSpreadFromCenter = distanceFromCenter * (level.random.nextFloat() - 0.5F); + float upSpread = level.random.nextFloat() * 6F / 16F; fxY += upSpread; - ParticleRender.addEntityHoneyDustFX(world, fxX - distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); - ParticleRender.addEntityHoneyDustFX(world, fxX + distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); - ParticleRender.addEntityHoneyDustFX(world, fxX + leftRightSpreadFromCenter, fxY, fxZ - distanceFromCenter); - ParticleRender.addEntityHoneyDustFX(world, fxX + leftRightSpreadFromCenter, fxY, fxZ + distanceFromCenter); + ParticleRender.addEntityHoneyDustFX(level, fxX - distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); + ParticleRender.addEntityHoneyDustFX(level, fxX + distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); + ParticleRender.addEntityHoneyDustFX(level, fxX + leftRightSpreadFromCenter, fxY, fxZ - distanceFromCenter); + ParticleRender.addEntityHoneyDustFX(level, fxX + leftRightSpreadFromCenter, fxY, fxZ + distanceFromCenter); } @Override public void serverTick(Level level, BlockPos pos, BlockState state) { if (this.beeLogic.canWork()) { - this.beeLogic.doWork(); + this.beeLogic.doWork(); } // every 64 ticks, update the climate state in case of changed biome or climate (& is faster than modulus) @@ -161,20 +149,20 @@ public int getHealthScaled(int i) { } @Override - public void writeGuiData(FriendlyByteBuf data) { - data.writeVarInt(this.beeLogic.getBeeProgressPercent()); - NetworkUtil.writeClimateState(data, this.climate); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + buffer.writeVarInt(this.beeLogic.getBeeProgressPercent()); + NetworkUtil.writeClimateState(buffer, this.climate); } @Override - public void readGuiData(FriendlyByteBuf data) { - this.breedingProgressPercent = data.readVarInt(); - this.climate = NetworkUtil.readClimateState(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.breedingProgressPercent = buffer.readVarInt(); + this.climate = NetworkUtil.readClimateState(buffer); } // / IBEEHOUSING @Override - public Holder getBiome() { + public Holder getBiome(HolderLookup.Provider registries) { return this.level.getBiome(getBlockPos()); } @@ -195,7 +183,7 @@ public boolean isRaining() { } @Override - public GameProfile getOwner() { + public @Nullable ResolvableProfile getOwner() { return getOwnerHandler().getOwner(); } diff --git a/src/main/java/forestry/apiculture/tiles/TileHive.java b/src/main/java/forestry/apiculture/tiles/TileHive.java index b1fbc799e6..180a05a04a 100644 --- a/src/main/java/forestry/apiculture/tiles/TileHive.java +++ b/src/main/java/forestry/apiculture/tiles/TileHive.java @@ -1,34 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.apiculture.tiles; import com.google.common.base.Predicate; -import com.mojang.authlib.GameProfile; import forestry.api.IForestryApi; import forestry.api.apiculture.*; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.hives.IHiveTile; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.core.HumidityType; import forestry.api.core.IErrorLogic; import forestry.api.core.ISpectacleBlock; import forestry.api.core.TemperatureType; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.util.TickHelper; -import forestry.apiculture.ModuleApiculture; import forestry.apiculture.WorldgenBeekeepingLogic; import forestry.apiculture.blocks.BlockBeeHive; import forestry.apiculture.features.ApicultureTiles; import forestry.apiculture.genetics.effects.ThrottledBeeEffect; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.config.ForestryConfig; +import forestry.core.features.CoreDamageTypes; import forestry.core.inventory.InventoryAdapter; import forestry.core.network.packets.PacketActiveUpdate; import forestry.core.tiles.IActivatable; @@ -38,9 +26,11 @@ import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Difficulty; import net.minecraft.world.entity.EntitySelector; import net.minecraft.world.entity.LivingEntity; @@ -49,6 +39,7 @@ import net.minecraft.world.entity.monster.ZombifiedPiglin; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.entity.BlockEntity; @@ -62,7 +53,8 @@ import java.util.Collections; import java.util.List; -public class TileHive extends BlockEntity implements IHiveTile, IActivatable, IBeeHousing, ISpectacleBlock { +// The block entity used by wild bee hives. +public class TileHive extends BlockEntity implements IActivatable, IBeeHousing, ISpectacleBlock { private final InventoryAdapter contained = new InventoryAdapter(2, "Contained"); private final HiveBeeHousingInventory inventory; private final WorldgenBeekeepingLogic beeLogic; @@ -77,8 +69,8 @@ public class TileHive extends BlockEntity implements IHiveTile, IActivatable, IB private int calmTime; // For addons - public TileHive(BlockEntityType tileType, BlockPos pos, BlockState state) { - super(tileType, pos, state); + public TileHive(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); this.inventory = new HiveBeeHousingInventory(this); this.beeLogic = new WorldgenBeekeepingLogic(this); @@ -93,12 +85,12 @@ public TileHive(BlockPos pos, BlockState state) { } public void tick(Level level) { - this.tickHelper.onTick(); + this.tickHelper.onTick(); if (level.isClientSide) { if (this.active && this.tickHelper.updateOnInterval(4)) { if (this.beeLogic.canDoBeeFX()) { - this.beeLogic.doBeeFX(); + this.beeLogic.doBeeFX(); } } } else { @@ -107,21 +99,21 @@ public void tick(Level level) { if (this.tickHelper.updateOnInterval(this.angry ? 10 : 200)) { if (this.calmTime == 0) { if (canWork) { - if (this.angry && ModuleApiculture.hiveDamageOnAttack && (level.getLevelData().getDifficulty() != Difficulty.PEACEFUL || ModuleApiculture.hivesDamageOnPeaceful)) { + if (this.angry && ForestryConfig.SERVER.wildHiveDamage.get() && (level.getLevelData().getDifficulty() != Difficulty.PEACEFUL || ForestryConfig.SERVER.wildHivePeacefulDamage.get())) { AABB boundingBox = ThrottledBeeEffect.getBounding(this, getContainedBee().getGenome()); List entities = level.getEntitiesOfClass(LivingEntity.class, boundingBox, this.beeTargetPredicate); if (!entities.isEmpty()) { Collections.shuffle(entities); LivingEntity entity = entities.get(0); - if ((entity instanceof Player || !ModuleApiculture.hivesDamageOnlyPlayers) && (!entity.isInWater() || ModuleApiculture.hivesDamageUnderwater)) { + if ((entity instanceof Player || !ForestryConfig.SERVER.wildHiveDamageMobs.get()) && (!entity.isInWater() || ForestryConfig.SERVER.wildHivesDamageUnderwater.get())) { attack(entity, 2); } } } - this.beeLogic.doWork(); + this.beeLogic.doWork(); } } else { - this.calmTime--; + this.calmTime--; } } @@ -154,40 +146,36 @@ public void setContained(List bees) { } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.contained.read(compoundNBT); - this.beeLogic.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.contained.read(nbt, registries); + this.beeLogic.read(nbt, registries); } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.contained.write(compoundNBT); - this.beeLogic.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.contained.write(nbt, registries); + this.beeLogic.write(nbt, registries); } - @Override public void calmBees() { - this.calmTime = 5; - this.angry = false; + this.calmTime = 5; + this.angry = false; setActive(false); } - @Override public boolean isAngry() { return this.angry; } - @Override public void onAttack(Level world, BlockPos pos, Player player) { if (this.calmTime == 0) { - this.angry = true; + this.angry = true; } } - @Override public void onBroken(Level world, BlockPos pos, Player player, boolean canHarvest) { if (this.calmTime == 0) { attack(player, 10); @@ -208,7 +196,7 @@ private static void attack(LivingEntity entity, int maxDamage) { int damage = (int) (attackAmount * maxDamage); if (damage > 0) { // Entities are not attacked if they wear a full set of apiarist's armor. - int count = BeeManager.armorApiaristHelper.wearsItems(entity, null, true); + int count = IBeeProtection.getBeeProtectionLevel(entity, null, true); if (level.random.nextInt(4) >= count) { entity.hurt(CoreDamageTypes.source(level, CoreDamageTypes.HIVE), damage); } @@ -227,8 +215,8 @@ public void setActive(boolean active) { } this.active = active; - if (!this.level.isClientSide) { - NetworkUtil.sendNetworkPacket(new PacketActiveUpdate(this), this.worldPosition, this.level); + if (this.level instanceof ServerLevel serverLevel) { + NetworkUtil.sendToPlayersTrackingPos(new PacketActiveUpdate(this), this.worldPosition, serverLevel); } } @@ -238,26 +226,26 @@ public ClientboundBlockEntityDataPacket getUpdatePacket() { } @Override - public CompoundTag getUpdateTag() { - CompoundTag nbt = super.getUpdateTag(); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag nbt = super.getUpdateTag(registries); nbt.putBoolean("active", this.calmTime == 0); - this.beeLogic.write(nbt); + this.beeLogic.write(nbt, registries); return nbt; } // todo wtf are these two methods (loading from NBT several times per packet) @Override - public void handleUpdateTag(CompoundTag tag) { - super.handleUpdateTag(tag); + public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider registries) { + super.handleUpdateTag(tag, registries); setActive(tag.getBoolean("active")); - this.beeLogic.read(tag); + this.beeLogic.read(tag, registries); } @Override - public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { - super.onDataPacket(net, pkt); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider registries) { + super.onDataPacket(net, pkt, registries); CompoundTag nbt = pkt.getTag(); - handleUpdateTag(nbt); + handleUpdateTag(nbt, registries); } @Override @@ -282,12 +270,12 @@ public IBeekeepingLogic getBeekeepingLogic() { @Override public TemperatureType temperature() { - return IForestryApi.INSTANCE.getClimateManager().getTemperature(getBiome()); + return IForestryApi.INSTANCE.getClimateManager().getTemperature(getBiome(this.level.registryAccess())); } @Override public HumidityType humidity() { - return IForestryApi.INSTANCE.getClimateManager().getHumidity(getBiome()); + return IForestryApi.INSTANCE.getClimateManager().getHumidity(getBiome(this.level.registryAccess())); } @Override @@ -306,18 +294,18 @@ public boolean isRaining() { } @Override - public @Nullable Level getWorldObj() { + public @Nullable Level getLevel() { return this.level; } @Override - public Holder getBiome() { + public Holder getBiome(HolderLookup.Provider registries) { return this.level.getBiome(this.worldPosition); } @Override @Nullable - public GameProfile getOwner() { + public ResolvableProfile getOwner() { return null; } @@ -333,11 +321,11 @@ public IErrorLogic getErrorLogic() { } @Override - public BlockPos getCoordinates() { + public BlockPos getBlockPos() { return this.worldPosition; } - private record BeeTargetPredicate(IHiveTile hive) implements Predicate { + private record BeeTargetPredicate(TileHive hive) implements Predicate { @Override public boolean apply(@Nullable LivingEntity input) { if (input != null && input.isAlive() && !input.isInvisible()) { diff --git a/src/main/java/forestry/apiculture/tiles/package-info.java b/src/main/java/forestry/apiculture/tiles/package-info.java index 3b585ad1f8..2c8007bad8 100644 --- a/src/main/java/forestry/apiculture/tiles/package-info.java +++ b/src/main/java/forestry/apiculture/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.tiles; diff --git a/src/main/java/forestry/apiculture/villagers/ApicultureVillagers.java b/src/main/java/forestry/apiculture/villagers/ApicultureVillagers.java index 611cb4102f..7b70a37931 100644 --- a/src/main/java/forestry/apiculture/villagers/ApicultureVillagers.java +++ b/src/main/java/forestry/apiculture/villagers/ApicultureVillagers.java @@ -3,7 +3,7 @@ import com.google.common.collect.ImmutableSet; import forestry.api.ForestryTags; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.modules.ForestryModuleIds; import forestry.apiculture.blocks.BlockTypeApiculture; import forestry.apiculture.features.ApicultureBlocks; @@ -31,11 +31,10 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.trading.ItemCost; import net.minecraft.world.item.trading.MerchantOffer; -import net.minecraftforge.event.village.VillagerTradesEvent; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; -import net.minecraftforge.server.ServerLifecycleHooks; +import net.neoforged.neoforge.event.village.VillagerTradesEvent; +import net.neoforged.neoforge.registries.DeferredRegister; import java.util.List; import java.util.Objects; @@ -49,18 +48,18 @@ public class ApicultureVillagers { private static final DeferredRegister POINTS_OF_INTEREST = REGISTRY.getRegistry(Registries.POINT_OF_INTEREST_TYPE); private static final DeferredRegister PROFESSIONS = REGISTRY.getRegistry(Registries.VILLAGER_PROFESSION); - public static final RegistryObject POI_ESCRITOIRE = POINTS_OF_INTEREST.register("escritoire", () -> new PoiType(Set.copyOf(CoreBlocks.BASE.get(BlockTypeCoreTesr.ESCRITOIRE).block().getStateDefinition().getPossibleStates()), 1, 1)); - public static final RegistryObject PROF_BEEKEEPER = PROFESSIONS.register("beekeeper", () -> { + public static final Holder POI_ESCRITOIRE = POINTS_OF_INTEREST.register("escritoire", () -> new PoiType(Set.copyOf(CoreBlocks.BASE.get(BlockTypeCoreTesr.ESCRITOIRE).block().getStateDefinition().getPossibleStates()), 1, 1)); + public static final Holder PROF_BEEKEEPER = PROFESSIONS.register("beekeeper", () -> { ResourceKey key = Objects.requireNonNull(POI_ESCRITOIRE.getKey()); Predicate> jobSitePredicate = e -> e.is(key); return new VillagerProfession("beekeeper", jobSitePredicate, jobSitePredicate, ImmutableSet.of(), ImmutableSet.of(), SoundEvents.VILLAGER_WORK_LIBRARIAN); }); public static void villagerTrades(VillagerTradesEvent event) { - if (event.getType().equals(PROF_BEEKEEPER.get())) { + if (event.getType().equals(PROF_BEEKEEPER.value())) { Int2ObjectMap> trades = event.getTrades(); - List combs = ServerLifecycleHooks.getCurrentServer().registryAccess().registryOrThrow(Registries.ITEM).getTag(ForestryTags.Items.VILLAGE_COMBS).get().stream() - .map(Holder::get) + List combs = event.getRegistryAccess().registryOrThrow(Registries.ITEM).getTag(ForestryTags.Items.VILLAGE_COMBS).get().stream() + .map(Holder::value) .toList(); trades.get(1).add(new GiveHoneyCombForItem(combs, Items.WHEAT, new VillagerTrade.PriceInterval(2, 4), new VillagerTrade.PriceInterval(8, 12), 8, 2, 0F)); @@ -89,7 +88,7 @@ public record GiveHoneyCombForItem(List itemHoneyCombs, @Override public MerchantOffer getOffer(Entity trader, RandomSource rand) { - ItemStack buy = new ItemStack(this.buying, this.buyingPriceInfo.getPrice(rand)); + ItemCost buy = new ItemCost(this.buying, this.buyingPriceInfo.getPrice(rand)); ItemStack sell = new ItemStack(this.itemHoneyCombs.get(rand.nextInt(this.itemHoneyCombs.size())), this.sellingPriceInfo.getPrice(rand)); return new MerchantOffer(buy, sell, this.maxUses, this.xp, this.priceMult); } @@ -105,7 +104,7 @@ public MerchantOffer getOffer(Entity trader, RandomSource rand) { ItemStack randomHiveDrone = SpeciesUtil.getBeeSpecies(forestryMundane[rand.nextInt(forestryMundane.length)]).createStack(BeeLifeStage.DRONE); randomHiveDrone.setCount(this.sellingPriceInfo.getPrice(rand)); - return new MerchantOffer(new ItemStack(this.buying, this.buyingPriceInfo.getPrice(rand)), randomHiveDrone, this.maxUses, this.xp, this.priceMult); + return new MerchantOffer(new ItemCost(this.buying, this.buyingPriceInfo.getPrice(rand)), randomHiveDrone, this.maxUses, this.xp, this.priceMult); } } } diff --git a/src/main/java/forestry/apiculture/villagers/package-info.java b/src/main/java/forestry/apiculture/villagers/package-info.java index b527dd0977..36588f1a90 100644 --- a/src/main/java/forestry/apiculture/villagers/package-info.java +++ b/src/main/java/forestry/apiculture/villagers/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.apiculture.villagers; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java b/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java deleted file mode 100755 index 4c25db91bb..0000000000 --- a/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java +++ /dev/null @@ -1,428 +0,0 @@ -///******************************************************************************* -// * Copyright (c) 2011-2014 SirSengir. -// * All rights reserved. This program and the accompanying materials -// * are made available under the terms of the GNU Lesser Public License v3 -// * which accompanies this distribution, and is available at -// * http://www.gnu.org/licenses/lgpl-3.0.txt -// * -// * Various Contributors including, but not limited to: -// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges -// ******************************************************************************/ -//package forestry.apiculture.worldgen; -// -//import javax.annotation.Nullable; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Random; -// -//import net.minecraft.block.Block; -//import net.minecraft.block.DoorBlock; -//import net.minecraft.block.HorizontalBlock; -//import net.minecraft.block.LogBlock; -//import net.minecraft.block.SlabBlock; -//import net.minecraft.block.StairsBlock; -//import net.minecraft.block.TorchBlock; -//import net.minecraft.block.BlockState; -//import net.minecraft.block.Blocks; -//import net.minecraft.item.ItemStack; -//import net.minecraft.util.Direction; -//import net.minecraft.util.math.BlockPos; -//import net.minecraft.util.math.MutableBoundingBox; -//import net.minecraft.world.World; -//import net.minecraft.world.biome.Biome; -//import net.minecraft.world.gen.feature.StructurePiece; -//import net.minecraft.world.gen.feature.VillagePieces; -// -//import net.minecraftforge.registries.ForgeRegistry; -// -//import net.minecraftforge.fml.common.registry.ForgeRegistries; -//import net.minecraftforge.fml.common.registry.VillagerRegistry; -// -//import forestry.api.apiculture.BeeManager; -//import forestry.api.apiculture.genetics.EnumBeeType; -//import forestry.api.apiculture.FlowerManager; -//import forestry.api.apiculture.genetics.IAlleleBeeSpecies; -//import forestry.api.apiculture.genetics.IBee; -//import forestry.api.apiculture.genetics.IBeeGenome; -//import forestry.api.arboriculture.EnumForestryWoodType; -//import forestry.api.arboriculture.EnumVanillaWoodType; -//import forestry.api.arboriculture.IWoodAccess; -//import forestry.api.arboriculture.IWoodType; -//import forestry.api.arboriculture.TreeManager; -//import forestry.api.arboriculture.WoodBlockKind; -//import forestry.api.core.EnumHumidity; -//import forestry.api.core.EnumTemperature; -//import forestry.api.genetics.alleles.AlleleManager; -//import forestry.apiculture.ModuleApiculture; -//import forestry.apiculture.flowers.Flower; -//import forestry.apiculture.flowers.FlowerRegistry; -//import forestry.apiculture.tiles.TileBeeHouse; -//import forestry.arboriculture.ModuleArboriculture; -//import forestry.core.ModuleCore; -//import forestry.core.blocks.BlockBase; -//import forestry.core.config.Constants; -//import forestry.core.tiles.TileUtil; -//import forestry.modules.ForestryModuleUids; -//import forestry.modules.ModuleHelper; -////TODO - villages and worldgen -//public class VillageApiaristHouse extends VillagePieces.House1 { -// -// private static final Random random = new Random(); -// -// private final Materials materials; -// private int averageGroundLevel = -1; -// -// @SuppressWarnings("unused") -// public VillageApiaristHouse() { -// this.materials = new Materials(random); -// } -// -// public VillageApiaristHouse(VillagePieces.Start startPiece, int componentType, Random random, MutableBoundingBox boundingBox, Direction facing) { -// super(startPiece, componentType, random, boundingBox, facing); -// -// this.materials = new Materials(random); -// } -// -// @Nullable -// public static VillageApiaristHouse buildComponent(VillagePieces.Start startPiece, List pieces, Random random, int structureMinX, int structureMinY, int structureMinZ, Direction facing, int componentType) { -// MutableBoundingBox bbox = MutableBoundingBox.getComponentToAddBoundingBox(structureMinX, structureMinY, structureMinZ, -4, 0, 0, 12, 9, 12, facing); -// if (!canVillageGoDeeper(bbox) || StructurePiece.findIntersecting(pieces, bbox) != null) { -// return null; -// } -// -// return new VillageApiaristHouse(startPiece, componentType, random, bbox, facing); -// } -// -// @Override -// public boolean addComponentParts(World world, Random random, MutableBoundingBox structBoundingBox) { -// -// if (averageGroundLevel < 0) { -// averageGroundLevel = getAverageGroundLevel(world, structBoundingBox); -// if (averageGroundLevel < 0) { -// return true; -// } -// -// boundingBox.offset(0, averageGroundLevel - boundingBox.maxY + 9 - 1, 0); -// } -// -// fillWithBlocks(world, structBoundingBox, 1, 1, 1, 7, 4, 4, Blocks.AIR.getDefaultState(), Blocks.AIR.getDefaultState(), false); -// fillWithBlocks(world, structBoundingBox, 2, 1, 6, 8, 4, 10, Blocks.AIR.getDefaultState(), Blocks.AIR.getDefaultState(), false); -// -// // Garden -// buildGarden(world, structBoundingBox); -// -// // Garden fence -// fillWithBlocks(world, structBoundingBox, 1, 1, 6, 1, 1, 10, materials.fence, materials.fence, false); -// fillWithBlocks(world, structBoundingBox, 8, 1, 6, 8, 1, 10, materials.fence, materials.fence, false); -// fillWithBlocks(world, structBoundingBox, 2, 1, 10, 7, 1, 10, materials.fence, materials.fence, false); -// -// setBlockState(world, materials.fenceGate.with(HorizontalBlock.FACING, Direction.EAST), 8, 1, 8, structBoundingBox); -// setBlockState(world, materials.fenceGate.with(HorizontalBlock.FACING, Direction.EAST), 1, 1, 8, structBoundingBox); -// setBlockState(world, materials.fenceGate.with(HorizontalBlock.FACING, Direction.NORTH), 4, 1, 10, structBoundingBox); -// -// // Flowers -// plantFlowerGarden(world, structBoundingBox, 2, 1, 5, 7, 1, 9); -// -// // Apiaries -// buildApiaries(world, structBoundingBox); -// -// // Floor -// BlockState slabFloor = materials.slabs.with(SlabBlock.HALF, SlabBlock.EnumBlockHalf.BOTTOM); -// fillWithBlocks(world, structBoundingBox, 2, 0, 1, 6, 0, 4, slabFloor, slabFloor, false); -// fillWithBlocks(world, structBoundingBox, 1, 0, 1, 1, 0, 4, materials.planks, materials.planks, false); -// fillWithBlocks(world, structBoundingBox, 7, 0, 1, 7, 0, 4, materials.planks, materials.planks, false); -// -// BlockState cobblestoneState = Blocks.COBBLESTONE.getDefaultState(); -// fillWithBlocks(world, structBoundingBox, 0, 0, 0, 0, 2, 5, cobblestoneState, cobblestoneState, false); -// fillWithBlocks(world, structBoundingBox, 8, 0, 0, 8, 2, 5, cobblestoneState, cobblestoneState, false); -// fillWithBlocks(world, structBoundingBox, 1, 0, 0, 7, 1, 0, cobblestoneState, cobblestoneState, false); -// fillWithBlocks(world, structBoundingBox, 1, 0, 5, 7, 1, 5, cobblestoneState, cobblestoneState, false); -// -// fillWithBlocks(world, structBoundingBox, 0, 3, 0, 0, 3, 5, materials.planks, materials.planks, false); -// fillWithBlocks(world, structBoundingBox, 8, 3, 0, 8, 3, 5, materials.planks, materials.planks, false); -// fillWithBlocks(world, structBoundingBox, 1, 2, 0, 7, 3, 0, materials.planks, materials.planks, false); -// fillWithBlocks(world, structBoundingBox, 1, 2, 5, 7, 3, 5, materials.planks, materials.planks, false); -// -// // Ceiling -// BlockState slabCeiling = materials.slabs.with(SlabBlock.HALF, SlabBlock.EnumBlockHalf.TOP); -// fillWithBlocks(world, structBoundingBox, 1, 4, 1, 7, 4, 4, slabCeiling, slabCeiling, false); -// -// BlockState logBracing = materials.logs.with(LogBlock.LOG_AXIS, LogBlock.EnumAxis.X); -// fillWithBlocks(world, structBoundingBox, 0, 4, 1, 8, 4, 1, logBracing, logBracing, false); -// fillWithBlocks(world, structBoundingBox, 0, 4, 4, 8, 4, 4, logBracing, logBracing, false); -// -// fillWithBlocks(world, structBoundingBox, 0, 5, 2, 8, 5, 3, materials.planks, materials.planks, false); -// -// setBlockState(world, materials.planks, 0, 4, 2, structBoundingBox); -// setBlockState(world, materials.planks, 0, 4, 3, structBoundingBox); -// setBlockState(world, materials.planks, 8, 4, 2, structBoundingBox); -// setBlockState(world, materials.planks, 8, 4, 3, structBoundingBox); -// -// buildRoof(world, structBoundingBox); -// -// // sides of windows -// setBlockState(world, materials.planks, 0, 2, 1, structBoundingBox); -// setBlockState(world, materials.planks, 0, 2, 4, structBoundingBox); -// setBlockState(world, materials.planks, 8, 2, 1, structBoundingBox); -// setBlockState(world, materials.planks, 8, 2, 4, structBoundingBox); -// -// BlockState glassPaneState = Blocks.GLASS_PANE.getDefaultState(); -// -// // Windows on east side -// setBlockState(world, glassPaneState, 0, 2, 2, structBoundingBox); -// setBlockState(world, glassPaneState, 0, 2, 3, structBoundingBox); -// // stairs over window -// BlockState eastStairs = materials.stairs.with(StairsBlock.FACING, Direction.EAST); -// setBlockState(world, eastStairs, -1, 3, 2, structBoundingBox); -// setBlockState(world, eastStairs, -1, 3, 3, structBoundingBox); -// -// // Windows on west side -// setBlockState(world, glassPaneState, 8, 2, 2, structBoundingBox); -// setBlockState(world, glassPaneState, 8, 2, 3, structBoundingBox); -// // stairs over window -// BlockState westStairs = materials.stairs.with(StairsBlock.FACING, Direction.WEST); -// setBlockState(world, westStairs, 9, 3, 2, structBoundingBox); -// setBlockState(world, westStairs, 9, 3, 3, structBoundingBox); -// -// // Windows garden side -// setBlockState(world, glassPaneState, 2, 2, 5, structBoundingBox); -// setBlockState(world, glassPaneState, 3, 2, 5, structBoundingBox); -// setBlockState(world, glassPaneState, 4, 2, 5, structBoundingBox); -// -// // Windows front side -// setBlockState(world, glassPaneState, 5, 2, 0, structBoundingBox); -// setBlockState(world, glassPaneState, 6, 2, 5, structBoundingBox); -// -// // Escritoire -// if (random.nextInt(2) == 0) { -// BlockState escritoireBlock = ModuleCore.getBlocks().escritoire.getDefaultState().with(BlockBase.FACING, Direction.EAST); -// setBlockState(world, escritoireBlock, 1, 1, 3, structBoundingBox); -// } -// -// BlockState airState = Blocks.AIR.getDefaultState(); -// -// this.setBlockState(world, materials.door.with(DoorBlock.FACING, Direction.NORTH), 2, 1, 0, structBoundingBox); -// this.setBlockState(world, materials.door.with(DoorBlock.FACING, Direction.NORTH).with(DoorBlock.HALF, DoorBlock.EnumDoorHalf.UPPER), 2, 2, 0, structBoundingBox); -// -// this.setBlockState(world, Blocks.TORCH.getDefaultState().with(TorchBlock.FACING, Direction.NORTH), 2, 3, 1, structBoundingBox); -// -// if (isAirBlockAtCurrentPosition(world, new BlockPos(2, 0, -1), structBoundingBox) && !isAirBlockAtCurrentPosition(world, new BlockPos(2, -1, -1), structBoundingBox)) { -// setBlockState(world, materials.stairs.with(StairsBlock.FACING, Direction.NORTH), 2, 0, -1, structBoundingBox); -// } -// -// setBlockState(world, airState, 6, 1, 5, structBoundingBox); -// setBlockState(world, airState, 6, 2, 5, structBoundingBox); -// -// this.setBlockState(world, Blocks.TORCH.getDefaultState().with(TorchBlock.FACING, Direction.SOUTH), 6, 3, 4, structBoundingBox); -// -// this.setBlockState(world, materials.door.with(DoorBlock.FACING, Direction.SOUTH), 6, 1, 5, structBoundingBox); -// this.setBlockState(world, materials.door.with(DoorBlock.FACING, Direction.SOUTH).with(DoorBlock.HALF, DoorBlock.EnumDoorHalf.UPPER), 6, 2, 5, structBoundingBox); -// -// for (int i = 0; i < 5; ++i) { -// for (int j = 0; j < 9; ++j) { -// clearCurrentPositionBlocksUpwards(world, j, 7, i, structBoundingBox); -// replaceAirAndLiquidDownwards(world, Blocks.COBBLESTONE.getDefaultState(), j, -1, i, structBoundingBox); -// } -// } -// -// generateChest(world, structBoundingBox, random, 7, 1, 3, Constants.VILLAGE_NATURALIST_LOOT_KEY); -// -// // Inside Corners -// fillWithBlocks(world, structBoundingBox, 1, 1, 1, 1, 3, 1, materials.fence, materials.fence, false); -// fillWithBlocks(world, structBoundingBox, 1, 1, 4, 1, 3, 4, materials.fence, materials.fence, false); -// fillWithBlocks(world, structBoundingBox, 7, 1, 1, 7, 3, 1, materials.fence, materials.fence, false); -// fillWithBlocks(world, structBoundingBox, 7, 1, 4, 7, 3, 4, materials.fence, materials.fence, false); -// -// spawnVillagers(world, boundingBox, 2, 1, 2, 2); -// -// return true; -// } -// -// private void buildRoof(World world, MutableBoundingBox structBoundingBox) { -// for (int z = -1; z <= 2; ++z) { -// for (int x = 0; x <= 8; ++x) { -// BlockState northStairs = materials.stairs.with(StairsBlock.FACING, Direction.NORTH); -// setBlockState(world, northStairs, x, 4 + z, z, structBoundingBox); -// -// BlockState southStairs = materials.stairs.with(StairsBlock.FACING, Direction.SOUTH); -// setBlockState(world, southStairs, x, 4 + z, 5 - z, structBoundingBox); -// } -// } -// } -// -// private void buildGarden(World world, MutableBoundingBox box) { -// -// Block ground = Blocks.DIRT; -// if (structureType == 1) { // desert -// ground = Blocks.SAND; -// } -// -// for (int i = 1; i <= 8; i++) { -// for (int j = 6; j <= 10; j++) { -// replaceAirAndLiquidDownwards(world, ground.getDefaultState(), i, 0, j, box); -// } -// } -// } -// -// private void plantFlowerGarden(World world, MutableBoundingBox box, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { -// -// if (structureType == 1) { // desert -// setBlockState(world, Blocks.CACTUS.getDefaultState(), 4, 1, 7, box); -// return; -// } -// -// for (int i = minY; i <= maxY; ++i) { -// for (int j = minX; j <= maxX; ++j) { -// for (int k = minZ; k <= maxZ; ++k) { -// if (world.rand.nextBoolean()) { -// int xCoord = getXWithOffset(j, k); -// int yCoord = getYWithOffset(i); -// int zCoord = getZWithOffset(j, k); -// -// BlockPos pos = new BlockPos(xCoord, yCoord, zCoord); -// BlockState blockState = world.getBlockState(pos); -// if (!Blocks.RED_FLOWER.canBlockStay(world, pos, blockState)) { -// continue; -// } -// -// FlowerRegistry flowerRegistry = (FlowerRegistry) FlowerManager.flowerRegistry; -// Flower flower = flowerRegistry.getRandomPlantableFlower(FlowerManager.FlowerTypeVanilla, world.rand); -// if (flower != null) { -// setBlockState(world, flower.getBlockState(), j, i, k, box); -// } -// } -// } -// } -// } -// } -// -// private void buildApiaries(World world, MutableBoundingBox box) { -// populateApiary(world, box, new BlockPos(3, 1, 8)); -// populateApiary(world, box, new BlockPos(6, 1, 8)); -// } -// -// private void populateApiary(World world, MutableBoundingBox box, BlockPos pos) { -// int xCoord = getXWithOffset(pos.getX(), pos.getZ()); -// int yCoord = getYWithOffset(pos.getY()); -// int zCoord = getZWithOffset(pos.getX(), pos.getZ()); -// BlockPos posNew = new BlockPos(xCoord, yCoord, zCoord); -// -// if (!box.isVecInside(posNew)) { -// return; -// } -// -// BlockState blockState = world.getBlockState(posNew); -// if (ModuleApiculture.getBlocks().beeHouse == blockState.getBlock() || !world.isBlockLoaded(posNew.down())) { -// return; -// } -// -// BlockState beeHouseDefaultState = ModuleApiculture.getBlocks().beeHouse.getDefaultState(); -// world.setBlockState(posNew, beeHouseDefaultState, Constants.FLAG_BLOCK_SYNC); -// -// TileBeeHouse beeHouse = TileUtil.getTile(world, posNew, TileBeeHouse.class); -// if (beeHouse == null) { -// return; -// } -// -// ItemStack randomVillagePrincess = getRandomVillageBeeStack(world, posNew, EnumBeeType.PRINCESS); -// beeHouse.getBeeInventory().setQueen(randomVillagePrincess); -// -// ItemStack randomVillageDrone = getRandomVillageBeeStack(world, posNew, EnumBeeType.DRONE); -// beeHouse.getBeeInventory().setDrone(randomVillageDrone); -// } -// -// private static ItemStack getRandomVillageBeeStack(World world, BlockPos pos, EnumBeeType beeType) { -// IBee randomVillageBee = getRandomVillageBee(world, pos); -// return BeeManager.beeRoot.getMemberStack(randomVillageBee, beeType); -// } -// -// private static IBee getRandomVillageBee(World world, BlockPos pos) { -// -// // Get current biome -// Biome biome = world.getBiome(pos); -// -// List candidates; -// if (BeeManager.uncommonVillageBees != null && !BeeManager.uncommonVillageBees.isEmpty() && world.rand.nextDouble() < 0.2) { -// candidates = BeeManager.uncommonVillageBees; -// } else { -// candidates = BeeManager.commonVillageBees; -// } -// -// EnumTemperature biomeTemperature = EnumTemperature.getFromBiome(biome, pos); -// EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.getRainfall()); -// -// // Add bees that can live in this environment -// List valid = new ArrayList<>(); -// for (IBeeGenome genome : candidates) { -// if (checkBiomeHazard(genome, biomeTemperature, biomeHumidity)) { -// valid.add(genome); -// } -// } -// -// // No valid ones found, return any of the common ones. -// if (valid.isEmpty()) { -// int index = world.rand.nextInt(BeeManager.commonVillageBees.size()); -// IBeeGenome genome = BeeManager.commonVillageBees.get(index); -// return BeeManager.beeRoot.getBee(genome); -// } -// -// return BeeManager.beeRoot.getBee(valid.get(world.rand.nextInt(valid.size()))); -// } -// -// private static boolean checkBiomeHazard(IBeeGenome genome, EnumTemperature biomeTemperature, EnumHumidity biomeHumidity) { -// IAlleleBeeSpecies species = genome.getPrimary(); -// return AlleleManager.climateHelper.isWithinLimits(biomeTemperature, biomeHumidity, -// species.getTemperature(), genome.getToleranceTemp(), -// species.getHumidity(), genome.getToleranceHumid()); -// } -// -// @Override -// protected int chooseProfession(int villagerCount, int currentVillagerProfession) { -// ForgeRegistry registry = (ForgeRegistry) ForgeRegistries.VILLAGER_PROFESSIONS; -// -// if (villagerCount <= 0) { -// return registry.getID(ModuleApiculture.villagerApiarist); -// } else if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { -// return registry.getID(ModuleArboriculture.villagerArborist); -// } else { -// return currentVillagerProfession; -// } -// } -// -// private boolean isAirBlockAtCurrentPosition(World world, BlockPos pos, MutableBoundingBox box) { -// BlockState blockStateFromPos = getBlockStateFromPos(world, pos.getX(), pos.getY(), pos.getZ(), box); -// return blockStateFromPos.getBlock().isAir(blockStateFromPos, world, pos); -// } -// -// private static class Materials { -// public final BlockState planks; -// public final BlockState slabs; -// public final BlockState logs; -// public final BlockState stairs; -// public final BlockState fence; -// public final BlockState door; -// public final BlockState fenceGate; -// -// public Materials(Random random) { -// IWoodType woodType; -// boolean fireproof; -// -// if (ModuleHelper.isEnabled(ForestryModuleUids.ARBORICULTURE)) { -// woodType = EnumForestryWoodType.getRandom(random); -// fireproof = random.nextInt(4) == 0; -// } else { -// woodType = EnumVanillaWoodType.getRandom(random); -// fireproof = false; -// } -// -// IWoodAccess woodAccess = TreeManager.woodAccess; -// this.logs = woodAccess.getBlock(woodType, WoodBlockKind.LOG, fireproof).with(LogBlock.LOG_AXIS, LogBlock.EnumAxis.X); -// this.planks = woodAccess.getBlock(woodType, WoodBlockKind.PLANKS, fireproof); -// this.slabs = woodAccess.getBlock(woodType, WoodBlockKind.SLAB, fireproof); -// this.stairs = woodAccess.getBlock(woodType, WoodBlockKind.STAIRS, fireproof); -// this.fence = woodAccess.getBlock(woodType, WoodBlockKind.FENCE, fireproof); -// this.door = woodAccess.getBlock(woodType, WoodBlockKind.DOOR, false); -// this.fenceGate = woodAccess.getBlock(woodType, WoodBlockKind.FENCE_GATE, fireproof); -// } -// } -//} diff --git a/src/main/java/forestry/apiimpl/client/BeeClientManager.java b/src/main/java/forestry/apiimpl/client/BeeClientManager.java index 109bad019a..0bb28374ef 100644 --- a/src/main/java/forestry/apiimpl/client/BeeClientManager.java +++ b/src/main/java/forestry/apiimpl/client/BeeClientManager.java @@ -1,6 +1,6 @@ package forestry.apiimpl.client; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.client.apiculture.IBeeClientManager; import forestry.api.genetics.ILifeStage; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/forestry/apiimpl/client/ForestryClientApiImpl.java b/src/main/java/forestry/apiimpl/client/ForestryClientApiImpl.java index 5cdb678e2a..8a6d6c4f3b 100644 --- a/src/main/java/forestry/apiimpl/client/ForestryClientApiImpl.java +++ b/src/main/java/forestry/apiimpl/client/ForestryClientApiImpl.java @@ -8,7 +8,7 @@ import forestry.api.client.plugin.IClientHelper; import forestry.apiimpl.client.plugin.ClientHelper; import forestry.core.render.ForestryTextureManager; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; +import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/forestry/apiimpl/client/TreeClientManager.java b/src/main/java/forestry/apiimpl/client/TreeClientManager.java index 471b4a7a7c..4597b6b37c 100644 --- a/src/main/java/forestry/apiimpl/client/TreeClientManager.java +++ b/src/main/java/forestry/apiimpl/client/TreeClientManager.java @@ -1,7 +1,7 @@ package forestry.apiimpl.client; import com.mojang.datafixers.util.Pair; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.client.arboriculture.ILeafSprite; import forestry.api.client.arboriculture.ILeafTint; import forestry.api.client.arboriculture.ITreeClientManager; diff --git a/src/main/java/forestry/apiimpl/client/package-info.java b/src/main/java/forestry/apiimpl/client/package-info.java index 06dcbd41d8..b4256d4323 100644 --- a/src/main/java/forestry/apiimpl/client/package-info.java +++ b/src/main/java/forestry/apiimpl/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiimpl.client; diff --git a/src/main/java/forestry/apiimpl/client/plugin/package-info.java b/src/main/java/forestry/apiimpl/client/plugin/package-info.java index b07a9cfb83..fed6dc62fa 100644 --- a/src/main/java/forestry/apiimpl/client/plugin/package-info.java +++ b/src/main/java/forestry/apiimpl/client/plugin/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiimpl.client.plugin; diff --git a/src/main/java/forestry/apiimpl/package-info.java b/src/main/java/forestry/apiimpl/package-info.java index 76bb8377fb..60864b4b89 100644 --- a/src/main/java/forestry/apiimpl/package-info.java +++ b/src/main/java/forestry/apiimpl/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiimpl; diff --git a/src/main/java/forestry/apiimpl/plugin/ApicultureRegistration.java b/src/main/java/forestry/apiimpl/plugin/ApicultureRegistration.java index 343a98afb0..a729681fee 100644 --- a/src/main/java/forestry/apiimpl/plugin/ApicultureRegistration.java +++ b/src/main/java/forestry/apiimpl/plugin/ApicultureRegistration.java @@ -2,10 +2,10 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.IFlowerType; -import forestry.api.apiculture.genetics.IBeeEffect; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.IFlowerType; +import forestry.api.apiculture.bee.IBeeEffect; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.apiculture.hives.IHiveDefinition; import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.alleles.IAllele; diff --git a/src/main/java/forestry/apiimpl/plugin/ArboricultureRegistration.java b/src/main/java/forestry/apiimpl/plugin/ArboricultureRegistration.java index 6b33aafb09..6fcd849c23 100644 --- a/src/main/java/forestry/apiimpl/plugin/ArboricultureRegistration.java +++ b/src/main/java/forestry/apiimpl/plugin/ArboricultureRegistration.java @@ -1,8 +1,9 @@ package forestry.apiimpl.plugin; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import forestry.api.arboriculture.ICharcoalManager; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.ICharcoalPileWall; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.ITreeEffect; @@ -10,7 +11,7 @@ import forestry.api.plugin.IArboricultureRegistration; import forestry.api.plugin.ITreeSpeciesBuilder; import forestry.arboriculture.TreeManager; -import forestry.arboriculture.charcoal.CharcoalManager; +import forestry.arboriculture.charcoal.CharcoalPileWall; import net.minecraft.network.chat.TextColor; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; @@ -20,7 +21,7 @@ public class ArboricultureRegistration extends SpeciesRegistration fruits = new Registrar<>(IFruit.class); private final Registrar effects = new Registrar<>(ITreeEffect.class); private final ImmutableMap.Builder refractoryWaxables = ImmutableMap.builder(); - private final ICharcoalManager charcoalPitWalls = new CharcoalManager(); + private final ImmutableList.Builder charcoalPitWalls = ImmutableList.builder(); public ArboricultureRegistration(ISpeciesType type) { super(type); @@ -56,7 +57,17 @@ public void registerRefractoryWaxable(Block block, Block waxedForm) { @Override public void registerCharcoalPitWall(BlockState state, int charcoal) { - this.charcoalPitWalls.registerWall(state, charcoal); + this.charcoalPitWalls.add(new CharcoalPileWall(state, charcoal)); + } + + @Override + public void registerCharcoalPitWall(Block block, int charcoal) { + this.charcoalPitWalls.add(new CharcoalPileWall(block, charcoal)); + } + + @Override + public void registerCharcoalPitWall(ICharcoalPileWall wall) { + this.charcoalPitWalls.add(wall); } public ImmutableMap getFruits() { @@ -68,6 +79,6 @@ public ImmutableMap getEffects() { } public TreeManager buildTreeManager() { - return new TreeManager(this.refractoryWaxables.build(), new CharcoalManager()); + return new TreeManager(this.refractoryWaxables.build(), this.charcoalPitWalls.build()); } } diff --git a/src/main/java/forestry/apiimpl/plugin/BeeSpeciesBuilder.java b/src/main/java/forestry/apiimpl/plugin/BeeSpeciesBuilder.java index f0cb7b70b8..e95d191808 100644 --- a/src/main/java/forestry/apiimpl/plugin/BeeSpeciesBuilder.java +++ b/src/main/java/forestry/apiimpl/plugin/BeeSpeciesBuilder.java @@ -1,8 +1,8 @@ package forestry.apiimpl.plugin; -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.IBeeJubilance; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.api.core.IProduct; import forestry.api.plugin.IBeeSpeciesBuilder; import forestry.apiculture.BeeSpecies; diff --git a/src/main/java/forestry/apiimpl/plugin/CircuitRegistration.java b/src/main/java/forestry/apiimpl/plugin/CircuitRegistration.java index 42d034a01b..a41e0a6787 100644 --- a/src/main/java/forestry/apiimpl/plugin/CircuitRegistration.java +++ b/src/main/java/forestry/apiimpl/plugin/CircuitRegistration.java @@ -3,7 +3,7 @@ import forestry.api.circuits.CircuitHolder; import forestry.api.circuits.ICircuit; import forestry.api.plugin.ICircuitRegistration; -import forestry.core.circuits.CircuitLayout; +import forestry.api.circuits.CircuitLayout; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/forestry/apiimpl/plugin/GeneticRegistration.java b/src/main/java/forestry/apiimpl/plugin/GeneticRegistration.java index 1e6a8ab9c8..f90dd25883 100644 --- a/src/main/java/forestry/apiimpl/plugin/GeneticRegistration.java +++ b/src/main/java/forestry/apiimpl/plugin/GeneticRegistration.java @@ -73,11 +73,6 @@ public void defineTaxon(String parent, String name, Consumer acti } } - @Override - public ISpeciesTypeBuilder registerSpeciesType(ResourceLocation id, ISpeciesTypeFactory factory) { - return this.speciesTypes.create(id, new SpeciesTypeBuilder(factory)); - } - @Override public void modifySpeciesType(ResourceLocation id, Consumer action) { this.speciesTypes.modify(id, action); diff --git a/src/main/java/forestry/apiimpl/plugin/PluginManager.java b/src/main/java/forestry/apiimpl/plugin/PluginManager.java index ea7e2ae71b..48d19465ef 100644 --- a/src/main/java/forestry/apiimpl/plugin/PluginManager.java +++ b/src/main/java/forestry/apiimpl/plugin/PluginManager.java @@ -5,11 +5,10 @@ import com.mojang.datafixers.util.Pair; import forestry.Forestry; import forestry.api.IForestryApi; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.circuits.CircuitHolder; -import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; +import forestry.api.circuits.CircuitLayout; import forestry.api.client.IForestryClientApi; import forestry.api.client.arboriculture.ILeafSprite; import forestry.api.client.arboriculture.ILeafTint; @@ -30,7 +29,6 @@ import forestry.apiimpl.client.TreeClientManager; import forestry.apiimpl.client.plugin.ClientRegistration; import forestry.arboriculture.client.FixedLeafTint; -import forestry.core.circuits.CircuitLayout; import forestry.core.circuits.CircuitManager; import forestry.core.errors.ErrorManager; import forestry.core.genetics.PollenManager; @@ -43,10 +41,7 @@ import it.unimi.dsi.fastutil.objects.Object2ShortOpenHashMap; import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; -import javax.annotation.Nullable; import java.util.*; public class PluginManager { @@ -59,7 +54,7 @@ public static void loadPlugins() { serviceLoader.stream().map(ServiceLoader.Provider::get).sorted(Comparator.comparing(IForestryPlugin::id)).forEachOrdered(plugin -> { if (plugin.shouldLoad()) { if (plugin.getClass() == DefaultForestryPlugin.class) { - LOADED_PLUGINS.add(0, plugin); + LOADED_PLUGINS.addFirst(plugin); } else { LOADED_PLUGINS.add(plugin); } @@ -100,32 +95,24 @@ public static void registerCircuits() { CircuitRegistration registration = new CircuitRegistration(); for (IForestryPlugin plugin : LOADED_PLUGINS) { - // TODO remove in 1.20 when FMLCommonSetupEvent throws - // rethrow swallowed exception - try { - plugin.registerCircuits(registration); - } catch (Throwable e) { - asyncThrown = new RuntimeException("An error was thrown by plugin " + plugin.id() + " during IForestryPlugin.registerCircuits", e); - Forestry.LOGGER.fatal(asyncThrown); - } + plugin.registerCircuits(registration); } ArrayList layouts = registration.getLayouts(); - ImmutableMap.Builder layoutsByIdBuilder = ImmutableMap.builderWithExpectedSize(layouts.size()); + ImmutableMap.Builder layoutsByIdBuilder = ImmutableMap.builderWithExpectedSize(layouts.size()); for (CircuitLayout layout : layouts) { // Layouts by ID - layoutsByIdBuilder.put(layout.getId(), layout); + layoutsByIdBuilder.put(layout.id(), layout); } - ImmutableMap layoutsById = layoutsByIdBuilder.build(); + ImmutableMap layoutsById = layoutsByIdBuilder.build(); ArrayList circuits = registration.getCircuits(); - ImmutableMultimap.Builder circuitHoldersBuilder = new ImmutableMultimap.Builder<>(); - ImmutableMap.Builder circuitsBuilder = ImmutableMap.builderWithExpectedSize(circuits.size()); + ImmutableMultimap.Builder circuitHoldersBuilder = new ImmutableMultimap.Builder<>(); for (CircuitHolder holder : circuits) { - ICircuitLayout layout = layoutsById.get(holder.layoutId()); + CircuitLayout layout = layoutsById.get(holder.layoutId()); if (layout == null) { throw new IllegalStateException("Attempted to register a CircuitHolder but no layout was registered with its layout ID: " + holder); @@ -133,13 +120,10 @@ public static void registerCircuits() { // Circuit holders by layout circuitHoldersBuilder.put(layout, holder); - // Circuits by ID - ICircuit circuit = holder.circuit(); - circuitsBuilder.put(circuit.getId(), circuit); } try { - ((ForestryApiImpl) IForestryApi.INSTANCE).setCircuitManager(new CircuitManager(circuitHoldersBuilder.build(), layoutsById, circuitsBuilder.buildOrThrow())); + ((ForestryApiImpl) IForestryApi.INSTANCE).setCircuitManager(new CircuitManager(circuitHoldersBuilder.build(), layoutsById)); } catch (IllegalArgumentException exception) { Forestry.LOGGER.fatal("Failed to register circuits: two circuits were registered with the same ID"); throw exception; @@ -239,20 +223,6 @@ public static void registerPollen() { ((ForestryApiImpl) IForestryApi.INSTANCE).setPollenManager(new PollenManager(ImmutableMap.copyOf(pollenTypes))); } - // Todo remove in 1.20 when FMLCommonSetupEvent throws exceptions again - @Nullable - @Deprecated - private static RuntimeException asyncThrown = null; - - @Deprecated - public static void registerAsyncException(IEventBus modBus) { - modBus.addListener((FMLLoadCompleteEvent event) -> { - if (asyncThrown != null) { - throw asyncThrown; - } - }); - } - public static void registerClient() { ClientRegistration registration = new ClientRegistration(); @@ -309,8 +279,8 @@ public static void registerClient() { // default sapling block and item models (removes the "tree_" prefix) String path = id.getPath().replace("tree_", ""); models.put(species, Pair.of( - new ResourceLocation(id.getNamespace(), "block/sapling/" + path), - new ResourceLocation(id.getNamespace(), "item/sapling/" + path) + ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "block/sapling/" + path), + ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "item/sapling/" + path) )); } } @@ -332,8 +302,8 @@ public static void registerClient() { // default butterfly item and entity textures String path = id.getPath().replace("butterfly_", ""); butterflyTextures.put(species, butterflyTexturesById.getOrDefault(id, Pair.of( - new ResourceLocation(id.getNamespace(), "item/butterfly/" + path), - new ResourceLocation(id.getNamespace(), "textures/entity/butterfly/" + path + ".png") + ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "item/butterfly/" + path), + ResourceLocation.fromNamespaceAndPath(id.getNamespace(), "textures/entity/butterfly/" + path + ".png") ))); } } diff --git a/src/main/java/forestry/apiimpl/plugin/SpeciesTypeBuilder.java b/src/main/java/forestry/apiimpl/plugin/SpeciesTypeBuilder.java index 64b1b7a88b..3a9e0dfadf 100644 --- a/src/main/java/forestry/apiimpl/plugin/SpeciesTypeBuilder.java +++ b/src/main/java/forestry/apiimpl/plugin/SpeciesTypeBuilder.java @@ -19,8 +19,8 @@ import java.util.Set; import java.util.function.Consumer; -public class SpeciesTypeBuilder implements ISpeciesTypeBuilder { - private final ISpeciesTypeFactory typeFactory; +public class SpeciesTypeBuilder> implements ISpeciesTypeBuilder { + private final ISpeciesTypeFactory typeFactory; private final Set stages; @Nullable @@ -29,7 +29,7 @@ public class SpeciesTypeBuilder implements ISpeciesTypeBuilder { private Consumer karyotype = null; private Consumer> researchMaterials; - public SpeciesTypeBuilder(ISpeciesTypeFactory typeFactory) { + public SpeciesTypeBuilder(ISpeciesTypeFactory typeFactory) { this.typeFactory = typeFactory; this.stages = new LinkedHashSet<>(); @@ -86,7 +86,7 @@ public void buildResearchMaterials(Reference2FloatMap materialMap) { this.researchMaterials.accept(materialMap); } - public ISpeciesType build() { + public T build() { Preconditions.checkState(this.karyotype != null, "Missing karyotype for species type"); Karyotype.Builder builder = new Karyotype.Builder(); diff --git a/src/main/java/forestry/apiimpl/plugin/TreeSpeciesBuilder.java b/src/main/java/forestry/apiimpl/plugin/TreeSpeciesBuilder.java index 3a3321b29a..d11a5d7fe5 100644 --- a/src/main/java/forestry/apiimpl/plugin/TreeSpeciesBuilder.java +++ b/src/main/java/forestry/apiimpl/plugin/TreeSpeciesBuilder.java @@ -1,9 +1,8 @@ package forestry.apiimpl.plugin; import com.google.common.base.Preconditions; -import forestry.api.arboriculture.ITreeGenData; import forestry.api.arboriculture.ITreeGenerator; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.plugin.ITreeSpeciesBuilder; @@ -48,7 +47,7 @@ public ITreeSpeciesBuilder setWoodType(IWoodType woodType) { } @Override - public ITreeSpeciesBuilder setTreeFeature(Function> factory) { + public ITreeSpeciesBuilder setTreeFeature(Function> factory) { Preconditions.checkState(this.woodType != null, "Must call setWoodType before setTreeFeature"); return setGenerator(new DefaultTreeGenerator(factory, this.woodType)); diff --git a/src/main/java/forestry/apiimpl/plugin/package-info.java b/src/main/java/forestry/apiimpl/plugin/package-info.java index b040764961..9145595811 100644 --- a/src/main/java/forestry/apiimpl/plugin/package-info.java +++ b/src/main/java/forestry/apiimpl/plugin/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.apiimpl.plugin; diff --git a/src/main/java/forestry/arboriculture/DummyFruit.java b/src/main/java/forestry/arboriculture/DummyFruit.java index 5f8c907caf..48d26487ec 100644 --- a/src/main/java/forestry/arboriculture/DummyFruit.java +++ b/src/main/java/forestry/arboriculture/DummyFruit.java @@ -1,24 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture; import forestry.api.arboriculture.genetics.IFruit; -import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.core.IProduct; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.TreeChromosomes; -import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; @@ -45,17 +32,7 @@ public List getFruits(IGenome genome, Level level, int ripeningTime) } @Override - public boolean requiresFruitBlocks() { - return false; - } - - @Override - public boolean trySpawnFruitBlock(IGenome genome, LevelAccessor world, RandomSource rand, BlockPos pos) { - return false; - } - - @Override - public int getColour(IGenome genome, BlockGetter world, BlockPos pos, int ripeningTime) { + public int getColour(IGenome genome, BlockGetter level, BlockPos pos, int ripeningTime) { return 0xffffff; } @@ -71,12 +48,7 @@ public boolean isFruitLeaf() { @Override public float getFruitChance(IGenome genome, LevelAccessor level) { - ITreeSpeciesType treeRoot = SpeciesUtil.TREE_TYPE.get(); - if (treeRoot == null) { - return 0f; - } - //float yieldModifier = treeRoot.getTreekeepingMode(level).getYieldModifier(genome, 1.0F); - return genome.getActiveValue(TreeChromosomes.YIELD) * 2.5F;// * yieldModifier; + return genome.getActiveValue(TreeChromosomes.YIELD) * 2.5f; } @Override @@ -96,7 +68,7 @@ public List getSpecialty() { @Nullable @Override - public ResourceLocation getSprite(IGenome genome, BlockGetter world, BlockPos pos, int ripeningTime) { + public ResourceLocation getSprite(IGenome genome, BlockGetter level, BlockPos pos, int ripeningTime) { return getDecorativeSprite(); } diff --git a/src/main/java/forestry/arboriculture/Fruit.java b/src/main/java/forestry/arboriculture/Fruit.java index 05622b792d..53499c73b6 100644 --- a/src/main/java/forestry/arboriculture/Fruit.java +++ b/src/main/java/forestry/arboriculture/Fruit.java @@ -22,7 +22,7 @@ public Fruit(boolean dominant, int ripeningPeriod, List products) { } @Override - public List getFruits(@Nullable IGenome genome, Level level, int ripeningTime) { + public List getFruits(IGenome genome, Level level, int ripeningTime) { RandomSource rand = level.random; if (ripeningTime >= this.ripeningPeriod) { diff --git a/src/main/java/forestry/arboriculture/IWoodTyped.java b/src/main/java/forestry/arboriculture/IWoodTyped.java index 615ea10bc6..9636b78958 100755 --- a/src/main/java/forestry/arboriculture/IWoodTyped.java +++ b/src/main/java/forestry/arboriculture/IWoodTyped.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture; import forestry.api.arboriculture.IWoodType; diff --git a/src/main/java/forestry/arboriculture/ModuleArboriculture.java b/src/main/java/forestry/arboriculture/ModuleArboriculture.java index 08e676fdd2..c7934190b4 100644 --- a/src/main/java/forestry/arboriculture/ModuleArboriculture.java +++ b/src/main/java/forestry/arboriculture/ModuleArboriculture.java @@ -1,46 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import forestry.api.arboriculture.TreeManager; -import forestry.api.arboriculture.genetics.ITree; +import forestry.api.ForestryCapabilities; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.client.IClientModuleHandler; -import forestry.api.core.IArmorNaturalist; -import forestry.api.genetics.IIndividual; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.api.modules.IPacketRegistry; +import forestry.arboriculture.capabilities.SpectacleVision; import forestry.arboriculture.client.ArboricultureClientHandler; import forestry.arboriculture.commands.CommandTree; import forestry.arboriculture.features.ArboricultureItems; import forestry.arboriculture.items.ForestryBoatDispenserBehavior; import forestry.arboriculture.network.PacketRipeningUpdate; import forestry.arboriculture.villagers.ArboricultureVillagers; +import forestry.core.features.CoreItems; import forestry.core.genetics.capability.IndividualHandlerItem; import forestry.core.network.PacketIdClient; import forestry.core.utils.SpeciesUtil; import forestry.modules.BlankForestryModule; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.DispenserBlock; import net.minecraft.world.level.block.state.properties.WoodType; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; -import net.minecraftforge.event.AttachCapabilitiesEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.function.Consumer; @@ -53,30 +41,10 @@ public ResourceLocation getId() { @Override public void registerEvents(IEventBus modBus) { - MinecraftForge.EVENT_BUS.addListener(ArboricultureVillagers::villagerTrades); + NeoForge.EVENT_BUS.addListener(ArboricultureVillagers::villagerTrades); modBus.addListener(ModuleArboriculture::registerCapabilities); modBus.addListener(ModuleArboriculture::commonSetup); - MinecraftForge.EVENT_BUS.addGenericListener(ItemStack.class, ModuleArboriculture::attachCapabilities); - } - - private static void attachCapabilities(AttachCapabilitiesEvent event) { - // Add genetics capabilities to vanilla saplings - if (!event.getCapabilities().containsKey(IIndividual.CAPABILITY_ID)) { - ItemStack stack = event.getObject(); - - ITreeSpeciesType type = SpeciesUtil.TREE_TYPE.get(); - ITree individual = type.getVanillaIndividual(stack.getItem()); - - if (individual != null) { - event.addCapability(IIndividual.CAPABILITY_ID, new IndividualHandlerItem(type, stack, individual, TreeLifeStage.SAPLING)); - } - } - } - - @Override - public void setupApi() { - TreeManager.woodAccess = WoodAccess.INSTANCE; } @Override @@ -85,7 +53,11 @@ public void addToRootCommand(LiteralArgumentBuilder command) } private static void registerCapabilities(RegisterCapabilitiesEvent event) { - event.register(IArmorNaturalist.class); + event.registerItem(ForestryCapabilities.SPECTACLE_VISION, (stack, v) -> SpectacleVision.INSTANCE, CoreItems.SPECTACLES); + + // Add genetics capabilities to vanilla saplings + ITreeSpeciesType type = SpeciesUtil.TREE_TYPE.get(); + type.getAllVanillaIndividuals().forEach((item, individual) -> event.registerItem(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM, (stack, v) -> new IndividualHandlerItem(type, stack, individual, TreeLifeStage.SAPLING), item)); } private static void commonSetup(FMLCommonSetupEvent event) { @@ -99,8 +71,8 @@ private static void commonSetup(FMLCommonSetupEvent event) { } @Override - public void registerPackets(IPacketRegistry registry) { - registry.clientbound(PacketIdClient.RIPENING_UPDATE, PacketRipeningUpdate.class, PacketRipeningUpdate::decode, PacketRipeningUpdate::handle); + public void registerPackets(PayloadRegistrar registrar) { + registrar.playToClient(PacketIdClient.RIPENING_UPDATE, StreamCodec.of(PacketRipeningUpdate::encode, PacketRipeningUpdate::decode), PacketRipeningUpdate::handle); } @Override diff --git a/src/main/java/forestry/arboriculture/ModuleCharcoal.java b/src/main/java/forestry/arboriculture/ModuleCharcoal.java deleted file mode 100644 index d8e22301e1..0000000000 --- a/src/main/java/forestry/arboriculture/ModuleCharcoal.java +++ /dev/null @@ -1,22 +0,0 @@ -package forestry.arboriculture; - -import forestry.api.IForestryApi; -import forestry.api.arboriculture.TreeManager; -import forestry.api.modules.ForestryModule; -import forestry.api.modules.ForestryModuleIds; -import forestry.modules.BlankForestryModule; -import net.minecraft.resources.ResourceLocation; - -// todo: merge into arboriculture in 1.21 -@ForestryModule -public class ModuleCharcoal extends BlankForestryModule { - @Override - public ResourceLocation getId() { - return ForestryModuleIds.CHARCOAL; - } - - @Override - public void setupApi() { - TreeManager.charcoalManager = IForestryApi.INSTANCE.getTreeManager().getCharcoalManager(); - } -} diff --git a/src/main/java/forestry/arboriculture/PodFruit.java b/src/main/java/forestry/arboriculture/PodFruit.java index f5724d2128..ba3e5e528e 100644 --- a/src/main/java/forestry/arboriculture/PodFruit.java +++ b/src/main/java/forestry/arboriculture/PodFruit.java @@ -1,34 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture; -import forestry.api.ForestryTags; +import forestry.api.IForestryApi; +import forestry.api.arboriculture.IWoodAccess; +import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.genetics.IFruit; +import forestry.api.arboriculture.genetics.IPodFruit; import forestry.api.core.IProduct; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.TreeChromosomes; +import forestry.arboriculture.blocks.BlockFruitPod; import forestry.arboriculture.blocks.ForestryPodType; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.SpeciesUtil; +import forestry.arboriculture.features.ArboricultureBlocks; +import forestry.arboriculture.tiles.TileFruitPod; +import forestry.core.ClientsideCode; import net.minecraft.core.BlockPos; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.TagKey; -import net.minecraft.util.RandomSource; +import net.minecraft.core.Direction; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import javax.annotation.Nullable; import java.util.List; // Fruits that grow on the side of a tree's trunk, like cocoa beans -public class PodFruit extends Fruit { +// todo use loot tables like Vanilla +public class PodFruit extends Fruit implements IPodFruit { private final ForestryPodType type; public PodFruit(boolean dominant, ForestryPodType type, List products) { @@ -38,31 +35,60 @@ public PodFruit(boolean dominant, ForestryPodType type, List products) } @Override - public boolean requiresFruitBlocks() { - return true; + public boolean canSurviveOn(BlockState state) { + IWoodAccess manager = IForestryApi.INSTANCE.getTreeManager().getWoodAccess(); + + IWoodType woodType = switch (this.type) { + case DATES -> ForestryWoodType.PALM; + case PAPAYA -> ForestryWoodType.PAPAYA; + }; + + return state.is(manager.getLogBlockTag(woodType, false)) || state.is(manager.getLogBlockTag(woodType, true)); } - @Override - public boolean trySpawnFruitBlock(IGenome genome, LevelAccessor world, RandomSource rand, BlockPos pos) { - if (rand.nextFloat() > getFruitChance(genome, world)) { + public static boolean isValidPodLocation(LevelReader level, BlockPos pos, Direction direction, IPodFruit fruit) { + pos = pos.relative(direction); + if (!level.hasChunkAt(pos)) { return false; } + return fruit.canSurviveOn(level.getBlockState(pos)); + } - if (this.type == ForestryPodType.COCOA) { - return BlockUtil.tryPlantCocoaPod(world, pos); - } else { - IFruit activeAllele = genome.getActiveValue(TreeChromosomes.FRUIT); - return SpeciesUtil.TREE_TYPE.get().setFruitBlock(world, genome, activeAllele, genome.getActiveValue(TreeChromosomes.YIELD), pos); + @Nullable + public static Direction getValidPodFacing(LevelAccessor level, BlockPos pos, IFruit fruit) { + if (!(fruit instanceof IPodFruit podFruit)) { + return null; + } + for (Direction facing : Direction.Plane.HORIZONTAL) { + if (isValidPodLocation(level, pos, facing, podFruit)) { + return facing; + } } + return null; } @Override - public TagKey getLogTag() { - return switch (this.type) { - case DATES -> ForestryTags.Blocks.PALM_LOGS; - case PAPAYA -> ForestryTags.Blocks.PAPAYA_LOGS; - default -> BlockTags.JUNGLE_LOGS; - }; + public boolean tryPlace(LevelAccessor level, BlockPos pos, IGenome genome) { + Direction facing = getValidPodFacing(level, pos, this); + if (facing == null) { + return false; + } + + BlockState state = ArboricultureBlocks.PODS.get(this.type).defaultState().setValue(BlockFruitPod.FACING, facing); + + if (level.setBlock(pos, state, Block.UPDATE_CLIENTS | Block.UPDATE_KNOWN_SHAPE)) { + if (level.getBlockEntity(pos) instanceof TileFruitPod pod) { + pod.setProperties(genome, this, genome.getActiveValue(TreeChromosomes.YIELD)); + + if (level.isClientSide()) { + ClientsideCode.markForUpdate(pos); + } + + return true; + } + } + + return false; } public ForestryPodType getType() { diff --git a/src/main/java/forestry/arboriculture/RipeningFruit.java b/src/main/java/forestry/arboriculture/RipeningFruit.java index e16df684a9..5a4e848786 100644 --- a/src/main/java/forestry/arboriculture/RipeningFruit.java +++ b/src/main/java/forestry/arboriculture/RipeningFruit.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture; import forestry.api.core.IProduct; @@ -50,7 +40,7 @@ public boolean isFruitLeaf() { } @Override - public int getColour(IGenome genome, BlockGetter world, BlockPos pos, int ripeningTime) { + public int getColour(IGenome genome, BlockGetter level, BlockPos pos, int ripeningTime) { float stage = getRipeningStage(ripeningTime); return getColour(stage); } @@ -69,7 +59,7 @@ public int getDecorativeColor() { } @Override - public ResourceLocation getSprite(IGenome genome, BlockGetter world, BlockPos pos, int ripeningTime) { + public ResourceLocation getSprite(IGenome genome, BlockGetter level, BlockPos pos, int ripeningTime) { return this.sprite; } diff --git a/src/main/java/forestry/arboriculture/TreeManager.java b/src/main/java/forestry/arboriculture/TreeManager.java index 08cbf1dec8..159cdf438c 100644 --- a/src/main/java/forestry/arboriculture/TreeManager.java +++ b/src/main/java/forestry/arboriculture/TreeManager.java @@ -1,20 +1,23 @@ package forestry.arboriculture; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import forestry.api.arboriculture.ICharcoalManager; +import forestry.api.arboriculture.ICharcoalPileWall; import forestry.api.arboriculture.ITreeManager; import forestry.api.arboriculture.IWoodAccess; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nullable; +import java.util.List; public class TreeManager implements ITreeManager { private final ImmutableMap refractoryWaxables; - private final ICharcoalManager charcoalManager; + private final ImmutableList charcoalWalls; - public TreeManager(ImmutableMap refractoryWaxables, ICharcoalManager charcoalManager) { + public TreeManager(ImmutableMap refractoryWaxables, ImmutableList charcoalWalls) { this.refractoryWaxables = refractoryWaxables; - this.charcoalManager = charcoalManager; + this.charcoalWalls = charcoalWalls; } @Nullable @@ -24,8 +27,20 @@ public Block getRefractoryWaxed(Block block) { } @Override - public ICharcoalManager getCharcoalManager() { - return this.charcoalManager; + public List getWalls() { + return this.charcoalWalls; + } + + @Nullable + @Override + public ICharcoalPileWall getWall(BlockState state) { + for (ICharcoalPileWall wall : this.charcoalWalls) { + if (wall.matches(state)) { + return wall; + } + } + + return null; } @Override diff --git a/src/main/java/forestry/arboriculture/TreeSpecies.java b/src/main/java/forestry/arboriculture/TreeSpecies.java index abd9d97f8c..d88eb8b53e 100644 --- a/src/main/java/forestry/arboriculture/TreeSpecies.java +++ b/src/main/java/forestry/arboriculture/TreeSpecies.java @@ -1,7 +1,8 @@ package forestry.arboriculture; import forestry.api.arboriculture.ITreeGenerator; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; +import forestry.api.arboriculture.genetics.IPodFruit; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.arboriculture.genetics.TreeLifeStage; @@ -99,12 +100,7 @@ public ITree createIndividual(IGenome genome) { return new Tree(genome); } - @Override - public int getEscritoireColor() { - return this.escritoireColor; - } - - @Override + @Override public float getRarity() { return this.rarity; } @@ -119,6 +115,13 @@ public float getHeightModifier(IGenome genome) { return genome.getActiveValue(TreeChromosomes.HEIGHT); } + @Override + public Component getItemDisplayName(ILifeStage stage) { + Component speciesName = getDisplayName(); + Component typeName = Component.translatable("for.trees.grammar." + stage.getSerializedName() + ".type"); + return Component.translatable("for.trees.grammar." + stage.getSerializedName(), speciesName, typeName); + } + @Override public void addTooltip(ITree individual, List tooltip) { // No info 4 u! @@ -212,13 +215,15 @@ public boolean setLogBlock(IGenome genome, LevelAccessor level, BlockPos pos, Di } @Override - public boolean allowsFruitBlocks(IGenome genome) { - return genome.getActiveValue(TreeChromosomes.FRUIT).requiresFruitBlocks(); - } + public void trySpawnFruitPod(LevelAccessor level, RandomSource rand, BlockPos pos) { + IPodFruit fruit = (IPodFruit) this.defaultGenome.getActiveValue(TreeChromosomes.FRUIT); - @Override - public boolean trySpawnFruitBlock(LevelAccessor level, RandomSource rand, BlockPos pos) { - return this.defaultGenome.getActiveValue(TreeChromosomes.FRUIT).trySpawnFruitBlock(this.defaultGenome, level, rand, pos); + if (rand.nextFloat() > fruit.getFruitChance(this.defaultGenome, level)) { + return; + } + + // return value is unused. does this matter? + fruit.tryPlace(level, pos, this.defaultGenome); } @Override diff --git a/src/main/java/forestry/arboriculture/VanillaCocoaPodFruit.java b/src/main/java/forestry/arboriculture/VanillaCocoaPodFruit.java new file mode 100644 index 0000000000..786f83d009 --- /dev/null +++ b/src/main/java/forestry/arboriculture/VanillaCocoaPodFruit.java @@ -0,0 +1,39 @@ +package forestry.arboriculture; + +import forestry.api.IForestryApi; +import forestry.api.arboriculture.genetics.IPodFruit; +import forestry.api.core.IProduct; +import forestry.api.genetics.IGenome; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.CocoaBlock; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.List; + +public class VanillaCocoaPodFruit extends Fruit implements IPodFruit { + public VanillaCocoaPodFruit(List products) { + super(false, 2, products); + } + + @Override + public boolean canSurviveOn(BlockState state) { + return state.is(BlockTags.JUNGLE_LOGS) || state.is(IForestryApi.INSTANCE.getTreeManager().getWoodAccess().getLogBlockTag(VanillaWoodType.JUNGLE, true)); + } + + @Override + public boolean tryPlace(LevelAccessor level, BlockPos pos, IGenome genome) { + Direction facing = PodFruit.getValidPodFacing(level, pos, this); + if (facing == null) { + return false; + } + + BlockState state = Blocks.COCOA.defaultBlockState().setValue(CocoaBlock.FACING, facing); + + return level.setBlock(pos, state, Block.UPDATE_CLIENTS | Block.UPDATE_KNOWN_SHAPE); + } +} diff --git a/src/main/java/forestry/arboriculture/WoodAccess.java b/src/main/java/forestry/arboriculture/WoodAccess.java index 0099408de2..da9d8f2837 100644 --- a/src/main/java/forestry/arboriculture/WoodAccess.java +++ b/src/main/java/forestry/arboriculture/WoodAccess.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture; import forestry.api.arboriculture.IWoodAccess; @@ -274,8 +264,8 @@ public BlockState getBlock(IWoodType woodType, WoodBlockKind woodBlockKind, bool } @Override - public TagKey getLogBlockTag(IWoodType kind, boolean fireproof) { - return (fireproof ? this.fireproofLogBlockTags : this.logBlockTags).get(kind); + public TagKey getLogBlockTag(IWoodType type, boolean fireproof) { + return (fireproof ? this.fireproofLogBlockTags : this.logBlockTags).get(type); } @Override diff --git a/src/main/java/forestry/arboriculture/WoodHelper.java b/src/main/java/forestry/arboriculture/WoodHelper.java index af2138fe09..53dc1aca30 100644 --- a/src/main/java/forestry/arboriculture/WoodHelper.java +++ b/src/main/java/forestry/arboriculture/WoodHelper.java @@ -1,7 +1,7 @@ package forestry.arboriculture; +import forestry.api.IForestryApi; import forestry.api.arboriculture.IWoodType; -import forestry.api.arboriculture.TreeManager; import forestry.api.arboriculture.WoodBlockKind; import forestry.core.utils.Translator; import net.minecraft.network.chat.Component; @@ -22,7 +22,7 @@ public static Component getDisplayName(WoodBlockKind kind, boolean fireproof, IW displayName = Component.translatable("for." + kind + ".grammar", Component.translatable("for.trees.woodType." + woodType)); } } else if (woodType instanceof VanillaWoodType) { - displayName = TreeManager.woodAccess.getStack(woodType, kind, false).getHoverName(); + displayName = IForestryApi.INSTANCE.getTreeManager().getWoodAccess().getStack(woodType, kind, false).getHoverName(); } else { throw new IllegalArgumentException("Unknown wood type: " + woodType); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockAbstractLeaves.java b/src/main/java/forestry/arboriculture/blocks/BlockAbstractLeaves.java index a791eca40f..80e9498940 100755 --- a/src/main/java/forestry/arboriculture/blocks/BlockAbstractLeaves.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockAbstractLeaves.java @@ -2,7 +2,7 @@ import com.mojang.authlib.GameProfile; import forestry.api.arboriculture.ForestryTreeSpecies; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.TreeChromosomes; @@ -11,6 +11,7 @@ import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.registries.Registries; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; @@ -18,6 +19,7 @@ import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; @@ -29,7 +31,6 @@ import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -62,8 +63,8 @@ public String getDescriptionId() { } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, Player player) { - ITree tree = getTree(world, pos); + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { + ITree tree = getTree(level, pos); if (tree == null) { return ItemStack.EMPTY; } @@ -71,10 +72,9 @@ public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGett return species.getDecorativeLeaves(); } - @Nonnull @Override - public List onSheared(@Nullable Player player, @Nonnull ItemStack item, Level world, BlockPos pos, int fortune) { - ITree tree = getTree(world, pos); + public List onSheared(@Nullable Player player, ItemStack stack, Level level, BlockPos pos) { + ITree tree = getTree(level, pos); ITreeSpecies species; if (tree == null) { species = SpeciesUtil.getTreeSpecies(ForestryTreeSpecies.OAK); @@ -90,37 +90,37 @@ public List onSheared(@Nullable Player player, @Nonnull ItemStack ite } @Override - public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { - ITree tree = getTree(worldIn, pos); + public VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { + ITree tree = getTree(level, pos); if (tree != null && tree.getSpecies().id().equals(ForestryTreeSpecies.WILLOW)) { return Shapes.empty(); } - return super.getCollisionShape(state, worldIn, pos, context); + return super.getCollisionShape(state, level, pos, context); } /** * Used for walking through willow leaves. */ @Override - public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { - super.entityInside(state, worldIn, pos, entityIn); + public void entityInside(BlockState state, Level level, BlockPos pos, Entity entityIn) { + super.entityInside(state, level, pos, entityIn); Vec3 motion = entityIn.getDeltaMovement(); entityIn.setDeltaMovement(motion.x() * 0.4D, motion.y(), motion.z() * 0.4D); } /* PROPERTIES */ @Override - public final int getFlammability(BlockState state, BlockGetter world, BlockPos pos, Direction face) { + public final int getFlammability(BlockState state, BlockGetter level, BlockPos pos, Direction face) { return 60; } @Override - public final boolean isFlammable(BlockState state, BlockGetter world, BlockPos pos, Direction face) { + public final boolean isFlammable(BlockState state, BlockGetter level, BlockPos pos, Direction face) { return true; } @Override - public final int getFireSpreadSpeed(BlockState state, BlockGetter world, BlockPos pos, Direction face) { + public final int getFireSpreadSpeed(BlockState state, BlockGetter level, BlockPos pos, Direction face) { if (face == Direction.DOWN) { return 20; } else if (face != Direction.UP) { @@ -141,13 +141,13 @@ public List getDrops(BlockState state, LootParams.Builder context) { } ItemStack tool = context.getOptionalParameter(LootContextParams.TOOL); BlockPos pos = BlockUtil.getPos(context); - getLeafDrop(drops, context.getLevel(), pos, profile, 1f, tool != null ? tool.getEnchantmentLevel(Enchantments.BLOCK_FORTUNE) : 0, context); + getLeafDrop(drops, context.getLevel(), pos, profile, 1f, tool != null ? tool.getEnchantmentLevel(context.getLevel().holderLookup(Registries.ENCHANTMENT).getOrThrow(Enchantments.FORTUNE)) : 0, context); return drops; } @Override - public void animateTick(BlockState pState, Level level, BlockPos pos, RandomSource rand) { - super.animateTick(pState, level, pos, rand); + public void animateTick(BlockState state, Level level, BlockPos pos, RandomSource rand) { + super.animateTick(state, level, pos, rand); ITree tree = getTree(level, pos); diff --git a/src/main/java/forestry/arboriculture/blocks/BlockDecorativeLeaves.java b/src/main/java/forestry/arboriculture/blocks/BlockDecorativeLeaves.java index ed640a005d..1990a923de 100755 --- a/src/main/java/forestry/arboriculture/blocks/BlockDecorativeLeaves.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockDecorativeLeaves.java @@ -20,13 +20,13 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.IForgeShearable; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.common.IShearable; import javax.annotation.Nullable; -public class BlockDecorativeLeaves extends Block implements IColoredBlock, IForgeShearable { +public class BlockDecorativeLeaves extends Block implements IColoredBlock, IShearable { private final ForestryLeafType type; public BlockDecorativeLeaves(ForestryLeafType type) { @@ -68,7 +68,6 @@ public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity e entityIn.setDeltaMovement(motion.multiply(0.4D, 1.0D, 0.4D)); } - /* PROPERTIES */ @Override public int getFlammability(BlockState state, BlockGetter world, BlockPos pos, Direction face) { return 60; @@ -91,7 +90,6 @@ public int getFireSpreadSpeed(BlockState state, BlockGetter world, BlockPos pos, } @Override - @OnlyIn(Dist.CLIENT) public int colorMultiplier(BlockState state, @Nullable BlockAndTintGetter level, @Nullable BlockPos pos, int tintIndex) { ITree individual = this.type.getIndividual(); diff --git a/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeaves.java b/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeaves.java index f6523c6eec..52581604d8 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeaves.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeaves.java @@ -13,8 +13,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootParams; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.List; @@ -39,7 +39,7 @@ public ForestryLeafType getType() { } @Override - protected void getLeafDrop(List drops, Level level, @Nullable BlockPos pos, @Nullable GameProfile profile, float saplingModifier, int fortune, LootParams.Builder context) { + protected void getLeafDrop(List drops, Level level, BlockPos pos, @Nullable GameProfile profile, float saplingModifier, int fortune, LootParams.Builder context) { ITree tree = this.type.getIndividual(); // Add saplings diff --git a/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeavesFruit.java b/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeavesFruit.java index 9100395ead..15286b1692 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeavesFruit.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockDefaultLeavesFruit.java @@ -11,7 +11,6 @@ import forestry.core.utils.BlockUtil; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -23,9 +22,9 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.items.ItemHandlerHelper; import javax.annotation.Nullable; import java.util.List; @@ -42,34 +41,28 @@ public BlockDefaultLeavesFruit(ForestryLeafType type) { } @Override - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult traceResult) { - ItemStack mainHand = player.getItemInHand(InteractionHand.MAIN_HAND); - ItemStack offHand = player.getItemInHand(InteractionHand.OFF_HAND); - if (mainHand.isEmpty() && offHand.isEmpty()) { - ITree tree = getTree(level, pos); - if (tree == null) { - return InteractionResult.FAIL; - } - if (level.isClientSide) { - return InteractionResult.SUCCESS; - } - BlockUtil.sendDestroyEffects(level, pos, state); - IFruit fruitProvider = tree.getGenome().getActiveValue(TreeChromosomes.FRUIT); - List products = tree.produceStacks(level, pos, fruitProvider.getRipeningPeriod()); - level.setBlock(pos, ArboricultureBlocks.LEAVES_DEFAULT.get(this.type).defaultState() - .setValue(LeavesBlock.PERSISTENT, state.getValue(LeavesBlock.PERSISTENT)) - .setValue(LeavesBlock.DISTANCE, state.getValue(LeavesBlock.DISTANCE)), Block.UPDATE_CLIENTS); - for (ItemStack fruit : products) { - ItemHandlerHelper.giveItemToPlayer(player, fruit); - } - return InteractionResult.CONSUME; + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + ITree tree = getTree(level, pos); + if (tree == null) { + return InteractionResult.PASS; } - - return InteractionResult.PASS; + if (level.isClientSide) { + return InteractionResult.SUCCESS; + } + BlockUtil.sendDestroyEffects(level, pos, state); + IFruit fruitProvider = tree.getGenome().getActiveValue(TreeChromosomes.FRUIT); + List products = tree.produceStacks(level, pos, fruitProvider.getRipeningPeriod()); + level.setBlock(pos, ArboricultureBlocks.LEAVES_DEFAULT.get(this.type).defaultState() + .setValue(LeavesBlock.PERSISTENT, state.getValue(LeavesBlock.PERSISTENT)) + .setValue(LeavesBlock.DISTANCE, state.getValue(LeavesBlock.DISTANCE)), Block.UPDATE_CLIENTS); + for (ItemStack fruit : products) { + ItemHandlerHelper.giveItemToPlayer(player, fruit); + } + return InteractionResult.CONSUME; } @Override - protected void getLeafDrop(List drops, Level level, @Nullable BlockPos pos, @Nullable GameProfile profile, float saplingModifier, int fortune, LootParams.Builder context) { + protected void getLeafDrop(List drops, Level level, BlockPos pos, @Nullable GameProfile profile, float saplingModifier, int fortune, LootParams.Builder context) { ITree tree = this.type.getIndividual(); // Add saplings diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryButton.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryButton.java index ad6d7bcd8d..a615a285ea 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryButton.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryButton.java @@ -11,7 +11,7 @@ public class BlockForestryButton extends ButtonBlock implements IWoodTyped { private final ForestryWoodType type; public BlockForestryButton(ForestryWoodType type) { - super(Properties.of().noCollission().strength(0.5f).pushReaction(PushReaction.DESTROY), type.getBlockSetType(), 30, true); + super(type.getBlockSetType(), 30, Properties.of().noCollission().strength(0.5f).pushReaction(PushReaction.DESTROY)); this.type = type; } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryDoor.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryDoor.java index 9a2ed30983..ce12b90bd1 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryDoor.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryDoor.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.blocks; import forestry.api.arboriculture.IWoodType; @@ -22,7 +12,7 @@ public class BlockForestryDoor extends DoorBlock implements IWoodTyped { private final ForestryWoodType woodType; public BlockForestryDoor(ForestryWoodType woodType) { - super(Block.Properties.of().strength(woodType.getHardness(), woodType.getHardness() * 1.5F).sound(SoundType.WOOD).noOcclusion(), woodType.getBlockSetType()); + super(woodType.getBlockSetType(), Block.Properties.of().strength(woodType.getHardness(), woodType.getHardness() * 1.5F).sound(SoundType.WOOD).noOcclusion()); this.woodType = woodType; } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java index 3bbec2f4c2..7522fb4d20 100755 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.blocks; import forestry.api.arboriculture.IWoodType; diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryHangingSign.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryHangingSign.java index a9a9f9afc5..c5f03c245c 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryHangingSign.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryHangingSign.java @@ -4,6 +4,7 @@ import forestry.arboriculture.ForestryWoodType; import forestry.arboriculture.IWoodTyped; import forestry.arboriculture.features.ArboricultureTiles; +import forestry.arboriculture.tiles.TileForestryHangingSign; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.CeilingHangingSignBlock; @@ -21,7 +22,7 @@ public class BlockForestryHangingSign extends CeilingHangingSignBlock implements private final ForestryWoodType type; public BlockForestryHangingSign(ForestryWoodType type) { - super(Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1f).ignitedByLava(), type.getWoodType()); + super(type.getWoodType(), Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1f).ignitedByLava()); this.type = type; } @@ -49,6 +50,6 @@ public BlockEntityTicker getTicker(Level level, Block @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new HangingSignBlockEntity(ArboricultureTiles.HANGING_SIGN.tileType(), pos, state); + return new TileForestryHangingSign(pos, state); } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java index 8c84557af4..0c90fe782b 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.blocks; import com.mojang.authlib.GameProfile; @@ -26,6 +16,7 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.*; @@ -35,9 +26,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.items.ItemHandlerHelper; import javax.annotation.Nullable; import java.util.List; @@ -76,7 +65,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { } @Override - protected void getLeafDrop(List drops, Level level, @Nullable BlockPos pos, @Nullable GameProfile profile, float saplingModifier, int fortune, LootParams.Builder context) { + protected void getLeafDrop(List drops, Level level, BlockPos pos, @Nullable GameProfile profile, float saplingModifier, int fortune, LootParams.Builder context) { if (!(level.getBlockEntity(pos) instanceof TileLeaves leaves)) { return; } @@ -102,54 +91,63 @@ protected void getLeafDrop(List drops, Level level, @Nullable BlockPo } @Override - public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - TileLeaves leaves = TileUtil.getTile(level, pos, TileLeaves.class); - if (leaves != null) { - IButterfly caterpillar = leaves.getCaterpillar(); - ItemStack heldItem = player.getItemInHand(hand); - ItemStack otherHand = player.getItemInHand(hand == InteractionHand.MAIN_HAND ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND); - if (heldItem.isEmpty() && otherHand.isEmpty()) { - if (leaves.hasFruit() && leaves.getRipeness() >= 0.9F) { + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + if (stack.is(ForestryTags.Items.SCOOPS)) { + if (level.getBlockEntity(pos) instanceof TileLeaves leaves) { + IButterfly caterpillar = leaves.getCaterpillar(); + if (caterpillar != null) { + if (!level.isClientSide) { + ItemStackUtil.dropItemStackAsEntity(caterpillar.createStack(ButterflyLifeStage.CATERPILLAR), level, pos.below()); + leaves.setCaterpillar(null); + } + + return ItemInteractionResult.sidedSuccess(level.isClientSide); + } + } + } + + return super.useItemOn(stack, state, level, pos, player, hand, hitResult); + } + + @Override + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + if (level.getBlockEntity(pos) instanceof TileLeaves leaves) { + if (leaves.hasFruit() && leaves.getRipeness() >= 0.9f) { + if (!level.isClientSide) { BlockUtil.sendDestroyEffects(level, pos, state); - for (ItemStack fruit : leaves.pickFruit(ItemStack.EMPTY)) { + + for (ItemStack fruit : leaves.pickFruit()) { ItemHandlerHelper.giveItemToPlayer(player, fruit); } - return InteractionResult.SUCCESS; } - } else if (heldItem.is(ForestryTags.Items.SCOOPS) && caterpillar != null) { - ItemStack butterfly = SpeciesUtil.BUTTERFLY_TYPE.get().createStack(caterpillar, ButterflyLifeStage.CATERPILLAR); - ItemStackUtil.dropItemStackAsEntity(butterfly, level, pos.below()); - leaves.setCaterpillar(null); - return InteractionResult.SUCCESS; + + return InteractionResult.sidedSuccess(level.isClientSide); } } - return InteractionResult.PASS; + return super.useWithoutItem(state, level, pos, player, hitResult); } - /* IGrowable */ - @Override - public boolean isValidBonemealTarget(LevelReader world, BlockPos pos, BlockState state, boolean isClient) { - TileLeaves leafTile = TileUtil.getTile(world, pos, TileLeaves.class); + public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state) { + TileLeaves leafTile = TileUtil.getTile(level, pos, TileLeaves.class); return leafTile != null && leafTile.hasFruit() && leafTile.getRipeness() < 1.0f; } @Override - public boolean isBonemealSuccess(Level worldIn, RandomSource rand, BlockPos pos, BlockState state) { + public boolean isBonemealSuccess(Level level, RandomSource rand, BlockPos pos, BlockState state) { return true; } @Override - public void performBonemeal(ServerLevel world, RandomSource rand, BlockPos pos, BlockState state) { - TileLeaves leafTile = TileUtil.getTile(world, pos, TileLeaves.class); + public void performBonemeal(ServerLevel level, RandomSource rand, BlockPos pos, BlockState state) { + TileLeaves leafTile = TileUtil.getTile(level, pos, TileLeaves.class); if (leafTile != null) { leafTile.addRipeness(0.5f); } } @Override - @OnlyIn(Dist.CLIENT) public int colorMultiplier(BlockState state, @Nullable BlockAndTintGetter level, @Nullable BlockPos pos, int tintIndex) { if (level != null && pos != null) { TileLeaves leaves = TileUtil.getTile(level, pos, TileLeaves.class); diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java index 11ea224943..123f8ffbc1 100755 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java @@ -12,8 +12,8 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.RotatedPillarBlock; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.ToolAction; -import net.minecraftforge.common.ToolActions; +import net.neoforged.neoforge.common.ItemAbilities; +import net.neoforged.neoforge.common.ItemAbility; import org.jetbrains.annotations.Nullable; public class BlockForestryLog extends RotatedPillarBlock implements IWoodTyped { @@ -65,8 +65,8 @@ public final int getFlammability(BlockState state, BlockGetter world, BlockPos p } @Override - public @Nullable BlockState getToolModifiedState(BlockState state, UseOnContext context, ToolAction toolAction, boolean simulate) { - if (toolAction == ToolActions.AXE_STRIP) { + public @Nullable BlockState getToolModifiedState(BlockState state, UseOnContext context, ItemAbility toolAction, boolean simulate) { + if (toolAction == ItemAbilities.AXE_STRIP) { if (this.woodType instanceof ForestryWoodType type) { if (this.kind == WoodBlockKind.LOG) { return (this.fireproof ? ArboricultureBlocks.STRIPPED_LOGS_FIREPROOF : ArboricultureBlocks.STRIPPED_LOGS) diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryPlank.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryPlank.java index ac0df0eec8..2c3036a770 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryPlank.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryPlank.java @@ -11,13 +11,13 @@ import net.minecraft.world.level.block.state.BlockState; public class BlockForestryPlank extends Block implements IWoodTyped { + private final boolean fireproof; + private final IWoodType woodType; + public static Properties createWoodProperties(IWoodType woodType) { return Block.Properties.of().strength(woodType.getHardness(), woodType.getHardness() * 1.5F).sound(SoundType.WOOD); } - private final boolean fireproof; - private final IWoodType woodType; - public BlockForestryPlank(boolean fireproof, IWoodType woodType) { super(createWoodProperties(woodType)); this.fireproof = fireproof; @@ -40,18 +40,11 @@ public WoodBlockKind getBlockKind() { @Override public int getFlammability(BlockState state, BlockGetter world, BlockPos pos, Direction face) { - if (this.fireproof) { - return 0; - } - return 20; + return this.fireproof ? 0 : 20; } @Override public int getFireSpreadSpeed(BlockState state, BlockGetter world, BlockPos pos, Direction face) { - if (this.fireproof) { - return 0; - } - return 5; + return this.fireproof ? 0 : 5; } - } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryPressurePlate.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryPressurePlate.java index dfe7ac7860..0720f5c5c6 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryPressurePlate.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryPressurePlate.java @@ -13,7 +13,7 @@ public class BlockForestryPressurePlate extends PressurePlateBlock implements IW private final ForestryWoodType type; public BlockForestryPressurePlate(ForestryWoodType type) { - super(Sensitivity.EVERYTHING, Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(0.5f).ignitedByLava().pushReaction(PushReaction.DESTROY), type.getBlockSetType()); + super(type.getBlockSetType(), Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(0.5f).ignitedByLava().pushReaction(PushReaction.DESTROY)); this.type = type; } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java b/src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java index 526210b63e..4312ed8fad 100755 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java @@ -15,7 +15,7 @@ public class BlockForestrySlab extends SlabBlock implements IWoodTyped { private final IWoodType woodType; public BlockForestrySlab(BlockForestryPlank plank) { - super(Block.Properties.copy(plank)); + super(Block.Properties.ofFullCopy(plank)); this.fireproof = plank.isFireproof(); this.woodType = plank.getWoodType(); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java index f0e7645be0..029ddfd8bb 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java @@ -15,7 +15,7 @@ public class BlockForestryStairs extends StairBlock implements IWoodTyped { private final IWoodType woodType; public BlockForestryStairs(BlockForestryPlank plank) { - super(plank.defaultBlockState(), Block.Properties.copy(plank)); + super(plank.defaultBlockState(), Block.Properties.ofFullCopy(plank)); this.fireproof = plank.isFireproof(); this.woodType = plank.getWoodType(); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryStandingSign.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryStandingSign.java index 95684a8562..6fcb98431e 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryStandingSign.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryStandingSign.java @@ -21,7 +21,7 @@ public class BlockForestryStandingSign extends StandingSignBlock implements IWoo private final ForestryWoodType type; public BlockForestryStandingSign(ForestryWoodType type) { - super(Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1.0F).ignitedByLava(), type.getWoodType()); + super(type.getWoodType(), Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1.0F).ignitedByLava()); this.type = type; } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryTrapdoor.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryTrapdoor.java index e6bdf6087c..ac7bcb4b16 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryTrapdoor.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryTrapdoor.java @@ -13,7 +13,7 @@ public class BlockForestryTrapdoor extends TrapDoorBlock implements IWoodTyped { private final ForestryWoodType type; public BlockForestryTrapdoor(ForestryWoodType type) { - super(Properties.of().mapColor(MapColor.WOOD).instrument(NoteBlockInstrument.BASS).strength(3f).noOcclusion().isValidSpawn(BlockUtil.NEVER_SPAWN).ignitedByLava(), type.getBlockSetType()); + super(type.getBlockSetType(), Properties.of().mapColor(MapColor.WOOD).instrument(NoteBlockInstrument.BASS).strength(3f).noOcclusion().isValidSpawn(BlockUtil.NEVER_SPAWN).ignitedByLava()); this.type = type; } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryWallHangingSign.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryWallHangingSign.java index a9cfa56210..f99fba0d10 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryWallHangingSign.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryWallHangingSign.java @@ -6,6 +6,7 @@ import forestry.arboriculture.IWoodTyped; import forestry.arboriculture.features.ArboricultureBlocks; import forestry.arboriculture.features.ArboricultureTiles; +import forestry.arboriculture.tiles.TileForestryHangingSign; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.WallHangingSignBlock; @@ -23,7 +24,7 @@ public class BlockForestryWallHangingSign extends WallHangingSignBlock implement private final ForestryWoodType type; public BlockForestryWallHangingSign(ForestryWoodType type) { - super(Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1.0F).lootFrom(ArboricultureBlocks.HANGING_SIGN.get(type)::block).ignitedByLava(), type.getWoodType()); + super(type.getWoodType(), Properties.of().mapColor(MapColor.WOOD).forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1.0F).lootFrom(ArboricultureBlocks.HANGING_SIGN.get(type)::block).ignitedByLava()); this.type = type; } @@ -51,6 +52,6 @@ public BlockEntityTicker getTicker(Level level, Block @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new HangingSignBlockEntity(ArboricultureTiles.HANGING_SIGN.tileType(), pos, state); + return new TileForestryHangingSign(pos, state); } } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryWallSign.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryWallSign.java index 20f78abb7b..1f6258ec26 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryWallSign.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryWallSign.java @@ -22,7 +22,7 @@ public class BlockForestryWallSign extends WallSignBlock implements IWoodTyped { private final ForestryWoodType type; public BlockForestryWallSign(ForestryWoodType type) { - super(Properties.of().forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1.0F).lootFrom(ArboricultureBlocks.SIGN.get(type)::block).ignitedByLava(), type.getWoodType()); + super(type.getWoodType(), Properties.of().forceSolidOn().instrument(NoteBlockInstrument.BASS).noCollission().strength(1.0F).lootFrom(ArboricultureBlocks.SIGN.get(type)::block).ignitedByLava()); this.type = type; } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java b/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java index b863d45a57..45725d375b 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java @@ -1,15 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.blocks; +import forestry.arboriculture.PodFruit; import forestry.arboriculture.tiles.TileFruitPod; import forestry.core.tiles.TileUtil; import forestry.core.utils.BlockUtil; @@ -19,7 +10,6 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.CocoaBlock; @@ -42,7 +32,7 @@ public BlockFruitPod(ForestryPodType podType) { } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter level, BlockPos pos, Player player) { + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { TileFruitPod tile = TileUtil.getTile(level, pos, TileFruitPod.class); if (tile == null) { return ItemStack.EMPTY; @@ -82,7 +72,7 @@ public List getDrops(BlockState state, LootParams.Builder context) { @Override public boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) { Direction facing = state.getValue(FACING); - return BlockUtil.isValidPodLocation(level, pos, facing, this.podType.getFruit().getLogTag()); + return PodFruit.isValidPodLocation(level, pos, facing, this.podType.getFruit()); } @Override @@ -90,9 +80,8 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new TileFruitPod(pos, state); } - /* IGrowable */ @Override - public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state, boolean isClient) { + public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state) { TileFruitPod podTile = TileUtil.getTile(level, pos, TileFruitPod.class); return podTile != null && podTile.canMature(); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockSapling.java b/src/main/java/forestry/arboriculture/blocks/BlockSapling.java index d892e124eb..4e209f54cf 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockSapling.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockSapling.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.blocks; import forestry.api.arboriculture.genetics.ITree; @@ -98,7 +88,7 @@ public List getDrops(BlockState blockState, LootParams.Builder builde } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter level, BlockPos pos, Player player) { + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { TileSapling sapling = TileUtil.getTile(level, pos, TileSapling.class); if (sapling == null || sapling.getTree() == null) { return ItemStack.EMPTY; @@ -118,7 +108,7 @@ private static ItemStack getDrop(BlockEntity blockEntity) { } @Override - public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state, boolean isClient) { + public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state) { return true; } diff --git a/src/main/java/forestry/arboriculture/blocks/DecorativeLogPileBlock.java b/src/main/java/forestry/arboriculture/blocks/DecorativeLogPileBlock.java index bcbfa8d157..6f40c89a69 100644 --- a/src/main/java/forestry/arboriculture/blocks/DecorativeLogPileBlock.java +++ b/src/main/java/forestry/arboriculture/blocks/DecorativeLogPileBlock.java @@ -7,12 +7,8 @@ import net.minecraft.world.level.block.RotatedPillarBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.EnumProperty; -// todo this doesn't seem to be implemented ? public class DecorativeLogPileBlock extends RotatedPillarBlock { - public static final EnumProperty AXIS = EnumProperty.create("axis", Direction.Axis.class); - public DecorativeLogPileBlock() { super(Block.Properties.of() .sound(SoundType.WOOD) diff --git a/src/main/java/forestry/arboriculture/blocks/ForestryLeafType.java b/src/main/java/forestry/arboriculture/blocks/ForestryLeafType.java index 4b6add424d..2325fbfb04 100644 --- a/src/main/java/forestry/arboriculture/blocks/ForestryLeafType.java +++ b/src/main/java/forestry/arboriculture/blocks/ForestryLeafType.java @@ -1,7 +1,7 @@ package forestry.arboriculture.blocks; import forestry.api.arboriculture.ForestryTreeSpecies; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.ITree; import forestry.api.core.IBlockSubtype; @@ -77,7 +77,7 @@ public void setSpecies(ITreeSpecies species) { } @Override - public String getSerializedName() { + public String identifier() { return this.speciesId.getPath(); } diff --git a/src/main/java/forestry/arboriculture/blocks/ForestryPodType.java b/src/main/java/forestry/arboriculture/blocks/ForestryPodType.java index 0bf644ab7e..b8bcec9867 100644 --- a/src/main/java/forestry/arboriculture/blocks/ForestryPodType.java +++ b/src/main/java/forestry/arboriculture/blocks/ForestryPodType.java @@ -1,30 +1,28 @@ package forestry.arboriculture.blocks; -import forestry.api.arboriculture.genetics.IFruit; +import forestry.api.arboriculture.genetics.IPodFruit; import forestry.api.core.IBlockSubtype; import forestry.api.genetics.alleles.ForestryAlleles; import forestry.api.genetics.alleles.IValueAllele; import java.util.Locale; -// todo add coconut, was planned public enum ForestryPodType implements IBlockSubtype { - COCOA(ForestryAlleles.FRUIT_COCOA), DATES(ForestryAlleles.FRUIT_DATES), PAPAYA(ForestryAlleles.FRUIT_PAPAYA); - private final IValueAllele allele; + private final IValueAllele allele; - ForestryPodType(IValueAllele allele) { + ForestryPodType(IValueAllele allele) { this.allele = allele; } @Override - public String getSerializedName() { - return name().toLowerCase(Locale.ROOT); + public String identifier() { + return name().toLowerCase(Locale.ENGLISH); } - public IFruit getFruit() { + public IPodFruit getFruit() { return this.allele.value(); } } diff --git a/src/main/java/forestry/arboriculture/blocks/LogPileBlock.java b/src/main/java/forestry/arboriculture/blocks/LogPileBlock.java index e1434941cc..51fb16223b 100644 --- a/src/main/java/forestry/arboriculture/blocks/LogPileBlock.java +++ b/src/main/java/forestry/arboriculture/blocks/LogPileBlock.java @@ -1,10 +1,8 @@ package forestry.arboriculture.blocks; -import com.google.common.base.Preconditions; -import forestry.api.arboriculture.ICharcoalManager; +import forestry.api.IForestryApi; import forestry.api.arboriculture.ICharcoalPileWall; -import forestry.api.arboriculture.TreeManager; -import forestry.arboriculture.charcoal.CharcoalManager; +import forestry.api.arboriculture.ITreeManager; import forestry.arboriculture.features.CharcoalBlocks; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -25,14 +23,14 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; public class LogPileBlock extends Block { public static final BooleanProperty IS_ACTIVE = BooleanProperty.create("active"); public static final IntegerProperty AGE = BlockStateProperties.AGE_7; public static final int RANDOM_TICK = 160; public static final int TICK_RATE = 960; + public static final int CHARCOAL_AMOUNT_BASE = 8; + public static final int CHARCOAL_WALL_CHECK_RANGE = 16; public LogPileBlock() { super(Block.Properties.of().strength(1.5f).sound(SoundType.WOOD).noOcclusion()); @@ -103,7 +101,7 @@ public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource if (state.getValue(AGE) < 7) { world.setBlock(pos, state.setValue(AGE, state.getValue(AGE) + 1), Block.UPDATE_CLIENTS); } else { - BlockState ashState = CharcoalBlocks.ASH.setValue(BlockAsh.AMOUNT, Math.min(Math.round(CharcoalManager.charcoalAmountBase + getCharcoalAmount(world, pos)), 63)); + BlockState ashState = CharcoalBlocks.ASH.setValue(BlockAsh.AMOUNT, Math.min(Math.round(CHARCOAL_AMOUNT_BASE + getCharcoalAmount(world, pos)), 63)); world.setBlock(pos, ashState, Block.UPDATE_CLIENTS); } } @@ -134,7 +132,6 @@ public int getLightEmission(BlockState state, BlockGetter world, BlockPos pos) { return super.getLightEmission(state, world, pos); } - @OnlyIn(Dist.CLIENT) @Override public void animateTick(BlockState state, Level level, BlockPos pos, RandomSource rand) { if (state.getValue(IS_ACTIVE)) { @@ -154,22 +151,21 @@ public void animateTick(BlockState state, Level level, BlockPos pos, RandomSourc } } - //TODO: Precalculate, like leaf distance private float getCharcoalAmount(Level world, BlockPos pos) { float charcoalAmount = 0F; for (Direction facing : Direction.VALUES) { charcoalAmount += getCharcoalFaceAmount(world, pos, facing); } - return Mth.clamp(charcoalAmount / 6, CharcoalManager.charcoalAmountBase, 63.0F - CharcoalManager.charcoalAmountBase); + return Mth.clamp(charcoalAmount / 6, CHARCOAL_AMOUNT_BASE, 63.0F - CHARCOAL_AMOUNT_BASE); } private int getCharcoalFaceAmount(Level world, BlockPos pos, Direction facing) { - ICharcoalManager charcoalManager = Preconditions.checkNotNull(TreeManager.charcoalManager); + ITreeManager charcoalManager = IForestryApi.INSTANCE.getTreeManager(); BlockPos.MutableBlockPos testPos = pos.mutable(); testPos.move(facing); int i = 0; - while (i < CharcoalManager.charcoalWallCheckRange && world.hasChunkAt(testPos) && !world.isEmptyBlock(testPos)) { + while (i < CHARCOAL_WALL_CHECK_RANGE && world.hasChunkAt(testPos) && !world.isEmptyBlock(testPos)) { BlockState state = world.getBlockState(testPos); ICharcoalPileWall wall = charcoalManager.getWall(state); if (wall != null) { diff --git a/src/main/java/forestry/arboriculture/blocks/package-info.java b/src/main/java/forestry/arboriculture/blocks/package-info.java index 1a1023613a..c81a12f55c 100644 --- a/src/main/java/forestry/arboriculture/blocks/package-info.java +++ b/src/main/java/forestry/arboriculture/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.blocks; diff --git a/src/main/java/forestry/arboriculture/capabilities/ArmorNaturalist.java b/src/main/java/forestry/arboriculture/capabilities/SpectacleVision.java similarity index 72% rename from src/main/java/forestry/arboriculture/capabilities/ArmorNaturalist.java rename to src/main/java/forestry/arboriculture/capabilities/SpectacleVision.java index 84b47ccdf6..e12212dfa1 100644 --- a/src/main/java/forestry/arboriculture/capabilities/ArmorNaturalist.java +++ b/src/main/java/forestry/arboriculture/capabilities/SpectacleVision.java @@ -1,10 +1,10 @@ package forestry.arboriculture.capabilities; -import forestry.api.core.IArmorNaturalist; +import forestry.api.core.ISpectacleVision; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -public enum ArmorNaturalist implements IArmorNaturalist { +public enum SpectacleVision implements ISpectacleVision { INSTANCE; @Override diff --git a/src/main/java/forestry/arboriculture/capabilities/package-info.java b/src/main/java/forestry/arboriculture/capabilities/package-info.java index e10f3e167c..b6364b7049 100644 --- a/src/main/java/forestry/arboriculture/capabilities/package-info.java +++ b/src/main/java/forestry/arboriculture/capabilities/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.capabilities; diff --git a/src/main/java/forestry/arboriculture/charcoal/CharcoalManager.java b/src/main/java/forestry/arboriculture/charcoal/CharcoalManager.java deleted file mode 100644 index 56343b37fe..0000000000 --- a/src/main/java/forestry/arboriculture/charcoal/CharcoalManager.java +++ /dev/null @@ -1,68 +0,0 @@ -package forestry.arboriculture.charcoal; - -import com.google.common.base.Preconditions; -import forestry.api.arboriculture.ICharcoalManager; -import forestry.api.arboriculture.ICharcoalPileWall; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; - -public class CharcoalManager implements ICharcoalManager { - // Charcoal - public static final int charcoalAmountBase = 8; - public static final int charcoalWallCheckRange = 16; - private final List walls = new ArrayList<>(); - - @Override - public void registerWall(Block block, int amount) { - Preconditions.checkNotNull(block, "block must not be null."); - Preconditions.checkArgument(amount > (-charcoalAmountBase) && amount < (63 - charcoalAmountBase), "amount must be bigger than -10 and smaller than 64."); - this.walls.add(new CharcoalPileWall(block, amount)); - } - - @Override - public void registerWall(BlockState blockState, int amount) { - Preconditions.checkNotNull(blockState, "block state must not be null."); - Preconditions.checkArgument(amount > (-charcoalAmountBase) && amount < (63 - charcoalAmountBase), "amount must be bigger than -10 and smaller than 64."); - this.walls.add(new CharcoalPileWall(blockState, amount)); - } - - @Override - public void registerWall(ICharcoalPileWall wall) { - this.walls.add(wall); - } - - @Nullable - @Override - public ICharcoalPileWall getWall(BlockState state) { - for (ICharcoalPileWall wall : this.walls) { - if (wall.matches(state)) { - return wall; - } - } - return null; - } - - @Override - public boolean removeWall(Block block) { - return removeWall(block.defaultBlockState()); - } - - @Override - public boolean removeWall(BlockState state) { - for (ICharcoalPileWall wall : this.walls) { - if (wall.matches(state)) { - return this.walls.remove(wall); - } - } - return false; - } - - @Override - public List getWalls() { - return this.walls; - } -} diff --git a/src/main/java/forestry/arboriculture/charcoal/CharcoalPileWall.java b/src/main/java/forestry/arboriculture/charcoal/CharcoalPileWall.java index e75d60bcd4..a629f4f9cc 100644 --- a/src/main/java/forestry/arboriculture/charcoal/CharcoalPileWall.java +++ b/src/main/java/forestry/arboriculture/charcoal/CharcoalPileWall.java @@ -1,26 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.charcoal; -import com.google.common.base.Preconditions; import forestry.api.arboriculture.ICharcoalPileWall; -import net.minecraft.core.NonNullList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; public class CharcoalPileWall implements ICharcoalPileWall { - @Nullable private final BlockState blockState; @Nullable @@ -50,15 +39,12 @@ public boolean matches(BlockState state) { } @Override - public NonNullList getDisplayItems() { + public List getDisplayItems() { if (this.block == null) { - Preconditions.checkNotNull(this.blockState); - return NonNullList.withSize(1, new ItemStack(this.blockState.getBlock())); //TODO loss of properties? + return Collections.singletonList(new ItemStack(this.blockState.getBlock())); } else if (this.blockState == null) { - Preconditions.checkNotNull(this.block); - return NonNullList.withSize(1, new ItemStack(this.block)); + return Collections.singletonList(new ItemStack(this.block)); } - return NonNullList.create(); + return List.of(); } - } diff --git a/src/main/java/forestry/arboriculture/charcoal/jei/CharcoalJeiPlugin.java b/src/main/java/forestry/arboriculture/charcoal/jei/CharcoalJeiPlugin.java deleted file mode 100644 index a1d2219737..0000000000 --- a/src/main/java/forestry/arboriculture/charcoal/jei/CharcoalJeiPlugin.java +++ /dev/null @@ -1,47 +0,0 @@ -package forestry.arboriculture.charcoal.jei; - -import forestry.api.ForestryConstants; -import forestry.api.arboriculture.ICharcoalManager; -import forestry.api.arboriculture.ICharcoalPileWall; -import forestry.api.arboriculture.TreeManager; -import forestry.api.modules.ForestryModuleIds; -import forestry.arboriculture.features.CharcoalBlocks; -import mezz.jei.api.IModPlugin; -import mezz.jei.api.JeiPlugin; -import mezz.jei.api.helpers.IGuiHelper; -import mezz.jei.api.recipe.RecipeType; -import mezz.jei.api.registration.IRecipeCatalystRegistration; -import mezz.jei.api.registration.IRecipeCategoryRegistration; -import mezz.jei.api.registration.IRecipeRegistration; -import net.minecraft.resources.ResourceLocation; - -@JeiPlugin -public class CharcoalJeiPlugin implements IModPlugin { - public static final RecipeType RECIPE_TYPE = RecipeType.create(ForestryConstants.MOD_ID, "charcoal.pile", ICharcoalPileWall.class); - - @Override - public ResourceLocation getPluginUid() { - return ForestryModuleIds.CHARCOAL; - } - - @Override - public void registerCategories(IRecipeCategoryRegistration registry) { - IGuiHelper guiHelper = registry.getJeiHelpers().getGuiHelper(); - registry.addRecipeCategories(new CharcoalPileWallCategory(guiHelper)); - } - - @Override - public void registerRecipes(IRecipeRegistration registration) { - ICharcoalManager charcoalManager = TreeManager.charcoalManager; - if (charcoalManager == null) { - return; - } - - registration.addRecipes(RECIPE_TYPE, charcoalManager.getWalls()); - } - - @Override - public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) { - registration.addRecipeCatalyst(CharcoalBlocks.LOG_PILE.stack(), RECIPE_TYPE); - } -} diff --git a/src/main/java/forestry/arboriculture/charcoal/jei/package-info.java b/src/main/java/forestry/arboriculture/charcoal/jei/package-info.java deleted file mode 100644 index 9b107aa65b..0000000000 --- a/src/main/java/forestry/arboriculture/charcoal/jei/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault -@net.minecraft.MethodsReturnNonnullByDefault -package forestry.arboriculture.charcoal.jei; diff --git a/src/main/java/forestry/arboriculture/charcoal/package-info.java b/src/main/java/forestry/arboriculture/charcoal/package-info.java index 526018dc5d..af2c63adc0 100644 --- a/src/main/java/forestry/arboriculture/charcoal/package-info.java +++ b/src/main/java/forestry/arboriculture/charcoal/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.charcoal; diff --git a/src/main/java/forestry/arboriculture/client/ArboricultureClientHandler.java b/src/main/java/forestry/arboriculture/client/ArboricultureClientHandler.java index b1e03ec23a..df74bd4846 100644 --- a/src/main/java/forestry/arboriculture/client/ArboricultureClientHandler.java +++ b/src/main/java/forestry/arboriculture/client/ArboricultureClientHandler.java @@ -1,15 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.client; +import forestry.api.ForestryConstants; import forestry.api.client.IClientModuleHandler; import forestry.arboriculture.ForestryWoodType; import forestry.arboriculture.blocks.BlockDecorativeLeaves; @@ -25,11 +16,11 @@ import net.minecraft.client.renderer.Sheets; import net.minecraft.client.renderer.blockentity.HangingSignRenderer; import net.minecraft.client.renderer.blockentity.SignRenderer; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.neoforge.client.event.EntityRenderersEvent; +import net.neoforged.neoforge.client.event.ModelEvent; +import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent; public class ArboricultureClientHandler implements IClientModuleHandler { @Override @@ -68,7 +59,7 @@ private static void onClientSetup(FMLClientSetupEvent event) { } private static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register("sapling_ge", new SaplingModelLoader()); + event.register(ForestryConstants.forestry("sapling_ge"), new SaplingModelLoader()); } private static void registerEntityRenderers(EntityRenderersEvent.RegisterRenderers event) { @@ -82,8 +73,6 @@ private static void registerModelLayers(EntityRenderersEvent.RegisterLayerDefini for (ForestryWoodType type : ForestryWoodType.VALUES) { event.registerLayerDefinition(ForestryBoatRenderer.createBoatModelLocation(type, false), BoatModel::createBodyModel); event.registerLayerDefinition(ForestryBoatRenderer.createBoatModelLocation(type, true), ChestBoatModel::createBodyModel); - //event.registerLayerDefinition(ModelLayers.createSignModelName(type.getWoodType()), SignRenderer::createSignLayer); - //event.registerLayerDefinition(ModelLayers.createHangingSignModelName(type.getWoodType()), HangingSignRenderer::createHangingSignLayer); } } } diff --git a/src/main/java/forestry/arboriculture/client/ProxyArboriculture.java b/src/main/java/forestry/arboriculture/client/ProxyArboriculture.java deleted file mode 100644 index 93f3c258ea..0000000000 --- a/src/main/java/forestry/arboriculture/client/ProxyArboriculture.java +++ /dev/null @@ -1,14 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.client; - -public class ProxyArboriculture { -} diff --git a/src/main/java/forestry/arboriculture/client/package-info.java b/src/main/java/forestry/arboriculture/client/package-info.java index 890597f884..f0d1c5f549 100644 --- a/src/main/java/forestry/arboriculture/client/package-info.java +++ b/src/main/java/forestry/arboriculture/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.client; diff --git a/src/main/java/forestry/arboriculture/commands/CommandTree.java b/src/main/java/forestry/arboriculture/commands/CommandTree.java index 81301f307c..d2aed86048 100644 --- a/src/main/java/forestry/arboriculture/commands/CommandTree.java +++ b/src/main/java/forestry/arboriculture/commands/CommandTree.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.commands; import net.minecraft.commands.CommandSourceStack; diff --git a/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java b/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java index 60ee246a19..42400ca647 100644 --- a/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java +++ b/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.commands; import com.mojang.brigadier.builder.ArgumentBuilder; diff --git a/src/main/java/forestry/arboriculture/commands/ForestSpawner.java b/src/main/java/forestry/arboriculture/commands/ForestSpawner.java index da79c018a0..645ee2469f 100755 --- a/src/main/java/forestry/arboriculture/commands/ForestSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/ForestSpawner.java @@ -1,16 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.commands; import forestry.api.arboriculture.genetics.ITree; +import forestry.arboriculture.worldgen.TreeGenHelper; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; diff --git a/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java b/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java index 96cfe1d95b..ba97959ccc 100644 --- a/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/ITreeSpawner.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.commands; import forestry.api.arboriculture.genetics.ITree; diff --git a/src/main/java/forestry/arboriculture/commands/TreeSpawner.java b/src/main/java/forestry/arboriculture/commands/TreeSpawner.java index 8858788e39..3820c24b27 100755 --- a/src/main/java/forestry/arboriculture/commands/TreeSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/TreeSpawner.java @@ -1,15 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.commands; +import forestry.arboriculture.worldgen.TreeGenHelper; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; diff --git a/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java b/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java index 805ff224ca..d31fdf3c6b 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java +++ b/src/main/java/forestry/arboriculture/commands/TreeStatsSaveHelper.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.commands; import com.mojang.authlib.GameProfile; diff --git a/src/main/java/forestry/arboriculture/commands/package-info.java b/src/main/java/forestry/arboriculture/commands/package-info.java index cb1c3d8d51..f5cd64e872 100644 --- a/src/main/java/forestry/arboriculture/commands/package-info.java +++ b/src/main/java/forestry/arboriculture/commands/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.commands; diff --git a/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java b/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java index 87ce122b77..fb02c468af 100644 --- a/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java +++ b/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java @@ -1,30 +1,53 @@ package forestry.arboriculture.compat; +import forestry.api.ForestryConstants; +import forestry.api.IForestryApi; +import forestry.api.arboriculture.ICharcoalPileWall; import forestry.api.genetics.alleles.TreeChromosomes; import forestry.api.modules.ForestryModuleIds; import forestry.arboriculture.features.ArboricultureItems; -import forestry.core.utils.JeiUtil; +import forestry.arboriculture.features.CharcoalBlocks; +import forestry.compat.jei.JeiUtil; import forestry.core.utils.SpeciesUtil; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; +import mezz.jei.api.helpers.IGuiHelper; +import mezz.jei.api.recipe.RecipeType; +import mezz.jei.api.registration.IRecipeCatalystRegistration; +import mezz.jei.api.registration.IRecipeCategoryRegistration; import mezz.jei.api.registration.IRecipeRegistration; import mezz.jei.api.registration.ISubtypeRegistration; import net.minecraft.resources.ResourceLocation; @JeiPlugin public class ArboricultureJeiPlugin implements IModPlugin { + public static final RecipeType CHARCOAL_PILE = RecipeType.create(ForestryConstants.MOD_ID, "charcoal.pile", ICharcoalPileWall.class); + @Override public ResourceLocation getPluginUid() { return ForestryModuleIds.ARBORICULTURE; } @Override - public void registerItemSubtypes(ISubtypeRegistration registry) { - JeiUtil.registerItemSubtypes(registry, TreeChromosomes.SPECIES, SpeciesUtil.TREE_TYPE.get()); + public void registerItemSubtypes(ISubtypeRegistration registration) { + JeiUtil.registerItemSubtypes(registration, SpeciesUtil.TREE_TYPE.get()); } @Override public void registerRecipes(IRecipeRegistration registration) { JeiUtil.addDescription(registration, ArboricultureItems.GRAFTER.item(), ArboricultureItems.GRAFTER_PROVEN.item()); + + registration.addRecipes(CHARCOAL_PILE, IForestryApi.INSTANCE.getTreeManager().getWalls()); + } + + @Override + public void registerCategories(IRecipeCategoryRegistration registration) { + IGuiHelper guiHelper = registration.getJeiHelpers().getGuiHelper(); + registration.addRecipeCategories(new CharcoalPileWallCategory(guiHelper)); + } + + @Override + public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) { + registration.addRecipeCatalyst(CharcoalBlocks.LOG_PILE.stack(), CHARCOAL_PILE); } } diff --git a/src/main/java/forestry/arboriculture/charcoal/jei/CharcoalPileWallCategory.java b/src/main/java/forestry/arboriculture/compat/CharcoalPileWallCategory.java similarity index 93% rename from src/main/java/forestry/arboriculture/charcoal/jei/CharcoalPileWallCategory.java rename to src/main/java/forestry/arboriculture/compat/CharcoalPileWallCategory.java index cdf96732d3..058a951a5d 100644 --- a/src/main/java/forestry/arboriculture/charcoal/jei/CharcoalPileWallCategory.java +++ b/src/main/java/forestry/arboriculture/compat/CharcoalPileWallCategory.java @@ -1,4 +1,4 @@ -package forestry.arboriculture.charcoal.jei; +package forestry.arboriculture.compat; import forestry.api.ForestryConstants; import forestry.api.arboriculture.ICharcoalPileWall; @@ -32,10 +32,10 @@ public class CharcoalPileWallCategory extends ForestryRecipeCategory getRecipeType() { - return CharcoalJeiPlugin.RECIPE_TYPE; + return ArboricultureJeiPlugin.CHARCOAL_PILE; } @Override diff --git a/src/main/java/forestry/arboriculture/compat/package-info.java b/src/main/java/forestry/arboriculture/compat/package-info.java index 8b7f7bc1cb..585b5813e7 100644 --- a/src/main/java/forestry/arboriculture/compat/package-info.java +++ b/src/main/java/forestry/arboriculture/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.compat; diff --git a/src/main/java/forestry/arboriculture/entities/ForestryBoat.java b/src/main/java/forestry/arboriculture/entities/ForestryBoat.java index c284f24602..1e96988aa3 100644 --- a/src/main/java/forestry/arboriculture/entities/ForestryBoat.java +++ b/src/main/java/forestry/arboriculture/entities/ForestryBoat.java @@ -34,14 +34,9 @@ public ForestryBoat(Level level, double x, double y, double z) { } @Override - protected void defineSynchedData() { - super.defineSynchedData(); - this.entityData.define(DATA_ID_WOOD_TYPE, ForestryWoodType.ACACIA_DESERT.ordinal()); - } - - @Override - public double getPassengersRidingOffset() { - return -0.1; + protected void defineSynchedData(SynchedEntityData.Builder builder) { + super.defineSynchedData(builder); + builder.define(DATA_ID_WOOD_TYPE, ForestryWoodType.ACACIA_DESERT.ordinal()); } @Override diff --git a/src/main/java/forestry/arboriculture/entities/ForestryChestBoat.java b/src/main/java/forestry/arboriculture/entities/ForestryChestBoat.java index 55ea7596d3..ad0d01f273 100644 --- a/src/main/java/forestry/arboriculture/entities/ForestryChestBoat.java +++ b/src/main/java/forestry/arboriculture/entities/ForestryChestBoat.java @@ -4,7 +4,7 @@ import forestry.arboriculture.features.ArboricultureItems; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.Containers; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; @@ -24,9 +24,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.gameevent.GameEvent; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.wrapper.InvWrapper; +import net.minecraft.world.level.storage.loot.LootTable; import javax.annotation.Nullable; @@ -35,7 +33,7 @@ public class ForestryChestBoat extends ForestryBoat implements HasCustomInventor private NonNullList items = NonNullList.withSize(CONTAINER_SIZE, ItemStack.EMPTY); @Nullable - private ResourceLocation lootTable; + private ResourceKey lootTable; private long lootTableSeed; public ForestryChestBoat(EntityType type, Level level) { @@ -59,7 +57,7 @@ public Item getDropItem() { // @Override protected float getSinglePassengerXOffset() { - return 0.15F; + return 0.15f; } @Override @@ -68,15 +66,15 @@ protected int getMaxPassengers() { } @Override - protected void addAdditionalSaveData(CompoundTag pCompound) { - super.addAdditionalSaveData(pCompound); - addChestVehicleSaveData(pCompound); + protected void addAdditionalSaveData(CompoundTag nbt) { + super.addAdditionalSaveData(nbt); + addChestVehicleSaveData(nbt, registryAccess()); } @Override - protected void readAdditionalSaveData(CompoundTag pCompound) { - super.readAdditionalSaveData(pCompound); - readChestVehicleSaveData(pCompound); + protected void readAdditionalSaveData(CompoundTag nbt) { + super.readAdditionalSaveData(nbt); + readChestVehicleSaveData(nbt, registryAccess()); } @Override @@ -96,16 +94,23 @@ public void remove(Entity.RemovalReason reason) { @Override public InteractionResult interact(Player player, InteractionHand hand) { - if (canAddPassenger(player) && !player.isSecondaryUseActive()) { - return super.interact(player, hand); + if (!player.isSecondaryUseActive()) { + InteractionResult result = super.interact(player, hand); + if (result != InteractionResult.PASS) { + return result; + } + } + + if (this.canAddPassenger(player) && !player.isSecondaryUseActive()) { + return InteractionResult.PASS; } else { - InteractionResult interactionresult = interactWithContainerVehicle(player); - if (interactionresult.consumesAction()) { + InteractionResult result = this.interactWithContainerVehicle(player); + if (result.consumesAction()) { gameEvent(GameEvent.CONTAINER_OPEN, player); PiglinAi.angerNearbyPiglins(player, true); } - return interactionresult; + return result; } } @@ -113,7 +118,7 @@ public InteractionResult interact(Player player, InteractionHand hand) { public void openCustomInventoryScreen(Player player) { player.openMenu(this); if (!player.level().isClientSide) { - this.gameEvent(GameEvent.CONTAINER_OPEN, player); + gameEvent(GameEvent.CONTAINER_OPEN, player); PiglinAi.angerNearbyPiglins(player, true); } } @@ -175,12 +180,12 @@ public AbstractContainerMenu createMenu(int windowId, Inventory playerInv, Playe @Nullable @Override - public ResourceLocation getLootTable() { + public ResourceKey getLootTable() { return this.lootTable; } @Override - public void setLootTable(@Nullable ResourceLocation lootTable) { + public void setLootTable(@Nullable ResourceKey lootTable) { this.lootTable = lootTable; } @@ -205,31 +210,8 @@ public void clearItemStacks() { } // - // - private net.minecraftforge.common.util.LazyOptional itemHandler = LazyOptional.of(() -> new InvWrapper(this)); - - @Override - public net.minecraftforge.common.util.LazyOptional getCapability(net.minecraftforge.common.capabilities.Capability capability, @Nullable net.minecraft.core.Direction facing) { - if (capability == ForgeCapabilities.ITEM_HANDLER && isAlive()) { - return this.itemHandler.cast(); - } - return super.getCapability(capability, facing); - } - - @Override - public void invalidateCaps() { - super.invalidateCaps(); - this.itemHandler.invalidate(); - } - @Override - public void reviveCaps() { - super.reviveCaps(); - this.itemHandler = LazyOptional.of(() -> new InvWrapper(this)); - } - public void stopOpen(Player player) { level().gameEvent(GameEvent.CONTAINER_CLOSE, position(), GameEvent.Context.of(player)); } - // } diff --git a/src/main/java/forestry/arboriculture/entities/package-info.java b/src/main/java/forestry/arboriculture/entities/package-info.java index d2607d817e..e7f4182908 100644 --- a/src/main/java/forestry/arboriculture/entities/package-info.java +++ b/src/main/java/forestry/arboriculture/entities/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.entities; diff --git a/src/main/java/forestry/arboriculture/features/ArboricultureFeatures.java b/src/main/java/forestry/arboriculture/features/ArboricultureFeatures.java index 174d21d92a..839e801f29 100644 --- a/src/main/java/forestry/arboriculture/features/ArboricultureFeatures.java +++ b/src/main/java/forestry/arboriculture/features/ArboricultureFeatures.java @@ -7,13 +7,15 @@ import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class ArboricultureFeatures { @@ -21,9 +23,9 @@ public class ArboricultureFeatures { public static final DeferredRegister> FEATURES = REGISTRY.getRegistry(Registries.FEATURE); - public static final RegistryObject TREE_DECORATOR = FEATURES.register("tree", TreeDecorator::new); + public static final DeferredHolder, Feature> TREE_DECORATOR = FEATURES.register("tree", TreeDecorator::new); public static final ResourceKey> CONFIGURED_TREE = ResourceKey.create(Registries.CONFIGURED_FEATURE, ForestryConstants.forestry("tree")); public static final ResourceKey PLACED_TREE = ResourceKey.create(Registries.PLACED_FEATURE, ForestryConstants.forestry("tree")); - public static final RegistryObject CUSTOM_TREE = FEATURES.register("custom_tree", ForestryTreeFeature::new); + public static final Holder> CUSTOM_TREE = FEATURES.register("custom_tree", ForestryTreeFeature::new); } diff --git a/src/main/java/forestry/arboriculture/features/ArboricultureTiles.java b/src/main/java/forestry/arboriculture/features/ArboricultureTiles.java index 3374627f18..3ffc5ae660 100644 --- a/src/main/java/forestry/arboriculture/features/ArboricultureTiles.java +++ b/src/main/java/forestry/arboriculture/features/ArboricultureTiles.java @@ -4,10 +4,7 @@ import forestry.arboriculture.tiles.TileFruitPod; import forestry.arboriculture.tiles.TileLeaves; import forestry.arboriculture.tiles.TileSapling; -import forestry.modules.features.FeatureProvider; -import forestry.modules.features.FeatureTileType; -import forestry.modules.features.IFeatureRegistry; -import forestry.modules.features.ModFeatureRegistry; +import forestry.modules.features.*; import net.minecraft.world.level.block.entity.SignBlockEntity; import java.util.stream.Stream; @@ -20,6 +17,6 @@ public class ArboricultureTiles { public static final FeatureTileType LEAVES = REGISTRY.tile(TileLeaves::new, "leaves", ArboricultureBlocks.LEAVES::collect); public static final FeatureTileType PODS = REGISTRY.tile(TileFruitPod::new, "pods", ArboricultureBlocks.PODS::getBlocks); - public static final FeatureTileType SIGN = REGISTRY.tile((pos, state) -> new SignBlockEntity(ArboricultureTiles.SIGN.tileType(), pos, state), "sign", () -> Stream.concat(ArboricultureBlocks.SIGN.getList().stream(), ArboricultureBlocks.WALL_SIGN.getList().stream()).toList()); - public static final FeatureTileType HANGING_SIGN = REGISTRY.tile((pos, state) -> new SignBlockEntity(ArboricultureTiles.SIGN.tileType(), pos, state), "hanging_sign", () -> Stream.concat(ArboricultureBlocks.HANGING_SIGN.getList().stream(), ArboricultureBlocks.WALL_HANGING_SIGN.getList().stream()).toList()); + public static final FeatureTileType SIGN = REGISTRY.tile((pos, state) -> new SignBlockEntity(ArboricultureTiles.SIGN.tileType(), pos, state), "sign", () -> Stream.concat(ArboricultureBlocks.SIGN.getBlocks().stream(), ArboricultureBlocks.WALL_SIGN.getBlocks().stream()).toList()); + public static final FeatureTileType HANGING_SIGN = REGISTRY.tile((pos, state) -> new SignBlockEntity(ArboricultureTiles.SIGN.tileType(), pos, state), "hanging_sign", () -> Stream.concat(ArboricultureBlocks.HANGING_SIGN.getBlocks().stream(), ArboricultureBlocks.WALL_HANGING_SIGN.getBlocks().stream()).toList()); } diff --git a/src/main/java/forestry/arboriculture/features/CharcoalBlocks.java b/src/main/java/forestry/arboriculture/features/CharcoalBlocks.java index 93c459dbc8..5ffc811ac6 100644 --- a/src/main/java/forestry/arboriculture/features/CharcoalBlocks.java +++ b/src/main/java/forestry/arboriculture/features/CharcoalBlocks.java @@ -15,7 +15,7 @@ @FeatureProvider public class CharcoalBlocks { - private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CHARCOAL); + private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.ARBORICULTURE); public static final FeatureBlock> CHARCOAL = REGISTRY.block(BlockCharcoal::new, (block) -> new ItemBlockForestry<>(block, new ItemProperties().burnTime(16000)), "charcoal"); public static final FeatureBlock LOG_PILE = REGISTRY.block(LogPileBlock::new, (block) -> new ItemBlockForestry<>(block, new ItemProperties().burnTime(1200)), "log_pile"); diff --git a/src/main/java/forestry/arboriculture/features/package-info.java b/src/main/java/forestry/arboriculture/features/package-info.java index d6cf4c30d4..d6823ce25b 100644 --- a/src/main/java/forestry/arboriculture/features/package-info.java +++ b/src/main/java/forestry/arboriculture/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.features; diff --git a/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java b/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java index d50ec2a1c5..206a259c9d 100755 --- a/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java +++ b/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.genetics; import forestry.api.arboriculture.IArboristTracker; diff --git a/src/main/java/forestry/arboriculture/genetics/DummyTreeEffect.java b/src/main/java/forestry/arboriculture/genetics/DummyTreeEffect.java index acd2043ae4..e0a9e88561 100644 --- a/src/main/java/forestry/arboriculture/genetics/DummyTreeEffect.java +++ b/src/main/java/forestry/arboriculture/genetics/DummyTreeEffect.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.genetics; import forestry.api.arboriculture.genetics.ITreeEffect; diff --git a/src/main/java/forestry/arboriculture/genetics/Tree.java b/src/main/java/forestry/arboriculture/genetics/Tree.java index 3810a2c90e..780cf90d73 100755 --- a/src/main/java/forestry/arboriculture/genetics/Tree.java +++ b/src/main/java/forestry/arboriculture/genetics/Tree.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.genetics; import com.google.common.collect.ImmutableList; import com.mojang.authlib.GameProfile; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.ITreeEffect; import forestry.api.arboriculture.genetics.ITreeSpeciesType; @@ -23,6 +13,7 @@ import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.AllelePair; import forestry.api.genetics.alleles.TreeChromosomes; +import forestry.arboriculture.features.ArboricultureBlocks; import forestry.core.genetics.Individual; import forestry.core.genetics.mutations.Mutation; import forestry.core.utils.SpeciesUtil; @@ -36,15 +27,13 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.common.PlantType; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Optional; -public class Tree extends Individual implements ITree, IPlantable { +public class Tree extends Individual implements ITree { public static final Codec CODEC = RecordCodecBuilder.create(instance -> { Codec genomeCodec = SpeciesUtil.TREE_TYPE.get().getKaryotype().getGenomeCodec(); @@ -103,19 +92,7 @@ public boolean canStay(BlockGetter level, BlockPos pos) { BlockState state = level.getBlockState(below); Block block = state.getBlock(); - return block.canSustainPlant(state, level, below, Direction.UP, this); - } - - // IPlantable - @Override - public BlockState getPlant(BlockGetter level, BlockPos pos) { - return level.getBlockState(pos); - } - - // IPlantable - @Override - public PlantType getPlantType(BlockGetter level, BlockPos pos) { - return PlantType.PLAINS; + return !block.canSustainPlant(state, level, below, Direction.UP, ArboricultureBlocks.SAPLING_GE.defaultState()).isFalse(); } @Override @@ -129,7 +106,6 @@ public int getResilience() { return (Math.max(base, 1)) * 10; } - /* REPRODUCTION */ @Override public List getSaplings(Level level, BlockPos pos, @Nullable GameProfile playerProfile, float modifier) { List prod = new ArrayList<>(); diff --git a/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java b/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java index 828972706a..5242691809 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.genetics; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.core.IProduct; @@ -19,7 +9,7 @@ import forestry.api.genetics.ISpecies; import forestry.api.genetics.alleles.TreeChromosomes; import forestry.api.genetics.capability.IIndividualHandlerItem; -import forestry.core.gui.GuiAlyzer; +import forestry.core.gui.PortableAnalyzerScreen; import forestry.core.gui.GuiForestry; import forestry.core.gui.TextLayoutHelper; import forestry.core.gui.widgets.ItemStackWidget; @@ -46,17 +36,17 @@ public enum TreeAlyzerPlugin implements IAlyzerPlugin { @Override public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, (individual, type) -> { if (individual instanceof ITree tree) { IGenome genome = tree.getGenome(); TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); - textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); textLayout.newLine(); @@ -73,9 +63,9 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack int activeGirth = genome.getActiveValue(TreeChromosomes.GIRTH); int inactiveGirth = genome.getInactiveValue(TreeChromosomes.GIRTH); - textLayout.drawLine(graphics, TreeChromosomes.GIRTH.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); - guiAlyzer.drawLine(graphics, String.format("%sx%s", activeGirth, activeGirth), GuiAlyzer.COLUMN_1, tree, TreeChromosomes.GIRTH, false); - guiAlyzer.drawLine(graphics, String.format("%sx%s", inactiveGirth, inactiveGirth), GuiAlyzer.COLUMN_2, tree, TreeChromosomes.GIRTH, true); + textLayout.drawLine(graphics, TreeChromosomes.GIRTH.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawLine(graphics, String.format("%sx%s", activeGirth, activeGirth), PortableAnalyzerScreen.COLUMN_1, tree, TreeChromosomes.GIRTH, false); + guiAlyzer.drawLine(graphics, String.format("%sx%s", inactiveGirth, inactiveGirth), PortableAnalyzerScreen.COLUMN_2, tree, TreeChromosomes.GIRTH, true); textLayout.newLineCompressed(); @@ -94,7 +84,7 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack @Override public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, individual -> { if (individual instanceof ITree tree) { IGenome genome = tree.getGenome(); @@ -105,13 +95,13 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - int speciesDominance0 = GuiAlyzer.getColorCoding(primary.isDominant()); - int speciesDominance1 = GuiAlyzer.getColorCoding(secondary.isDominant()); + int speciesDominance0 = PortableAnalyzerScreen.getColorCoding(primary.isDominant()); + int speciesDominance1 = PortableAnalyzerScreen.getColorCoding(secondary.isDominant()); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); - textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); textLayout.newLine(); @@ -134,23 +124,23 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack @Override public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, individual -> { if (individual instanceof ITree tree) { TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); WidgetManager widgetManager = guiAlyzer.getWidgetManager(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.produce").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.produce").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - int x = GuiAlyzer.COLUMN_0; + int x = PortableAnalyzerScreen.COLUMN_0; for (IProduct product : tree.getProducts()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), product.createStack())); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } @@ -160,15 +150,15 @@ public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack stack textLayout.newLine(); textLayout.newLine(); - textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.specialty").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.beealyzer.specialty").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; for (IProduct product : tree.getProducts()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), product.createStack())); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } diff --git a/src/main/java/forestry/arboriculture/genetics/TreePollenType.java b/src/main/java/forestry/arboriculture/genetics/TreePollenType.java index 67b615acf5..319124d85b 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreePollenType.java +++ b/src/main/java/forestry/arboriculture/genetics/TreePollenType.java @@ -1,6 +1,6 @@ package forestry.arboriculture.genetics; -import forestry.api.apiculture.genetics.IBee; +import forestry.api.apiculture.bee.IBee; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.genetics.pollen.ForestryPollenTypes; diff --git a/src/main/java/forestry/arboriculture/genetics/TreeSpeciesType.java b/src/main/java/forestry/arboriculture/genetics/TreeSpeciesType.java index cd0817501d..f78dd473cc 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeSpeciesType.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeSpeciesType.java @@ -1,26 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.genetics; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.mojang.authlib.GameProfile; import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import forestry.api.IForestryApi; import forestry.api.arboriculture.IArboristTracker; import forestry.api.arboriculture.ILeafTickHandler; -import forestry.api.arboriculture.ITreeSpecies; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.ITree; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.core.IProduct; import forestry.api.genetics.*; @@ -30,36 +20,28 @@ import forestry.api.plugin.ISpeciesTypeBuilder; import forestry.apiimpl.ForestryApiImpl; import forestry.apiimpl.plugin.ArboricultureRegistration; -import forestry.arboriculture.PodFruit; -import forestry.arboriculture.blocks.BlockFruitPod; import forestry.arboriculture.blocks.ForestryLeafType; import forestry.arboriculture.features.ArboricultureBlocks; -import forestry.arboriculture.tiles.TileFruitPod; import forestry.arboriculture.tiles.TileSapling; import forestry.arboriculture.tiles.TileTreeContainer; -import forestry.core.ClientsideCode; import forestry.core.genetics.SpeciesType; import forestry.core.genetics.root.BreedingTrackerManager; import forestry.core.tiles.TileUtil; import forestry.core.utils.BlockUtil; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nullable; -import java.util.Collection; -import java.util.IdentityHashMap; -import java.util.LinkedList; -import java.util.List; +import java.util.*; public class TreeSpeciesType extends SpeciesType implements ITreeSpeciesType, IBreedingTrackerHandler { // todo make both of these reloadable @@ -94,7 +76,7 @@ public void onSpeciesRegistered(ImmutableMap all if (species != null) { type.setSpecies(species); } else { - throw new IllegalStateException("Invalid ForestryLeafType " + type.getSerializedName() + ": no tree species found with ID: " + type.getSpeciesId()); + throw new IllegalStateException("Invalid ForestryLeafType " + type.identifier() + ": no tree species found with ID: " + type.getSpeciesId()); } } } @@ -163,7 +145,7 @@ public boolean plantSapling(Level level, ITree tree, GameProfile owner, BlockPos } sapling.setTree(tree.copy()); - sapling.getOwnerHandler().setOwner(owner); + sapling.getOwnerHandler().setOwner(new ResolvableProfile(owner)); BlockUtil.sendPlaceSound(level, pos, blockState); @@ -171,44 +153,12 @@ public boolean plantSapling(Level level, ITree tree, GameProfile owner, BlockPos } @Override - public boolean setFruitBlock(LevelAccessor level, IGenome genome, IFruit fruit, float yield, BlockPos pos) { - Direction facing = BlockUtil.getValidPodFacing(level, pos, fruit.getLogTag()); - - // todo make this not hardcoded to forestry pods - if (facing != null && fruit instanceof PodFruit podFruit && ArboricultureBlocks.PODS.has(podFruit.getType())) { - BlockFruitPod fruitPod = ArboricultureBlocks.PODS.get(podFruit.getType()).block(); - BlockState state = fruitPod.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, facing); - boolean placed = level.setBlock(pos, state, 18); - - if (placed) { - Block block = level.getBlockState(pos).getBlock(); - - if (fruitPod == block) { - TileFruitPod pod = TileUtil.getTile(level, pos, TileFruitPod.class); - - if (pod != null) { - pod.setProperties(genome, fruit, yield); - if (level.isClientSide()) { - ClientsideCode.markForUpdate(pos); - } - return true; - } else { - level.setBlock(pos, Blocks.AIR.defaultBlockState(), 18); - return false; - } - } - } - } - return false; - } - - @Override - public IArboristTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile) { + public IArboristTracker getBreedingTracker(LevelAccessor level, @Nullable @Nullable ResolvableProfile profile) { return BreedingTrackerManager.INSTANCE.getTracker(this, level, profile); } @Override - public String getBreedingTrackerFile(@Nullable GameProfile profile) { + public String getBreedingTrackerFile(@Nullable @Nullable ResolvableProfile profile) { return "ArboristTracker." + (profile == null ? "common" : profile.getId()); } @@ -218,9 +168,9 @@ public IBreedingTracker createBreedingTracker() { } @Override - public void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level world, @Nullable GameProfile profile) { + public void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level level, @Nullable @Nullable ResolvableProfile profile) { if (tracker instanceof ArboristTracker arboristTracker) { - arboristTracker.setLevel(world); + arboristTracker.setLevel(level); arboristTracker.setUsername(profile); } } @@ -253,7 +203,12 @@ public ITree getVanillaIndividual(Item item) { } @Override - public Codec getIndividualCodec() { + public Map getAllVanillaIndividuals() { + return Collections.unmodifiableMap(this.vanillaItems); + } + + @Override + public MapCodec getIndividualCodec() { return Tree.CODEC; } diff --git a/src/main/java/forestry/arboriculture/genetics/package-info.java b/src/main/java/forestry/arboriculture/genetics/package-info.java index ddc23c3877..367415af38 100644 --- a/src/main/java/forestry/arboriculture/genetics/package-info.java +++ b/src/main/java/forestry/arboriculture/genetics/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.genetics; diff --git a/src/main/java/forestry/arboriculture/items/ForestryBoatDispenserBehavior.java b/src/main/java/forestry/arboriculture/items/ForestryBoatDispenserBehavior.java index d7939bb069..3893d1e51e 100644 --- a/src/main/java/forestry/arboriculture/items/ForestryBoatDispenserBehavior.java +++ b/src/main/java/forestry/arboriculture/items/ForestryBoatDispenserBehavior.java @@ -4,13 +4,14 @@ import forestry.arboriculture.entities.ForestryBoat; import forestry.arboriculture.entities.ForestryChestBoat; import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockSource; import net.minecraft.core.Direction; +import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.phys.Vec3; public class ForestryBoatDispenserBehavior extends DefaultDispenseItemBehavior { private final DefaultDispenseItemBehavior defaultDispenseItemBehavior = new DefaultDispenseItemBehavior(); @@ -24,13 +25,14 @@ public ForestryBoatDispenserBehavior(ForestryWoodType type, boolean hasChest) { @Override public ItemStack execute(BlockSource source, ItemStack stack) { - Direction direction = source.getBlockState().getValue(DispenserBlock.FACING); - Level level = source.getLevel(); + Direction direction = source.state().getValue(DispenserBlock.FACING); + ServerLevel level = source.level(); double x = 0.5625D + (double) EntityType.BOAT.getWidth() / 2.0D; - double y = source.x() + (double) direction.getStepX() * x; - double z = source.y() + (double) ((float) direction.getStepY() * 1.125F); - double d3 = source.z() + (double) direction.getStepZ() * x; - BlockPos blockpos = source.getPos().relative(direction); + Vec3 center = source.center(); + double y = center.x() + (double) direction.getStepX() * x; + double z = center.y() + (double) ((float) direction.getStepY() * 1.125F); + double d3 = center.z() + (double) direction.getStepZ() * x; + BlockPos blockpos = source.pos().relative(direction); ForestryBoat boat = (this.hasChest ? new ForestryChestBoat(level, x, y, z) : new ForestryBoat(level, x, y, z)); boat.setWoodType(this.type); boat.setYRot(direction.toYRot()); @@ -53,6 +55,6 @@ public ItemStack execute(BlockSource source, ItemStack stack) { @Override protected void playSound(BlockSource source) { - source.getLevel().levelEvent(1000, source.getPos(), 0); + source.level().levelEvent(1000, source.pos(), 0); } } diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java b/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java index df2c11c4bf..9934a37252 100755 --- a/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java @@ -13,8 +13,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ItemBlockDecorativeLeaves extends ItemBlockForestry implements IColoredItem { public ItemBlockDecorativeLeaves(BlockDecorativeLeaves block) { diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java b/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java index 94e362644b..dfbd5fb283 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockLeaves.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.items; import forestry.api.arboriculture.genetics.ITree; diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWood.java b/src/main/java/forestry/arboriculture/items/ItemBlockWood.java index 13994ba822..ea27120a10 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWood.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWood.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.items; import forestry.api.arboriculture.IWoodType; diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java b/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java index 4e54f9c44c..6b753dae4e 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java @@ -1,27 +1,29 @@ package forestry.arboriculture.items; import forestry.arboriculture.blocks.BlockForestryDoor; +import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nullable; public class ItemBlockWoodDoor extends ItemBlockWood { - public ItemBlockWoodDoor(BlockForestryDoor block) { super(block); } - /** - * Copy of {@link net.minecraft.item.TallBlockItem#placeBlock(BlockItemUseContext, BlockState)} - */ + // Copy of DoubleHighBlockItem.placeBlock @Override - protected boolean placeBlock(BlockPlaceContext p_195941_1_, BlockState p_195941_2_) { - p_195941_1_.getLevel().setBlock(p_195941_1_.getClickedPos().above(), Blocks.AIR.defaultBlockState(), 27); - return super.placeBlock(p_195941_1_, p_195941_2_); + protected boolean placeBlock(BlockPlaceContext context, BlockState state) { + Level level = context.getLevel(); + BlockPos blockpos = context.getClickedPos().above(); + BlockState blockstate = level.isWaterAt(blockpos) ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState(); + level.setBlock(blockpos, blockstate, 27); + return super.placeBlock(context, state); } @Override diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java b/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java index d1d456f15f..553b1753c9 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java @@ -25,12 +25,6 @@ public Component getName(ItemStack itemstack) { @Override public int getBurnTime(ItemStack itemStack, @Nullable RecipeType recipeType) { - BlockForestrySlab forestrySlab = (BlockForestrySlab) getBlock(); - - if (forestrySlab.isFireproof()) { - return 0; - } else { - return 150; - } + return ((BlockForestrySlab) getBlock()).isFireproof() ? 0 : 150; } } diff --git a/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java b/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java index f37225683c..6d11d63e18 100644 --- a/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java +++ b/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.items; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.genetics.IIndividual; diff --git a/src/main/java/forestry/arboriculture/items/ItemGrafter.java b/src/main/java/forestry/arboriculture/items/ItemGrafter.java index f8f207fad0..7e0a24dc68 100755 --- a/src/main/java/forestry/arboriculture/items/ItemGrafter.java +++ b/src/main/java/forestry/arboriculture/items/ItemGrafter.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.items; import forestry.api.ForestryTags; @@ -27,7 +17,6 @@ import net.minecraft.world.level.block.LeavesBlock; import net.minecraft.world.level.block.state.BlockState; -import javax.annotation.Nullable; import java.util.List; public class ItemGrafter extends ItemForestry implements IToolGrafter { @@ -36,16 +25,16 @@ public ItemGrafter(int maxDamage) { } @Override - public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag advanced) { - super.appendHoverText(stack, world, tooltip, advanced); + public void appendHoverText(ItemStack stack, TooltipContext ctx, List tooltip, TooltipFlag advanced) { + super.appendHoverText(stack, ctx, tooltip, advanced); if (!stack.isDamaged()) { tooltip.add(Component.translatable("item.forestry.uses", stack.getMaxDamage() + 1).withStyle(ChatFormatting.GRAY)); } } @Override - public boolean isCorrectToolForDrops(BlockState state) { - return state.getBlock() instanceof LeavesBlock || state.is(BlockTags.LEAVES) || super.isCorrectToolForDrops(state); + public boolean isCorrectToolForDrops(ItemStack stack, BlockState state) { + return state.getBlock() instanceof LeavesBlock || state.is(BlockTags.LEAVES) || super.isCorrectToolForDrops(stack, state); } @Override @@ -57,10 +46,11 @@ public float getDestroySpeed(ItemStack itemstack, BlockState state) { } } + // mostly copied from ShearsItem.mineBlock @Override public boolean mineBlock(ItemStack stack, Level world, BlockState state, BlockPos pos, LivingEntity entity) { if (!world.isClientSide && !state.is(BlockTags.FIRE)) { - stack.hurtAndBreak(1, entity, living -> living.broadcastBreakEvent(EquipmentSlot.MAINHAND)); + stack.hurtAndBreak(1, entity, EquipmentSlot.MAINHAND); } return state.is(BlockTags.LEAVES); } diff --git a/src/main/java/forestry/arboriculture/items/package-info.java b/src/main/java/forestry/arboriculture/items/package-info.java index 3bcb675a7c..1b58cdb072 100644 --- a/src/main/java/forestry/arboriculture/items/package-info.java +++ b/src/main/java/forestry/arboriculture/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.items; diff --git a/src/main/java/forestry/arboriculture/loot/CountBlockFunction.java b/src/main/java/forestry/arboriculture/loot/CountBlockFunction.java index 432145c0e1..9823e3324a 100644 --- a/src/main/java/forestry/arboriculture/loot/CountBlockFunction.java +++ b/src/main/java/forestry/arboriculture/loot/CountBlockFunction.java @@ -1,9 +1,8 @@ package forestry.arboriculture.loot; import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.arboriculture.blocks.BlockAsh; import forestry.core.loot.CoreLootFunctions; import net.minecraft.world.item.ItemStack; @@ -15,10 +14,13 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import java.util.List; import java.util.Set; public class CountBlockFunction extends LootItemConditionalFunction { - protected CountBlockFunction(LootItemCondition[] conditions) { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> commonFields(instance).apply(instance, CountBlockFunction::new)); + + private CountBlockFunction(List conditions) { super(conditions); } @@ -27,8 +29,8 @@ public static LootItemConditionalFunction.Builder builder() { } @Override - public LootItemFunctionType getType() { - return CoreLootFunctions.COUNT.get(); + public LootItemFunctionType getType() { + return CoreLootFunctions.COUNT.value(); } @Override @@ -46,17 +48,4 @@ protected ItemStack run(ItemStack stack, LootContext context) { public Set> getReferencedContextParams() { return ImmutableSet.of(LootContextParams.BLOCK_STATE); } - - public static class Serializer extends LootItemConditionalFunction.Serializer { - - @Override - public void serialize(JsonObject object, CountBlockFunction function, JsonSerializationContext context) { - super.serialize(object, function, context); - } - - @Override - public CountBlockFunction deserialize(JsonObject object, JsonDeserializationContext jsonDeserializationContext, LootItemCondition[] conditions) { - return new CountBlockFunction(conditions); - } - } } diff --git a/src/main/java/forestry/arboriculture/loot/GrafterLootModifier.java b/src/main/java/forestry/arboriculture/loot/GrafterLootModifier.java index 4bdcc4ad57..092cfb6fd3 100644 --- a/src/main/java/forestry/arboriculture/loot/GrafterLootModifier.java +++ b/src/main/java/forestry/arboriculture/loot/GrafterLootModifier.java @@ -1,6 +1,6 @@ package forestry.arboriculture.loot; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.arboriculture.IToolGrafter; import forestry.api.arboriculture.genetics.IFruit; @@ -29,16 +29,16 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.loot.IGlobalLootModifier; -import net.minecraftforge.common.loot.LootModifier; -import net.minecraftforge.event.ForgeEventFactory; +import net.neoforged.neoforge.common.loot.IGlobalLootModifier; +import net.neoforged.neoforge.common.loot.LootModifier; +import net.neoforged.neoforge.event.EventHooks; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.util.List; public class GrafterLootModifier extends LootModifier { - public static final Codec CODEC = RecordCodecBuilder.create(inst -> codecStart(inst).apply(inst, GrafterLootModifier::new)); + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> codecStart(instance).apply(instance, GrafterLootModifier::new)); public GrafterLootModifier(LootItemCondition[] conditionsIn) { super(conditionsIn); @@ -63,7 +63,7 @@ public GrafterLootModifier(LootItemCondition[] conditionsIn) { } harvestingTool.hurt(1, context.getRandom(), (ServerPlayer) player); if (harvestingTool.isEmpty()) { - ForgeEventFactory.onPlayerDestroyItem(player, harvestingTool, InteractionHand.MAIN_HAND); + EventHooks.onPlayerDestroyItem(player, harvestingTool, InteractionHand.MAIN_HAND); } return generatedLoot; } @@ -92,7 +92,7 @@ public void handleLoot(List generatedLoot, Player player, ItemStack h } } if (tileEntity instanceof IFruitBearer bearer) { - generatedLoot.addAll(bearer.pickFruit(harvestingTool)); + generatedLoot.addAll(bearer.pickFruit()); } if (state.getBlock() instanceof BlockDefaultLeavesFruit) { IGenome genome = tree.getGenome(); @@ -115,7 +115,7 @@ private ITree getTree(BlockState state, @Nullable BlockEntity entity) { } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/forestry/arboriculture/loot/package-info.java b/src/main/java/forestry/arboriculture/loot/package-info.java index 7f37447d7b..d02fcf6ff7 100644 --- a/src/main/java/forestry/arboriculture/loot/package-info.java +++ b/src/main/java/forestry/arboriculture/loot/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.loot; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/arboriculture/models/LeafSprite.java b/src/main/java/forestry/arboriculture/models/LeafSprite.java index dfee1c7391..55f0415f36 100644 --- a/src/main/java/forestry/arboriculture/models/LeafSprite.java +++ b/src/main/java/forestry/arboriculture/models/LeafSprite.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.models; import forestry.api.client.arboriculture.ILeafSprite; @@ -31,10 +21,10 @@ public static LeafSprite create(ResourceLocation id) { String path = "block/leaves/" + id.getPath(); return new LeafSprite( - new ResourceLocation(namespace, path + "_fast"), - new ResourceLocation(namespace, path), - new ResourceLocation(namespace, path + "_pollinated_fast"), - new ResourceLocation(namespace, path + "_pollinated") + ResourceLocation.fromNamespaceAndPath(namespace, path + "_fast"), + ResourceLocation.fromNamespaceAndPath(namespace, path), + ResourceLocation.fromNamespaceAndPath(namespace, path + "_pollinated_fast"), + ResourceLocation.fromNamespaceAndPath(namespace, path + "_pollinated") ); } diff --git a/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java b/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java index 7ee63e5cf0..8ce07ef346 100644 --- a/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java +++ b/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.models; import com.google.common.base.Preconditions; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.client.IForestryClientApi; import forestry.api.client.arboriculture.ILeafSprite; import forestry.api.genetics.alleles.TreeChromosomes; @@ -29,7 +19,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; public class ModelDecorativeLeaves extends ModelBlockCached { public ModelDecorativeLeaves(Class blockClass) { @@ -83,7 +73,7 @@ protected BakedModel bakeModel(BlockState state, ModelDefaultLeaves.Key key, B b bakeBlock(block, extraData, key, baker, false); - this.blockModel = baker.bake(false); + this.blockModel = baker.bake(false); onCreateModel(this.blockModel); return this.blockModel; } diff --git a/src/main/java/forestry/arboriculture/models/ModelDefaultLeaves.java b/src/main/java/forestry/arboriculture/models/ModelDefaultLeaves.java index d7501edc48..f813ce18c1 100644 --- a/src/main/java/forestry/arboriculture/models/ModelDefaultLeaves.java +++ b/src/main/java/forestry/arboriculture/models/ModelDefaultLeaves.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.models; import com.google.common.base.Preconditions; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.client.IForestryClientApi; import forestry.api.client.arboriculture.ILeafSprite; import forestry.arboriculture.blocks.BlockAbstractLeaves; @@ -28,13 +18,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; import java.util.Objects; -@OnlyIn(Dist.CLIENT) public class ModelDefaultLeaves extends ModelBlockCached { public ModelDefaultLeaves() { super(BlockDefaultLeaves.class); diff --git a/src/main/java/forestry/arboriculture/models/ModelDefaultLeavesFruit.java b/src/main/java/forestry/arboriculture/models/ModelDefaultLeavesFruit.java index 8ff8fac4be..19127c28c5 100644 --- a/src/main/java/forestry/arboriculture/models/ModelDefaultLeavesFruit.java +++ b/src/main/java/forestry/arboriculture/models/ModelDefaultLeavesFruit.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.models; import forestry.arboriculture.blocks.BlockDefaultLeavesFruit; @@ -17,8 +7,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.ChunkRenderTypeSet; +import net.neoforged.neoforge.client.model.data.ModelData; public class ModelDefaultLeavesFruit extends ModelDecorativeLeaves { public ModelDefaultLeavesFruit() { diff --git a/src/main/java/forestry/arboriculture/models/ModelLeaves.java b/src/main/java/forestry/arboriculture/models/ModelLeaves.java index 1fff6e3020..70b3c6fe85 100644 --- a/src/main/java/forestry/arboriculture/models/ModelLeaves.java +++ b/src/main/java/forestry/arboriculture/models/ModelLeaves.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.models; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.client.IForestryClientApi; import forestry.arboriculture.blocks.BlockAbstractLeaves; import forestry.arboriculture.blocks.BlockForestryLeaves; @@ -30,16 +20,13 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.ChunkRenderTypeSet; +import net.neoforged.neoforge.client.model.data.ModelData; import org.joml.Vector3f; import javax.annotation.Nullable; import java.util.Objects; -@OnlyIn(Dist.CLIENT) public class ModelLeaves extends ModelBlockCached { // copied from "minecraft:block/block.json" model public static final ItemTransforms TRANSFORMS = new ItemTransforms( diff --git a/src/main/java/forestry/arboriculture/models/ModelSapling.java b/src/main/java/forestry/arboriculture/models/ModelSapling.java index a02ab5aa0f..ade7c5b33c 100644 --- a/src/main/java/forestry/arboriculture/models/ModelSapling.java +++ b/src/main/java/forestry/arboriculture/models/ModelSapling.java @@ -2,7 +2,7 @@ import com.mojang.datafixers.util.Pair; import forestry.api.arboriculture.ForestryTreeSpecies; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.client.IForestryClientApi; import forestry.api.client.arboriculture.ITreeClientManager; @@ -22,9 +22,9 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.client.model.geometry.IGeometryBakingContext; -import net.minecraftforge.client.model.geometry.IUnbakedGeometry; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; +import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; import javax.annotation.Nullable; import java.util.IdentityHashMap; @@ -34,7 +34,7 @@ public class ModelSapling implements IUnbakedGeometry { @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { IdentityHashMap itemModels = new IdentityHashMap<>(); IdentityHashMap blockModels = new IdentityHashMap<>(); diff --git a/src/main/java/forestry/arboriculture/models/SaplingModelLoader.java b/src/main/java/forestry/arboriculture/models/SaplingModelLoader.java index 0e7e65f8f6..4fd1741e73 100644 --- a/src/main/java/forestry/arboriculture/models/SaplingModelLoader.java +++ b/src/main/java/forestry/arboriculture/models/SaplingModelLoader.java @@ -3,11 +3,11 @@ import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import net.minecraftforge.client.model.geometry.IGeometryLoader; +import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; public class SaplingModelLoader implements IGeometryLoader { @Override - public ModelSapling read(JsonObject modelContents, JsonDeserializationContext context) throws JsonParseException { + public ModelSapling read(JsonObject json, JsonDeserializationContext context) throws JsonParseException { return new ModelSapling(); } } diff --git a/src/main/java/forestry/arboriculture/models/package-info.java b/src/main/java/forestry/arboriculture/models/package-info.java index ea3893b14d..bbb6e9917f 100644 --- a/src/main/java/forestry/arboriculture/models/package-info.java +++ b/src/main/java/forestry/arboriculture/models/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.models; diff --git a/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java b/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java deleted file mode 100644 index 6ec779e22a..0000000000 --- a/src/main/java/forestry/arboriculture/network/IRipeningPacketReceiver.java +++ /dev/null @@ -1,15 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.network; - -public interface IRipeningPacketReceiver { - void fromRipeningPacket(int ripeningValue); -} diff --git a/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java b/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java index 30319ff777..d03dbab4b7 100644 --- a/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java +++ b/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.network; import forestry.api.modules.IForestryPacketClient; @@ -15,9 +5,9 @@ import forestry.core.network.PacketIdClient; import forestry.core.tiles.TileUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.entity.player.Player; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketRipeningUpdate(BlockPos pos, int value) implements IForestryPacketClient { public PacketRipeningUpdate(TileLeaves leaves) { @@ -25,21 +15,20 @@ public PacketRipeningUpdate(TileLeaves leaves) { } @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.RIPENING_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeVarInt(this.value); + public static void encode(RegistryFriendlyByteBuf buffer, PacketRipeningUpdate msg) { + buffer.writeBlockPos(msg.pos); + buffer.writeVarInt(msg.value); } - public static PacketRipeningUpdate decode(FriendlyByteBuf buffer) { + public static PacketRipeningUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketRipeningUpdate(buffer.readBlockPos(), buffer.readVarInt()); } - public static void handle(PacketRipeningUpdate msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, IRipeningPacketReceiver.class, tile -> tile.fromRipeningPacket(msg.value)); + public static void handle(PacketRipeningUpdate msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, TileLeaves.class, tile -> tile.fromRipeningPacket(msg.value)); } } diff --git a/src/main/java/forestry/arboriculture/network/package-info.java b/src/main/java/forestry/arboriculture/network/package-info.java index e97e237f8f..6860707384 100644 --- a/src/main/java/forestry/arboriculture/network/package-info.java +++ b/src/main/java/forestry/arboriculture/network/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.network; diff --git a/src/main/java/forestry/arboriculture/package-info.java b/src/main/java/forestry/arboriculture/package-info.java index 1b7363d7a2..9a0a726996 100644 --- a/src/main/java/forestry/arboriculture/package-info.java +++ b/src/main/java/forestry/arboriculture/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture; diff --git a/src/main/java/forestry/arboriculture/tiles/TileForestryHangingSign.java b/src/main/java/forestry/arboriculture/tiles/TileForestryHangingSign.java new file mode 100644 index 0000000000..9cb28703c3 --- /dev/null +++ b/src/main/java/forestry/arboriculture/tiles/TileForestryHangingSign.java @@ -0,0 +1,18 @@ +package forestry.arboriculture.tiles; + +import forestry.arboriculture.features.ArboricultureTiles; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.entity.HangingSignBlockEntity; +import net.minecraft.world.level.block.state.BlockState; + +public class TileForestryHangingSign extends HangingSignBlockEntity { + public TileForestryHangingSign(BlockPos pos, BlockState state) { + super(pos, state); + } + + @Override + public BlockEntityType getType() { + return ArboricultureTiles.HANGING_SIGN.tileType(); + } +} diff --git a/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java b/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java index 166cbe1909..43968536c4 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java +++ b/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.tiles; import forestry.api.IForestryApi; @@ -25,9 +15,10 @@ import forestry.core.utils.NBTUtilForestry; import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; @@ -64,21 +55,20 @@ public void setProperties(IGenome genome, IFruit allele, float yield) { setChanged(); } - /* SAVING & LOADING */ @Override - public void writeData(FriendlyByteBuf data) { + public void writeData(RegistryFriendlyByteBuf buffer) { if (this.fruit != null) { - data.writeBoolean(true); - data.writeResourceLocation(TreeChromosomes.FRUIT.getId(this.fruit)); + buffer.writeBoolean(true); + buffer.writeResourceLocation(TreeChromosomes.FRUIT.getId(this.fruit)); } else { - data.writeBoolean(false); + buffer.writeBoolean(false); } } @Override - public void readData(FriendlyByteBuf data) { - if (data.readBoolean()) { - IValueAllele stored = IForestryApi.INSTANCE.getAlleleManager().getAllele(data.readResourceLocation()).cast(); + public void readData(RegistryFriendlyByteBuf buffer) { + if (buffer.readBoolean()) { + IValueAllele stored = IForestryApi.INSTANCE.getAlleleManager().getAllele(buffer.readResourceLocation()).cast(); if (stored.value() instanceof IFruit newFruit) { this.fruit = newFruit; @@ -88,22 +78,22 @@ public void readData(FriendlyByteBuf data) { } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); if (this.fruit != null) { - compoundNBT.putString(NBT_FRUIT, TreeChromosomes.FRUIT.getId(this.fruit).toString()); + nbt.putString(NBT_FRUIT, TreeChromosomes.FRUIT.getId(this.fruit).toString()); } - compoundNBT.putShort(NBT_MATURITY, this.maturity); - compoundNBT.putFloat(NBT_YIELD, this.yield); + nbt.putShort(NBT_MATURITY, this.maturity); + nbt.putFloat(NBT_YIELD, this.yield); } @Override - public void load(CompoundTag nbt) { - super.load(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); String fruitNbt = nbt.getString(NBT_FRUIT); if (!fruitNbt.isEmpty()) { - this.fruit = TreeChromosomes.FRUIT.getSafe(new ResourceLocation(fruitNbt)); + this.fruit = TreeChromosomes.FRUIT.getSafe(ResourceLocation.tryParse(fruitNbt)); } if (this.fruit == null) { this.fruit = ForestryAlleles.FRUIT_COCOA.value(); @@ -113,7 +103,6 @@ public void load(CompoundTag nbt) { this.yield = nbt.getFloat(NBT_YIELD); } - /* UPDATING */ public void onBlockTick(RandomSource rand) { if (canMature() && rand.nextFloat() <= this.yield) { addRipeness(0.5f); @@ -158,22 +147,22 @@ public ClientboundBlockEntityDataPacket getUpdatePacket() { } @Override - public CompoundTag getUpdateTag() { - CompoundTag tag = super.getUpdateTag(); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag tag = super.getUpdateTag(registries); return NBTUtilForestry.writeStreamableToNbt(this, tag); } @Override - public void handleUpdateTag(CompoundTag tag) { - super.handleUpdateTag(tag); + public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider registries) { + super.handleUpdateTag(tag, registries); NBTUtilForestry.readStreamableFromNbt(this, tag); } @Override - public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { - super.onDataPacket(net, pkt); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider registries) { + super.onDataPacket(net, pkt, registries); CompoundTag nbt = pkt.getTag(); - handleUpdateTag(nbt); + handleUpdateTag(nbt, registries); } /* IFRUITBEARER */ @@ -183,9 +172,9 @@ public boolean hasFruit() { } @Override - public List pickFruit(ItemStack tool) { + public List pickFruit() { List fruits = getDrops(); - this.maturity = 0; + this.maturity = 0; BlockState oldState = getBlockState(); BlockState newState = oldState.setValue(CocoaBlock.AGE, 0); @@ -203,15 +192,15 @@ public float getRipeness() { public void addRipeness(float add) { int previousAge = this.maturity; - this.maturity += MAX_MATURITY * add; + this.maturity += (short) (MAX_MATURITY * add); if (this.maturity > MAX_MATURITY) { - this.maturity = MAX_MATURITY; + this.maturity = MAX_MATURITY; } int age = this.maturity; if (age - previousAge > 0) { BlockState state = getBlockState().setValue(CocoaBlock.AGE, age); - this.level.setBlockAndUpdate(getBlockPos(), state); + this.level.setBlockAndUpdate(this.worldPosition, state); } } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileLeaves.java b/src/main/java/forestry/arboriculture/tiles/TileLeaves.java index 4f0e423028..bb11eda079 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileLeaves.java +++ b/src/main/java/forestry/arboriculture/tiles/TileLeaves.java @@ -1,22 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.tiles; import forestry.api.IForestryApi; import forestry.api.arboriculture.ForestryTreeSpecies; import forestry.api.arboriculture.ILeafTickHandler; -import forestry.api.arboriculture.ITreeSpecies; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.ITree; import forestry.api.arboriculture.genetics.ITreeEffect; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.client.IForestryClientApi; import forestry.api.climate.IBiomeProvider; import forestry.api.core.HumidityType; @@ -30,7 +20,6 @@ import forestry.api.lepidopterology.IButterflyNursery; import forestry.api.lepidopterology.genetics.IButterfly; import forestry.arboriculture.features.ArboricultureTiles; -import forestry.arboriculture.network.IRipeningPacketReceiver; import forestry.arboriculture.network.PacketRipeningUpdate; import forestry.core.ClientsideCode; import forestry.core.network.packets.PacketTileStream; @@ -39,27 +28,29 @@ import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.client.model.data.ModelProperty; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelProperty; import javax.annotation.Nullable; import java.util.IdentityHashMap; import java.util.List; import java.util.Objects; -public class TileLeaves extends TileTreeContainer implements IFruitBearer, IButterflyNursery, IRipeningPacketReceiver, IBiomeProvider, ISpectacleBlock { +public class TileLeaves extends TileTreeContainer implements IFruitBearer, IButterflyNursery, IBiomeProvider, ISpectacleBlock { private static final String NBT_RIPENING = "RT"; private static final String NBT_DAMAGE = "ENC"; private static final String NBT_FRUIT_LEAF = "FL"; @@ -95,8 +86,8 @@ public TileLeaves(BlockPos pos, BlockState state) { /* SAVING & LOADING */ @Override - public void load(CompoundTag nbt) { - super.load(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); this.ripeningTime = nbt.getInt(NBT_RIPENING); this.damage = nbt.getInt(NBT_DAMAGE); @@ -122,8 +113,8 @@ public void load(CompoundTag nbt) { } @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); nbt.putInt(NBT_RIPENING, this.ripeningTime); nbt.putInt(NBT_DAMAGE, this.damage); @@ -161,16 +152,14 @@ public void onBlockTick(Level worldIn, BlockPos pos, BlockState state, RandomSou } if (this.damage > 0) { - this.damage--; + this.damage--; } if (hasFruit() && getRipeningTime() < this.ripeningPeriod) { - //ITreekeepingMode treekeepingMode = SpeciesUtil.TREE_TYPE.get().getTreekeepingMode(level); - //float sappinessModifier = treekeepingMode.getSappinessModifier(genome, 1f); - float sappiness = genome.getActiveValue(TreeChromosomes.SAPPINESS);// * sappinessModifier; + float sappiness = genome.getActiveValue(TreeChromosomes.SAPPINESS); if (rand.nextFloat() < sappiness) { - this.ripeningTime++; + this.ripeningTime++; sendNetworkUpdateRipening(); } } @@ -179,7 +168,7 @@ public void onBlockTick(Level worldIn, BlockPos pos, BlockState state, RandomSou matureCaterpillar(); } - this.effectData = tree.doEffect(this.effectData, this.level, getBlockPos()); + this.effectData = tree.doEffect(this.effectData, this.level, getBlockPos()); } @Override @@ -248,7 +237,7 @@ public int getFoliageColour() { public int getFruitColour() { if (this.colourFruits == 0 && hasFruit()) { - this.colourFruits = determineFruitColour(); + this.colourFruits = determineFruitColour(); } return this.colourFruits; } @@ -283,9 +272,8 @@ public void setMate(ITree pollen) { } } - /* NETWORK */ public void sendNetworkUpdate() { - NetworkUtil.sendNetworkPacket(new PacketTileStream(this), this.worldPosition, this.level); + NetworkUtil.sendToPlayersTrackingPos(new PacketTileStream(this), this.worldPosition, (ServerLevel) this.level); } private void sendNetworkUpdateRipening() { @@ -296,10 +284,12 @@ private void sendNetworkUpdateRipening() { if (newColourFruits == this.colourFruits) { return; } - this.colourFruits = newColourFruits; + this.colourFruits = newColourFruits; - PacketRipeningUpdate ripeningUpdate = new PacketRipeningUpdate(this); - NetworkUtil.sendNetworkPacket(ripeningUpdate, this.worldPosition, this.level); + if (this.level instanceof ServerLevel serverLevel) { + PacketRipeningUpdate ripeningUpdate = new PacketRipeningUpdate(this); + NetworkUtil.sendToPlayersTrackingPos(ripeningUpdate, this.worldPosition, serverLevel); + } setChanged(); } @@ -310,12 +300,12 @@ private void sendNetworkUpdateRipening() { private static final short FLAG_HAS_INACTIVE_EFFECT = 1 << 3; @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); byte leafState = 0; IGenome genome = getTree().getGenome(); - AllelePair> effects = genome.getAllelePair(TreeChromosomes.EFFECT); + AllelePair> effects = genome.getAllelePair(TreeChromosomes.EFFECT); boolean hasActiveEffect = effects.active() != ForestryAlleles.TREE_EFFECT_NONE; boolean hasInactiveEffect = effects.inactive() != ForestryAlleles.TREE_EFFECT_NONE; boolean hasFruit = hasFruit(); @@ -335,32 +325,32 @@ public void writeData(FriendlyByteBuf data) { leafState |= FLAG_HAS_INACTIVE_EFFECT; } - data.writeByte(leafState); + buffer.writeByte(leafState); if (hasFruit) { String fruitAlleleUID = genome.getActiveAllele(TreeChromosomes.FRUIT).alleleId().toString(); int colourFruits = getFruitColour(); - data.writeUtf(fruitAlleleUID); - data.writeInt(colourFruits); + buffer.writeUtf(fruitAlleleUID); + buffer.writeInt(colourFruits); } // todo come up with a way to send numeric IDs instead of string IDs if (hasActiveEffect) { - data.writeUtf(effects.active().alleleId().toString()); + buffer.writeUtf(effects.active().alleleId().toString()); } if (hasInactiveEffect) { - data.writeUtf(effects.inactive().alleleId().toString()); + buffer.writeUtf(effects.inactive().alleleId().toString()); } } @Override - public void readData(FriendlyByteBuf data) { + public void readData(RegistryFriendlyByteBuf buffer) { ResourceLocation speciesId = null; - if (data.readBoolean()) { - speciesId = data.readResourceLocation(); // this is called instead of super.readData, be careful! + if (buffer.readBoolean()) { + speciesId = buffer.readResourceLocation(); // this is called instead of super.readData, be careful! } - byte leafState = data.readByte(); + byte leafState = buffer.readByte(); this.isPollinatedState = (leafState & FLAG_IS_POLLINATED) != 0; this.isFruitLeaf = (leafState & FLAG_HAS_FRUIT) != 0; @@ -369,12 +359,12 @@ public void readData(FriendlyByteBuf data) { ResourceLocation fruitId = null; if (this.isFruitLeaf) { - fruitId = data.readResourceLocation(); - this.colourFruits = data.readInt(); + fruitId = buffer.readResourceLocation(); + this.colourFruits = buffer.readInt(); } - ResourceLocation activeEffectAlleleId = hasActiveEffect ? data.readResourceLocation() : null; - ResourceLocation inactiveEffectAlleleId = hasInactiveEffect ? data.readResourceLocation() : null; + ResourceLocation activeEffectAlleleId = hasActiveEffect ? buffer.readResourceLocation() : null; + ResourceLocation inactiveEffectAlleleId = hasInactiveEffect ? buffer.readResourceLocation() : null; ITreeSpecies treeTemplate = SpeciesUtil.TREE_TYPE.get().getSpeciesSafe(speciesId); if (treeTemplate != null) { @@ -406,25 +396,24 @@ public void readData(FriendlyByteBuf data) { } } - @Override public void fromRipeningPacket(int newColourFruits) { if (newColourFruits == this.colourFruits) { return; } - this.colourFruits = newColourFruits; + this.colourFruits = newColourFruits; ClientsideCode.markForUpdate(this.worldPosition); } /* IFRUITBEARER */ @Override - public List pickFruit(ItemStack tool) { + public List pickFruit() { ITree tree = getTree(); if (tree == null || !hasFruit()) { return List.of(); } List produceStacks = tree.produceStacks(this.level, this.worldPosition, getRipeningTime()); - this.ripeningTime = 0; + this.ripeningTime = 0; sendNetworkUpdateRipening(); return produceStacks; } @@ -460,11 +449,11 @@ private void matureCaterpillar() { if (this.caterpillar == null) { return; } - this.maturationTime++; + this.maturationTime++; ITree tree = getTree(); boolean wasDestroyed = isDestroyed(tree, this.damage); - this.damage += this.caterpillar.getGenome().getActiveValue(ButterflyChromosomes.METABOLISM); + this.damage += this.caterpillar.getGenome().getActiveValue(ButterflyChromosomes.METABOLISM); IGenome caterpillarGenome = this.caterpillar.getGenome(); int caterpillarMatureTime = Math.round((float) caterpillarGenome.getActiveValue(ButterflyChromosomes.LIFESPAN) / (caterpillarGenome.getActiveValue(ButterflyChromosomes.FERTILITY) * 2)); @@ -477,11 +466,6 @@ private void matureCaterpillar() { } } - @Override - public BlockPos getCoordinates() { - return getBlockPos(); - } - @Override @Nullable public IButterfly getCaterpillar() { @@ -495,7 +479,7 @@ public IIndividual getNanny() { @Override public void setCaterpillar(@Nullable IButterfly caterpillar) { - this.maturationTime = 0; + this.maturationTime = 0; this.caterpillar = caterpillar; sendNetworkUpdate(); } @@ -507,22 +491,22 @@ public boolean canNurse(IButterfly caterpillar) { } @Override - public Holder getBiome() { + public Holder getBiome(HolderLookup.Provider registries) { return this.level.getBiome(this.worldPosition); } @Override public TemperatureType temperature() { - return IForestryApi.INSTANCE.getClimateManager().getTemperature(getBiome()); + return IForestryApi.INSTANCE.getClimateManager().getTemperature(getBiome(this.level.registryAccess())); } @Override public HumidityType humidity() { - return IForestryApi.INSTANCE.getClimateManager().getHumidity(getBiome()); + return IForestryApi.INSTANCE.getClimateManager().getHumidity(getBiome(this.level.registryAccess())); } @Override - public Level getWorldObj() { + public Level getLevel() { return this.level; } diff --git a/src/main/java/forestry/arboriculture/tiles/TileSapling.java b/src/main/java/forestry/arboriculture/tiles/TileSapling.java index 1ad850a591..15b2b82dc1 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileSapling.java +++ b/src/main/java/forestry/arboriculture/tiles/TileSapling.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.tiles; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.genetics.IBreedingTracker; import forestry.arboriculture.features.ArboricultureTiles; @@ -21,6 +11,7 @@ import forestry.core.utils.SpeciesUtil; import forestry.core.worldgen.FeatureBase; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; @@ -30,8 +21,8 @@ import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.client.model.data.ModelProperty; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelProperty; import javax.annotation.Nonnull; import java.util.Optional; @@ -47,35 +38,28 @@ public TileSapling(BlockPos pos, BlockState state) { super(ArboricultureTiles.SAPLING.tileType(), pos, state); } - /* SAVING & LOADING */ @Override - public void load(CompoundTag nbt) { - super.load(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - this.timesTicked = nbt.getInt("TT"); - this.ownerHandler.read(nbt); + this.timesTicked = nbt.getInt("TT"); + this.ownerHandler.read(nbt, registries); } @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); nbt.putInt("TT", this.timesTicked); - this.ownerHandler.write(nbt); + this.ownerHandler.write(nbt, registries); } @Override public void onBlockTick(Level worldIn, BlockPos pos, BlockState state, RandomSource rand) { - this.timesTicked++; + this.timesTicked++; tryGrow(rand, false); } - private static int getRequiredMaturity(Level world, ITree tree) { - //ITreekeepingMode treekeepingMode = SpeciesUtil.TREE_TYPE.get().getTreekeepingMode(world); - //float maturationModifier = treekeepingMode.getMaturationModifier(tree.getGenome(), 1f); - return tree.getRequiredMaturity();//Math.round(tree.getRequiredMaturity() * maturationModifier); - } - public boolean canAcceptBoneMeal(RandomSource rand) { ITree tree = getTree(); @@ -83,7 +67,7 @@ public boolean canAcceptBoneMeal(RandomSource rand) { return false; } - int maturity = getRequiredMaturity(this.level, tree); + int maturity = tree.getRequiredMaturity(); if (this.timesTicked < maturity) { return true; } @@ -104,10 +88,10 @@ public void tryGrow(RandomSource random, boolean boneMealed) { return; } - int maturity = getRequiredMaturity(this.level, tree); + int maturity = tree.getRequiredMaturity(); if (this.timesTicked < maturity) { if (boneMealed) { - this.timesTicked = maturity; + this.timesTicked = maturity; } return; } diff --git a/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java b/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java index 38f57037c5..352a688af7 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java +++ b/src/main/java/forestry/arboriculture/tiles/TileTreeContainer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.tiles; import forestry.api.arboriculture.genetics.ITree; @@ -16,10 +6,11 @@ import forestry.core.utils.NBTUtilForestry; import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; @@ -43,8 +34,8 @@ public TileTreeContainer(BlockEntityType type, BlockPos pos, BlockState state /* SAVING & LOADING */ @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); if (this.containedTree != null) { Tag serialized = SpeciesUtil.serializeIndividual(this.containedTree); @@ -55,8 +46,8 @@ public void saveAdditional(CompoundTag nbt) { } @Override - public void load(CompoundTag nbt) { - super.load(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); Tag treeNbt = nbt.get("ContainedTree"); @@ -66,21 +57,21 @@ public void load(CompoundTag nbt) { } @Override - public void writeData(FriendlyByteBuf data) { + public void writeData(RegistryFriendlyByteBuf buffer) { ITree tree = getTree(); if (tree != null) { - data.writeBoolean(true); + buffer.writeBoolean(true); ResourceLocation speciesId = tree.getSpecies().id(); - data.writeResourceLocation(speciesId); + buffer.writeResourceLocation(speciesId); } else { - data.writeBoolean(false); + buffer.writeBoolean(false); } } @Override - public void readData(FriendlyByteBuf data) { - if (data.readBoolean()) { - ResourceLocation speciesId = data.readResourceLocation(); + public void readData(RegistryFriendlyByteBuf buffer) { + if (buffer.readBoolean()) { + ResourceLocation speciesId = buffer.readResourceLocation(); ITree tree = SpeciesUtil.getTreeSpecies(speciesId).createIndividual(); setTree(tree); } @@ -92,7 +83,7 @@ public void setTree(ITree tree) { if (this.level != null && this.level.isClientSide) { ClientsideCode.markForUpdate(this.worldPosition); - } + } } @Nullable @@ -100,8 +91,6 @@ public ITree getTree() { return this.containedTree; } - /* UPDATING */ - /** * Leaves and saplings will implement their logic here. */ @@ -113,21 +102,21 @@ public ClientboundBlockEntityDataPacket getUpdatePacket() { } @Override - public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { - super.onDataPacket(net, pkt); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider registries) { + super.onDataPacket(net, pkt, registries); CompoundTag nbt = pkt.getTag(); - handleUpdateTag(nbt); + handleUpdateTag(nbt, registries); } @Override - public CompoundTag getUpdateTag() { - CompoundTag tag = super.getUpdateTag(); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag tag = super.getUpdateTag(registries); return NBTUtilForestry.writeStreamableToNbt(this, tag); } @Override - public void handleUpdateTag(CompoundTag tag) { - super.handleUpdateTag(tag); + public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider registries) { + super.handleUpdateTag(tag, registries); NBTUtilForestry.readStreamableFromNbt(this, tag); } } diff --git a/src/main/java/forestry/arboriculture/tiles/package-info.java b/src/main/java/forestry/arboriculture/tiles/package-info.java index 855fd77503..c342a3a949 100644 --- a/src/main/java/forestry/arboriculture/tiles/package-info.java +++ b/src/main/java/forestry/arboriculture/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.tiles; diff --git a/src/main/java/forestry/arboriculture/villagers/ArboricultureVillagers.java b/src/main/java/forestry/arboriculture/villagers/ArboricultureVillagers.java index 7c964c0c27..3fa4111319 100644 --- a/src/main/java/forestry/arboriculture/villagers/ArboricultureVillagers.java +++ b/src/main/java/forestry/arboriculture/villagers/ArboricultureVillagers.java @@ -1,8 +1,8 @@ package forestry.arboriculture.villagers; import com.google.common.collect.ImmutableSet; -import forestry.api.arboriculture.ITreeSpecies; -import forestry.api.arboriculture.TreeManager; +import forestry.api.IForestryApi; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.WoodBlockKind; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.genetics.ILifeStage; @@ -28,10 +28,10 @@ import net.minecraft.world.entity.npc.VillagerTrades; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.trading.ItemCost; import net.minecraft.world.item.trading.MerchantOffer; -import net.minecraftforge.event.village.VillagerTradesEvent; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.event.village.VillagerTradesEvent; +import net.neoforged.neoforge.registries.DeferredRegister; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; @@ -48,15 +48,15 @@ public class ArboricultureVillagers { private static final DeferredRegister POINTS_OF_INTEREST = REGISTRY.getRegistry(Registries.POINT_OF_INTEREST_TYPE); private static final DeferredRegister PROFESSIONS = REGISTRY.getRegistry(Registries.VILLAGER_PROFESSION); - public static final RegistryObject POI_TREE_CHEST = POINTS_OF_INTEREST.register("tree_chest", () -> new PoiType(Set.copyOf(CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST).block().getStateDefinition().getPossibleStates()), 1, 1)); - public static final RegistryObject ARBORIST = PROFESSIONS.register("arborist", () -> { + public static final Holder POI_TREE_CHEST = POINTS_OF_INTEREST.register("tree_chest", () -> new PoiType(Set.copyOf(CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST).block().getStateDefinition().getPossibleStates()), 1, 1)); + public static final Holder ARBORIST = PROFESSIONS.register("arborist", () -> { ResourceKey key = Objects.requireNonNull(POI_TREE_CHEST.getKey()); Predicate> jobSitePredicate = poi -> poi.is(key); return new VillagerProfession("arborist", jobSitePredicate, jobSitePredicate, ImmutableSet.of(), ImmutableSet.of(), SoundEvents.VILLAGER_WORK_FISHERMAN); }); public static void villagerTrades(VillagerTradesEvent event) { - if (event.getType() == ARBORIST.get()) { + if (event.getType() == ARBORIST.value()) { Int2ObjectMap> trades = event.getTrades(); trades.get(1).add(new GivePlanksForEmeralds(new VillagerTrade.PriceInterval(1, 4), new VillagerTrade.PriceInterval(10, 32), 8, 2, 0F)); trades.get(1).add(new GivePollenForEmeralds(new VillagerTrade.PriceInterval(1, 1), new VillagerTrade.PriceInterval(1, 3), TreeLifeStage.SAPLING, 4, 8, 2, 0F)); @@ -77,28 +77,26 @@ public static void villagerTrades(VillagerTradesEvent event) { private record GivePlanksForEmeralds(VillagerTrade.PriceInterval emeraldsPriceInfo, VillagerTrade.PriceInterval sellingPriceInfo, int maxUses, int xp, float priceMult) implements VillagerTrades.ItemListing { - @Override public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource rand) { ForestryWoodType woodType = ForestryWoodType.getRandom(rand); - ItemStack sellStack = TreeManager.woodAccess.getStack(woodType, WoodBlockKind.PLANKS, false); + ItemStack sellStack = IForestryApi.INSTANCE.getTreeManager().getWoodAccess().getStack(woodType, WoodBlockKind.PLANKS, false); sellStack.setCount(this.sellingPriceInfo.getPrice(rand)); - return new MerchantOffer(new ItemStack(Items.EMERALD, this.emeraldsPriceInfo.getPrice(rand)), sellStack, this.maxUses, this.xp, this.priceMult); + return new MerchantOffer(new ItemCost(Items.EMERALD, this.emeraldsPriceInfo.getPrice(rand)), sellStack, this.maxUses, this.xp, this.priceMult); } } private record GiveLogsForEmeralds(VillagerTrade.PriceInterval emeraldsPriceInfo, VillagerTrade.PriceInterval sellingPriceInfo, int maxUses, int xp, float priceMult) implements VillagerTrades.ItemListing { - @Override public MerchantOffer getOffer(@NotNull Entity trader, @NotNull RandomSource rand) { ForestryWoodType woodType = ForestryWoodType.getRandom(rand); - ItemStack sellStack = TreeManager.woodAccess.getStack(woodType, WoodBlockKind.LOG, false); + ItemStack sellStack = IForestryApi.INSTANCE.getTreeManager().getWoodAccess().getStack(woodType, WoodBlockKind.LOG, false); sellStack.setCount(this.sellingPriceInfo.getPrice(rand)); - return new MerchantOffer(new ItemStack(Items.EMERALD, this.emeraldsPriceInfo.getPrice(rand)), sellStack, this.maxUses, this.xp, this.priceMult); + return new MerchantOffer(new ItemCost(Items.EMERALD, this.emeraldsPriceInfo.getPrice(rand)), sellStack, this.maxUses, this.xp, this.priceMult); } } @@ -106,11 +104,9 @@ private record GivePollenForEmeralds(VillagerTrade.PriceInterval buyingPriceInfo VillagerTrade.PriceInterval sellingPriceInfo, ILifeStage stage, int maxComplexity, int maxUses, int xp, float priceMult) implements VillagerTrades.ItemListing { - @Nullable @Override public MerchantOffer getOffer(Entity trader, RandomSource rand) { - // todo this could be optimized to just pick random entries from tree species until one with suitable complexity is found // instead of copying the whole thing and then picking once List registeredSpecies = SpeciesUtil.getAllTreeSpecies(); ArrayList potentialSpecies = new ArrayList<>(); @@ -128,7 +124,7 @@ public MerchantOffer getOffer(Entity trader, RandomSource rand) { ItemStack sellStack = chosenSpecies.createStack(this.stage); sellStack.setCount(this.sellingPriceInfo.getPrice(rand)); - return new MerchantOffer(new ItemStack(Items.EMERALD, this.buyingPriceInfo.getPrice(rand)), sellStack, this.maxUses, this.xp, this.priceMult); + return new MerchantOffer(new ItemCost(Items.EMERALD, this.buyingPriceInfo.getPrice(rand)), sellStack, this.maxUses, this.xp, this.priceMult); } } } diff --git a/src/main/java/forestry/arboriculture/villagers/package-info.java b/src/main/java/forestry/arboriculture/villagers/package-info.java index 93feee755a..08b462a67f 100644 --- a/src/main/java/forestry/arboriculture/villagers/package-info.java +++ b/src/main/java/forestry/arboriculture/villagers/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.villagers; diff --git a/src/main/java/forestry/arboriculture/worldgen/DefaultTreeGenerator.java b/src/main/java/forestry/arboriculture/worldgen/DefaultTreeGenerator.java index 5662ab02a1..0cf2edf139 100644 --- a/src/main/java/forestry/arboriculture/worldgen/DefaultTreeGenerator.java +++ b/src/main/java/forestry/arboriculture/worldgen/DefaultTreeGenerator.java @@ -1,7 +1,9 @@ package forestry.arboriculture.worldgen; import com.google.common.base.Preconditions; +import forestry.api.IForestryApi; import forestry.api.arboriculture.*; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.TreeChromosomes; import forestry.arboriculture.features.ArboricultureBlocks; @@ -24,23 +26,23 @@ import java.util.function.Function; public class DefaultTreeGenerator implements ITreeGenerator { - private final Function> factory; + private final Function> factory; private final IWoodType woodType; - public DefaultTreeGenerator(Function> factory, IWoodType woodType) { + public DefaultTreeGenerator(Function> factory, IWoodType woodType) { this.factory = factory; this.woodType = Preconditions.checkNotNull(woodType); } @Override - public Feature getTreeFeature(ITreeGenData tree) { + public Feature getTreeFeature(ITreeSpecies tree) { return this.factory.apply(tree); } @Override public boolean setLogBlock(IGenome genome, LevelAccessor level, BlockPos pos, Direction facing) { boolean fireproof = genome.getActiveValue(TreeChromosomes.FIREPROOF); - BlockState logBlock = TreeManager.woodAccess.getBlock(this.woodType, WoodBlockKind.LOG, fireproof); + BlockState logBlock = IForestryApi.INSTANCE.getTreeManager().getWoodAccess().getBlock(this.woodType, WoodBlockKind.LOG, fireproof); Direction.Axis axis = facing.getAxis(); return level.setBlock(pos, logBlock.setValue(RotatedPillarBlock.AXIS, axis), Block.UPDATE_KNOWN_SHAPE | Block.UPDATE_ALL); diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureAcacia.java b/src/main/java/forestry/arboriculture/worldgen/FeatureAcacia.java index 307ee79d03..3772090b1a 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureAcacia.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureAcacia.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -21,7 +11,7 @@ import java.util.Set; public class FeatureAcacia extends FeatureTree { - public FeatureAcacia(ITreeGenData tree) { + public FeatureAcacia(ITreeSpecies tree) { super(tree, 5, 2); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureArboriculture.java b/src/main/java/forestry/arboriculture/worldgen/FeatureArboriculture.java index 536552b029..8b2143da01 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureArboriculture.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureArboriculture.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; import forestry.arboriculture.blocks.BlockSapling; import forestry.core.utils.VecUtil; @@ -51,21 +41,21 @@ public abstract class FeatureArboriculture extends FeatureBase { // skips performance-heavy checks during world generation or sapling generation public static final ThreadLocal SKIP_EXTENDED_CHECKS = ThreadLocal.withInitial(() -> false); - protected final ITreeGenData tree; + protected final ITreeSpecies species; - protected FeatureArboriculture(ITreeGenData tree) { - this.tree = tree; + protected FeatureArboriculture(ITreeSpecies species) { + this.species = species; } @Override public IGenome getDefaultGenome() { - return this.tree.getDefaultGenome(); + return this.species.getDefaultGenome(); } @Override public boolean place(IGenome genome, LevelAccessor level, RandomSource rand, BlockPos pos, boolean forced) { - TreeBlockTypeLeaf leaf = new TreeBlockTypeLeaf(this.tree, genome); - TreeBlockTypeLog wood = new TreeBlockTypeLog(this.tree, genome); + TreeBlockTypeLeaf leaf = new TreeBlockTypeLeaf(this.species, genome); + TreeBlockTypeLog wood = new TreeBlockTypeLog(this.species, genome); // Calculate height and girth preGenerate(genome, level, rand, pos); @@ -91,7 +81,7 @@ public boolean place(IGenome genome, LevelAccessor level, RandomSource rand, Blo // Generate leaves and pods generateLeaves(level, rand, leaf, contour, genPos); - generateExtras(level, rand, genPos); + generateExtras(level, rand, genome, genPos); if (contour.boundingBox != null) { // Correctly update the leaf distance states on the leaf blocks @@ -188,7 +178,7 @@ private static void setBlockKnownShape(LevelWriter level, BlockPos pos, BlockSta protected abstract void generateLeaves(LevelAccessor level, RandomSource rand, TreeBlockTypeLeaf leaf, TreeContour contour, BlockPos startPos); - protected abstract void generateExtras(LevelAccessor level, RandomSource rand, BlockPos startPos); + protected abstract void generateExtras(LevelAccessor level, RandomSource rand, IGenome genome, BlockPos startPos); @Nullable public abstract BlockPos getValidGrowthPos(LevelAccessor level, BlockPos pos); @@ -197,7 +187,7 @@ private static void setBlockKnownShape(LevelWriter level, BlockPos pos, BlockSta * Removes all saplings before generating the trunk. */ public void clearSaplings(LevelAccessor level, BlockPos genPos) { - int treeGirth = this.tree.getGirth(this.tree.getDefaultGenome()); + int treeGirth = this.species.getGirth(this.species.getDefaultGenome()); for (int x = 0; x < treeGirth; x++) { for (int z = 0; z < treeGirth; z++) { BlockPos saplingPos = genPos.offset(x, 0, z); @@ -207,8 +197,4 @@ public void clearSaplings(LevelAccessor level, BlockPos genPos) { } } } - - public boolean hasPods() { - return this.tree.allowsFruitBlocks(this.tree.getDefaultGenome()); - } } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureBalsa.java b/src/main/java/forestry/arboriculture/worldgen/FeatureBalsa.java index f596ffd003..69b87b18a0 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureBalsa.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureBalsa.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -18,8 +8,7 @@ import net.minecraft.world.level.LevelAccessor; public class FeatureBalsa extends FeatureTree { - - public FeatureBalsa(ITreeGenData tree) { + public FeatureBalsa(ITreeSpecies tree) { super(tree, 6, 6); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureBaobab.java b/src/main/java/forestry/arboriculture/worldgen/FeatureBaobab.java index f49cd98c64..db003fe092 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureBaobab.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureBaobab.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -19,7 +9,7 @@ import java.util.Set; public class FeatureBaobab extends FeatureTree { - public FeatureBaobab(ITreeGenData tree) { + public FeatureBaobab(ITreeSpecies tree) { super(tree, 6, 6); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureBushCherry.java b/src/main/java/forestry/arboriculture/worldgen/FeatureBushCherry.java index d449923ea4..8088c25441 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureBushCherry.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureBushCherry.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -20,7 +10,7 @@ import java.util.Set; public class FeatureBushCherry extends FeatureTree { - public FeatureBushCherry(ITreeGenData tree) { + public FeatureBushCherry(ITreeSpecies tree) { super(tree, 4, 4); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureCherryVanilla.java b/src/main/java/forestry/arboriculture/worldgen/FeatureCherryVanilla.java index 13bf9135c3..3b9dd780e2 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureCherryVanilla.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureCherryVanilla.java @@ -1,6 +1,6 @@ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -16,8 +16,8 @@ public class FeatureCherryVanilla extends FeatureTree { private static final float HANGING_LEAVES_CHANCE = 1f / 6f; private static final float HANGING_LEAVES_EXTENSION_CHANCE = 1f / 3f; - public FeatureCherryVanilla(ITreeGenData data) { - super(data, 7, 1); + public FeatureCherryVanilla(ITreeSpecies species) { + super(species, 7, 1); } // todo support custom girth diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureChestnut.java b/src/main/java/forestry/arboriculture/worldgen/FeatureChestnut.java index a219d056c4..8f8ae07d1a 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureChestnut.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureChestnut.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -19,8 +9,7 @@ import java.util.Set; public class FeatureChestnut extends FeatureTree { - - public FeatureChestnut(ITreeGenData tree) { + public FeatureChestnut(ITreeSpecies tree) { super(tree, 7, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureCocobolo.java b/src/main/java/forestry/arboriculture/worldgen/FeatureCocobolo.java index 61dfdc52e5..e96db4df08 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureCocobolo.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureCocobolo.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -19,8 +9,7 @@ import java.util.Set; public class FeatureCocobolo extends FeatureTree { - - public FeatureCocobolo(ITreeGenData tree) { + public FeatureCocobolo(ITreeSpecies tree) { super(tree, 8, 8); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureDate.java b/src/main/java/forestry/arboriculture/worldgen/FeatureDate.java index 47e3fe69b5..29173b61bc 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureDate.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureDate.java @@ -10,15 +10,14 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; import net.minecraft.world.level.LevelAccessor; public class FeatureDate extends FeatureTree { - - public FeatureDate(ITreeGenData tree) { + public FeatureDate(ITreeSpecies tree) { super(tree, 6, 2); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureEbony.java b/src/main/java/forestry/arboriculture/worldgen/FeatureEbony.java index dddd693a18..b6457e4332 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureEbony.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureEbony.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -22,7 +22,7 @@ public class FeatureEbony extends FeatureTree { - public FeatureEbony(ITreeGenData tree) { + public FeatureEbony(ITreeSpecies tree) { super(tree, 10, 4); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureGiganteum.java b/src/main/java/forestry/arboriculture/worldgen/FeatureGiganteum.java index 6d9c7bc512..760a231dd8 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureGiganteum.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureGiganteum.java @@ -10,11 +10,11 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; public class FeatureGiganteum extends FeatureSequoia { - public FeatureGiganteum(ITreeGenData tree) { + public FeatureGiganteum(ITreeSpecies tree) { super(tree, 35, 15); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureGreenheart.java b/src/main/java/forestry/arboriculture/worldgen/FeatureGreenheart.java index 96b9b5788a..8e14e1e7ce 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureGreenheart.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureGreenheart.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeatureGreenheart extends FeatureTree { - public FeatureGreenheart(ITreeGenData tree) { + public FeatureGreenheart(ITreeSpecies tree) { super(tree, 10, 8); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureIpe.java b/src/main/java/forestry/arboriculture/worldgen/FeatureIpe.java index ef5907221c..3b659b3216 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureIpe.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureIpe.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeatureIpe extends FeatureTree { - public FeatureIpe(ITreeGenData tree) { + public FeatureIpe(ITreeSpecies tree) { super(tree, 6, 4); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureJungle.java b/src/main/java/forestry/arboriculture/worldgen/FeatureJungle.java index 07f3c99bab..c4d7c15db7 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureJungle.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureJungle.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -20,7 +20,7 @@ import java.util.Set; public class FeatureJungle extends FeatureTreeVanilla { - public FeatureJungle(ITreeGenData tree) { + public FeatureJungle(ITreeSpecies tree) { super(tree); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureKapok.java b/src/main/java/forestry/arboriculture/worldgen/FeatureKapok.java index b9b24eb254..a8fec034da 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureKapok.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureKapok.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeatureKapok extends FeatureTree { - public FeatureKapok(ITreeGenData tree) { + public FeatureKapok(ITreeSpecies tree) { super(tree, 10, 8); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureLarch.java b/src/main/java/forestry/arboriculture/worldgen/FeatureLarch.java index 95b950235e..463c366a29 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureLarch.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureLarch.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -18,7 +18,7 @@ public class FeatureLarch extends FeatureTree { - public FeatureLarch(ITreeGenData tree) { + public FeatureLarch(ITreeSpecies tree) { super(tree, 6, 5); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureLemon.java b/src/main/java/forestry/arboriculture/worldgen/FeatureLemon.java index 5fa52ceaf0..b64669a747 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureLemon.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureLemon.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -18,7 +18,7 @@ public class FeatureLemon extends FeatureTree { - public FeatureLemon(ITreeGenData tree) { + public FeatureLemon(ITreeSpecies tree) { super(tree, 6, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureMahoe.java b/src/main/java/forestry/arboriculture/worldgen/FeatureMahoe.java index 677c8f9a90..b1cf98a7ff 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureMahoe.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureMahoe.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -20,7 +20,7 @@ import java.util.Set; public class FeatureMahoe extends FeatureTree { - public FeatureMahoe(ITreeGenData tree) { + public FeatureMahoe(ITreeSpecies tree) { super(tree, 6, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureMahogany.java b/src/main/java/forestry/arboriculture/worldgen/FeatureMahogany.java index 774d554068..147a09aa19 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureMahogany.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureMahogany.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeatureMahogany extends FeatureTree { - public FeatureMahogany(ITreeGenData tree) { + public FeatureMahogany(ITreeSpecies tree) { super(tree, 12, 6); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureMaple.java b/src/main/java/forestry/arboriculture/worldgen/FeatureMaple.java index 69711a3394..7291d16327 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureMaple.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureMaple.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeatureMaple extends FeatureTree { - public FeatureMaple(ITreeGenData tree) { + public FeatureMaple(ITreeSpecies tree) { super(tree, 7, 5); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeaturePadauk.java b/src/main/java/forestry/arboriculture/worldgen/FeaturePadauk.java index 900e137928..9d348a6223 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeaturePadauk.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeaturePadauk.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -23,7 +23,7 @@ public class FeaturePadauk extends FeatureTree { - public FeaturePadauk(ITreeGenData tree) { + public FeaturePadauk(ITreeSpecies tree) { super(tree, 6, 6); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeaturePapaya.java b/src/main/java/forestry/arboriculture/worldgen/FeaturePapaya.java index a6fd3b03cc..bf415abfdc 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeaturePapaya.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeaturePapaya.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -20,7 +20,7 @@ public class FeaturePapaya extends FeatureTree { - public FeaturePapaya(ITreeGenData tree) { + public FeaturePapaya(ITreeSpecies tree) { super(tree, 7, 2); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeaturePine.java b/src/main/java/forestry/arboriculture/worldgen/FeaturePine.java index f4dcdc5fd7..34682588c8 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeaturePine.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeaturePine.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeaturePine extends FeatureTree { - public FeaturePine(ITreeGenData tree) { + public FeaturePine(ITreeSpecies tree) { super(tree, 6, 4); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeaturePlum.java b/src/main/java/forestry/arboriculture/worldgen/FeaturePlum.java index ac78533ba1..b730ebf00f 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeaturePlum.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeaturePlum.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -18,7 +18,7 @@ public class FeaturePlum extends FeatureTree { - public FeaturePlum(ITreeGenData tree) { + public FeaturePlum(ITreeSpecies tree) { super(tree, 6, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeaturePoplar.java b/src/main/java/forestry/arboriculture/worldgen/FeaturePoplar.java index 394b5b425f..b8b7a418ee 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeaturePoplar.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeaturePoplar.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -18,7 +18,7 @@ public class FeaturePoplar extends FeatureTree { - public FeaturePoplar(ITreeGenData tree) { + public FeaturePoplar(ITreeSpecies tree) { super(tree, 8, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureSequoia.java b/src/main/java/forestry/arboriculture/worldgen/FeatureSequoia.java index c1b01a353e..47edf7417e 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureSequoia.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureSequoia.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,11 +21,11 @@ public class FeatureSequoia extends FeatureTree { - public FeatureSequoia(ITreeGenData tree) { + public FeatureSequoia(ITreeSpecies tree) { this(tree, 20, 5); } - protected FeatureSequoia(ITreeGenData tree, int baseHeight, int heightVariation) { + protected FeatureSequoia(ITreeSpecies tree, int baseHeight, int heightVariation) { super(tree, baseHeight, heightVariation); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureSilverLime.java b/src/main/java/forestry/arboriculture/worldgen/FeatureSilverLime.java index bacf513cab..94001b76a2 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureSilverLime.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureSilverLime.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -20,7 +20,7 @@ public class FeatureSilverLime extends FeatureTree { - public FeatureSilverLime(ITreeGenData tree) { + public FeatureSilverLime(ITreeSpecies tree) { super(tree, 6, 4); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureSpruce.java b/src/main/java/forestry/arboriculture/worldgen/FeatureSpruce.java index f7581d740b..3b7b466047 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureSpruce.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureSpruce.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -20,8 +10,7 @@ import java.util.Set; public class FeatureSpruce extends FeatureTree { - - public FeatureSpruce(ITreeGenData tree) { + public FeatureSpruce(ITreeSpecies tree) { super(tree, 5, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureTeak.java b/src/main/java/forestry/arboriculture/worldgen/FeatureTeak.java index 6f5c585cb0..8920efc820 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureTeak.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureTeak.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -19,8 +9,7 @@ import java.util.Set; public class FeatureTeak extends FeatureTree { - - public FeatureTeak(ITreeGenData tree) { + public FeatureTeak(ITreeSpecies tree) { super(tree, 6, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureTree.java b/src/main/java/forestry/arboriculture/worldgen/FeatureTree.java index 65c405e2be..2670fbab5a 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureTree.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureTree.java @@ -1,17 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; +import forestry.api.arboriculture.genetics.IPodFruit; import forestry.api.genetics.IGenome; +import forestry.api.genetics.alleles.TreeChromosomes; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -30,8 +22,8 @@ public abstract class FeatureTree extends FeatureArboriculture { protected int girth; protected int height; - protected FeatureTree(ITreeGenData tree, int baseHeight, int heightVariation) { - super(tree); + protected FeatureTree(ITreeSpecies species, int baseHeight, int heightVariation) { + super(species); this.baseHeight = baseHeight; this.heightVariation = heightVariation; } @@ -52,34 +44,34 @@ protected void generateLeaves(LevelAccessor level, RandomSource rand, TreeBlockT } @Override - protected void generateExtras(LevelAccessor level, RandomSource rand, BlockPos startPos) { - if (hasPods()) { - FeatureHelper.generatePods(this.tree, level, rand, startPos, this.height, minPodHeight, this.girth, FeatureHelper.EnumReplaceMode.AIR); + protected void generateExtras(LevelAccessor level, RandomSource rand, IGenome genome, BlockPos startPos) { + if (genome.getActiveValue(TreeChromosomes.FRUIT) instanceof IPodFruit || genome.getInactiveValue(TreeChromosomes.FRUIT) instanceof IPodFruit) { + FeatureHelper.generatePods(this.species, level, rand, startPos, this.height, minPodHeight, this.girth, FeatureHelper.EnumReplaceMode.AIR); } } @Override @Nullable public BlockPos getValidGrowthPos(LevelAccessor level, BlockPos pos) { - return this.tree.getGrowthPos(this.tree.getDefaultGenome(), level, pos, this.girth, this.height); + return this.species.getGrowthPos(this.species.getDefaultGenome(), level, pos, this.girth, this.height); } @Override public final void preGenerate(IGenome genome, LevelAccessor level, RandomSource rand, BlockPos startPos) { this.height = determineHeight(level, rand, genome, this.baseHeight, this.heightVariation); - this.girth = this.tree.getGirth(genome); + this.girth = this.species.getGirth(genome); } protected int modifyByHeight(LevelAccessor world, int val, int min, int max) { //ITreeModifier treeModifier = SpeciesUtil.TREE_TYPE.get().getTreekeepingMode(world); - int determined = Math.round(val * this.tree.getHeightModifier(this.tree.getDefaultGenome()));/* * treeModifier.getHeightModifier(tree.getGenome(), 1f)*/ + int determined = Math.round(val * this.species.getHeightModifier(this.species.getDefaultGenome()));/* * treeModifier.getHeightModifier(tree.getGenome(), 1f)*/ return determined < min ? min : Math.min(determined, max); } protected int determineHeight(LevelAccessor world, RandomSource rand, IGenome genome, int baseHeight, int heightVariation) { //ITreeModifier treeModifier = SpeciesUtil.TREE_TYPE.get().getTreekeepingMode(world); int height = baseHeight + rand.nextInt(heightVariation); - int adjustedHeight = Math.round(height * this.tree.getHeightModifier(genome));/* * treeModifier.getHeightModifier(tree.getGenome(), 1f)*/ + int adjustedHeight = Math.round(height * this.species.getHeightModifier(genome));/* * treeModifier.getHeightModifier(tree.getGenome(), 1f)*/ return adjustedHeight < minHeight ? minHeight : Math.min(adjustedHeight, maxHeight); } } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureTreeVanilla.java b/src/main/java/forestry/arboriculture/worldgen/FeatureTreeVanilla.java index b87f26f3ec..18df40ad46 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureTreeVanilla.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureTreeVanilla.java @@ -10,10 +10,10 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; public class FeatureTreeVanilla extends FeatureTree { - public FeatureTreeVanilla(ITreeGenData tree) { + public FeatureTreeVanilla(ITreeSpecies tree) { super(tree, 5, 2); } } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureWalnut.java b/src/main/java/forestry/arboriculture/worldgen/FeatureWalnut.java index 565d6f5891..0916b7f1da 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureWalnut.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureWalnut.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +11,7 @@ public class FeatureWalnut extends FeatureTree { - public FeatureWalnut(ITreeGenData tree) { + public FeatureWalnut(ITreeSpecies tree) { super(tree, 7, 3); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureWenge.java b/src/main/java/forestry/arboriculture/worldgen/FeatureWenge.java index e6fbcc953a..d88f73887c 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureWenge.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureWenge.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +21,7 @@ public class FeatureWenge extends FeatureTree { - public FeatureWenge(ITreeGenData tree) { + public FeatureWenge(ITreeSpecies tree) { super(tree, 6, 2); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureWillow.java b/src/main/java/forestry/arboriculture/worldgen/FeatureWillow.java index 61e3ea7fa4..f2956869cd 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureWillow.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureWillow.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -21,7 +11,7 @@ public class FeatureWillow extends FeatureTree { - public FeatureWillow(ITreeGenData tree) { + public FeatureWillow(ITreeSpecies tree) { super(tree, 5, 2); } diff --git a/src/main/java/forestry/arboriculture/worldgen/FeatureZebrawood.java b/src/main/java/forestry/arboriculture/worldgen/FeatureZebrawood.java index 1f3a789715..78e9d01012 100644 --- a/src/main/java/forestry/arboriculture/worldgen/FeatureZebrawood.java +++ b/src/main/java/forestry/arboriculture/worldgen/FeatureZebrawood.java @@ -1,16 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ + package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.core.worldgen.FeatureHelper; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; @@ -19,7 +10,7 @@ import java.util.Set; public class FeatureZebrawood extends FeatureTree { - public FeatureZebrawood(ITreeGenData tree) { + public FeatureZebrawood(ITreeSpecies tree) { super(tree, 8, 8); } diff --git a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java index edb80d12e5..01d1e4fb63 100644 --- a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLeaf.java @@ -1,26 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.LevelAccessor; public class TreeBlockTypeLeaf implements ITreeBlockType { - private final ITreeGenData tree; + private final ITreeSpecies tree; private final IGenome genome; - public TreeBlockTypeLeaf(ITreeGenData tree, IGenome genome) { + public TreeBlockTypeLeaf(ITreeSpecies tree, IGenome genome) { this.tree = tree; this.genome = genome; } diff --git a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java index 80802b172b..8c85fd315a 100644 --- a/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeBlockTypeLog.java @@ -1,27 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.LevelAccessor; public class TreeBlockTypeLog implements ITreeBlockType { - private final ITreeGenData tree; + private final ITreeSpecies tree; private final IGenome genome; private Direction facing = Direction.UP; - public TreeBlockTypeLog(ITreeGenData tree, IGenome genome) { + public TreeBlockTypeLog(ITreeSpecies tree, IGenome genome) { this.tree = tree; this.genome = genome; } diff --git a/src/main/java/forestry/arboriculture/worldgen/TreeDecorator.java b/src/main/java/forestry/arboriculture/worldgen/TreeDecorator.java index fedfac2235..fc108a8fde 100644 --- a/src/main/java/forestry/arboriculture/worldgen/TreeDecorator.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeDecorator.java @@ -1,22 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.arboriculture.worldgen; import forestry.api.IForestryApi; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.climate.IClimateManager; import forestry.api.core.HumidityType; import forestry.api.core.TemperatureType; -import forestry.arboriculture.commands.TreeGenHelper; +import forestry.arboriculture.features.ArboricultureBlocks; import forestry.core.config.ForestryConfig; import forestry.core.utils.BlockUtil; import forestry.core.utils.SpeciesUtil; @@ -33,13 +23,13 @@ import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import net.minecraftforge.common.IPlantable; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; +// todo replace with biome-specific tree features rather than modifying the whole overworld public class TreeDecorator extends Feature { private static final IdentityHashMap, List> BIOME_CACHE = new IdentityHashMap<>(); @@ -48,7 +38,7 @@ public TreeDecorator() { } @Nullable - private static BlockPos getValidPos(WorldGenLevel world, int x, int z, ITree tree) { + private static BlockPos getValidPos(WorldGenLevel world, int x, int z) { // get to the ground final BlockPos topPos = world.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, new BlockPos(x, 0, z)); if (topPos.getY() == 0) { @@ -67,7 +57,7 @@ private static BlockPos getValidPos(WorldGenLevel world, int x, int z, ITree tre blockState = world.getBlockState(pos); } - if (tree instanceof IPlantable plantable && blockState.getBlock().canSustainPlant(blockState, world, pos, Direction.UP, plantable)) { + if (!blockState.getBlock().canSustainPlant(blockState, world, pos, Direction.UP, ArboricultureBlocks.SAPLING_GE.defaultState()).isFalse()) { return pos.above(); } @@ -91,7 +81,6 @@ private static synchronized void generateBiomeCache(WorldGenLevel level) { for (ITreeSpecies species : allSpecies) { if (species.getRarity() > 0.0f) { - // todo tolerance chromosomes if (temperature == species.getTemperature() && humidity == species.getHumidity()) { trees.add(treeInstances.computeIfAbsent(species, k -> species.createIndividual())); } @@ -106,7 +95,7 @@ public boolean place(FeaturePlaceContext context) { RandomSource rand = context.random(); BlockPos pos = context.origin(); - double globalRarity = ForestryConfig.SERVER.treesSpawnNaturally.get(); + double globalRarity = ForestryConfig.SERVER.treeSpawnChanceMultiplier.get(); if (globalRarity <= 0.0) { return false; } @@ -125,7 +114,7 @@ public boolean place(FeaturePlaceContext context) { for (ITree tree : trees) { ITreeSpecies species = tree.getSpecies(); if (species.getRarity() * globalRarity >= rand.nextFloat()) { - BlockPos validPos = getValidPos(level, x, z, tree); + BlockPos validPos = getValidPos(level, x, z); if (validPos == null) { continue; } diff --git a/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java b/src/main/java/forestry/arboriculture/worldgen/TreeGenHelper.java similarity index 68% rename from src/main/java/forestry/arboriculture/commands/TreeGenHelper.java rename to src/main/java/forestry/arboriculture/worldgen/TreeGenHelper.java index 53e6cb8c0f..60870c2f99 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java +++ b/src/main/java/forestry/arboriculture/worldgen/TreeGenHelper.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.commands; +package forestry.arboriculture.worldgen; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; import forestry.core.utils.BlockUtil; import forestry.core.worldgen.FeatureBase; @@ -27,7 +17,6 @@ import javax.annotation.Nullable; import java.util.Optional; -// todo move into forestry.arboriculture.worldgen public class TreeGenHelper { public static boolean generateTree(ITreeSpecies tree, @Nullable IGenome genome, WorldGenLevel level, RandomSource random, BlockPos pos) { Feature gen = tree.getGenerator().getTreeFeature(tree); diff --git a/src/main/java/forestry/arboriculture/worldgen/feature/ForestryTreeFeature.java b/src/main/java/forestry/arboriculture/worldgen/feature/ForestryTreeFeature.java index 5dc53b2f2f..8b043d7ac7 100644 --- a/src/main/java/forestry/arboriculture/worldgen/feature/ForestryTreeFeature.java +++ b/src/main/java/forestry/arboriculture/worldgen/feature/ForestryTreeFeature.java @@ -1,8 +1,8 @@ package forestry.arboriculture.worldgen.feature; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.genetics.IGenome; -import forestry.arboriculture.commands.TreeGenHelper; +import forestry.arboriculture.worldgen.TreeGenHelper; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; diff --git a/src/main/java/forestry/arboriculture/worldgen/feature/package-info.java b/src/main/java/forestry/arboriculture/worldgen/feature/package-info.java index d8aae67501..a13ce56472 100644 --- a/src/main/java/forestry/arboriculture/worldgen/feature/package-info.java +++ b/src/main/java/forestry/arboriculture/worldgen/feature/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.worldgen.feature; diff --git a/src/main/java/forestry/arboriculture/worldgen/package-info.java b/src/main/java/forestry/arboriculture/worldgen/package-info.java index f259ab4b56..410ac6ef60 100644 --- a/src/main/java/forestry/arboriculture/worldgen/package-info.java +++ b/src/main/java/forestry/arboriculture/worldgen/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.arboriculture.worldgen; diff --git a/src/main/java/forestry/compat/ModuleCurios.java b/src/main/java/forestry/compat/ModuleCurios.java index 2b10eec95b..2a556be99c 100644 --- a/src/main/java/forestry/compat/ModuleCurios.java +++ b/src/main/java/forestry/compat/ModuleCurios.java @@ -4,9 +4,9 @@ import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; import forestry.api.modules.IForestryModule; +import forestry.compat.curios.CuriosCompat; import forestry.compat.curios.client.CuriosClientHandler; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.ModList; import java.util.function.Consumer; @@ -19,7 +19,7 @@ public ResourceLocation getId() { @Override public void registerClientHandler(Consumer registrar) { - if (ModList.get().isLoaded("curios")) { + if (CuriosCompat.IS_LOADED) { registrar.accept(new CuriosClientHandler()); } } diff --git a/src/main/java/forestry/compat/curios/CuriosCompat.java b/src/main/java/forestry/compat/curios/CuriosCompat.java index 3176ae80c7..a7baecbeaa 100644 --- a/src/main/java/forestry/compat/curios/CuriosCompat.java +++ b/src/main/java/forestry/compat/curios/CuriosCompat.java @@ -1,31 +1,38 @@ package forestry.compat.curios; import forestry.core.utils.GeneticsUtil; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityManager; -import net.minecraftforge.common.capabilities.CapabilityToken; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; +import net.neoforged.neoforge.capabilities.EntityCapability; import top.theillusivec4.curios.api.type.capability.ICuriosItemHandler; +import top.theillusivec4.curios.api.type.inventory.ICurioStacksHandler; import top.theillusivec4.curios.api.type.inventory.IDynamicStackHandler; +import java.util.Optional; + public class CuriosCompat { public static final boolean IS_LOADED = ModList.get().isLoaded("curios"); - public static final Capability CURIOS_INVENTORY = CapabilityManager.get(new CapabilityToken<>() { - }); + public static final EntityCapability CURIOS_INVENTORY = EntityCapability.createVoid(ResourceLocation.fromNamespaceAndPath("curios", "item_handler"), ICuriosItemHandler.class); public static boolean hasNaturalistEye(Player player) { - return player.getCapability(CURIOS_INVENTORY).map(inventory -> inventory.getStacksHandler("head").map(handler -> { - IDynamicStackHandler stacks = handler.getStacks(); + ICuriosItemHandler inventory = player.getCapability(CURIOS_INVENTORY); + + if (inventory != null) { + Optional head = inventory.getStacksHandler("head"); + + if (head.isPresent()) { + IDynamicStackHandler stacks = head.get().getStacks(); - for (int i = 0; i < stacks.getSlots(); i++) { - if (GeneticsUtil.hasNaturalistEye(player, stacks.getStackInSlot(i))) { - return true; + for (int i = 0; i < stacks.getSlots(); i++) { + if (GeneticsUtil.hasNaturalistEye(player, stacks.getStackInSlot(i))) { + return true; + } } } + } - return false; - }).orElse(false)).orElse(false); + return false; } } diff --git a/src/main/java/forestry/compat/curios/client/CuriosClientHandler.java b/src/main/java/forestry/compat/curios/client/CuriosClientHandler.java index 97803314a9..8f2adc774e 100644 --- a/src/main/java/forestry/compat/curios/client/CuriosClientHandler.java +++ b/src/main/java/forestry/compat/curios/client/CuriosClientHandler.java @@ -2,8 +2,8 @@ import forestry.api.client.IClientModuleHandler; import forestry.core.features.CoreItems; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; import top.theillusivec4.curios.api.client.CuriosRendererRegistry; public class CuriosClientHandler implements IClientModuleHandler { diff --git a/src/main/java/forestry/compat/curios/client/SpectaclesCurioRenderer.java b/src/main/java/forestry/compat/curios/client/SpectaclesCurioRenderer.java index 53df641cc6..3aa7532369 100644 --- a/src/main/java/forestry/compat/curios/client/SpectaclesCurioRenderer.java +++ b/src/main/java/forestry/compat/curios/client/SpectaclesCurioRenderer.java @@ -51,11 +51,11 @@ public > void render(ItemStack // HumanoidArmorLayer.renderModel (with known args inlined) private void renderModel(PoseStack poseStack, MultiBufferSource buffers, int light) { VertexConsumer buffer = buffers.getBuffer(RenderType.armorCutoutNoCull(TEXTURE)); - this.armorModel.renderToBuffer(poseStack, buffer, light, OverlayTexture.NO_OVERLAY, 1f, 1f, 1f, 1f); + this.armorModel.renderToBuffer(poseStack, buffer, light, OverlayTexture.NO_OVERLAY); } // HumanoidArmorLayer.renderGlint (with known args inlined) private void renderGlint(PoseStack poseStack, MultiBufferSource buffers, int light) { - this.armorModel.renderToBuffer(poseStack, buffers.getBuffer(RenderType.armorEntityGlint()), light, OverlayTexture.NO_OVERLAY, 1f, 1f, 1f, 1f); + this.armorModel.renderToBuffer(poseStack, buffers.getBuffer(RenderType.armorEntityGlint()), light, OverlayTexture.NO_OVERLAY); } } diff --git a/src/main/java/forestry/compat/curios/client/package-info.java b/src/main/java/forestry/compat/curios/client/package-info.java index fcf43cd14d..587fec696b 100644 --- a/src/main/java/forestry/compat/curios/client/package-info.java +++ b/src/main/java/forestry/compat/curios/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.curios.client; diff --git a/src/main/java/forestry/compat/curios/package-info.java b/src/main/java/forestry/compat/curios/package-info.java index 1bdd10fc96..eb49959849 100644 --- a/src/main/java/forestry/compat/curios/package-info.java +++ b/src/main/java/forestry/compat/curios/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.curios; diff --git a/src/main/java/forestry/compat/jei/IndividualSubtypeInterpreter.java b/src/main/java/forestry/compat/jei/IndividualSubtypeInterpreter.java new file mode 100644 index 0000000000..a56535492d --- /dev/null +++ b/src/main/java/forestry/compat/jei/IndividualSubtypeInterpreter.java @@ -0,0 +1,27 @@ +package forestry.compat.jei; + +import forestry.api.ForestryCapabilities; +import forestry.api.genetics.capability.IIndividualHandlerItem; +import mezz.jei.api.ingredients.subtypes.ISubtypeInterpreter; +import mezz.jei.api.ingredients.subtypes.UidContext; +import net.minecraft.world.item.ItemStack; + +import javax.annotation.Nullable; + +public class IndividualSubtypeInterpreter implements ISubtypeInterpreter { + @Nullable + @Override + public Object getSubtypeData(ItemStack ingredient, UidContext context) { + return getLegacyStringSubtypeInfo(ingredient, context); + } + + @Override + public String getLegacyStringSubtypeInfo(ItemStack ingredient, UidContext context) { + IIndividualHandlerItem handler = ingredient.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM); + if (handler != null) { + return handler.getIndividual().getGenome().getActiveSpecies().getBinomial(); + } else { + return ""; + } + } +} diff --git a/src/main/java/forestry/core/utils/JeiUtil.java b/src/main/java/forestry/compat/jei/JeiUtil.java similarity index 90% rename from src/main/java/forestry/core/utils/JeiUtil.java rename to src/main/java/forestry/compat/jei/JeiUtil.java index fa74831ee9..cc6aab289c 100644 --- a/src/main/java/forestry/core/utils/JeiUtil.java +++ b/src/main/java/forestry/compat/jei/JeiUtil.java @@ -1,4 +1,4 @@ -package forestry.core.utils; +package forestry.compat.jei; import forestry.Forestry; import forestry.api.ForestryCapabilities; @@ -6,6 +6,7 @@ import forestry.api.genetics.ISpecies; import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.alleles.IRegistryChromosome; +import forestry.core.utils.ModUtil; import forestry.modules.features.FeatureItem; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; @@ -30,8 +31,8 @@ import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.level.block.Block; -import net.minecraftforge.common.crafting.IShapedRecipe; import java.text.DecimalFormat; import java.util.ArrayList; @@ -104,9 +105,9 @@ public static List layoutSlotGrid(IRecipeLayoutBuilder build public static void setCraftingItems(List craftingSlots, CraftingRecipe craftingGridRecipe, ICraftingGridHelper craftingGridHelper) { int width = 0; int height = 0; - if (craftingGridRecipe instanceof IShapedRecipe shapedRecipe) { - width = shapedRecipe.getRecipeWidth(); - height = shapedRecipe.getRecipeHeight(); + if (craftingGridRecipe instanceof ShapedRecipe shapedRecipe) { + width = shapedRecipe.getWidth(); + height = shapedRecipe.getHeight(); } setCraftingItems(craftingSlots, craftingGridRecipe.getIngredients(), width, height, craftingGridHelper); } @@ -134,13 +135,9 @@ public static NonNullList getFirstItemStacks(IRecipeSlotsView recipeS return result; } - public static > void registerItemSubtypes(ISubtypeRegistration registry, IRegistryChromosome species, ISpeciesType type) { - IIngredientSubtypeInterpreter interpreter = (stack, context) -> stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM) - .map(individual -> individual.getIndividual().getGenome().getActiveValue(species).getBinomial()) - .orElse(IIngredientSubtypeInterpreter.NONE); - + public static > void registerItemSubtypes(ISubtypeRegistration registry, ISpeciesType type) { for (ILifeStage stage : type.getLifeStages()) { - registry.registerSubtypeInterpreter(VanillaTypes.ITEM_STACK, stage.getItemForm(), interpreter); + registry.registerSubtypeInterpreter(VanillaTypes.ITEM_STACK, stage.getItemForm(), new IndividualSubtypeInterpreter()); } } diff --git a/src/main/java/forestry/core/particles/package-info.java b/src/main/java/forestry/compat/jei/package-info.java similarity index 53% rename from src/main/java/forestry/core/particles/package-info.java rename to src/main/java/forestry/compat/jei/package-info.java index 628c460017..2d17fb9d39 100644 --- a/src/main/java/forestry/core/particles/package-info.java +++ b/src/main/java/forestry/compat/jei/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault -package forestry.core.particles; +package forestry.compat.jei; diff --git a/src/main/java/forestry/compat/kubejs/ForestryKubeJsPlugin.java b/src/main/java/forestry/compat/kubejs/ForestryKubeJsPlugin.java index ddf31ca647..1357db38b0 100644 --- a/src/main/java/forestry/compat/kubejs/ForestryKubeJsPlugin.java +++ b/src/main/java/forestry/compat/kubejs/ForestryKubeJsPlugin.java @@ -1,7 +1,8 @@ package forestry.compat.kubejs; -import dev.latvian.mods.kubejs.KubeJSPlugin; -import dev.latvian.mods.kubejs.script.BindingsEvent; +import dev.latvian.mods.kubejs.event.EventGroupRegistry; +import dev.latvian.mods.kubejs.plugin.KubeJSPlugin; +import dev.latvian.mods.kubejs.script.BindingRegistry; import forestry.api.IForestryApi; import forestry.api.client.IForestryClientApi; import forestry.api.core.HumidityType; @@ -15,21 +16,21 @@ /** * A KubeJS plugin that registers Forestry-specific compatibility. */ -public class ForestryKubeJsPlugin extends KubeJSPlugin { +public class ForestryKubeJsPlugin implements KubeJSPlugin { @Override - public void registerEvents() { - ForestryEvents.GROUP.register(); - ForestryClientEvents.GROUP.register(); + public void registerEvents(EventGroupRegistry registry) { + registry.register(ForestryEvents.GROUP); + registry.register(ForestryClientEvents.GROUP); } @Override - public void registerBindings(BindingsEvent event) { - event.add("ForestryAlleles", ForestryAlleles.class); - event.add("BeeChromosomes", BeeChromosomes.class); - event.add("IForestryApi", IForestryApi.INSTANCE); - event.add("IForestryClientApi", IForestryClientApi.INSTANCE); - event.add("HumidityType", HumidityType.class); - event.add("TemperatureType", TemperatureType.class); - event.add("ForestryTaxa", ForestryTaxa.class); + public void registerBindings(BindingRegistry bindings) { + bindings.add("ForestryAlleles", ForestryAlleles.class); + bindings.add("BeeChromosomes", BeeChromosomes.class); + bindings.add("IForestryApi", IForestryApi.INSTANCE); + bindings.add("IForestryClientApi", IForestryClientApi.INSTANCE); + bindings.add("HumidityType", HumidityType.class); + bindings.add("TemperatureType", TemperatureType.class); + bindings.add("ForestryTaxa", ForestryTaxa.class); } } diff --git a/src/main/java/forestry/compat/kubejs/KubeForestryPlugin.java b/src/main/java/forestry/compat/kubejs/KubeForestryPlugin.java index 8a6d11dc7d..d2dae6defb 100644 --- a/src/main/java/forestry/compat/kubejs/KubeForestryPlugin.java +++ b/src/main/java/forestry/compat/kubejs/KubeForestryPlugin.java @@ -7,7 +7,7 @@ import forestry.api.plugin.IGeneticRegistration; import forestry.compat.kubejs.event.*; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; import java.util.function.Consumer; diff --git a/src/main/java/forestry/compat/kubejs/apiculture/KubeActivityType.java b/src/main/java/forestry/compat/kubejs/apiculture/KubeActivityType.java index b817b3739f..f911691e50 100644 --- a/src/main/java/forestry/compat/kubejs/apiculture/KubeActivityType.java +++ b/src/main/java/forestry/compat/kubejs/apiculture/KubeActivityType.java @@ -1,7 +1,7 @@ package forestry.compat.kubejs.apiculture; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.LightPreference; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.LightPreference; import forestry.api.core.IError; import net.minecraft.core.BlockPos; diff --git a/src/main/java/forestry/compat/kubejs/apiculture/KubeBeeEffect.java b/src/main/java/forestry/compat/kubejs/apiculture/KubeBeeEffect.java index d662ab3203..f3580dcd8d 100644 --- a/src/main/java/forestry/compat/kubejs/apiculture/KubeBeeEffect.java +++ b/src/main/java/forestry/compat/kubejs/apiculture/KubeBeeEffect.java @@ -2,7 +2,7 @@ import com.mojang.datafixers.util.Function3; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.bee.IBeeEffect; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IGenome; diff --git a/src/main/java/forestry/compat/kubejs/apiculture/KubeFlowerType.java b/src/main/java/forestry/compat/kubejs/apiculture/KubeFlowerType.java index 4f2beb7c82..2503983f9a 100644 --- a/src/main/java/forestry/compat/kubejs/apiculture/KubeFlowerType.java +++ b/src/main/java/forestry/compat/kubejs/apiculture/KubeFlowerType.java @@ -1,6 +1,6 @@ package forestry.compat.kubejs.apiculture; -import forestry.api.apiculture.IFlowerType; +import forestry.api.apiculture.bee.IFlowerType; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; diff --git a/src/main/java/forestry/compat/kubejs/apiculture/KubeHiveDefinition.java b/src/main/java/forestry/compat/kubejs/apiculture/KubeHiveDefinition.java index 41c900af8b..d094da4796 100644 --- a/src/main/java/forestry/compat/kubejs/apiculture/KubeHiveDefinition.java +++ b/src/main/java/forestry/compat/kubejs/apiculture/KubeHiveDefinition.java @@ -1,7 +1,7 @@ package forestry.compat.kubejs.apiculture; import forestry.api.apiculture.hives.IHiveDefinition; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.api.core.HumidityType; import forestry.api.core.TemperatureType; import net.minecraft.core.BlockPos; @@ -14,11 +14,11 @@ import java.util.function.Predicate; // I was told that KubeJS cannot make classes that implement an interface with more than one method. So... -public record KubeHiveDefinition(IHiveGen placement, BlockState hiveState, Predicate> isGoodBiome, - Predicate isGoodHumidity, Predicate isGoodTemperature, - float genChance, PostGenFunction postGen) implements IHiveDefinition { +public record KubeHiveDefinition(IHivePlacement placement, BlockState hiveState, Predicate> isGoodBiome, + Predicate isGoodHumidity, Predicate isGoodTemperature, + float genChance, PostGenFunction postGen) implements IHiveDefinition { @Override - public IHiveGen getHiveGen() { + public IHivePlacement getHiveGen() { return this.placement; } diff --git a/src/main/java/forestry/compat/kubejs/apiculture/package-info.java b/src/main/java/forestry/compat/kubejs/apiculture/package-info.java index e092baa02b..3bee221609 100644 --- a/src/main/java/forestry/compat/kubejs/apiculture/package-info.java +++ b/src/main/java/forestry/compat/kubejs/apiculture/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.kubejs.apiculture; diff --git a/src/main/java/forestry/compat/kubejs/event/ApicultureEventJS.java b/src/main/java/forestry/compat/kubejs/event/ApicultureEventJS.java index f08699368f..e251b4f8f6 100644 --- a/src/main/java/forestry/compat/kubejs/event/ApicultureEventJS.java +++ b/src/main/java/forestry/compat/kubejs/event/ApicultureEventJS.java @@ -1,10 +1,10 @@ package forestry.compat.kubejs.event; import com.mojang.datafixers.util.Function3; -import dev.latvian.mods.kubejs.event.EventJS; +import dev.latvian.mods.kubejs.event.KubeEvent; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.LightPreference; -import forestry.api.apiculture.hives.IHiveGen; +import forestry.api.apiculture.bee.LightPreference; +import forestry.api.apiculture.hives.IHivePlacement; import forestry.api.core.HumidityType; import forestry.api.core.TemperatureType; import forestry.api.genetics.IEffectData; @@ -33,7 +33,7 @@ import java.util.function.Predicate; import java.util.function.UnaryOperator; -public class ApicultureEventJS extends EventJS { +public class ApicultureEventJS implements KubeEvent { private final IApicultureRegistration wrapped; public ApicultureEventJS(IApicultureRegistration wrapped) { @@ -68,7 +68,7 @@ public void addVillageBee(ResourceLocation speciesId, boolean rare, Map> isGoodBiome, Predicate isGoodHumidity, Predicate isGoodTemperature, float genChance, KubeHiveDefinition.PostGenFunction postGen) { + public IHiveBuilder registerCustomHive(ResourceLocation id, IHivePlacement placement, BlockState hiveState, Predicate> isGoodBiome, Predicate isGoodHumidity, Predicate isGoodTemperature, float genChance, KubeHiveDefinition.PostGenFunction postGen) { return this.wrapped.registerHive(id, new KubeHiveDefinition(placement, hiveState, isGoodBiome, isGoodHumidity, isGoodTemperature, genChance, postGen)); } diff --git a/src/main/java/forestry/compat/kubejs/event/ForestryClientEventJS.java b/src/main/java/forestry/compat/kubejs/event/ForestryClientEventJS.java index 0cfbb0ed26..2dcb727e83 100644 --- a/src/main/java/forestry/compat/kubejs/event/ForestryClientEventJS.java +++ b/src/main/java/forestry/compat/kubejs/event/ForestryClientEventJS.java @@ -1,13 +1,13 @@ package forestry.compat.kubejs.event; -import dev.latvian.mods.kubejs.event.EventJS; +import dev.latvian.mods.kubejs.event.KubeEvent; import forestry.api.client.arboriculture.ILeafSprite; import forestry.api.client.arboriculture.ILeafTint; import forestry.api.client.plugin.IClientRegistration; import forestry.api.genetics.ILifeStage; import net.minecraft.resources.ResourceLocation; -public class ForestryClientEventJS extends EventJS { +public class ForestryClientEventJS implements KubeEvent { private final IClientRegistration wrapped; public ForestryClientEventJS(IClientRegistration wrapped) { diff --git a/src/main/java/forestry/compat/kubejs/event/GeneticsEventJS.java b/src/main/java/forestry/compat/kubejs/event/GeneticsEventJS.java index e8484a4c95..48145c589f 100644 --- a/src/main/java/forestry/compat/kubejs/event/GeneticsEventJS.java +++ b/src/main/java/forestry/compat/kubejs/event/GeneticsEventJS.java @@ -1,6 +1,6 @@ package forestry.compat.kubejs.event; -import dev.latvian.mods.kubejs.event.EventJS; +import dev.latvian.mods.kubejs.event.KubeEvent; import forestry.api.plugin.IGeneticRegistration; import forestry.api.plugin.ISpeciesTypeBuilder; import forestry.api.plugin.ITaxonBuilder; @@ -8,7 +8,7 @@ import java.util.function.Consumer; -public class GeneticsEventJS extends EventJS { +public class GeneticsEventJS implements KubeEvent { private final IGeneticRegistration wrapped; public GeneticsEventJS(IGeneticRegistration wrapped) { diff --git a/src/main/java/forestry/compat/kubejs/event/package-info.java b/src/main/java/forestry/compat/kubejs/event/package-info.java index f9a3b2d34e..0ac817f385 100644 --- a/src/main/java/forestry/compat/kubejs/event/package-info.java +++ b/src/main/java/forestry/compat/kubejs/event/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.kubejs.event; diff --git a/src/main/java/forestry/compat/kubejs/package-info.java b/src/main/java/forestry/compat/kubejs/package-info.java index 8b61a3d9c7..e1263d4577 100644 --- a/src/main/java/forestry/compat/kubejs/package-info.java +++ b/src/main/java/forestry/compat/kubejs/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.kubejs; diff --git a/src/main/java/forestry/compat/package-info.java b/src/main/java/forestry/compat/package-info.java index 64d3c2c693..a520ee0ea0 100644 --- a/src/main/java/forestry/compat/package-info.java +++ b/src/main/java/forestry/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat; diff --git a/src/main/java/forestry/compat/patchouli/component/FluidComponent.java b/src/main/java/forestry/compat/patchouli/component/FluidComponent.java index 6a00b57cc6..b20e6f46d7 100644 --- a/src/main/java/forestry/compat/patchouli/component/FluidComponent.java +++ b/src/main/java/forestry/compat/patchouli/component/FluidComponent.java @@ -5,12 +5,14 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.InventoryMenu; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; import vazkii.patchouli.api.IComponentRenderContext; import vazkii.patchouli.api.ICustomComponent; import vazkii.patchouli.api.IVariable; @@ -44,7 +46,7 @@ public void render(GuiGraphics graphics, IComponentRenderContext context, float ResourceLocation fluidStill = fluidAttributes.getStillTexture(this.fluidStack); TextureAtlasSprite sprite = Minecraft.getInstance().getTextureAtlas(InventoryMenu.BLOCK_ATLAS).apply(fluidStill); ResourceLocation spriteLocation = sprite.contents().name(); - ResourceLocation fluidTexture = new ResourceLocation(spriteLocation.getNamespace(), "textures/" + spriteLocation.getPath() + ".png"); + ResourceLocation fluidTexture = spriteLocation.withPath("textures/" + spriteLocation.getPath() + ".png"); setGLColorFromInt(fluidAttributes.getTintColor(this.fluidStack)); // MatrixStack transform, int x, int y, float u, float v, int width, int height, int ?, int ? @@ -52,7 +54,7 @@ public void render(GuiGraphics graphics, IComponentRenderContext context, float if (context.isAreaHovered(mouseX, mouseY, this.x, this.y, this.w, this.h)) { List toolTips = new ArrayList<>(); - toolTips.add(this.fluidStack.getDisplayName()); + toolTips.add(this.fluidStack.getHoverName()); toolTips.add(Component.translatable("for.gui.tooltip.liquid.amount", this.level, this.maxLevel)); context.setHoverTooltipComponents(toolTips); @@ -62,12 +64,12 @@ public void render(GuiGraphics graphics, IComponentRenderContext context, float } @Override - public void onVariablesAvailable(UnaryOperator lookup) { - ResourceLocation id = new ResourceLocation(lookup.apply(this.fluid).asString()); + public void onVariablesAvailable(UnaryOperator lookup, HolderLookup.Provider registries) { + ResourceLocation id = ResourceLocation.parse(lookup.apply(this.fluid).asString()); int mb = lookup.apply(this.amount).asNumber().intValue(); try { - this.fluidStack = new FluidStack(ForgeRegistries.FLUIDS.getValue(id), mb); + this.fluidStack = new FluidStack(registries.holderOrThrow(ResourceKey.create(Registries.FLUID, id)), mb); } catch (Exception e) { this.fluidStack = FluidStack.EMPTY; } diff --git a/src/main/java/forestry/compat/patchouli/component/package-info.java b/src/main/java/forestry/compat/patchouli/component/package-info.java index 133338b51a..c3488e0dae 100644 --- a/src/main/java/forestry/compat/patchouli/component/package-info.java +++ b/src/main/java/forestry/compat/patchouli/component/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.patchouli.component; diff --git a/src/main/java/forestry/compat/patchouli/package-info.java b/src/main/java/forestry/compat/patchouli/package-info.java index 0b05d8ca8c..2a90d15b0a 100644 --- a/src/main/java/forestry/compat/patchouli/package-info.java +++ b/src/main/java/forestry/compat/patchouli/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.patchouli; diff --git a/src/main/java/forestry/compat/patchouli/processor/CarpenterProcessor.java b/src/main/java/forestry/compat/patchouli/processor/CarpenterProcessor.java index c2e882683f..f01332eae3 100644 --- a/src/main/java/forestry/compat/patchouli/processor/CarpenterProcessor.java +++ b/src/main/java/forestry/compat/patchouli/processor/CarpenterProcessor.java @@ -3,8 +3,9 @@ import com.google.common.base.Preconditions; import forestry.api.recipes.ICarpenterRecipe; import forestry.core.utils.ModUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryRecipeTypes; +import net.minecraft.core.RegistryAccess; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; @@ -21,16 +22,17 @@ public class CarpenterProcessor implements IComponentProcessor { @Override public void setup(Level level, IVariableProvider variables) { - ItemStack stack = variables.get("item").as(ItemStack.class, ItemStack.EMPTY); + ItemStack stack = variables.get("item", level.registryAccess()).as(ItemStack.class, ItemStack.EMPTY); - this.recipe = RecipeUtils.getRecipeByOutput(FactoryRecipeTypes.CARPENTER, level.registryAccess(), stack); + this.recipe = RecipeUtil.getRecipeByOutput(FactoryRecipeTypes.CARPENTER, level.registryAccess(), stack).value(); } @Override public IVariable process(Level level, String key) { Preconditions.checkNotNull(this.recipe); if (key.equals("output")) { - return IVariable.from(this.recipe.getResultItem(level.registryAccess())); + RegistryAccess lookup = level.registryAccess(); + return IVariable.from(this.recipe.getResultItem(lookup), lookup); } else if (key.equals("fluid")) { return IVariable.wrap(ModUtil.getRegistryName(this.recipe.getInputFluid().getFluid()).toString()); } else if (key.equals("fluidAmount")) { @@ -47,7 +49,7 @@ public IVariable process(Level level, String key) { } catch (Exception e) { ingredient = Ingredient.EMPTY; } - return IVariable.from(ingredient.getItems()); + return IVariable.from(ingredient.getItems(), level.registryAccess()); } else { return IVariable.empty(); } diff --git a/src/main/java/forestry/compat/patchouli/processor/FabricatorProcessor.java b/src/main/java/forestry/compat/patchouli/processor/FabricatorProcessor.java index e51dfb0461..3c7ee0bc21 100644 --- a/src/main/java/forestry/compat/patchouli/processor/FabricatorProcessor.java +++ b/src/main/java/forestry/compat/patchouli/processor/FabricatorProcessor.java @@ -3,12 +3,14 @@ import com.google.common.base.Preconditions; import forestry.api.recipes.IFabricatorRecipe; import forestry.core.utils.ModUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryRecipeTypes; +import net.minecraft.core.RegistryAccess; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; import vazkii.patchouli.api.IComponentProcessor; import vazkii.patchouli.api.IVariable; import vazkii.patchouli.api.IVariableProvider; @@ -23,9 +25,10 @@ public class FabricatorProcessor implements IComponentProcessor { @Override public void setup(Level level, IVariableProvider variables) { - ItemStack stack = variables.get("item").as(ItemStack.class, ItemStack.EMPTY); + RegistryAccess registries = level.registryAccess(); + ItemStack stack = variables.get("item", registries).as(ItemStack.class, ItemStack.EMPTY); - this.recipe = RecipeUtils.getRecipeByOutput(FactoryRecipeTypes.FABRICATOR, level.registryAccess(), stack); + this.recipe = RecipeUtil.getRecipeByOutput(FactoryRecipeTypes.FABRICATOR, registries, stack).value(); } @Override @@ -34,9 +37,9 @@ public IVariable process(Level level, String key) { if (key.equals("output")) { return IVariable.from(this.recipe.getCraftingGridRecipe().getResultItem(level.registryAccess())); } else if (key.equals("fluid")) { - return IVariable.wrap(ModUtil.getRegistryName(this.recipe.getResultFluid().getFluid()).toString()); + return IVariable.wrap(ModUtil.getRegistryName(this.recipe.getRequiredFluid().getFluid()).toString()); } else if (key.equals("fluidAmount")) { - return IVariable.wrap(this.recipe.getResultFluid().getAmount()); + return IVariable.wrap(this.recipe.getRequiredFluid().map(SizedFluidIngredient::amount).orElse(0)); } else if (key.startsWith("ingredient")) { int index = Integer.parseInt(key.substring("ingredient".length())); if (index < 1 || index > 9) { @@ -53,12 +56,12 @@ public IVariable process(Level level, String key) { } else if (key.equals("plan")) { return IVariable.from(this.recipe.getPlan()); } else if (key.equals("metal")) { - if (ModUtil.getRegistryName(this.recipe.getResultFluid().getFluid()).getPath().contains("glass")) { + if (ModUtil.getRegistryName(this.recipe.getRequiredFluid().getFluid()).getPath().contains("glass")) { return IVariable.from(new ItemStack(Items.SAND)); } - return RecipeUtils.getRecipes(RecipeUtils.getRecipeManager(), FactoryRecipeTypes.FABRICATOR_SMELTING) - .filter(recipe -> recipe.getResultFluid().isFluidEqual(this.recipe.getResultFluid())) + return RecipeUtil.getRecipes(RecipeUtil.getRecipeManager(), FactoryRecipeTypes.FABRICATOR_SMELTING) + .filter(recipe -> recipe.getResultFluid().isFluidEqual(this.recipe.getRequiredFluid())) .flatMap(r -> Arrays.stream(r.getInput().getItems())) .findFirst() .map(IVariable::from) diff --git a/src/main/java/forestry/compat/patchouli/processor/package-info.java b/src/main/java/forestry/compat/patchouli/processor/package-info.java index dfedcdbbc9..1e72de484d 100644 --- a/src/main/java/forestry/compat/patchouli/processor/package-info.java +++ b/src/main/java/forestry/compat/patchouli/processor/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.compat.patchouli.processor; diff --git a/src/main/java/forestry/core/EventHandlerCore.java b/src/main/java/forestry/core/EventHandlerCore.java index 642e38eac9..f85dfda8f7 100755 --- a/src/main/java/forestry/core/EventHandlerCore.java +++ b/src/main/java/forestry/core/EventHandlerCore.java @@ -1,22 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core; import forestry.api.ForestryConstants; +import forestry.api.ForestryDataMaps; import forestry.api.IForestryApi; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesType; import forestry.apiculture.ApiaristAI; import forestry.apiculture.features.ApicultureEffects; import forestry.apiculture.villagers.ApicultureVillagers; +import forestry.core.inventory.ItemInventory; import forestry.core.worldgen.VillagerJigsaw; import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; @@ -28,14 +20,16 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.living.LivingAttackEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.server.ServerAboutToStartEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.server.ServerAboutToStartEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.registries.datamaps.RegisterDataMapTypesEvent; -@Mod.EventBusSubscriber(modid = ForestryConstants.MOD_ID) +@EventBusSubscriber(modid = ForestryConstants.MOD_ID) public class EventHandlerCore { @SubscribeEvent public static void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { @@ -93,4 +87,17 @@ public static void serverAboutToStart(ServerAboutToStartEvent event) { VillagerJigsaw.init(pools, processors); } + + @SubscribeEvent + public static void registerCapabilities(RegisterCapabilitiesEvent event) { + event.registerItem(Capabilities.ItemHandler.ITEM, ItemInventory::getCapability); + } + + @SubscribeEvent + public static void registerDataMaps(RegisterDataMapTypesEvent event) { + event.register(ForestryDataMaps.FERMENTER_FUELS); + event.register(ForestryDataMaps.RAINMAKER_FUELS); + event.register(ForestryDataMaps.BIOGAS_FUELS); + event.register(ForestryDataMaps.PEAT_FUELS); + } } diff --git a/src/main/java/forestry/core/ModuleCore.java b/src/main/java/forestry/core/ModuleCore.java index 753d153cf0..aa04351814 100644 --- a/src/main/java/forestry/core/ModuleCore.java +++ b/src/main/java/forestry/core/ModuleCore.java @@ -1,69 +1,55 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core; import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import forestry.api.ForestryCapabilities; import forestry.api.ForestryConstants; +import forestry.api.ForestryRegistries; import forestry.api.IForestryApi; import forestry.api.client.IClientModuleHandler; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; import forestry.api.modules.IForestryModule; -import forestry.api.modules.IPacketRegistry; -import forestry.apiculture.features.ApicultureItems; -import forestry.apiculture.items.ItemPollenCluster; import forestry.apiimpl.plugin.PluginManager; -import forestry.arboriculture.features.ArboricultureBlocks; -import forestry.arboriculture.features.ArboricultureItems; -import forestry.arboriculture.loot.GrafterLootModifier; import forestry.core.blocks.TileStreamUpdateTracker; import forestry.core.client.CoreClientHandler; import forestry.core.climate.ForestryClimateManager; import forestry.core.commands.DiagnosticsCommand; import forestry.core.commands.DumpCommand; +import forestry.core.features.CoreDataComponents; import forestry.core.features.CoreItems; -import forestry.core.items.definitions.EnumCraftingMaterial; -import forestry.core.loot.ConditionLootModifier; +import forestry.core.items.ItemSpectacles; +import forestry.core.items.definitions.EnumContainerType; +import forestry.core.items.definitions.FluidHandlerItemForestry; +import forestry.core.multiblock.MultiblockRegistry; import forestry.core.network.PacketIdClient; import forestry.core.network.PacketIdServer; import forestry.core.network.packets.*; -import forestry.core.owner.GameProfileDataSerializer; import forestry.core.recipes.RecipeManagers; import forestry.core.utils.ModUtil; -import forestry.core.utils.NetworkUtil; -import forestry.lepidopterology.features.LepidopterologyItems; import forestry.modules.BlankForestryModule; -import forestry.modules.ForestryModuleManager; import forestry.modules.ModuleUtil; -import forestry.modules.features.FeatureItem; -import it.unimi.dsi.fastutil.objects.Object2FloatMap; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.registries.Registries; -import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Unit; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.ComposterBlock; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.event.RegisterCommandsEvent; -import net.minecraftforge.event.TagsUpdatedEvent; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegisterEvent; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.AddReloadListenerEvent; +import net.neoforged.neoforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.event.TagsUpdatedEvent; +import net.neoforged.neoforge.event.level.ChunkEvent; +import net.neoforged.neoforge.event.level.LevelEvent; +import net.neoforged.neoforge.event.tick.ServerTickEvent; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.capability.templates.FluidHandlerItemStack; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; +import net.neoforged.neoforge.registries.NewRegistryEvent; import java.util.List; import java.util.function.Consumer; @@ -78,59 +64,22 @@ public ResourceLocation getId() { @Override public void registerEvents(IEventBus modBus) { modBus.addListener(ModuleCore::onCommonSetup); - modBus.addListener(ModuleCore::registerGlobalLootModifiers); ModUtil.addRegistryListener(Registries.ITEM, ModuleCore::postItemRegistry); ModuleUtil.loadFeatureProviders(); - MinecraftForge.EVENT_BUS.addListener(ModuleCore::onItemPickup); - MinecraftForge.EVENT_BUS.addListener(ModuleCore::onLevelTick); - MinecraftForge.EVENT_BUS.addListener(ModuleCore::onTagsUpdated); - MinecraftForge.EVENT_BUS.addListener(ModuleCore::registerReloadListeners); - MinecraftForge.EVENT_BUS.addListener(ModuleCore::registerCommands); - - PluginManager.registerAsyncException(modBus); + //NeoForge.EVENT_BUS.addListener(ModuleCore::onItemPickup); + NeoForge.EVENT_BUS.addListener(ModuleCore::onLevelTick); + NeoForge.EVENT_BUS.addListener(ModuleCore::onTagsUpdated); + NeoForge.EVENT_BUS.addListener(ModuleCore::registerReloadListeners); + NeoForge.EVENT_BUS.addListener(ModuleCore::registerCommands); + NeoForge.EVENT_BUS.addListener(ModuleCore::registerNewRegistries); + NeoForge.EVENT_BUS.addListener(ModuleCore::registerCapabilities); + NeoForge.EVENT_BUS.addListener(ModuleCore::onChunkLoad); + NeoForge.EVENT_BUS.addListener(ModuleCore::onWorldUnload); } private static void onCommonSetup(FMLCommonSetupEvent event) { - event.enqueueWork(() -> { - ((ForestryModuleManager) IForestryApi.INSTANCE.getModuleManager()).setupApi(); - PluginManager.registerCircuits(); - EntityDataSerializers.registerSerializer(GameProfileDataSerializer.INSTANCE); - registerComposts(); - }); - } - - private static void registerComposts() { - // cast avoids stupid typos (IItemLike can be different than Item, then composter will not work) - @SuppressWarnings({"unchecked", "rawtypes"}) - Object2FloatMap composts = ((Object2FloatMap) ComposterBlock.COMPOSTABLES); - - for (FeatureItem fruit : CoreItems.FRUITS.getFeatures()) { - composts.put(fruit.item(), 0.65f); - } - composts.put(CoreItems.MOULDY_WHEAT.item(), 0.65f); - composts.put(CoreItems.DECAYING_WHEAT.item(), 0.65f); - composts.put(CoreItems.MULCH.item(), 0.65f); - composts.put(CoreItems.ASH.item(), 0.65f); - composts.put(CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.WOOD_PULP), 0.65f); - composts.put(CoreItems.PEAT.item(), 0.75f); - composts.put(CoreItems.COMPOST.item(), 1f); - for (ItemPollenCluster pollen : ApicultureItems.POLLEN_CLUSTER.getItems()) { - composts.put(pollen, 0.3f); - } - composts.put(ArboricultureItems.SAPLING.item(), 0.3f); - composts.put(ArboricultureItems.POLLEN_FERTILE.item(), 0.3f); - for (BlockItem leaves : ArboricultureBlocks.LEAVES_DECORATIVE.getItems()) { - composts.put(leaves, 0.3f); - } - composts.put(LepidopterologyItems.COCOON_GE.item(), 0.3f); - } - - private static void registerGlobalLootModifiers(RegisterEvent event) { - event.register(ForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, helper -> { - helper.register(ForestryConstants.forestry("condition_modifier"), ConditionLootModifier.CODEC); - helper.register(ForestryConstants.forestry("grafter_modifier"), GrafterLootModifier.CODEC); - }); + event.enqueueWork(PluginManager::registerCircuits); } private static void postItemRegistry() { @@ -139,17 +88,16 @@ private static void postItemRegistry() { PluginManager.registerPollen(); } - private static void onItemPickup(EntityItemPickupEvent event) { + // todo backpack + /*private static void onItemPickup(EntityItemPickupEvent event) { if (event.isCanceled() || event.getResult() == Event.Result.ALLOW) { return; } PickupHandlerCore.onItemPickup(event.getEntity(), event.getItem()); - } + }*/ - private static void onLevelTick(TickEvent.LevelTickEvent event) { - if (event.phase == TickEvent.Phase.END) { - TileStreamUpdateTracker.syncVisualUpdates(); - } + private static void onLevelTick(ServerTickEvent.Post event) { + TileStreamUpdateTracker.syncVisualUpdates(event.getServer()); } private static void onTagsUpdated(TagsUpdatedEvent event) { @@ -162,7 +110,7 @@ private static void registerReloadListeners(AddReloadListenerEvent event) { event.addListener((prepBarrier, resourceManager, prepProfiler, reloadProfiler, backgroundExecutor, gameExecutor) -> { return prepBarrier.wait(Unit.INSTANCE).thenRunAsync(() -> { RecipeManagers.invalidateCaches(); - NetworkUtil.sendToAllPlayers(new RecipeCachePacket()); + PacketDistributor.sendToAllPlayers(new RecipeCachePacket()); }); }); } @@ -182,6 +130,10 @@ private static void registerCommands(RegisterCommandsEvent event) { event.getDispatcher().register(forestryCommand); } + private static void registerNewRegistries(NewRegistryEvent event) { + event.register(ForestryRegistries.CIRCUIT); + } + @Override public boolean isCore() { return true; @@ -193,24 +145,44 @@ public List getModuleDependencies() { } @Override - public void registerPackets(IPacketRegistry registry) { - registry.serverbound(PacketIdServer.GUI_SELECTION_REQUEST, PacketGuiSelectRequest.class, PacketGuiSelectRequest::decode, PacketGuiSelectRequest::handle); - registry.serverbound(PacketIdServer.PIPETTE_CLICK, PacketPipetteClick.class, PacketPipetteClick::decode, PacketPipetteClick::handle); - registry.serverbound(PacketIdServer.CHIPSET_CLICK, PacketChipsetClick.class, PacketChipsetClick::decode, PacketChipsetClick::handle); - registry.serverbound(PacketIdServer.SOLDERING_IRON_CLICK, PacketSolderingIronClick.class, PacketSolderingIronClick::decode, PacketSolderingIronClick::handle); - - registry.clientbound(PacketIdClient.ERROR_UPDATE, PacketErrorUpdate.class, PacketErrorUpdate::decode, PacketErrorUpdate::handle); - registry.clientbound(PacketIdClient.GUI_UPDATE, PacketGuiStream.class, PacketGuiStream::decode, PacketGuiStream::handle); - registry.clientbound(PacketIdClient.GUI_LAYOUT_SELECT, PacketGuiLayoutSelect.class, PacketGuiLayoutSelect::decode, PacketGuiLayoutSelect::handle); - registry.clientbound(PacketIdClient.GUI_ENERGY, PacketGuiEnergy.class, PacketGuiEnergy::decode, PacketGuiEnergy::handle); - registry.clientbound(PacketIdClient.SOCKET_UPDATE, PacketSocketUpdate.class, PacketSocketUpdate::decode, PacketSocketUpdate::handle); - registry.clientbound(PacketIdClient.TILE_FORESTRY_UPDATE, PacketTileStream.class, PacketTileStream::decode, PacketTileStream::handle); - registry.clientbound(PacketIdClient.TILE_FORESTRY_ACTIVE, PacketActiveUpdate.class, PacketActiveUpdate::decode, PacketActiveUpdate::handle); - registry.clientbound(PacketIdClient.ITEMSTACK_DISPLAY, PacketItemStackDisplay.class, PacketItemStackDisplay::decode, PacketItemStackDisplay::handle); - registry.clientbound(PacketIdClient.GENOME_TRACKER_UPDATE, PacketTankLevelUpdate.class, PacketTankLevelUpdate::decode, PacketTankLevelUpdate::handle); - registry.clientbound(PacketIdClient.TANK_LEVEL_UPDATE, PacketGenomeTrackerSync.class, PacketGenomeTrackerSync::decode, PacketGenomeTrackerSync::handle); - registry.clientbound(PacketIdClient.RECIPE_CACHE, RecipeCachePacket.class, RecipeCachePacket::decode, RecipeCachePacket::handle); - registry.clientbound(PacketIdClient.REFRACTORY_WAX_ON, PacketRefractoryWax.class, PacketRefractoryWax::decode, PacketRefractoryWax::handle); + public void registerPackets(PayloadRegistrar registrar) { + registrar.playToServer(PacketIdServer.GUI_SELECTION_REQUEST, StreamCodec.of(PacketGuiSelectRequest::encode, PacketGuiSelectRequest::decode), PacketGuiSelectRequest::handle); + registrar.playToServer(PacketIdServer.PIPETTE_CLICK, StreamCodec.of(PacketPipetteClick::encode, PacketPipetteClick::decode), PacketPipetteClick::handle); + registrar.playToServer(PacketIdServer.CHIPSET_CLICK, StreamCodec.of(PacketChipsetClick::encode, PacketChipsetClick::decode), PacketChipsetClick::handle); + registrar.playToServer(PacketIdServer.SOLDERING_IRON_CLICK, StreamCodec.of(PacketSolderingIronClick::encode, PacketSolderingIronClick::decode), PacketSolderingIronClick::handle); + + registrar.playToClient(PacketIdClient.ERROR_UPDATE, StreamCodec.of(PacketErrorUpdate::encode, PacketErrorUpdate::decode), PacketErrorUpdate::handle); + registrar.playToClient(PacketIdClient.GUI_STREAM, StreamCodec.of(PacketGuiStream::encode, PacketGuiStream::decode), PacketGuiStream::handle); + registrar.playToClient(PacketIdClient.GUI_LAYOUT_SELECT, StreamCodec.of(PacketGuiLayoutSelect::encode, PacketGuiLayoutSelect::decode), PacketGuiLayoutSelect::handle); + registrar.playToClient(PacketIdClient.GUI_ENERGY, StreamCodec.of(PacketGuiEnergy::encode, PacketGuiEnergy::decode), PacketGuiEnergy::handle); + registrar.playToClient(PacketIdClient.SOCKET_UPDATE, StreamCodec.of(PacketSocketUpdate::encode, PacketSocketUpdate::decode), PacketSocketUpdate::handle); + registrar.playToClient(PacketIdClient.TILE_STREAM, StreamCodec.of(PacketTileStream::encode, PacketTileStream::decode), PacketTileStream::handle); + registrar.playToClient(PacketIdClient.ACTIVE_UPDATE, StreamCodec.of(PacketActiveUpdate::encode, PacketActiveUpdate::decode), PacketActiveUpdate::handle); + registrar.playToClient(PacketIdClient.ITEMSTACK_DISPLAY, StreamCodec.of(PacketItemStackDisplay::encode, PacketItemStackDisplay::decode), PacketItemStackDisplay::handle); + registrar.playToClient(PacketIdClient.TANK_LEVEL_UPDATE, StreamCodec.of(PacketTankLevelUpdate::encode, PacketTankLevelUpdate::decode), PacketTankLevelUpdate::handle); + registrar.playToClient(PacketIdClient.GENOME_TRACKER_UPDATE, StreamCodec.of(PacketGenomeTrackerSync::encode, PacketGenomeTrackerSync::decode), PacketGenomeTrackerSync::handle); + registrar.playToClient(PacketIdClient.RECIPE_CACHE, StreamCodec.unit(new RecipeCachePacket()), RecipeCachePacket::handle); + registrar.playToClient(PacketIdClient.REFRACTORY_WAX_ON, StreamCodec.of(PacketRefractoryWax::encode, PacketRefractoryWax::decode), PacketRefractoryWax::handle); + } + + public static void registerCapabilities(RegisterCapabilitiesEvent event) { + event.registerItem(Capabilities.FluidHandler.ITEM, (stack, v) -> new FluidHandlerItemStack(CoreDataComponents.FLUID_CONTENTS, stack, FluidType.BUCKET_VOLUME), CoreItems.PIPETTE); + + for (EnumContainerType type : EnumContainerType.values()) { + event.registerItem(Capabilities.FluidHandler.ITEM, (stack, v) -> new FluidHandlerItemForestry(stack, type)); + } + + event.registerItem(ForestryCapabilities.SPECTACLE_VISION, (stack, v) -> ItemSpectacles.VISION, CoreItems.SPECTACLES); + } + + public static void onChunkLoad(ChunkEvent.Load event) { + ChunkAccess chunk = event.getChunk(); + MultiblockRegistry.onChunkLoaded(event.getLevel(), chunk.getPos().x, chunk.getPos().z); + } + + // Cleanup, for nice memory usageness + public static void onWorldUnload(LevelEvent.Unload event) { + MultiblockRegistry.onWorldUnloaded(event.getLevel()); } @Override diff --git a/src/main/java/forestry/core/ModuleFluids.java b/src/main/java/forestry/core/ModuleFluids.java deleted file mode 100644 index d0af12b5b1..0000000000 --- a/src/main/java/forestry/core/ModuleFluids.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core; - -import forestry.api.modules.ForestryModule; -import forestry.api.modules.ForestryModuleIds; -import forestry.modules.BlankForestryModule; -import net.minecraft.resources.ResourceLocation; - -@ForestryModule -public class ModuleFluids extends BlankForestryModule { - @Override - public ResourceLocation getId() { - return ForestryModuleIds.FLUIDS; - } -} diff --git a/src/main/java/forestry/core/PickupHandlerCore.java b/src/main/java/forestry/core/PickupHandlerCore.java index dca6ff332d..8855eb82ef 100755 --- a/src/main/java/forestry/core/PickupHandlerCore.java +++ b/src/main/java/forestry/core/PickupHandlerCore.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core; import forestry.api.genetics.IBreedingTracker; diff --git a/src/main/java/forestry/core/blocks/BlockBase.java b/src/main/java/forestry/core/blocks/BlockBase.java index 2a0f1e157c..fdd91b2357 100755 --- a/src/main/java/forestry/core/blocks/BlockBase.java +++ b/src/main/java/forestry/core/blocks/BlockBase.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; -import forestry.api.farming.HorizontalDirection; import forestry.core.circuits.ISocketable; import forestry.core.tiles.TileBase; import forestry.core.tiles.TileForestry; @@ -19,50 +8,38 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.Container; -import net.minecraft.world.Containers; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; +import net.minecraft.world.*; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.Rotation; 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.StateDefinition; -import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidUtil; import javax.annotation.Nullable; -public class BlockBase

& IBlockType> extends BlockForestry implements EntityBlock { - /** - * use this instead of {@link net.minecraft.world.level.block.HorizontalDirectionalBlock#FACING} so the blocks rotate in a circle instead of NSWE order. - */ - public static final EnumProperty FACING = EnumProperty.create("facing", Direction.class, HorizontalDirection.VALUES); - +public class BlockBase

extends BlockForestry implements EntityBlock { public final P blockType; - private static Block.Properties createProperties(Block.Properties properties) { - return properties.strength(2.0f); - } - public BlockBase(P blockType, Block.Properties properties) { - super(createProperties(properties)); + super(properties.strength(2.0f)); - if (getStateDefinition().any().hasProperty(FACING)) { - registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH)); + if (getStateDefinition().any().hasProperty(HorizontalDirectionalBlock.FACING)) { + registerDefaultState(getStateDefinition().any().setValue(HorizontalDirectionalBlock.FACING, Direction.NORTH)); } this.blockType = blockType; @@ -72,7 +49,7 @@ public BlockBase(P blockType, Block.Properties properties) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING); + builder.add(HorizontalDirectionalBlock.FACING); } @Override @@ -107,32 +84,35 @@ public VoxelShape getShape(BlockState state, BlockGetter reader, BlockPos pos, C return definition.getShape(state, reader, pos, context); } - /* INTERACTION */ @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult hit) { - TileBase tile = TileUtil.getTile(worldIn, pos, TileBase.class); - if (tile == null) { - return InteractionResult.PASS; - } - if (TileUtil.isUsableByPlayer(playerIn, tile)) { - if (!playerIn.isShiftKeyDown()) { - if (FluidUtil.interactWithFluidHandler(playerIn, hand, worldIn, pos, hit.getDirection())) { - return InteractionResult.sidedSuccess(worldIn.isClientSide); + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + TileBase tile = TileUtil.getTile(level, pos, TileBase.class); + if (tile != null) { + if (TileUtil.isUsableByPlayer(player, tile)) { + // todo do we need this SHIFT check + if ((!player.isShiftKeyDown() && FluidUtil.interactWithFluidHandler(player, hand, level, pos, hitResult.getDirection())) + || (tile.interactWithItem(level, pos, player, hand, stack))) { + return ItemInteractionResult.sidedSuccess(level.isClientSide); } } + } + return super.useItemOn(stack, state, level, pos, player, hand, hitResult); + } - if (!worldIn.isClientSide) { - ServerPlayer sPlayer = (ServerPlayer) playerIn; - tile.openGui(sPlayer, hand, pos); - } + @Override + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + TileBase tile = TileUtil.getTile(level, pos, TileBase.class); + + if (tile != null && tile.interactNoItem(level, player, pos)) { + return InteractionResult.sidedSuccess(level.isClientSide); } - return InteractionResult.SUCCESS; + return super.useWithoutItem(state, level, pos, player, hitResult); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite()); + return defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, context.getHorizontalDirection().getOpposite()); } @Override @@ -156,7 +136,7 @@ public void onRemove(BlockState state, Level level, BlockPos pos, BlockState new @Override public BlockState rotate(BlockState state, Rotation rot) { - Direction facing = state.getValue(FACING); - return state.setValue(FACING, rot.rotate(facing)); + Direction facing = state.getValue(HorizontalDirectionalBlock.FACING); + return state.setValue(HorizontalDirectionalBlock.FACING, rot.rotate(facing)); } } diff --git a/src/main/java/forestry/core/blocks/BlockBogEarth.java b/src/main/java/forestry/core/blocks/BlockBogEarth.java index db9fae7458..3ddc249cba 100755 --- a/src/main/java/forestry/core/blocks/BlockBogEarth.java +++ b/src/main/java/forestry/core/blocks/BlockBogEarth.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; import forestry.core.features.CoreBlocks; @@ -23,14 +13,14 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraftforge.common.IPlantable; +import net.neoforged.neoforge.common.util.TriState; /** * bog earth, which becomes peat */ public class BlockBogEarth extends Block { private static final int maturityDelimiter = 3; //maturity at which bogEarth becomes peat - public static final IntegerProperty MATURITY = IntegerProperty.create("maturity", 0, maturityDelimiter); + public static final IntegerProperty MATURITY = IntegerProperty.create("maturity", 0, 3); public BlockBogEarth() { super(Block.Properties.of() @@ -77,7 +67,7 @@ private static boolean isMoistened(Level world, BlockPos pos) { } @Override - public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction direction, IPlantable plantable) { - return false; + public TriState canSustainPlant(BlockState state, BlockGetter level, BlockPos soilPosition, Direction facing, BlockState plant) { + return TriState.FALSE; } } diff --git a/src/main/java/forestry/core/blocks/BlockCore.java b/src/main/java/forestry/core/blocks/BlockCore.java index 36b0de0b19..4fdf41a1e0 100644 --- a/src/main/java/forestry/core/blocks/BlockCore.java +++ b/src/main/java/forestry/core/blocks/BlockCore.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; import net.minecraft.world.level.block.Block; diff --git a/src/main/java/forestry/core/blocks/BlockForestry.java b/src/main/java/forestry/core/blocks/BlockForestry.java index f03c49bd2b..de1abb8698 100644 --- a/src/main/java/forestry/core/blocks/BlockForestry.java +++ b/src/main/java/forestry/core/blocks/BlockForestry.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; import com.mojang.authlib.GameProfile; @@ -25,18 +15,15 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import javax.annotation.Nullable; + public abstract class BlockForestry extends Block { protected BlockForestry(Block.Properties properties) { - this(properties, false); - } - - protected BlockForestry(Block.Properties properties, boolean defaultStrength) { - super(defaultStrength ? properties - .strength(1.5f) : properties); + super(properties); } @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { + public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { if (world.isClientSide) { return; } diff --git a/src/main/java/forestry/core/blocks/BlockHumus.java b/src/main/java/forestry/core/blocks/BlockHumus.java index 770a5d3741..09229466e0 100755 --- a/src/main/java/forestry/core/blocks/BlockHumus.java +++ b/src/main/java/forestry/core/blocks/BlockHumus.java @@ -14,8 +14,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.common.PlantType; +import net.neoforged.neoforge.common.util.TriState; public class BlockHumus extends Block { private static final int DEGRADE_STEPS = 3; @@ -80,8 +79,7 @@ private static void degradeSoil(Level world, final BlockPos pos) { } @Override - public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction direction, IPlantable plantable) { - PlantType plantType = plantable.getPlantType(world, pos); - return plantType == PlantType.CROP || plantType == PlantType.PLAINS; + public TriState canSustainPlant(BlockState state, BlockGetter level, BlockPos soilPosition, Direction facing, BlockState plant) { + return plant.is(BlockTags.CROPS) ? TriState.TRUE : TriState.DEFAULT; } } diff --git a/src/main/java/forestry/core/blocks/BlockResourceStorage.java b/src/main/java/forestry/core/blocks/BlockResourceStorage.java index f08c50b55a..0e127d9328 100755 --- a/src/main/java/forestry/core/blocks/BlockResourceStorage.java +++ b/src/main/java/forestry/core/blocks/BlockResourceStorage.java @@ -1,16 +1,10 @@ package forestry.core.blocks; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.SoundType; public class BlockResourceStorage extends Block { - private final EnumResourceType type; - - public BlockResourceStorage(EnumResourceType type) { - super(Block.Properties.of().strength(3f, 5f)); - this.type = type; - } - - public EnumResourceType getType() { - return this.type; + public BlockResourceStorage() { + super(Block.Properties.of().strength(3f, 5f).sound(SoundType.METAL)); } } diff --git a/src/main/java/forestry/core/blocks/BlockStructure.java b/src/main/java/forestry/core/blocks/BlockStructure.java index 6beb8a4114..56c066b526 100644 --- a/src/main/java/forestry/core/blocks/BlockStructure.java +++ b/src/main/java/forestry/core/blocks/BlockStructure.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; import com.mojang.authlib.GameProfile; @@ -21,6 +11,7 @@ import net.minecraft.world.Containers; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -29,61 +20,70 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; +import javax.annotation.Nullable; + public abstract class BlockStructure extends BlockForestry { + protected long previousMessageTick = 0; + protected BlockStructure(Block.Properties properties) { super(properties.strength(1f)); } - protected long previousMessageTick = 0; - @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult hit) { - if (playerIn.isShiftKeyDown()) { //isSneaking - return InteractionResult.PASS; - } + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + if (stack.isEmpty()) { + MultiblockTileEntityForestry part = TileUtil.getTile(level, pos, MultiblockTileEntityForestry.class); + if (part == null) { + return ItemInteractionResult.FAIL; + } - MultiblockTileEntityForestry part = TileUtil.getTile(worldIn, pos, MultiblockTileEntityForestry.class); - if (part == null) { - return InteractionResult.FAIL; - } - IMultiblockController controller = part.getMultiblockLogic().getController(); + IMultiblockController controller = part.getMultiblockLogic().getController(); - ItemStack heldItem = playerIn.getItemInHand(hand); - // If the player's hands are empty and they right-click on a multiblock, they get a - // multiblock-debugging message if the machine is not assembled. - if (heldItem.isEmpty()) { if (!controller.isAssembled()) { String validationError = controller.getLastValidationError(); + if (validationError != null) { - long tick = worldIn.getGameTime(); + long tick = level.getGameTime(); + if (tick > this.previousMessageTick + 20) { - playerIn.sendSystemMessage(Component.literal(validationError)); - this.previousMessageTick = tick; + player.sendSystemMessage(Component.literal(validationError)); + this.previousMessageTick = tick; } - return InteractionResult.SUCCESS; + + return ItemInteractionResult.sidedSuccess(level.isClientSide); } } } + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + } - // Don't open the GUI if the multiblock isn't assembled - if (controller == null || !controller.isAssembled()) { - return InteractionResult.PASS; + @Override + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + MultiblockTileEntityForestry part = TileUtil.getTile(level, pos, MultiblockTileEntityForestry.class); + if (part == null) { + return InteractionResult.FAIL; } - if (!worldIn.isClientSide) { - part.openGui((ServerPlayer) playerIn, pos); + IMultiblockController controller = part.getMultiblockLogic().getController(); + + if (controller.isAssembled()) { + if (!level.isClientSide) { + part.openGui((ServerPlayer) player, pos); + } + return InteractionResult.sidedSuccess(level.isClientSide); } - return InteractionResult.SUCCESS; + + return InteractionResult.PASS; } @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { - if (world.isClientSide) { + public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { + if (level.isClientSide) { return; } if (placer instanceof Player) { - TileUtil.actOnTile(world, pos, MultiblockTileEntityForestry.class, tile -> { + TileUtil.actOnTile(level, pos, MultiblockTileEntityForestry.class, tile -> { Player player = (Player) placer; GameProfile gameProfile = player.getGameProfile(); tile.setOwner(gameProfile); diff --git a/src/main/java/forestry/core/blocks/BlockTesr.java b/src/main/java/forestry/core/blocks/BlockTesr.java index 14defc2167..710c2a3a5e 100644 --- a/src/main/java/forestry/core/blocks/BlockTesr.java +++ b/src/main/java/forestry/core/blocks/BlockTesr.java @@ -1,11 +1,13 @@ package forestry.core.blocks; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; -public class BlockTesr

& IBlockType> extends BlockBase

{ - public BlockTesr(P blockType, Properties properties) { - super(blockType, properties.noOcclusion()); +public class BlockTesr

extends BlockBase

{ + public BlockTesr(P blockType) { + super(blockType, Block.Properties.of().sound(SoundType.WOOD).noOcclusion()); } @Override diff --git a/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java b/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java index 7111898153..593e65708e 100644 --- a/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java +++ b/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; import forestry.core.features.CoreTiles; @@ -15,6 +5,7 @@ import forestry.core.tiles.TileEscritoire; import forestry.modules.features.FeatureTileType; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; @@ -48,7 +39,7 @@ private static MachineProperties createEscritoirePrope }; return new MachineProperties.Builder<>(teClass, name) - .setShape((state, level, pos, context) -> shapes[state.getValue(BlockBase.FACING).get2DDataValue()]) + .setShape((state, level, pos, context) -> shapes[state.getValue(HorizontalDirectionalBlock.FACING).get2DDataValue()]) .create(); } diff --git a/src/main/java/forestry/core/blocks/EnumResourceType.java b/src/main/java/forestry/core/blocks/EnumResourceType.java index 00e6738678..33a3c41b99 100644 --- a/src/main/java/forestry/core/blocks/EnumResourceType.java +++ b/src/main/java/forestry/core/blocks/EnumResourceType.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; import forestry.api.core.IBlockSubtype; @@ -20,7 +10,7 @@ public enum EnumResourceType implements IBlockSubtype { BRONZE; @Override - public String getSerializedName() { + public String identifier() { return name().toLowerCase(Locale.ENGLISH); } } diff --git a/src/main/java/forestry/core/blocks/IColoredBlock.java b/src/main/java/forestry/core/blocks/IColoredBlock.java index f7c0fd535a..6ebdfa66d3 100644 --- a/src/main/java/forestry/core/blocks/IColoredBlock.java +++ b/src/main/java/forestry/core/blocks/IColoredBlock.java @@ -3,12 +3,18 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; public interface IColoredBlock { - @OnlyIn(Dist.CLIENT) + /** + * Called on the client to determine the tint color to use for each layer of this block's texture. + * + * @param state The current block state. + * @param level The level. + * @param pos The position of the block. + * @param tintIndex The layer index. + * @return The 24-bit color multiplier to use when applying a tint. {@code 0xffffff} means no tint will be applied. + */ int colorMultiplier(BlockState state, @Nullable BlockAndTintGetter level, @Nullable BlockPos pos, int tintIndex); } diff --git a/src/main/java/forestry/core/blocks/IMachineProperties.java b/src/main/java/forestry/core/blocks/IMachineProperties.java index 97c8b06b9c..7340430367 100644 --- a/src/main/java/forestry/core/blocks/IMachineProperties.java +++ b/src/main/java/forestry/core/blocks/IMachineProperties.java @@ -1,15 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.blocks; +import forestry.api.core.IFeatureSubtype; import forestry.core.tiles.IForestryTicker; import forestry.core.tiles.TileForestry; import net.minecraft.core.BlockPos; @@ -21,7 +12,7 @@ import javax.annotation.Nullable; -public interface IMachineProperties extends StringRepresentable, IShapeProvider { +public interface IMachineProperties extends IFeatureSubtype, IShapeProvider { BlockEntityType getTeType(); @Nullable diff --git a/src/main/java/forestry/core/blocks/MachineProperties.java b/src/main/java/forestry/core/blocks/MachineProperties.java index 9783c4fcb5..81b7eb40b4 100644 --- a/src/main/java/forestry/core/blocks/MachineProperties.java +++ b/src/main/java/forestry/core/blocks/MachineProperties.java @@ -26,6 +26,7 @@ public class MachineProperties implements IMachineProper private final IForestryTicker clientTicker; @Nullable private final IForestryTicker serverTicker; + @Nullable private Block block; @@ -76,7 +77,7 @@ public BlockEntityType getTeType() { } @Override - public String getSerializedName() { + public String identifier() { return this.name; } diff --git a/src/main/java/forestry/core/blocks/TileStreamUpdateTracker.java b/src/main/java/forestry/core/blocks/TileStreamUpdateTracker.java index 019c98532d..d39f6ac72d 100644 --- a/src/main/java/forestry/core/blocks/TileStreamUpdateTracker.java +++ b/src/main/java/forestry/core/blocks/TileStreamUpdateTracker.java @@ -1,50 +1,50 @@ package forestry.core.blocks; -import forestry.core.network.NetworkHandler; import forestry.core.network.packets.PacketTileStream; import forestry.core.tiles.TileForestry; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraftforge.network.PacketDistributor; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.neoforged.neoforge.network.PacketDistributor; +import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.WeakHashMap; -// Based on https://github.com/thedarkcolour/ExDeorum/blob/1.20.4/src/main/java/thedarkcolour/exdeorum/network/VisualUpdateTracker.java +// Based on https://github.com/thedarkcolour/ExDeorum/blob/1.21.1/src/main/java/thedarkcolour/exdeorum/network/VisualUpdateTracker.java public class TileStreamUpdateTracker { - private static final Map> UPDATES = new WeakHashMap<>(); + // Use sets to avoid duplicate updates + private static final Map, Map>> UPDATES = new HashMap<>(); public static void sendVisualUpdate(TileForestry tile) { var level = tile.getLevel(); if (level != null && !level.isClientSide) { - var dimension = level.getChunkAt(tile.getBlockPos()); - Set updatesList; - if (!UPDATES.containsKey(dimension)) { - UPDATES.put(dimension, updatesList = new HashSet<>()); - } else { - updatesList = UPDATES.get(dimension); - } - updatesList.add(tile.getBlockPos()); + Map> chunkUpdates = UPDATES.computeIfAbsent(level.dimension(), key -> new HashMap<>()); + chunkUpdates.computeIfAbsent(new ChunkPos(tile.getBlockPos()), key -> new HashSet<>()).add(tile.getBlockPos()); } } - public static void syncVisualUpdates() { + public static void syncVisualUpdates(MinecraftServer server) { for (var entry : UPDATES.entrySet()) { - var pendingUpdates = entry.getValue(); + var level = server.getLevel(entry.getKey()); + + if (level != null) { + var pendingUpdates = entry.getValue(); - for (var updatePos : pendingUpdates) { - var chunk = entry.getKey(); + for (var chunkUpdates : pendingUpdates.entrySet()) { + var chunkPos = chunkUpdates.getKey(); - if (chunk.getBlockEntity(updatePos) instanceof TileForestry blockEntity) { - // packet uses strong reference - NetworkHandler.CHANNEL.send(PacketDistributor.TRACKING_CHUNK.with(() -> chunk), new PacketTileStream(blockEntity)); + for (var updatePos : chunkUpdates.getValue()) { + if (level.getBlockEntity(updatePos) instanceof TileForestry blockEntity) { + PacketDistributor.sendToPlayersTrackingChunk(level, chunkPos, new PacketTileStream(blockEntity)); + } + } } } - - pendingUpdates.clear(); } } } diff --git a/src/main/java/forestry/core/blocks/package-info.java b/src/main/java/forestry/core/blocks/package-info.java index 38aa2a33ae..9e1dbffc74 100644 --- a/src/main/java/forestry/core/blocks/package-info.java +++ b/src/main/java/forestry/core/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.blocks; diff --git a/src/main/java/forestry/core/circuits/Circuit.java b/src/main/java/forestry/core/circuits/Circuit.java index e846dd529f..12edd98bee 100755 --- a/src/main/java/forestry/core/circuits/Circuit.java +++ b/src/main/java/forestry/core/circuits/Circuit.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; import forestry.api.circuits.ICircuit; diff --git a/src/main/java/forestry/core/circuits/CircuitBoard.java b/src/main/java/forestry/core/circuits/CircuitBoard.java index 9070d55111..f6561edb83 100755 --- a/src/main/java/forestry/core/circuits/CircuitBoard.java +++ b/src/main/java/forestry/core/circuits/CircuitBoard.java @@ -1,64 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; -import forestry.api.IForestryApi; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import forestry.api.circuits.CircuitLayout; import forestry.api.circuits.ICircuit; import forestry.api.circuits.ICircuitBoard; -import forestry.api.circuits.ICircuitLayout; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraft.util.StringRepresentable; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; +import java.util.Optional; public class CircuitBoard implements ICircuitBoard { + public static final Codec CODEC = RecordCodecBuilder.create(inst -> inst.group( + StringRepresentable.fromEnum(() -> EnumCircuitBoardType.values()).fieldOf("").forGetter(b -> b.type), + CircuitLayout.CODEC.optionalFieldOf("layout").forGetter(b -> Optional.ofNullable(b.layout)), + ICircuit.CODEC.listOf().fieldOf("circuits").forGetter(b -> b.circuits) + ).apply(inst, CircuitBoard::new)); + private final EnumCircuitBoardType type; @Nullable - private final ICircuitLayout layout; - private final ICircuit[] circuits; + private final CircuitLayout layout; + private final List circuits; - public CircuitBoard(EnumCircuitBoardType type, @Nullable ICircuitLayout layout, ICircuit[] circuits) { + public CircuitBoard(EnumCircuitBoardType type, Optional layout, List circuits) { this.type = type; - this.layout = layout; + this.layout = layout.orElse(null); this.circuits = circuits; } - public CircuitBoard(CompoundTag compound) { - this.type = EnumCircuitBoardType.values()[compound.getShort("T")]; - - // Layout - ICircuitLayout layout = null; - if (compound.contains("LY")) { - layout = IForestryApi.INSTANCE.getCircuitManager().getLayout(compound.getString("LY")); - } - this.layout = layout; - - this.circuits = new ICircuit[4]; - - for (int i = 0; i < 4; i++) { - if (!compound.contains("CA.I" + i)) { - continue; - } - ICircuit circuit = IForestryApi.INSTANCE.getCircuitManager().getCircuit(compound.getString("CA.I" + i)); - if (circuit != null) { - this.circuits[i] = circuit; - } - } + public static CircuitBoard empty(EnumCircuitBoardType type) { + return new CircuitBoard(type, Optional.empty(), List.of()); } @Override @@ -99,32 +78,10 @@ public void addTooltip(List list) { } } - @Override - public CompoundTag write(CompoundTag compound) { - - compound.putShort("T", (short) this.type.ordinal()); - - // Layout - if (this.layout != null) { - compound.putString("LY", this.layout.getId()); - } - - // Circuits - for (int i = 0; i < this.circuits.length; i++) { - ICircuit circuit = this.circuits[i]; - if (circuit == null) { - continue; - } - - compound.putString("CA.I" + i, circuit.getId()); - } - return compound; - } - @Override public void onInsertion(Object tile) { - for (int i = 0; i < this.circuits.length; i++) { - ICircuit circuit = this.circuits[i]; + for (int i = 0; i < this.circuits.size(); i++) { + ICircuit circuit = this.circuits.get(i); if (circuit == null) { continue; } @@ -134,8 +91,8 @@ public void onInsertion(Object tile) { @Override public void onLoad(Object tile) { - for (int i = 0; i < this.circuits.length; i++) { - ICircuit circuit = this.circuits[i]; + for (int i = 0; i < this.circuits.size(); i++) { + ICircuit circuit = this.circuits.get(i); if (circuit == null) { continue; } @@ -145,8 +102,8 @@ public void onLoad(Object tile) { @Override public void onRemoval(Object tile) { - for (int i = 0; i < this.circuits.length; i++) { - ICircuit circuit = this.circuits[i]; + for (int i = 0; i < this.circuits.size(); i++) { + ICircuit circuit = this.circuits.get(i); if (circuit == null) { continue; } @@ -156,8 +113,8 @@ public void onRemoval(Object tile) { @Override public void onTick(Object tile) { - for (int i = 0; i < this.circuits.length; i++) { - ICircuit circuit = this.circuits[i]; + for (int i = 0; i < this.circuits.size(); i++) { + ICircuit circuit = this.circuits.get(i); if (circuit == null) { continue; } @@ -166,7 +123,7 @@ public void onTick(Object tile) { } @Override - public ICircuit[] getCircuits() { + public List getCircuits() { return this.circuits; } @@ -176,6 +133,6 @@ public ResourceLocation getSocketType() { if (this.layout == null) { return null; } - return this.layout.getSocketType(); + return this.layout.socketType(); } } diff --git a/src/main/java/forestry/core/circuits/CircuitId.java b/src/main/java/forestry/core/circuits/CircuitId.java deleted file mode 100755 index 4be8cb99d6..0000000000 --- a/src/main/java/forestry/core/circuits/CircuitId.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.circuits; - -public class CircuitId { - public static final int ELECTRIC_CHOKE_I = 1; - public static final int FIRE_DAMPENER_I = 2; - public static final int ELECTRIC_EFFICIENCY_I = 3; - public static final int ELECTRIC_BOOST_I = 4; - public static final int ELECTRIC_BOOST_II = 5; -} diff --git a/src/main/java/forestry/core/circuits/CircuitLayout.java b/src/main/java/forestry/core/circuits/CircuitLayout.java deleted file mode 100755 index 7cb0fc022a..0000000000 --- a/src/main/java/forestry/core/circuits/CircuitLayout.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.circuits; - -import forestry.api.circuits.ICircuitLayout; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; - -public class CircuitLayout implements ICircuitLayout { - private final String uid; - private final ResourceLocation socketType; - - public CircuitLayout(String uid, ResourceLocation socketType) { - this.uid = uid; - this.socketType = socketType; - } - - @Override - public String getId() { - return this.uid; - } - - @Override - public Component getName() { - return Component.translatable("circuit.layout." + this.uid); - } - - @Override - public MutableComponent getUsage() { - return Component.translatable("circuit.layout." + this.uid + ".usage"); - } - - @Override - public ResourceLocation getSocketType() { - return this.socketType; - } -} diff --git a/src/main/java/forestry/core/circuits/CircuitManager.java b/src/main/java/forestry/core/circuits/CircuitManager.java index 1ec6955d38..075fd6d9bc 100644 --- a/src/main/java/forestry/core/circuits/CircuitManager.java +++ b/src/main/java/forestry/core/circuits/CircuitManager.java @@ -2,9 +2,11 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; -import forestry.api.circuits.*; +import forestry.api.circuits.CircuitHolder; +import forestry.api.circuits.CircuitLayout; +import forestry.api.circuits.ICircuit; +import forestry.api.circuits.ICircuitManager; import forestry.core.features.CoreItems; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; @@ -12,24 +14,22 @@ import java.util.List; public class CircuitManager implements ICircuitManager { - private final ImmutableMultimap circuitHolders; - private final ImmutableMap layoutsById; - private final ImmutableMap circuitsById; + private final ImmutableMultimap circuitHolders; + private final ImmutableMap layoutsById; - public CircuitManager(ImmutableMultimap circuitHolders, ImmutableMap layoutsById, ImmutableMap circuitsById) { + public CircuitManager(ImmutableMultimap circuitHolders, ImmutableMap layoutsById) { this.circuitHolders = circuitHolders; this.layoutsById = layoutsById; - this.circuitsById = circuitsById; } @Override - public List getLayouts() { + public List getLayouts() { return this.layoutsById.values().asList(); } @Nullable @Override - public ICircuit getCircuit(ICircuitLayout layout, ItemStack stack) { + public ICircuit getCircuit(CircuitLayout layout, ItemStack stack) { for (CircuitHolder holder : this.circuitHolders.get(layout)) { if (ItemStack.isSameItem(holder.stack(), stack)) { return holder.circuit(); @@ -40,23 +40,10 @@ public ICircuit getCircuit(ICircuitLayout layout, ItemStack stack) { @Nullable @Override - public ICircuit getCircuit(String circuitId) { - return this.circuitsById.get(circuitId); - } - - @Nullable - @Override - public ICircuitLayout getLayout(String layoutId) { + public CircuitLayout getLayout(String layoutId) { return this.layoutsById.get(layoutId); } - @Nullable - @Override - public ICircuitBoard getCircuitBoard(ItemStack stack) { - CompoundTag tag = stack.getTag(); - return tag == null ? null : new CircuitBoard(tag); - } - @Override public boolean isCircuitBoard(ItemStack stack) { return CoreItems.CIRCUITBOARDS.itemEqual(stack); diff --git a/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java b/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java index bd263e9226..2cc7fe263c 100755 --- a/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java +++ b/src/main/java/forestry/core/circuits/EnumCircuitBoardType.java @@ -1,23 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; import forestry.api.core.IItemSubtype; import forestry.core.render.ColourProperties; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraft.util.StringRepresentable; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.Locale; -public enum EnumCircuitBoardType implements IItemSubtype { +public enum EnumCircuitBoardType implements IItemSubtype, StringRepresentable { BASIC(1), ENHANCED(2), REFINED(3), @@ -35,6 +26,11 @@ public int getSockets() { return this.sockets; } + @Override + public String identifier() { + return this.name; + } + @Override public String getSerializedName() { return this.name; @@ -42,11 +38,11 @@ public String getSerializedName() { @OnlyIn(Dist.CLIENT) public int getPrimaryColor() { - return ColourProperties.INSTANCE.get("item.circuit." + name().toLowerCase(Locale.ENGLISH) + ".primary"); + return ColourProperties.INSTANCE.get("item.circuit." + this.name + ".primary"); } @OnlyIn(Dist.CLIENT) public int getSecondaryColor() { - return ColourProperties.INSTANCE.get("item.circuit." + name().toLowerCase(Locale.ENGLISH) + ".secondary"); + return ColourProperties.INSTANCE.get("item.circuit." + this.name + ".secondary"); } } diff --git a/src/main/java/forestry/core/circuits/GuiSolderingIron.java b/src/main/java/forestry/core/circuits/GuiSolderingIron.java index 07fd11926c..4a63dda62b 100755 --- a/src/main/java/forestry/core/circuits/GuiSolderingIron.java +++ b/src/main/java/forestry/core/circuits/GuiSolderingIron.java @@ -1,19 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; import forestry.api.IForestryApi; import forestry.api.circuits.ForestryCircuitSocketTypes; import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; import forestry.api.farming.HorizontalDirection; import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; @@ -28,10 +17,10 @@ import java.util.Locale; -public class GuiSolderingIron extends GuiForestry { +public class GuiSolderingIron extends GuiForestry { private final ItemInventorySolderingIron itemInventory; - public GuiSolderingIron(ContainerSolderingIron container, Inventory inv, Component title) { + public GuiSolderingIron(SolderingIronMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/solder.png", container, inv, title); this.itemInventory = container.getItemInventory(); @@ -61,7 +50,7 @@ protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseX, in graphics.drawString(this.font, description, this.leftPos + 32, this.topPos + 36 + row, ColourProperties.INSTANCE.get("gui.screen"), false); if (tube.isEmpty()) { - if (ForestryCircuitSocketTypes.FARM == layout.getSocketType()) { + if (ForestryCircuitSocketTypes.FARM == layout.socketType()) { Direction farmDirection = HorizontalDirection.VALUES.get(i); String farmDirectionString = farmDirection.toString().toLowerCase(Locale.ENGLISH); Component localizedDirection = Component.translatable("for.gui.solder." + farmDirectionString); @@ -75,11 +64,11 @@ protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseX, in public void init() { super.init(); - addRenderableWidget(Button.builder(Component.literal("<"), b -> ContainerSolderingIron.regressSelection(0)) + addRenderableWidget(Button.builder(Component.literal("<"), b -> SolderingIronMenu.regressSelection(0)) .pos(this.leftPos + 12, this.topPos + 10) .size(12, 18) .build()); - addRenderableWidget(Button.builder(Component.literal(">"), b -> ContainerSolderingIron.advanceSelection(0)) + addRenderableWidget(Button.builder(Component.literal(">"), b -> SolderingIronMenu.advanceSelection(0)) .pos(this.leftPos + 130, this.topPos + 10) .size(12, 18) .build()); diff --git a/src/main/java/forestry/core/circuits/ISocketable.java b/src/main/java/forestry/core/circuits/ISocketable.java index 57be708cd1..be2a069eb7 100644 --- a/src/main/java/forestry/core/circuits/ISocketable.java +++ b/src/main/java/forestry/core/circuits/ISocketable.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/forestry/core/circuits/ISolderingIron.java b/src/main/java/forestry/core/circuits/ISolderingIron.java deleted file mode 100755 index 06bd71ac03..0000000000 --- a/src/main/java/forestry/core/circuits/ISolderingIron.java +++ /dev/null @@ -1,15 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.circuits; - -// todo replace with tag -public interface ISolderingIron { -} diff --git a/src/main/java/forestry/core/circuits/ISpeedUpgradable.java b/src/main/java/forestry/core/circuits/ISpeedUpgradable.java index b6afc836e6..31208772bb 100644 --- a/src/main/java/forestry/core/circuits/ISpeedUpgradable.java +++ b/src/main/java/forestry/core/circuits/ISpeedUpgradable.java @@ -1,15 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; public interface ISpeedUpgradable { - void applySpeedUpgrade(double speedChange, double powerChange); + void applySpeedUpgrade(float speedChange, float powerChange); } diff --git a/src/main/java/forestry/core/circuits/ItemCircuitBoard.java b/src/main/java/forestry/core/circuits/ItemCircuitBoard.java index 106ac8cd73..43a1e9d1e8 100755 --- a/src/main/java/forestry/core/circuits/ItemCircuitBoard.java +++ b/src/main/java/forestry/core/circuits/ItemCircuitBoard.java @@ -1,37 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; import forestry.api.IForestryApi; +import forestry.api.circuits.CircuitLayout; import forestry.api.circuits.ICircuit; import forestry.api.circuits.ICircuitBoard; -import forestry.api.circuits.ICircuitLayout; +import forestry.core.features.CoreDataComponents; import forestry.core.features.CoreItems; import forestry.core.items.ItemForestry; import forestry.core.items.definitions.IColoredItem; -import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.List; +import java.util.Optional; public class ItemCircuitBoard extends ItemForestry implements IColoredItem { private final EnumCircuitBoardType type; public ItemCircuitBoard(EnumCircuitBoardType type) { + super(new Properties().component(CoreDataComponents.CIRCUIT_BOARD, new CircuitBoard(type, Optional.empty(), List.of()))); this.type = type; } @@ -50,18 +41,17 @@ public int getColorFromItemStack(ItemStack itemstack, int tintIndex) { } @Override - public void appendHoverText(ItemStack stack, @Nullable Level world, List list, TooltipFlag flag) { - ICircuitBoard circuitboard = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(stack); - if (circuitboard != null) { - circuitboard.addTooltip(list); + public void appendHoverText(ItemStack stack, @Nullable TooltipContext ctx, List list, TooltipFlag flag) { + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard board = stack.get(CoreDataComponents.CIRCUIT_BOARD); + if (board != null) { + board.addTooltip(list); } } - public static ItemStack createCircuitboard(EnumCircuitBoardType type, @Nullable ICircuitLayout layout, ICircuit[] circuits) { - CompoundTag compoundNBT = new CompoundTag(); - new CircuitBoard(type, layout, circuits).write(compoundNBT); + public static ItemStack createCircuitboard(EnumCircuitBoardType type, CircuitLayout layout, List circuits) { ItemStack stack = CoreItems.CIRCUITBOARDS.stack(type, 1); - stack.setTag(compoundNBT); + stack.set(CoreDataComponents.CIRCUIT_BOARD, new CircuitBoard(type, Optional.of(layout), circuits)); return stack; } diff --git a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java b/src/main/java/forestry/core/circuits/SolderingIronMenu.java old mode 100755 new mode 100644 similarity index 50% rename from src/main/java/forestry/core/circuits/ContainerSolderingIron.java rename to src/main/java/forestry/core/circuits/SolderingIronMenu.java index dd78a38f1b..b7686ddfb1 --- a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java +++ b/src/main/java/forestry/core/circuits/SolderingIronMenu.java @@ -1,43 +1,32 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.circuits; -import forestry.api.circuits.ICircuitLayout; +import forestry.api.circuits.CircuitLayout; import forestry.api.modules.IForestryPacketClient; -import forestry.api.modules.IForestryPacketServer; import forestry.core.features.CoreMenuTypes; -import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.IGuiSelectable; +import forestry.core.gui.ItemInventoryMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.inventory.ItemInventorySolderingIron; import forestry.core.network.packets.PacketGuiLayoutSelect; -import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.utils.NetworkUtil; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; +import net.neoforged.neoforge.network.PacketDistributor; -public class ContainerSolderingIron extends ContainerItemInventory implements IGuiSelectable { - public static ContainerSolderingIron fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { +public class SolderingIronMenu extends ItemInventoryMenu implements IGuiSelectable { + public static SolderingIronMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { InteractionHand hand = extraData.readBoolean() ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; Player player = playerInv.player; - ItemInventorySolderingIron inv = new ItemInventorySolderingIron(player, player.getItemInHand(hand)); - return new ContainerSolderingIron(windowId, player, inv); + ItemInventorySolderingIron inv = new ItemInventorySolderingIron(player.getItemInHand(hand)); + return new SolderingIronMenu(windowId, player, inv); } - public ContainerSolderingIron(int windowId, Player player, ItemInventorySolderingIron inventory) { - super(windowId, inventory, player.getInventory(), 8, 123, CoreMenuTypes.SOLDERING_IRON.menuType()); + public SolderingIronMenu(int windowId, Inventory playerInv, ItemInventorySolderingIron inventory) { + super(CoreMenuTypes.SOLDERING_IRON.menuType(), windowId, inventory, playerInv, 8, 123); // Input this.addSlot(new SlotFiltered(inventory, 0, 152, 12)); @@ -52,7 +41,7 @@ public ContainerSolderingIron(int windowId, Player player, ItemInventorySolderin this.addSlot(new SlotFiltered(inventory, 5, 12, 92)); } - public ICircuitLayout getLayout() { + public CircuitLayout getLayout() { return this.inventory.getLayout(); } @@ -65,25 +54,24 @@ public static void regressSelection(int index) { } private static void sendSelectionChange(int index, int advance) { - IForestryPacketServer packet = new PacketGuiSelectRequest(index, advance); - NetworkUtil.sendToServer(packet); + NetworkUtil.sendRecipeClick(index, advance); } @Override public void handleSelectionRequest(ServerPlayer player, int primary, int secondary) { if (secondary == 0) { if (primary == 0) { - this.inventory.advanceLayout(); + this.inventory.advanceLayout(); } } else if (primary == 0) { - this.inventory.regressLayout(); + this.inventory.regressLayout(); } - IForestryPacketClient packetResponse = new PacketGuiLayoutSelect(this.inventory.getLayout().getId()); - NetworkUtil.sendToPlayer(packetResponse, player); + IForestryPacketClient packetResponse = new PacketGuiLayoutSelect(this.inventory.getLayout().id()); + PacketDistributor.sendToPlayer(player, packetResponse); } - public void setLayout(ICircuitLayout layout) { - this.inventory.setLayout(layout); + public void setLayout(CircuitLayout layout) { + this.inventory.setLayout(layout); } } diff --git a/src/main/java/forestry/core/circuits/package-info.java b/src/main/java/forestry/core/circuits/package-info.java index 2bf939ac26..90c3c05ad8 100644 --- a/src/main/java/forestry/core/circuits/package-info.java +++ b/src/main/java/forestry/core/circuits/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.circuits; diff --git a/src/main/java/forestry/core/client/CoreClientHandler.java b/src/main/java/forestry/core/client/CoreClientHandler.java index 668cc1fedc..112d648919 100644 --- a/src/main/java/forestry/core/client/CoreClientHandler.java +++ b/src/main/java/forestry/core/client/CoreClientHandler.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.client; import com.mojang.blaze3d.vertex.DefaultVertexFormat; @@ -16,8 +6,8 @@ import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.datafixers.util.Pair; import forestry.api.ForestryConstants; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBeeSpecies; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBeeSpecies; import forestry.api.client.IClientModuleHandler; import forestry.api.client.IForestryClientApi; import forestry.api.client.apiculture.IBeeClientManager; @@ -37,7 +27,7 @@ import forestry.core.models.ClientManager; import forestry.core.models.FluidContainerModel; import forestry.core.models.ModelBlockCached; -import forestry.core.particles.CoreParticles; +import forestry.core.features.CoreParticles; import forestry.core.render.*; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.RenderUtil; @@ -50,8 +40,8 @@ import forestry.storage.features.BackpackItems; import forestry.storage.features.CrateItems; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.renderer.*; +import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Unit; @@ -60,18 +50,17 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.client.event.*; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.neoforge.client.event.*; +import net.neoforged.neoforge.common.NeoForge; import java.awt.*; import java.util.Map; import java.util.OptionalDouble; public class CoreClientHandler implements IClientModuleHandler { - public static BlockEntityWithoutLevelRenderer bewlr; // Copied from RenderStateShard.java (just LINES but with NO_DEPTH_TEST) public static final RenderType RENDER_TYPE_LINES_XRAY = RenderType.create("lines_xray", DefaultVertexFormat.POSITION_COLOR_NORMAL, VertexFormat.Mode.LINES, 256, false, false, RenderType.CompositeState.builder() .setShaderState(RenderStateShard.RENDERTYPE_LINES_SHADER) @@ -84,9 +73,12 @@ public class CoreClientHandler implements IClientModuleHandler { .setDepthTestState(RenderStateShard.NO_DEPTH_TEST) .createCompositeState(false)); + public static BlockEntityWithoutLevelRenderer bewlr; + @Override public void registerEvents(IEventBus modBus) { modBus.addListener(CoreClientHandler::onClientSetup); + modBus.addListener(CoreClientHandler::registerMenus); modBus.addListener(CoreClientHandler::registerModelLoaders); modBus.addListener(CoreClientHandler::additionalBakedModels); modBus.addListener(CoreClientHandler::bakeModels); @@ -96,7 +88,7 @@ public void registerEvents(IEventBus modBus) { modBus.addListener(CoreClientHandler::registerBlockColors); modBus.addListener(CoreClientHandler::registerItemColors); modBus.addListener(CoreClientHandler::registerParticleFactory); - MinecraftForge.EVENT_BUS.addListener(CoreClientHandler::onClientTick); + NeoForge.EVENT_BUS.addListener(CoreClientHandler::onClientTick); ModuleUtil.getModBus(ForestryConstants.MOD_ID).addListener(EventPriority.HIGHEST, ((ForestryClientApiImpl) IForestryClientApi.INSTANCE)::initializeTextureManager); } @@ -109,19 +101,21 @@ private static void onClientSetup(FMLClientSetupEvent event) { ItemBlockRenderTypes.setRenderLayer(fluid.getFluid(), RenderType.translucent()); ItemBlockRenderTypes.setRenderLayer(fluid.getFlowing(), RenderType.translucent()); } - - MenuScreens.register(CoreMenuTypes.ALYZER.menuType(), GuiAlyzer::new); - MenuScreens.register(CoreMenuTypes.ANALYZER.menuType(), GuiAnalyzer::new); - MenuScreens.register(CoreMenuTypes.NATURALIST_INVENTORY.menuType(), GuiNaturalistInventory::new); - MenuScreens.register(CoreMenuTypes.ESCRITOIRE.menuType(), GuiEscritoire::new); - MenuScreens.register(CoreMenuTypes.SOLDERING_IRON.menuType(), GuiSolderingIron::new); }); bewlr = new ForestryBewlr(Minecraft.getInstance().getBlockEntityRenderDispatcher()); } + private static void registerMenus(RegisterMenuScreensEvent event) { + event.register(CoreMenuTypes.ALYZER.menuType(), PortableAnalyzerScreen::new); + event.register(CoreMenuTypes.ANALYZER.menuType(), GuiAnalyzer::new); + event.register(CoreMenuTypes.NATURALIST_INVENTORY.menuType(), GuiNaturalistInventory::new); + event.register(CoreMenuTypes.ESCRITOIRE.menuType(), GuiEscritoire::new); + event.register(CoreMenuTypes.SOLDERING_IRON.menuType(), GuiSolderingIron::new); + } + private static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register("fluid_container", FluidContainerModel.Loader.INSTANCE); + event.register(ForestryConstants.forestry("fluid_container"), FluidContainerModel.Loader.INSTANCE); PluginManager.registerClient(); } @@ -133,15 +127,16 @@ private static void additionalBakedModels(ModelEvent.RegisterAdditional event) { Map models = beeManager.getBeeModels(stage); for (IBeeSpecies species : SpeciesUtil.getAllBeeSpecies()) { - event.register(models.get(species)); + event.register(ModelResourceLocation.inventory(models.get(species))); } } ITreeClientManager treeManager = IForestryClientApi.INSTANCE.getTreeManager(); for (Pair pair : treeManager.getAllSaplingModels()) { - event.register(pair.getFirst()); - event.register(pair.getSecond()); + // wrap for now, if the need to specify model variant comes up, it can be added later + event.register(ModelResourceLocation.inventory(pair.getFirst())); + event.register(ModelResourceLocation.inventory(pair.getSecond())); } } @@ -191,7 +186,7 @@ private static void registerReloadListeners(RegisterClientReloadListenersEvent e } private static void registerParticleFactory(RegisterParticleProvidersEvent event) { - event.registerSpriteSet(CoreParticles.REFRACTORY_WAX.get(), RefractoryWaxParticle::new); + event.registerSpriteSet(CoreParticles.REFRACTORY_WAX.value(), RefractoryWaxParticle::new); } private static void registerBlockColors(RegisterColorHandlersEvent.Block event) { @@ -232,8 +227,8 @@ private static void registerItemColors(RegisterColorHandlersEvent.Item event) { event.register(ClientManager.FORESTRY_ITEM_COLOR, ArboricultureItems.POLLEN_FERTILE.item()); // Lepidopterology - event.register(ClientManager.FORESTRY_ITEM_COLOR, LepidopterologyItems.CATERPILLAR_GE.item()); - event.register(ClientManager.FORESTRY_ITEM_COLOR, LepidopterologyItems.SERUM_GE.item()); + event.register(ClientManager.FORESTRY_ITEM_COLOR, LepidopterologyItems.CATERPILLAR.item()); + event.register(ClientManager.FORESTRY_ITEM_COLOR, LepidopterologyItems.SERUM.item()); // Backpacks event.register(ClientManager.FORESTRY_ITEM_COLOR, @@ -287,7 +282,7 @@ private static void onClientTick(RenderLevelStageEvent event) { BlockPos playerPos = minecraft.player.blockPosition(); ChunkPos playerChunkPos = new ChunkPos(playerPos); - Color color = RenderUtil.getRainbowColor(minecraft.level.getGameTime(), event.getPartialTick()); + Color color = RenderUtil.getRainbowColor(minecraft.level.getGameTime(), event.getPartialTick().getGameTimeDeltaPartialTick(true)); float r = color.getRed() / 255f; float g = color.getGreen() / 255f; diff --git a/src/main/java/forestry/core/client/package-info.java b/src/main/java/forestry/core/client/package-info.java index 5b59673f0f..b73d2c1b3e 100644 --- a/src/main/java/forestry/core/client/package-info.java +++ b/src/main/java/forestry/core/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.client; diff --git a/src/main/java/forestry/core/climate/ClimateProvider.java b/src/main/java/forestry/core/climate/ClimateProvider.java index 3d6707955e..b4315a98a7 100644 --- a/src/main/java/forestry/core/climate/ClimateProvider.java +++ b/src/main/java/forestry/core/climate/ClimateProvider.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.climate; import forestry.api.IForestryApi; @@ -17,6 +7,7 @@ import forestry.api.core.TemperatureType; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.biome.Biome; @@ -28,7 +19,7 @@ public ClimateProvider(LevelReader level, BlockPos pos) { } @Override - public Holder getBiome() { + public Holder getBiome(HolderLookup.Provider registries) { return this.biome; } diff --git a/src/main/java/forestry/core/climate/ForestryClimateManager.java b/src/main/java/forestry/core/climate/ForestryClimateManager.java index f28702f3c7..5d16f84371 100644 --- a/src/main/java/forestry/core/climate/ForestryClimateManager.java +++ b/src/main/java/forestry/core/climate/ForestryClimateManager.java @@ -22,8 +22,7 @@ public class ForestryClimateManager implements IClimateManager { @Override public TemperatureType getTemperature(Holder biome) { - // avoid Optional creation if possible - return getTemperature(biome instanceof Holder.Reference reference ? reference.key() : biome.unwrapKey().get()); + return getTemperature(biome.getKey()); } @Override @@ -33,8 +32,7 @@ public TemperatureType getTemperature(ResourceKey biome) { @Override public HumidityType getHumidity(Holder biome) { - // avoid Optional creation if possible - return getHumidity(biome instanceof Holder.Reference reference ? reference.key() : biome.unwrapKey().get()); + return getHumidity(biome.getKey()); } @Override diff --git a/src/main/java/forestry/core/climate/package-info.java b/src/main/java/forestry/core/climate/package-info.java index dd8b050fc8..24c84ff7d1 100644 --- a/src/main/java/forestry/core/climate/package-info.java +++ b/src/main/java/forestry/core/climate/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.climate; diff --git a/src/main/java/forestry/core/commands/CommandSaveStats.java b/src/main/java/forestry/core/commands/CommandSaveStats.java index cd38bf0f51..5d977179cd 100644 --- a/src/main/java/forestry/core/commands/CommandSaveStats.java +++ b/src/main/java/forestry/core/commands/CommandSaveStats.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.commands; import com.mojang.brigadier.Command; @@ -25,7 +15,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; import java.io.*; import java.nio.charset.StandardCharsets; diff --git a/src/main/java/forestry/core/commands/DiagnosticsCommand.java b/src/main/java/forestry/core/commands/DiagnosticsCommand.java index a7fe41f5ce..b2e5cf9f8d 100644 --- a/src/main/java/forestry/core/commands/DiagnosticsCommand.java +++ b/src/main/java/forestry/core/commands/DiagnosticsCommand.java @@ -13,8 +13,8 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.loading.FMLEnvironment; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; import java.util.Collection; import java.util.List; diff --git a/src/main/java/forestry/core/commands/DumpCommand.java b/src/main/java/forestry/core/commands/DumpCommand.java index 16b427e243..6e0c278885 100644 --- a/src/main/java/forestry/core/commands/DumpCommand.java +++ b/src/main/java/forestry/core/commands/DumpCommand.java @@ -7,8 +7,8 @@ import com.mojang.brigadier.context.CommandContext; import forestry.Forestry; import forestry.api.IForestryApi; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.api.climate.IClimateManager; import forestry.api.core.HumidityType; import forestry.api.core.TemperatureType; @@ -124,7 +124,7 @@ private static int backpacks(CommandContext ctx) { Forestry.LOGGER.debug("Listing Forestry backpack filters for {} backpack types (excluding Naturalist bags)", definitions.size()); for (FeatureItem backpack : definitions) { - Predicate filter = backpack.get().getDefinition().getFilter(); + Predicate filter = backpack.get().getDefinition().filter(); ArrayList allowedItems = new ArrayList<>(); for (Item item : ctx.getSource().registryAccess().registryOrThrow(Registries.ITEM)) { diff --git a/src/main/java/forestry/core/commands/IStatsSaveHelper.java b/src/main/java/forestry/core/commands/IStatsSaveHelper.java index 8c4ecc356c..172bb34818 100644 --- a/src/main/java/forestry/core/commands/IStatsSaveHelper.java +++ b/src/main/java/forestry/core/commands/IStatsSaveHelper.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.commands; import com.mojang.authlib.GameProfile; diff --git a/src/main/java/forestry/core/commands/package-info.java b/src/main/java/forestry/core/commands/package-info.java index 66fb2b16d8..a277d88837 100644 --- a/src/main/java/forestry/core/commands/package-info.java +++ b/src/main/java/forestry/core/commands/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.commands; diff --git a/src/main/java/forestry/core/config/Constants.java b/src/main/java/forestry/core/config/Constants.java index 9c930d35f8..29ffe8b759 100644 --- a/src/main/java/forestry/core/config/Constants.java +++ b/src/main/java/forestry/core/config/Constants.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.config; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidType; public class Constants { // System @@ -31,32 +21,6 @@ public class Constants { public static final int APIARY_MIN_LEVEL_LIGHT = 11; public static final int APIARY_BREEDING_TIME = 100; - // Energy - public static final int ENGINE_TANK_CAPACITY = 10 * FluidType.BUCKET_VOLUME; - public static final int ENGINE_CYCLE_DURATION_WATER = 1000; - public static final int ENGINE_CYCLE_DURATION_JUICE = 2500; - public static final int ENGINE_CYCLE_DURATION_HONEY = 2500; - public static final int ENGINE_CYCLE_DURATION_MILK = 10000; - public static final int ENGINE_CYCLE_DURATION_SEED_OIL = 2500; - public static final int ENGINE_CYCLE_DURATION_BIOMASS = 2500; - public static final int ENGINE_CYCLE_DURATION_ETHANOL = 15000; - public static final int ENGINE_FUEL_VALUE_WATER = 10; - public static final int ENGINE_FUEL_VALUE_JUICE = 10; - public static final int ENGINE_FUEL_VALUE_HONEY = 20; - public static final int ENGINE_FUEL_VALUE_MILK = 10; - public static final int ENGINE_FUEL_VALUE_SEED_OIL = 30; - public static final int ENGINE_FUEL_VALUE_BIOMASS = 50; - public static final int ENGINE_HEAT_VALUE_LAVA = 20; - - public static final float ENGINE_PISTON_SPEED_MAX = 0.08f; - - public static final int ENGINE_COPPER_CYCLE_DURATION_PEAT = 2500; - public static final int ENGINE_COPPER_FUEL_VALUE_PEAT = 20; - public static final int ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT = 3000; - public static final int ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT = 40; - public static final int ENGINE_COPPER_HEAT_MAX = 10000; - public static final int ENGINE_COPPER_ASH_FOR_ITEM = 7500; - // Factory public static final int PROCESSOR_TANK_CAPACITY = 10 * FluidType.BUCKET_VOLUME; diff --git a/src/main/java/forestry/core/config/ForestryConfig.java b/src/main/java/forestry/core/config/ForestryConfig.java index d0e0173983..443afa0183 100644 --- a/src/main/java/forestry/core/config/ForestryConfig.java +++ b/src/main/java/forestry/core/config/ForestryConfig.java @@ -1,37 +1,30 @@ package forestry.core.config; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.fml.ModLoadingContext; -import net.minecraftforge.fml.config.ModConfig; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.config.ModConfig; +import net.neoforged.neoforge.common.ModConfigSpec; import org.apache.commons.lang3.tuple.Pair; public class ForestryConfig { - private static final ForgeConfigSpec CLIENT_SPEC; - private static final ForgeConfigSpec COMMON_SPEC; - private static final ForgeConfigSpec SERVER_SPEC; + private static final ModConfigSpec CLIENT_SPEC; + private static final ModConfigSpec SERVER_SPEC; + public static final Client CLIENT; - public static final Common COMMON; public static final Server SERVER; - public static class Common { - public Common(ForgeConfigSpec.Builder builder) { - - } - } - public static class Client { // Misc - public final ForgeConfigSpec.BooleanValue showParticles; - public final ForgeConfigSpec.BooleanValue enableHints; - public final ForgeConfigSpec.BooleanValue enableGlints; + public final ModConfigSpec.BooleanValue showParticles; + public final ModConfigSpec.BooleanValue enableHints; + public final ModConfigSpec.BooleanValue enableGlints; // Mail - public final ForgeConfigSpec.BooleanValue mailAlertsEnabled; + public final ModConfigSpec.BooleanValue mailAlertsEnabled; // JEI Bees - public final ForgeConfigSpec.BooleanValue showRequirements; - public final ForgeConfigSpec.BooleanValue showSecretMutations; - public final ForgeConfigSpec.BooleanValue identifyGenome; + public final ModConfigSpec.BooleanValue showRequirements; + public final ModConfigSpec.BooleanValue showSecretMutations; + public final ModConfigSpec.BooleanValue identifyGenome; - public Client(ForgeConfigSpec.Builder builder) { + public Client(ModConfigSpec.Builder builder) { this.showParticles = builder .comment("Whether any of Forestry's particles are rendered.") .define("particles", true); @@ -62,31 +55,38 @@ public Client(ForgeConfigSpec.Builder builder) { public static class Server { // Genetics - public final ForgeConfigSpec.DoubleValue researchMutationBoostMultiplier; - public final ForgeConfigSpec.DoubleValue maxResearchMutationBoostPercent; + public final ModConfigSpec.DoubleValue researchMutationBoostMultiplier; + public final ModConfigSpec.DoubleValue maxResearchMutationBoostPercent; // Bees - public final ForgeConfigSpec.BooleanValue pollinateVanillaLeaves; - public final ForgeConfigSpec.DoubleValue wildHiveSpawnRate; - public final ForgeConfigSpec.BooleanValue useHaploidDrones; + public final ModConfigSpec.BooleanValue pollinateVanillaLeaves; + public final ModConfigSpec.DoubleValue wildHiveSpawnRate; + public final ModConfigSpec.BooleanValue wildHiveDamage; + public final ModConfigSpec.BooleanValue wildHivePeacefulDamage; + public final ModConfigSpec.BooleanValue wildHiveDamageMobs; + public final ModConfigSpec.BooleanValue wildHivesDamageUnderwater; + public final ModConfigSpec.BooleanValue useHaploidDrones; // Trees - public final ForgeConfigSpec.DoubleValue treesSpawnNaturally; + public final ModConfigSpec.DoubleValue treeSpawnChanceMultiplier; + public final ModConfigSpec.BooleanValue treesSelfPollination; // Butterflies - public final ForgeConfigSpec.BooleanValue disableButterflySpawning; - public final ForgeConfigSpec.IntValue butterflyClusterLimit; - public final ForgeConfigSpec.IntValue butterflyClusterWidth; - public final ForgeConfigSpec.IntValue butterflyClusterHeight; + public final ModConfigSpec.BooleanValue disableButterflySpawning; + public final ModConfigSpec.IntValue butterflyClusterLimit; + public final ModConfigSpec.IntValue butterflyClusterWidth; + public final ModConfigSpec.IntValue butterflyClusterHeight; // Farms - public final ForgeConfigSpec.IntValue multiFarmSize; - public final ForgeConfigSpec.BooleanValue squareMultiFarms; - public final ForgeConfigSpec.IntValue legacyFarmsPlanterRings; - public final ForgeConfigSpec.BooleanValue legacyFarmsUseRings; - public final ForgeConfigSpec.IntValue legacyFarmsRingSize; + public final ModConfigSpec.IntValue multiFarmFertilizerModifier; + public final ModConfigSpec.IntValue multiFarmSize; + public final ModConfigSpec.BooleanValue squareMultiFarms; + public final ModConfigSpec.IntValue legacyFarmFertilizerModifier; + public final ModConfigSpec.IntValue legacyFarmsPlanterRings; + public final ModConfigSpec.BooleanValue legacyFarmsUseRings; + public final ModConfigSpec.IntValue legacyFarmsRingSize; // Misc - public final ForgeConfigSpec.BooleanValue enableBackpackResupply; - public final ForgeConfigSpec.BooleanValue spawnTinOre; - public final ForgeConfigSpec.BooleanValue spawnApatiteOre; + public final ModConfigSpec.BooleanValue enableBackpackResupply; + public final ModConfigSpec.BooleanValue spawnTinOre; + public final ModConfigSpec.BooleanValue spawnApatiteOre; - public Server(ForgeConfigSpec.Builder builder) { + public Server(ModConfigSpec.Builder builder) { // Genetics builder.push("genetics"); this.researchMutationBoostMultiplier = builder @@ -102,22 +102,48 @@ public Server(ForgeConfigSpec.Builder builder) { this.pollinateVanillaLeaves = builder .comment("Whether bees and butterflies can pollinate Vanilla leaves. Might be undesirable for builds that rely on leaves.") .define("pollinate_vanilla_leaves", true); - this.wildHiveSpawnRate = builder - .comment("The base chance for a wild beehive to spawn naturally.") - .defineInRange("wild_hive_spawn_rate", 1.0, 0.0, 1000.0); this.useHaploidDrones = builder .comment("In real life, drone bees are haploid, which means they only carry one set of chromosomes. If this option is enabled, only a drone's active alleles will be used for inheritance, making drones effectively haploid. This CHANGES Forestry's bee breeding mechanics.") .define("use_haploid_drones", false); builder.pop(); - // Farming - builder.push("farming"); + // Wild Bee Hives + builder.push("wild_bee_hives"); + this.wildHiveSpawnRate = builder + .comment("The base chance for a wild beehive to spawn naturally.") + .defineInRange("wild_hive_spawn_rate", 1.0, 0.0, 1000.0); + this.wildHiveDamage = builder + .comment("Whether wild bees will deal damage when chasing after an entity.") + .define("wild_hives_damage_on_attack", true); + this.wildHivePeacefulDamage = builder + .comment("Whether wild bees will deal damage on Peaceful difficulty.") + .define("wild_hives_damage_in_peaceful", false); + this.wildHiveDamageMobs = builder + .comment("Whether wild bees can deal damage to non-player entities, like animals.") + .define("wild_hives_damage_players_only", false); + this.wildHivesDamageUnderwater = builder + .comment("Whether wild bees can deal damage to entities that are underwater.") + .define("wild_hives_damage_underwater", true); + builder.pop(); + + // Multifarms + builder.push("multiblock_farm"); + this.multiFarmFertilizerModifier = builder + .comment("Determines how much fertilizer value a multiblock farm uses when harvesting a block. For reference, 1 Fertilizer = 100 fertilizer value by default.") + .defineInRange("multiblock_farm_fertilizer_modifier", 4, 1, 10000); this.multiFarmSize = builder .comment("") .defineInRange("multiblock_farm_size", 2, 1, 10); this.squareMultiFarms = builder .comment("Whether Forestry multiblock farms have square shaped farmlands instead of the default diamond shape.") .define("square_multiblock_farms", false); + builder.pop(); + + // Legacy farms + builder.push("legacy_farm"); + this.legacyFarmFertilizerModifier = builder + .comment("Determines how much fertilizer value a legacy (single block) farm uses when harvesting a block. For reference, 1 Fertilizer = 100 fertilizer value by default.") + .defineInRange("legacy_farm_fertilizer_modifier", 4, 1, 10000); this.legacyFarmsPlanterRings = builder .comment("Sets the size of the farmland that is used by all legacy (single block) farms.") .defineInRange("legacy_farms_planter_rings", 4, 1, 10); @@ -125,15 +151,18 @@ public Server(ForgeConfigSpec.Builder builder) { .comment("Whether legacy (single block) farms use a ring layout. The farmland size of the ring layout is always one block smaller.") .define("legacy_farms_use_rings", true); this.legacyFarmsRingSize = builder - .comment("Sets the size of the inner ring of the ring layout.") + .comment("Sets the size of the inner ring of the ring layout used by legacy (single block) farms.") .defineInRange("legacy_farms_ring_size", 4, 1, 10); builder.pop(); // Trees builder.push("trees"); - this.treesSpawnNaturally = builder - .comment("Multiplies the chance of a Forestry tree spawning in the wild. Set to 0 to disable Forestry tree spawning.") + this.treeSpawnChanceMultiplier = builder + .comment("The chance of a Forestry tree spawning in the wild. 0 means Forestry tree spawning is disabled. 1 means default spawn chances.") .defineInRange("tree_spawn_chance_modifier", 0.0f, 0.0f, 1000000.0f); + this.treesSelfPollination = builder + .comment("Whether a tree leaf can be pollinated by its own pollen. Defaults to false because this behavior can be annoying.") + .define("tree_self_pollination", false); builder.pop(); // Butterflies @@ -156,34 +185,31 @@ public Server(ForgeConfigSpec.Builder builder) { this.enableBackpackResupply = builder .comment("Whether backpacks can have their resupply mode enabled, which stocks a player's inventory using blocks from the backpack's inventory.") .define("enable_backpack_resupply", true); + + builder.push("world_generation"); this.spawnTinOre = builder .comment("Whether Tin Ore veins generate naturally in the Overworld.") .define("spawn_tin_ore", true); this.spawnApatiteOre = builder .comment("Whether Apatite Ore veins generate naturally in the Overworld.") .define("spawn_apatite_ore", true); + builder.pop(); } } - public static void register(ModLoadingContext ctx) { + public static void register(ModContainer ctx) { ctx.registerConfig(ModConfig.Type.SERVER, SERVER_SPEC); - ctx.registerConfig(ModConfig.Type.COMMON, COMMON_SPEC); ctx.registerConfig(ModConfig.Type.CLIENT, CLIENT_SPEC); } static { { - Pair specPair = new ForgeConfigSpec.Builder().configure(Client::new); + Pair specPair = new ModConfigSpec.Builder().configure(Client::new); CLIENT = specPair.getLeft(); CLIENT_SPEC = specPair.getRight(); } { - Pair specPair = new ForgeConfigSpec.Builder().configure(Common::new); - COMMON = specPair.getLeft(); - COMMON_SPEC = specPair.getRight(); - } - { - Pair specPair = new ForgeConfigSpec.Builder().configure(Server::new); + Pair specPair = new ModConfigSpec.Builder().configure(Server::new); SERVER = specPair.getLeft(); SERVER_SPEC = specPair.getRight(); } diff --git a/src/main/java/forestry/core/config/Preference.java b/src/main/java/forestry/core/config/Preference.java deleted file mode 100644 index 991d5aebf7..0000000000 --- a/src/main/java/forestry/core/config/Preference.java +++ /dev/null @@ -1,16 +0,0 @@ -package forestry.core.config; - -// TODO: Remove entirely -public class Preference { - - public static final float ENERGY_DEMAND_MODIFIER = 1; - - public static final int FARM_FERTILIZER_MODIFIER = 4; - public static final int FERMENTATION_DURATION_FERTILIZER = 200; - public static final int FERMENTATION_DURATION_COMPOST = 250; - public static final int FERMENTED_CYCLE_FERTILIZER = 56; - public static final int FERMENTED_CYCLE_COMPOST = 48; - public static final int SQUEEZED_LIQUID_SEED = 10; - public static final int SQUEEZED_LIQUID_APPLE = 200; - public static final float SQUEEZED_MULCH_APPLE = 0.2f; -} diff --git a/src/main/java/forestry/core/config/SessionVars.java b/src/main/java/forestry/core/config/SessionVars.java index 1b5e3b9e2a..9083ccd87b 100755 --- a/src/main/java/forestry/core/config/SessionVars.java +++ b/src/main/java/forestry/core/config/SessionVars.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.config; import javax.annotation.Nullable; @@ -15,8 +5,7 @@ import java.util.Map; public class SessionVars { - - private static final Map stringVars = new HashMap<>(); + private static final HashMap stringVars = new HashMap<>(); @Nullable private static Class openedLedger; diff --git a/src/main/java/forestry/core/config/package-info.java b/src/main/java/forestry/core/config/package-info.java index 486c4c33b0..e04c14d731 100644 --- a/src/main/java/forestry/core/config/package-info.java +++ b/src/main/java/forestry/core/config/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.config; diff --git a/src/main/java/forestry/core/data/Data.java b/src/main/java/forestry/core/data/Data.java index 860d1e345e..367d155645 100644 --- a/src/main/java/forestry/core/data/Data.java +++ b/src/main/java/forestry/core/data/Data.java @@ -1,36 +1,36 @@ package forestry.core.data; -import forestry.api.ForestryConstants; -import forestry.api.IForestryApi; -import forestry.apiimpl.plugin.PluginManager; -import forestry.core.data.models.ForestryBlockStateProvider; -import forestry.core.data.models.ForestryItemModelProvider; -import forestry.core.data.models.ForestryWoodModelProvider; -import forestry.core.data.recipe.ForestryRecipeProvider; -import forestry.modules.ForestryModuleManager; +import java.util.concurrent.CompletableFuture; + import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.data.DataGenerator; import net.minecraft.data.PackOutput; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.data.event.GatherDataEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import thedarkcolour.modkit.data.DataHelper; -import java.util.concurrent.CompletableFuture; +import forestry.api.ForestryConstants; +import forestry.apiimpl.plugin.PluginManager; +import forestry.core.data.models.ForestryBlockStateProvider; +import forestry.core.data.models.ForestryWoodModelProvider; +import forestry.core.data.recipe.CoreRecipes; -@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.data.event.GatherDataEvent; +import thedarkcolour.modkit.data.DataHelper; + +@EventBusSubscriber(bus = EventBusSubscriber.Bus.MOD) public class Data { @SubscribeEvent public static void gatherData(GatherDataEvent event) { - preDataGen(); + // Hack fix to make API work in data generation environment + PluginManager.registerClient(); DataGenerator generator = event.getGenerator(); PackOutput output = generator.getPackOutput(); ExistingFileHelper existingFileHelper = event.getExistingFileHelper(); DataHelper dataHelper = new DataHelper(ForestryConstants.MOD_ID, event); - CompletableFuture lookup = event.getLookupProvider(); + CompletableFuture registries = event.getLookupProvider(); dataHelper.createTags(Registries.BLOCK, ForestryBlockTagsProvider::addTags); dataHelper.createTags(Registries.ITEM, (tags, l) -> { @@ -41,25 +41,18 @@ public static void gatherData(GatherDataEvent event) { dataHelper.createTags(Registries.FLUID, ForestryFluidTagsProvider::addTags); dataHelper.createTags(Registries.POINT_OF_INTEREST_TYPE, ForestryPoiTypeTagProvider::addTags); dataHelper.createTags(Registries.PAINTING_VARIANT, ForestryPaintingTagsProvider::addTags); - dataHelper.createRecipes(ForestryRecipeProvider::addRecipes); + dataHelper.createRecipes(CoreRecipes::addRecipes); dataHelper.createDamageTypes(ForestryDamageTypesProvider::addTypes); dataHelper.createItemModels(false, false, false, ForestryItemModels::addModels); - generator.addProvider(event.includeServer(), new ForestryAdvancementProvider(output, lookup, existingFileHelper)); + generator.addProvider(event.includeServer(), new ForestryAdvancementProvider(output, registries, existingFileHelper)); generator.addProvider(event.includeServer(), new ForestryLootTableProvider(output)); - generator.addProvider(event.includeServer(), new ForestryLootModifierProvider(output)); + generator.addProvider(event.includeServer(), new ForestryLootModifierProvider(output, registries)); generator.addProvider(event.includeClient(), new ForestryBlockStateProvider(output, existingFileHelper)); generator.addProvider(event.includeClient(), new ForestryWoodModelProvider(output, existingFileHelper)); - generator.addProvider(event.includeClient(), new ForestryItemModelProvider(output, existingFileHelper)); - generator.addProvider(event.includeClient(), new ForestryAtlasProvider(output, existingFileHelper)); - generator.addProvider(event.includeServer(), new ForestryFeaturesProvider(output, lookup)); - generator.addProvider(event.includeClient(), new ForestryCuriosProvider(output, existingFileHelper, lookup)); - } - - // Hack fix to make API work in data generation environment - public static void preDataGen() { - ((ForestryModuleManager) IForestryApi.INSTANCE.getModuleManager()).setupApi(); - - PluginManager.registerClient(); + generator.addProvider(event.includeClient(), new ForestryAtlasProvider(output, registries, existingFileHelper)); + generator.addProvider(event.includeServer(), new ForestryFeaturesProvider(output, registries)); + generator.addProvider(event.includeClient(), new ForestryCuriosProvider(output, existingFileHelper, registries)); + generator.addProvider(event.includeServer(), new ForestryDataMapProvider(output, registries)); } } diff --git a/src/main/java/forestry/core/data/ForestryAdvancementProvider.java b/src/main/java/forestry/core/data/ForestryAdvancementProvider.java index a731c9df6c..6362b140dd 100644 --- a/src/main/java/forestry/core/data/ForestryAdvancementProvider.java +++ b/src/main/java/forestry/core/data/ForestryAdvancementProvider.java @@ -2,36 +2,38 @@ import forestry.api.ForestryConstants; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.apiculture.features.ApicultureItems; import forestry.core.utils.SpeciesUtil; -import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.AdvancementRewards; -import net.minecraft.advancements.FrameType; +import net.minecraft.advancements.AdvancementType; import net.minecraft.advancements.critereon.InventoryChangeTrigger; -import net.minecraft.commands.CommandFunction; import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; import net.minecraft.data.PackOutput; import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.common.data.ForgeAdvancementProvider; +import net.neoforged.neoforge.common.data.AdvancementProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import java.util.List; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import static net.minecraft.advancements.Advancement.Builder.advancement; -public class ForestryAdvancementProvider extends ForgeAdvancementProvider { +public class ForestryAdvancementProvider extends AdvancementProvider { public ForestryAdvancementProvider(PackOutput output, CompletableFuture registries, ExistingFileHelper existingFileHelper) { super(output, registries, existingFileHelper, List.of(new CoreAdvancements())); } private static class CoreAdvancements implements AdvancementGenerator { @Override - public void generate(HolderLookup.Provider registries, Consumer writer, ExistingFileHelper existingFileHelper) { + public void generate(HolderLookup.Provider registries, Consumer writer, ExistingFileHelper existingFileHelper) { ItemStack icon = SpeciesUtil.BEE_TYPE.get().createStack(ForestryBeeSpecies.INDUSTRIOUS, BeeLifeStage.QUEEN); advancement() @@ -39,14 +41,14 @@ public void generate(HolderLookup.Provider registries, Consumer wri icon, Component.translatable("advancements.forestry.root.title"), Component.translatable("advancements.forestry.root.description"), - new ResourceLocation("textures/block/honeycomb_block.png"), - FrameType.TASK, + ResourceLocation.withDefaultNamespace("textures/block/honeycomb_block.png"), + AdvancementType.TASK, false, false, false ) .addCriterion("tick", InventoryChangeTrigger.TriggerInstance.hasItems(ApicultureItems.BEE_COMBS.itemArray())) - .rewards(new AdvancementRewards(0, new ResourceLocation[]{ForestryConstants.forestry("grant_guide")}, new ResourceLocation[0], CommandFunction.CacheableFunction.NONE)) + .rewards(new AdvancementRewards(0, List.of(ResourceKey.create(Registries.LOOT_TABLE, ForestryConstants.forestry("grant_guide"))), List.of(), Optional.empty())) .save(writer, ForestryConstants.MOD_ID + ":root"); } } diff --git a/src/main/java/forestry/core/data/ForestryAtlasProvider.java b/src/main/java/forestry/core/data/ForestryAtlasProvider.java index 96c9e5a3a2..026431f80e 100644 --- a/src/main/java/forestry/core/data/ForestryAtlasProvider.java +++ b/src/main/java/forestry/core/data/ForestryAtlasProvider.java @@ -3,17 +3,20 @@ import forestry.api.ForestryConstants; import forestry.core.render.ForestrySpriteUploader; import net.minecraft.client.renderer.texture.atlas.sources.DirectoryLister; +import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.common.data.SpriteSourceProvider; +import net.neoforged.neoforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.data.SpriteSourceProvider; + +import java.util.concurrent.CompletableFuture; public class ForestryAtlasProvider extends SpriteSourceProvider { - public ForestryAtlasProvider(PackOutput output, ExistingFileHelper fileHelper) { - super(output, fileHelper, ForestryConstants.MOD_ID); + public ForestryAtlasProvider(PackOutput output, CompletableFuture registries, ExistingFileHelper fileHelper) { + super(output, registries, ForestryConstants.MOD_ID, fileHelper); } @Override - protected void addSources() { + protected void gather() { SourceList icons = atlas(ForestrySpriteUploader.ATLAS_PATH); icons.addSource(new DirectoryLister("forestry/atlas/gui", "")); diff --git a/src/main/java/forestry/core/data/ForestryBackpackTagProvider.java b/src/main/java/forestry/core/data/ForestryBackpackTagProvider.java index b8edc85a01..8fbbee86d0 100644 --- a/src/main/java/forestry/core/data/ForestryBackpackTagProvider.java +++ b/src/main/java/forestry/core/data/ForestryBackpackTagProvider.java @@ -5,13 +5,13 @@ import net.minecraft.tags.ItemTags; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; import thedarkcolour.modkit.data.MKTagsProvider; public class ForestryBackpackTagProvider { public static void addTags(MKTagsProvider tags) { tags.tag(ForestryTags.Items.MINER_ALLOW).addTags( - Tags.Items.OBSIDIAN, + Tags.Items.OBSIDIANS, Tags.Items.ORES, Tags.Items.DUSTS, Tags.Items.GEMS, @@ -28,12 +28,12 @@ public static void addTags(MKTagsProvider tags) { tags.tag(ForestryTags.Items.MINER_REJECT); tags.tag(ForestryTags.Items.DIGGER_ALLOW).addTags( - Tags.Items.COBBLESTONE, - Tags.Items.GRAVEL, - Tags.Items.NETHERRACK, - Tags.Items.STONE, - Tags.Items.SANDSTONE, - Tags.Items.SAND, + Tags.Items.COBBLESTONES, + Tags.Items.GRAVELS, + Tags.Items.NETHERRACKS, + Tags.Items.STONES, + Tags.Items.SANDSTONE_BLOCKS, + Tags.Items.SANDS, ItemTags.DIRT ); tags.tag(ForestryTags.Items.DIGGER_ALLOW).add( @@ -64,7 +64,9 @@ public static void addTags(MKTagsProvider tags) { Items.CACTUS, Items.RED_MUSHROOM, Items.BROWN_MUSHROOM, - Items.GRASS, //TODO tag + Items.SHORT_GRASS, + Items.TALL_GRASS, + Items.SEAGRASS, Items.PUMPKIN, Items.MELON, Items.GOLDEN_APPLE, @@ -82,10 +84,10 @@ public static void addTags(MKTagsProvider tags) { Tags.Items.ENDER_PEARLS, Tags.Items.FEATHERS, ItemTags.FISHES, - Tags.Items.GUNPOWDER, - Tags.Items.LEATHER, - Tags.Items.SLIMEBALLS, - Tags.Items.STRING + Tags.Items.GUNPOWDERS, + Tags.Items.LEATHERS, + Tags.Items.SLIME_BALLS, + Tags.Items.STRINGS ); tags.tag(ForestryTags.Items.HUNTER_ALLOW).add( Items.BLAZE_POWDER, @@ -111,14 +113,11 @@ public static void addTags(MKTagsProvider tags) { Items.RABBIT_HIDE, Items.SPIDER_EYE, Items.FERMENTED_SPIDER_EYE, - Items.BONE_MEAL, // TODO correct item? + Items.BONE_MEAL, Items.HAY_BLOCK, - Items.WHITE_WOOL, // TODO tag Items.ENDER_EYE, Items.MAGMA_CREAM, - Items.GLISTERING_MELON_SLICE, // TODO right item? - Items.COD, // TODO tag - Items.COOKED_COD, // TODO tag + Items.GLISTERING_MELON_SLICE, Items.LEAD, Items.FISHING_ROD, Items.NAME_TAG, @@ -126,21 +125,25 @@ public static void addTags(MKTagsProvider tags) { Items.DIAMOND_HORSE_ARMOR, Items.GOLDEN_HORSE_ARMOR, Items.IRON_HORSE_ARMOR + ).addTags( + Tags.Items.FOODS_RAW_MEAT, + Tags.Items.FOODS_COOKED_MEAT, + ItemTags.WOOL, + Tags.Items.DYES ); tags.tag(ForestryTags.Items.HUNTER_REJECT); tags.tag(ForestryTags.Items.BUILDER_ALLOW).addTags( Tags.Items.GLASS_PANES, ItemTags.WOODEN_SLABS, - Tags.Items.STAINED_GLASS, - Tags.Items.STONE, - Tags.Items.SANDSTONE, + Tags.Items.STONES, + Tags.Items.SANDSTONE_BLOCKS, ItemTags.PLANKS, ItemTags.WOODEN_STAIRS, ItemTags.WOODEN_SLABS, ItemTags.WOODEN_FENCES, ItemTags.WOODEN_TRAPDOORS, - Tags.Items.GLASS, + Tags.Items.GLASS_BLOCKS, Tags.Items.CHESTS, ItemTags.WOODEN_DOORS, ItemTags.FENCE_GATES, diff --git a/src/main/java/forestry/core/data/ForestryBlockLootTables.java b/src/main/java/forestry/core/data/ForestryBlockLootTables.java index 90c8a5f1a6..69c982e9e2 100644 --- a/src/main/java/forestry/core/data/ForestryBlockLootTables.java +++ b/src/main/java/forestry/core/data/ForestryBlockLootTables.java @@ -13,6 +13,7 @@ import forestry.lepidopterology.features.LepidopterologyBlocks; import forestry.modules.features.FeatureBlock; import forestry.modules.features.FeatureBlockGroup; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.data.loot.BlockLootSubProvider; import net.minecraft.world.flag.FeatureFlags; @@ -46,8 +47,8 @@ public class ForestryBlockLootTables extends BlockLootSubProvider { private final LinkedHashSet added = new LinkedHashSet<>(); - protected ForestryBlockLootTables() { - super(Set.of(), FeatureFlags.DEFAULT_FLAGS); + protected ForestryBlockLootTables(HolderLookup.Provider registries) { + super(Set.of(), FeatureFlags.DEFAULT_FLAGS, registries); } @Override @@ -75,7 +76,7 @@ protected void generate() { } registerLootTable(CharcoalBlocks.ASH, (block) -> LootTable.lootTable().setParamSet(LootContextParamSets.BLOCK) .withPool(LootPool.lootPool().add(LootItem.lootTableItem(CoreItems.ASH)).apply(SetItemCountFunction.setCount(BinomialDistributionGenerator.binomial(2, 1.0f / 3.0f)))) - .withPool(LootPool.lootPool().add(LootItem.lootTableItem(Items.CHARCOAL)).apply(CountBlockFunction.builder()).apply(ApplyBonusCount.addBonusBinomialDistributionCount(Enchantments.BLOCK_FORTUNE, 23.0f / 40, 2)))); + .withPool(LootPool.lootPool().add(LootItem.lootTableItem(Items.CHARCOAL)).apply(CountBlockFunction.builder()).apply(ApplyBonusCount.addBonusBinomialDistributionCount(this.registries.holderOrThrow(Enchantments.FORTUNE), 23.0f / 40, 2)))); registerLootTable(CoreBlocks.PEAT, (block) -> LootTable.lootTable().withPool(LootPool.lootPool().add(LootItem.lootTableItem(Blocks.DIRT))).withPool(LootPool.lootPool().apply(SetItemCountFunction.setCount(ConstantValue.exactly(2))).add(LootItem.lootTableItem(CoreItems.PEAT.item())))); registerDropping(CoreBlocks.HUMUS, Blocks.DIRT); @@ -96,14 +97,14 @@ protected void generate() { } private LootTable.Builder createApatiteOreDrops(Block block) { - return createSilkTouchDispatchTable(block, applyExplosionDecay(block, LootItem.lootTableItem(CoreItems.APATITE.item()).apply(SetItemCountFunction.setCount(UniformGenerator.between(2.0F, 7.0F))).apply(ApplyBonusCount.addUniformBonusCount(Enchantments.BLOCK_FORTUNE, 2)))); + return createSilkTouchDispatchTable(block, applyExplosionDecay(block, LootItem.lootTableItem(CoreItems.APATITE.item()).apply(SetItemCountFunction.setCount(UniformGenerator.between(2.0F, 7.0F))).apply(ApplyBonusCount.addUniformBonusCount(this.registries.holderOrThrow(Enchantments.FORTUNE), 2)))); } public LootTable.Builder droppingWithChances(Block block, ForestryLeafType definition, float... chances) { return createSilkTouchOrShearsDispatchTable(block, applyExplosionCondition(block, LootItem.lootTableItem(ArboricultureItems.SAPLING) .apply(OrganismFunction.fromId(SpeciesUtil.TREE_TYPE.get().id(), definition.getSpeciesId()))) - .when(BonusLevelTableCondition.bonusLevelFlatChance(Enchantments.BLOCK_FORTUNE, chances))); + .when(BonusLevelTableCondition.bonusLevelFlatChance(this.registries.holderOrThrow(Enchantments.FORTUNE), chances))); } public void registerLootTable(FeatureBlock featureBlock, Function builderFunction) { diff --git a/src/main/java/forestry/core/data/ForestryBlockTagsProvider.java b/src/main/java/forestry/core/data/ForestryBlockTagsProvider.java index d66089b5df..583e7a100d 100644 --- a/src/main/java/forestry/core/data/ForestryBlockTagsProvider.java +++ b/src/main/java/forestry/core/data/ForestryBlockTagsProvider.java @@ -21,7 +21,7 @@ import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; import thedarkcolour.modkit.data.MKTagsProvider; import java.util.Collection; diff --git a/src/main/java/forestry/core/data/ForestryChestLootTables.java b/src/main/java/forestry/core/data/ForestryChestLootTables.java index b70dc32e87..365aa0313e 100644 --- a/src/main/java/forestry/core/data/ForestryChestLootTables.java +++ b/src/main/java/forestry/core/data/ForestryChestLootTables.java @@ -1,7 +1,9 @@ package forestry.core.data; import forestry.api.ForestryConstants; +import net.minecraft.core.registries.Registries; import net.minecraft.data.loot.LootTableSubProvider; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.storage.loot.LootTable; @@ -9,10 +11,10 @@ public class ForestryChestLootTables implements LootTableSubProvider { @Override - public void generate(BiConsumer consumer) { - consumer.accept(ForestryConstants.forestry("chests/village_naturalist"), LootTable.lootTable()); + public void generate(BiConsumer, LootTable.Builder> consumer) { + consumer.accept(ResourceKey.create(Registries.LOOT_TABLE, ForestryConstants.forestry("chests/village_naturalist")), LootTable.lootTable()); for (LootTableHelper.Entry entry : LootTableHelper.getInstance().entries.values()) { - consumer.accept(entry.getLocation(), entry.builder); + consumer.accept(entry.getLocation(), entry.builder()); } } } diff --git a/src/main/java/forestry/core/data/ForestryCuriosProvider.java b/src/main/java/forestry/core/data/ForestryCuriosProvider.java index 0732d51e9a..955436db4c 100644 --- a/src/main/java/forestry/core/data/ForestryCuriosProvider.java +++ b/src/main/java/forestry/core/data/ForestryCuriosProvider.java @@ -3,7 +3,7 @@ import forestry.api.ForestryConstants; import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import top.theillusivec4.curios.api.CuriosDataProvider; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/forestry/core/data/ForestryDamageTypesProvider.java b/src/main/java/forestry/core/data/ForestryDamageTypesProvider.java index 5b2428ee64..f6350c5188 100644 --- a/src/main/java/forestry/core/data/ForestryDamageTypesProvider.java +++ b/src/main/java/forestry/core/data/ForestryDamageTypesProvider.java @@ -1,6 +1,6 @@ package forestry.core.data; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.features.CoreDamageTypes; import thedarkcolour.modkit.data.MKDamageTypeProvider; public class ForestryDamageTypesProvider { diff --git a/src/main/java/forestry/core/data/ForestryDataMapProvider.java b/src/main/java/forestry/core/data/ForestryDataMapProvider.java new file mode 100644 index 0000000000..51aa8384d4 --- /dev/null +++ b/src/main/java/forestry/core/data/ForestryDataMapProvider.java @@ -0,0 +1,84 @@ +package forestry.core.data; + +import forestry.api.ForestryDataMaps; +import forestry.api.fuels.BiogasEngineFuel; +import forestry.api.fuels.PeatEngineFuel; +import forestry.api.fuels.RainmakerFuel; +import forestry.apiculture.features.ApicultureItems; +import forestry.arboriculture.features.ArboricultureBlocks; +import forestry.arboriculture.features.ArboricultureItems; +import forestry.core.features.CoreItems; +import forestry.core.fluids.ForestryFluids; +import forestry.core.items.definitions.EnumCraftingMaterial; +import forestry.lepidopterology.features.LepidopterologyItems; +import forestry.modules.features.FeatureItem; +import it.unimi.dsi.fastutil.objects.Object2FloatMap; +import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap; +import net.minecraft.core.HolderLookup; +import net.minecraft.data.PackOutput; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.material.Fluids; +import net.neoforged.neoforge.common.NeoForgeMod; +import net.neoforged.neoforge.common.data.DataMapProvider; +import net.neoforged.neoforge.registries.datamaps.builtin.Compostable; +import net.neoforged.neoforge.registries.datamaps.builtin.NeoForgeDataMaps; + +import java.util.concurrent.CompletableFuture; + +class ForestryDataMapProvider extends DataMapProvider { + ForestryDataMapProvider(PackOutput output, CompletableFuture registries) { + super(output, registries); + } + + @Override + protected void gather(HolderLookup.Provider registries) { + builder(ForestryDataMaps.RAINMAKER_FUELS) + .add(CoreItems.IODINE_CHARGE.holder(), new RainmakerFuel(10000, 0.01f, false), false) + .add(CoreItems.DISSIPATION_CHARGE.holder(), new RainmakerFuel(0, 0.075f, true), false) + ; + + builder(ForestryDataMaps.BIOGAS_FUELS) + .add(ForestryFluids.BIOMASS.holder(), new BiogasEngineFuel(50, 2500, 1), false) + .add(Fluids.WATER.builtInRegistryHolder(), new BiogasEngineFuel(10, 1000, 3), false) + .add(NeoForgeMod.MILK, new BiogasEngineFuel(10, 10000, 3), false) + .add(ForestryFluids.SEED_OIL.holder(), new BiogasEngineFuel(30, 2500, 1), false) + .add(ForestryFluids.HONEY.holder(), new BiogasEngineFuel(20, 2500, 1), false) + .add(ForestryFluids.JUICE.holder(), new BiogasEngineFuel(10, 2500, 1), false) + ; + + builder(ForestryDataMaps.PEAT_FUELS) + .add(CoreItems.PEAT.holder(), new PeatEngineFuel(20, 2500), false) + .add(CoreItems.BITUMINOUS_PEAT.holder(), new PeatEngineFuel(40, 3000), false) + ; + + registerCompostables(); + } + + private void registerCompostables() { + Object2FloatMap compostables = new Object2FloatOpenHashMap<>(); + + for (FeatureItem fruit : CoreItems.FRUITS.getFeatures()) { + compostables.put(fruit.item(), 0.65f); + } + compostables.put(CoreItems.MOULDY_WHEAT.item(), 0.65f); + compostables.put(CoreItems.DECAYING_WHEAT.item(), 0.65f); + compostables.put(CoreItems.MULCH.item(), 0.65f); + compostables.put(CoreItems.ASH.item(), 0.65f); + compostables.put(CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.WOOD_PULP), 0.65f); + compostables.put(CoreItems.PEAT.item(), 0.75f); + compostables.put(CoreItems.COMPOST.item(), 1f); + for (Item pollen : ApicultureItems.POLLEN_CLUSTER.getItems()) { + compostables.put(pollen, 0.3f); + } + compostables.put(ArboricultureItems.SAPLING.item(), 0.3f); + compostables.put(ArboricultureItems.POLLEN_FERTILE.item(), 0.3f); + for (BlockItem leaves : ArboricultureBlocks.LEAVES_DECORATIVE.getItems()) { + compostables.put(leaves, 0.3f); + } + compostables.put(LepidopterologyItems.COCOON_GE.item(), 0.3f); + + Builder compostablesDataMap = builder(NeoForgeDataMaps.COMPOSTABLES); + compostables.forEach((item, chance) -> compostablesDataMap.add(item.builtInRegistryHolder(), new Compostable(chance), false)); + } +} diff --git a/src/main/java/forestry/core/data/ForestryFeaturesProvider.java b/src/main/java/forestry/core/data/ForestryFeaturesProvider.java index d6a78586e9..2696ce5c7e 100644 --- a/src/main/java/forestry/core/data/ForestryFeaturesProvider.java +++ b/src/main/java/forestry/core/data/ForestryFeaturesProvider.java @@ -10,7 +10,7 @@ import net.minecraft.core.RegistrySetBuilder; import net.minecraft.core.registries.Registries; import net.minecraft.data.PackOutput; -import net.minecraft.data.worldgen.BootstapContext; +import net.minecraft.data.worldgen.BootstrapContext; import net.minecraft.data.worldgen.placement.OrePlacements; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.levelgen.VerticalAnchor; @@ -21,7 +21,7 @@ import net.minecraft.world.level.levelgen.placement.HeightRangePlacement; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.structure.templatesystem.TagMatchTest; -import net.minecraftforge.common.data.DatapackBuiltinEntriesProvider; +import net.neoforged.neoforge.common.data.DatapackBuiltinEntriesProvider; import java.util.List; import java.util.Set; @@ -34,7 +34,7 @@ public ForestryFeaturesProvider(PackOutput output, CompletableFuture> context) { + private static void addConfiguredFeatures(BootstrapContext> context) { context.register(CoreFeatures.ORE_APATITE, new ConfiguredFeature<>(Feature.ORE, new OreConfiguration(List.of( OreConfiguration.target(new TagMatchTest(BlockTags.STONE_ORE_REPLACEABLES), CoreBlocks.APATITE_ORE.defaultState()), OreConfiguration.target(new TagMatchTest(BlockTags.DEEPSLATE_ORE_REPLACEABLES), CoreBlocks.DEEPSLATE_APATITE_ORE.defaultState()) @@ -44,12 +44,12 @@ private static void addConfiguredFeatures(BootstapContext(ApicultureFeatures.HIVE.get(), FeatureConfiguration.NONE)); + context.register(ApicultureFeatures.CONFIGURED_HIVE, new ConfiguredFeature<>(ApicultureFeatures.HIVE.value(), FeatureConfiguration.NONE)); - context.register(ArboricultureFeatures.CONFIGURED_TREE, new ConfiguredFeature<>(ArboricultureFeatures.TREE_DECORATOR.get(), FeatureConfiguration.NONE)); + context.register(ArboricultureFeatures.CONFIGURED_TREE, new ConfiguredFeature<>(ArboricultureFeatures.TREE_DECORATOR.value(), FeatureConfiguration.NONE)); } - private static void addPlacedFeatures(BootstapContext context) { + private static void addPlacedFeatures(BootstrapContext context) { HolderGetter> holders = context.lookup(Registries.CONFIGURED_FEATURE); context.register(CoreFeatures.PLACED_APATITE, new PlacedFeature(holders.getOrThrow(CoreFeatures.ORE_APATITE), OrePlacements.commonOrePlacement(3, HeightRangePlacement.triangle( diff --git a/src/main/java/forestry/core/data/ForestryFluidTagsProvider.java b/src/main/java/forestry/core/data/ForestryFluidTagsProvider.java index dc5a77f5e5..d8691da183 100644 --- a/src/main/java/forestry/core/data/ForestryFluidTagsProvider.java +++ b/src/main/java/forestry/core/data/ForestryFluidTagsProvider.java @@ -1,13 +1,13 @@ package forestry.core.data; -import forestry.api.ForestryTags; import forestry.core.fluids.ForestryFluids; import net.minecraft.core.HolderLookup; import net.minecraft.world.level.material.Fluid; +import net.neoforged.neoforge.common.Tags; import thedarkcolour.modkit.data.MKTagsProvider; public class ForestryFluidTagsProvider { public static void addTags(MKTagsProvider tags, HolderLookup.Provider lookup) { - tags.tag(ForestryTags.Fluids.HONEY).add(ForestryFluids.HONEY.getFluid(), ForestryFluids.HONEY.getFlowing()); + tags.tag(Tags.Fluids.HONEY).add(ForestryFluids.HONEY.getFluid(), ForestryFluids.HONEY.getFlowing()); } } diff --git a/src/main/java/forestry/core/data/ForestryItemModels.java b/src/main/java/forestry/core/data/ForestryItemModels.java index 29b3ed90d2..ddcda58b58 100644 --- a/src/main/java/forestry/core/data/ForestryItemModels.java +++ b/src/main/java/forestry/core/data/ForestryItemModels.java @@ -1,21 +1,130 @@ package forestry.core.data; +import forestry.api.modules.ForestryModuleIds; import forestry.apiculture.features.ApicultureItems; import forestry.arboriculture.ForestryWoodType; import forestry.arboriculture.features.ArboricultureItems; +import forestry.core.data.models.FilledCrateModelBuilder; +import forestry.core.fluids.ForestryFluids; +import forestry.core.utils.ModUtil; +import forestry.cultivation.features.CultivationBlocks; +import forestry.lepidopterology.features.LepidopterologyItems; +import forestry.modules.features.ModFeatureRegistry; +import forestry.storage.features.CrateItems; +import forestry.storage.items.ItemBackpack; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemNameBlockItem; +import net.neoforged.neoforge.client.model.generators.loaders.DynamicFluidContainerModelBuilder; +import net.neoforged.neoforge.internal.versions.neoforge.NeoForgeVersion; import thedarkcolour.modkit.data.MKItemModelProvider; +import java.util.stream.Stream; + +import static forestry.api.ForestryConstants.forestry; +import static forestry.core.data.models.ForestryBlockStateProvider.file; + public class ForestryItemModels { public static void addModels(MKItemModelProvider models) { + // Resources models.generic2d(ApicultureItems.HONEY_DROP); models.generic2d(ApicultureItems.HONEYDEW); models.generic2d(ApicultureItems.EXPERIENCE_DROP); - models.generic2d(ApicultureItems.HONEY_POT); models.generic2d(ApicultureItems.HONEYED_SLICE); + // Boats for (ForestryWoodType type : ForestryWoodType.VALUES) { models.generic2d(ArboricultureItems.BOAT.get(type)); models.generic2d(ArboricultureItems.CHEST_BOAT.get(type)); } + + // Butterfly items + models.withExistingParent(LepidopterologyItems.CATERPILLAR.getName(), models.mcLoc("item/generated")) + .texture("layer0", forestry("item/caterpillar.body2")) + .texture("layer1", forestry("item/caterpillar.body")); + models.withExistingParent(LepidopterologyItems.SERUM.getName(), models.mcLoc("item/generated")) + .texture("layer0", forestry("item/liquids/jar.bottle")) + .texture("layer1", forestry("item/liquids/jar.contents")); + + // Crates + CrateItems.getCrates().forEach(featureCrated -> { + Item containedItem = featureCrated.get().getContained().getItem(); + String id = featureCrated.getName(); + + if (ApicultureItems.BEE_COMBS.itemEqual(containedItem)) { + filledCrateModelLayered(models, id, forestry("item/bee_combs.0"), forestry("item/bee_combs.1")); + } else if (ApicultureItems.POLLEN_CLUSTER.itemEqual(containedItem)) { + filledCrateModelLayered(models, id, forestry("item/pollen.0"), forestry("item/pollen.1")); + } else { + ResourceLocation contained = ModUtil.getRegistryName(containedItem); + ResourceLocation contentsTexture; + + if (containedItem instanceof BlockItem && !(containedItem instanceof ItemNameBlockItem)) { + contentsTexture = contained.withPrefix("block/"); + } else { + contentsTexture = contained.withPrefix("item/"); + } + + filledCrateModel(models, id, contentsTexture); + } + }); + + // 2d items + ApicultureItems.FRAME_CREATIVE.getItems().forEach(models::generic2d); + + // manual overrides + filledCrateModel(models, CrateItems.CRATED_CACTUS.getName(), models.mcLoc("block/cactus_side")); + filledCrateModel(models, CrateItems.CRATED_MYCELIUM.getName(), models.mcLoc("block/mycelium_side")); + filledCrateModel(models, CrateItems.CRATED_GRASS_BLOCK.getName(), models.mcLoc("block/grass_block_top")); + filledCrateModel(models, CrateItems.CRATED_PROPOLIS.getName(), forestry("item/propolis.0")); + + // Farm blocks + Stream.of(CultivationBlocks.MANAGED_PLANTER, CultivationBlocks.MANUAL_PLANTER) + .flatMap(g -> g.getFeatureByType().entrySet().stream()) + .forEachOrdered(entry -> models.withExistingParent(entry.getValue().getName(), forestry("block/" + entry.getKey().getSerializedName()))); + + // Buckets + for (ForestryFluids fluid : ForestryFluids.values()) { + models.getBuilder(path(fluid.getBucket())) + .customLoader(DynamicFluidContainerModelBuilder::begin) + .fluid(fluid.getFluid()) + .end() + .parent(models.getExistingFile(ResourceLocation.fromNamespaceAndPath(NeoForgeVersion.MOD_ID, "item/bucket"))); + } + + // Backpacks + for (Holder object : ModFeatureRegistry.get(ForestryModuleIds.STORAGE).getRegistry(Registries.ITEM).getEntries()) { + if (object.value() instanceof ItemBackpack) { + String path = object.getKey().location().getPath(); + boolean woven = path.endsWith("woven"); + + models.withExistingParent(path, woven ? forestry("item/backpack/woven_neutral") : forestry("item/backpack/normal_neutral")) + .override(file(woven ? forestry("item/backpack/woven_locked") : forestry("item/backpack/normal_locked"))).predicate(models.mcLoc("mode"), 1).end() + .override(file(woven ? forestry("item/backpack/woven_receive") : forestry("item/backpack/normal_receive"))).predicate(models.mcLoc("mode"), 2).end() + .override(file(woven ? forestry("item/backpack/woven_resupply") : forestry("item/backpack/normal_resupply"))).predicate(models.mcLoc("mode"), 3).end(); + } + } + } + + private static String path(Item item) { + return ModUtil.getRegistryName(item).getPath(); + } + + private static void filledCrateModel(MKItemModelProvider models, String id, ResourceLocation texture) { + models.getBuilder(id) + .customLoader(FilledCrateModelBuilder::begin) + .layer1(texture) + .end(); + } + + private static void filledCrateModelLayered(MKItemModelProvider models, String id, ResourceLocation layer1, ResourceLocation layer2) { + models.getBuilder(id) + .customLoader(FilledCrateModelBuilder::begin) + .layer1(layer1) + .layer2(layer2) + .end(); } } diff --git a/src/main/java/forestry/core/data/ForestryItemTagsProvider.java b/src/main/java/forestry/core/data/ForestryItemTagsProvider.java index 715ea1f885..62a8cf3f61 100644 --- a/src/main/java/forestry/core/data/ForestryItemTagsProvider.java +++ b/src/main/java/forestry/core/data/ForestryItemTagsProvider.java @@ -15,7 +15,7 @@ import net.minecraft.tags.ItemTags; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; import thedarkcolour.modkit.data.MKTagsProvider; public class ForestryItemTagsProvider { @@ -121,12 +121,6 @@ public static void addTags(MKTagsProvider tags) { tags.tag(ForestryTags.Items.DUSTS_ASH).add(CoreItems.ASH.item()); tags.tag(ForestryTags.Items.SAWDUST).add(CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.WOOD_PULP)); - tags.tag(ForestryTags.Items.CRAFTING_TABLES) - .addOptionalTag(new ResourceLocation("c", "player_workstations/crafting_tables")) - .addOptionalTag(new ResourceLocation("c", "workbenches")) - .addOptionalTag(new ResourceLocation("c", "workbench")) - .add(Items.CRAFTING_TABLE); - tags.tag(ForestryTags.Items.SCOOPS).add(ApicultureItems.SCOOP.item()); tags.tag(ForestryTags.Items.BEES).add(ApicultureItems.BEE_DRONE.get(), ApicultureItems.BEE_PRINCESS.get(), ApicultureItems.BEE_QUEEN.get(), ApicultureItems.BEE_LARVAE.get()); diff --git a/src/main/java/forestry/core/data/ForestryLootModifierProvider.java b/src/main/java/forestry/core/data/ForestryLootModifierProvider.java index faa4856d63..1bd6b086de 100644 --- a/src/main/java/forestry/core/data/ForestryLootModifierProvider.java +++ b/src/main/java/forestry/core/data/ForestryLootModifierProvider.java @@ -4,14 +4,17 @@ import forestry.arboriculture.features.ArboricultureItems; import forestry.arboriculture.loot.GrafterLootModifier; import forestry.core.loot.ConditionLootModifier; +import net.minecraft.core.HolderLookup; import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraftforge.common.data.GlobalLootModifierProvider; +import net.neoforged.neoforge.common.data.GlobalLootModifierProvider; import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; import static net.minecraft.advancements.critereon.ItemPredicate.Builder.item; import static net.minecraft.world.level.storage.loot.predicates.MatchTool.toolMatches; @@ -22,15 +25,15 @@ * Currently the only modifier is the {@link ConditionLootModifier} */ public class ForestryLootModifierProvider extends GlobalLootModifierProvider { - public ForestryLootModifierProvider(PackOutput output) { - super(output, ForestryConstants.MOD_ID); + public ForestryLootModifierProvider(PackOutput output, CompletableFuture registries) { + super(output, registries, ForestryConstants.MOD_ID); } @Override protected void start() { - for (Map.Entry> mapEntry : LootTableHelper.getInstance().entries.asMap().entrySet()) { - List extensions = mapEntry.getValue().stream().map(entry -> entry.extension).toList(); - add(mapEntry.getKey().getPath(), new ConditionLootModifier(mapEntry.getKey(), extensions)); + for (Map.Entry, Collection> mapEntry : LootTableHelper.getInstance().entries.asMap().entrySet()) { + List extensions = mapEntry.getValue().stream().map(LootTableHelper.Entry::extension).toList(); + add(mapEntry.getKey().location().getPath(), new ConditionLootModifier(mapEntry.getKey().location(), extensions)); } add("grafter", new GrafterLootModifier(new LootItemCondition[]{ toolMatches(item().of(ArboricultureItems.GRAFTER.item())).or(toolMatches(item().of(ArboricultureItems.GRAFTER_PROVEN.item()))).build() diff --git a/src/main/java/forestry/core/data/ForestryPoiTypeTagProvider.java b/src/main/java/forestry/core/data/ForestryPoiTypeTagProvider.java index 321cdec76c..6ce6b28526 100644 --- a/src/main/java/forestry/core/data/ForestryPoiTypeTagProvider.java +++ b/src/main/java/forestry/core/data/ForestryPoiTypeTagProvider.java @@ -9,6 +9,6 @@ public class ForestryPoiTypeTagProvider { protected static void addTags(MKTagsProvider tags, HolderLookup.Provider lookup) { - tags.tag(PoiTypeTags.ACQUIRABLE_JOB_SITE).add(ArboricultureVillagers.POI_TREE_CHEST.get(), ApicultureVillagers.POI_ESCRITOIRE.get()); + tags.tag(PoiTypeTags.ACQUIRABLE_JOB_SITE).add(ArboricultureVillagers.POI_TREE_CHEST.value(), ApicultureVillagers.POI_ESCRITOIRE.value()); } } diff --git a/src/main/java/forestry/core/data/LootTableHelper.java b/src/main/java/forestry/core/data/LootTableHelper.java index cdcd8cd352..d9a34aea77 100644 --- a/src/main/java/forestry/core/data/LootTableHelper.java +++ b/src/main/java/forestry/core/data/LootTableHelper.java @@ -5,7 +5,7 @@ import forestry.api.ForestryConstants; import forestry.api.ForestryTags; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.arboriculture.ForestryTreeSpecies; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.apiculture.features.ApicultureItems; @@ -14,6 +14,8 @@ import forestry.core.loot.OrganismFunction; import forestry.core.utils.SpeciesUtil; import forestry.storage.features.BackpackItems; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.storage.loot.BuiltInLootTables; @@ -46,7 +48,7 @@ public static LootTableHelper getInstance() { return instance; } - protected final Multimap entries = LinkedHashMultimap.create(); + protected final Multimap, Entry> entries = LinkedHashMultimap.create(); public LootTableHelper() { add(BuiltInLootTables.ABANDONED_MINESHAFT, "apiculture", @@ -180,7 +182,7 @@ public LootTableHelper() { .add(beeLoot(ForestryBeeSpecies.MONASTIC).setWeight(6)) .add(EmptyLootItem.emptyItem().setWeight(3)) )); - add(ForestryConstants.forestry("chests/village_naturalist"), "arboriculture", + add(ResourceKey.create(Registries.LOOT_TABLE, ForestryConstants.forestry("chests/village_naturalist")), "arboriculture", LootTable.lootTable().withPool(LootPool.lootPool() .name("forestry_arboriculture_items") .setRolls(ConstantValue.exactly(3)) @@ -191,7 +193,7 @@ public LootTableHelper() { .add(saplingLoot(ForestryTreeSpecies.TEAK)) .add(saplingLoot(ForestryTreeSpecies.PADAUK)) )); - add(ForestryConstants.forestry("chests/village_naturalist"), "apiculture", + add(ResourceKey.create(Registries.LOOT_TABLE, ForestryConstants.forestry("chests/village_naturalist")), "apiculture", LootTable.lootTable().withPool(LootPool.lootPool() .name("forestry_apiculture_items") .setRolls(ConstantValue.exactly(4)) @@ -230,11 +232,7 @@ public LootTableHelper() { } private LootPoolSingletonContainer.Builder saplingLoot(ResourceLocation species) { - return saplingLoot(TreeLifeStage.SAPLING, species); - } - - private LootPoolSingletonContainer.Builder saplingLoot(TreeLifeStage type, ResourceLocation species) { - return LootItem.lootTableItem(saplingItem(type)) + return LootItem.lootTableItem(saplingItem(TreeLifeStage.SAPLING)) .apply(OrganismFunction.fromDefinition(SpeciesUtil.TREE_TYPE.get(), SpeciesUtil.getTreeSpecies(species))); } @@ -263,23 +261,13 @@ private static Item beeItem(BeeLifeStage type) { }; } - protected void add(ResourceLocation location, String extension, LootTable.Builder builder) { + protected void add(ResourceKey location, String extension, LootTable.Builder builder) { this.entries.put(location, new Entry(location, extension, builder)); } - public static class Entry { - public final ResourceLocation defaultLocation; - public final String extension; - public final LootTable.Builder builder; - - public Entry(ResourceLocation defaultLocation, String extension, LootTable.Builder builder) { - this.defaultLocation = defaultLocation; - this.extension = extension; - this.builder = builder; - } - - public ResourceLocation getLocation() { - return ForestryConstants.forestry(this.defaultLocation.getPath() + "/" + this.extension); + public record Entry(ResourceKey defaultLocation, String extension, LootTable.Builder builder) { + public ResourceKey getLocation() { + return ResourceKey.create(Registries.LOOT_TABLE, ForestryConstants.forestry(this.defaultLocation.location().getPath() + "/" + this.extension)); } } } diff --git a/src/main/java/forestry/core/data/builder/CarpenterRecipeBuilder.java b/src/main/java/forestry/core/data/builder/CarpenterRecipeBuilder.java deleted file mode 100644 index 7f42f4832f..0000000000 --- a/src/main/java/forestry/core/data/builder/CarpenterRecipeBuilder.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.advancements.critereon.ImpossibleTrigger; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.data.recipes.ShapedRecipeBuilder; -import net.minecraft.data.recipes.ShapelessRecipeBuilder; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.fluids.FluidStack; -import org.apache.commons.lang3.mutable.MutableObject; - -import javax.annotation.Nullable; -import java.util.function.Consumer; - -public class CarpenterRecipeBuilder { - private int packagingTime = 5; - @Nullable - private FluidStack liquid; - private Ingredient box; - private FinishedRecipe recipe; - @Nullable - private ItemStack result; - - public CarpenterRecipeBuilder setPackagingTime(int packagingTime) { - this.packagingTime = packagingTime; - return this; - } - - public CarpenterRecipeBuilder setLiquid(@Nullable FluidStack liquid) { - this.liquid = liquid; - return this; - } - - public CarpenterRecipeBuilder setBox(Ingredient box) { - this.box = box; - return this; - } - - public CarpenterRecipeBuilder recipe(ShapedRecipeBuilder recipe) { - MutableObject holder = new MutableObject<>(); - recipe.unlockedBy("impossible", new ImpossibleTrigger.TriggerInstance()).save(holder::setValue); - this.recipe = holder.getValue(); - return this; - } - - public CarpenterRecipeBuilder recipe(ShapelessRecipeBuilder recipe) { - MutableObject holder = new MutableObject<>(); - recipe.unlockedBy("impossible", new ImpossibleTrigger.TriggerInstance()).save(holder::setValue); - this.recipe = holder.getValue(); - return this; - } - - /** - * In case the recipe should create an item stack, and not a basic item without NBT - * - * @param result The result to override {@link #recipe(ShapedRecipeBuilder)} - * @return This builder for chaining - */ - public CarpenterRecipeBuilder override(ItemStack result) { - this.result = result; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.packagingTime, this.liquid, this.box, this.recipe, this.result)); - } - - public static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final int packagingTime; - @Nullable - private final FluidStack liquid; - private final Ingredient box; - private final FinishedRecipe recipe; - @Nullable - private final ItemStack result; - - public Result(ResourceLocation id, int packagingTime, @Nullable FluidStack liquid, Ingredient box, FinishedRecipe recipe, @Nullable ItemStack result) { - this.id = id; - this.packagingTime = packagingTime; - this.liquid = liquid; - this.box = box; - this.recipe = recipe; - this.result = result; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.addProperty("time", this.packagingTime); - - if (this.liquid != null) { - json.add("liquid", RecipeSerializers.serializeFluid(this.liquid)); - } - - json.add("box", this.box.toJson()); - json.add("recipe", this.recipe.serializeRecipe()); - - if (this.result != null) { - json.add("result", RecipeSerializers.item(this.result)); - } - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.CARPENTER.serializer(); - } - - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/CentrifugeRecipeBuilder.java b/src/main/java/forestry/core/data/builder/CentrifugeRecipeBuilder.java deleted file mode 100644 index 5dcbc3fa36..0000000000 --- a/src/main/java/forestry/core/data/builder/CentrifugeRecipeBuilder.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.data.builder; - -import com.google.common.base.Preconditions; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import forestry.api.core.Product; -import forestry.core.utils.JsonUtil; -import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; - -import java.util.ArrayList; -import java.util.function.Consumer; - -public class CentrifugeRecipeBuilder { - private int processingTime; - private Ingredient input; - private final ArrayList outputs = new ArrayList<>(); - - public CentrifugeRecipeBuilder setProcessingTime(int processingTime) { - this.processingTime = processingTime; - return this; - } - - public CentrifugeRecipeBuilder setInput(Ingredient input) { - this.input = input; - return this; - } - - public CentrifugeRecipeBuilder product(float chance, ItemStack stack) { - this.outputs.add(new Product(stack.getItem(), stack.getCount(), stack.getTag(), chance)); - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - Preconditions.checkState(!this.outputs.isEmpty(), "Empty centrifuge recipes are not allowed"); - consumer.accept(new Result(id, this.processingTime, this.input, this.outputs)); - } - - public static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final int processingTime; - private final Ingredient input; - private final ArrayList outputs; - - public Result(ResourceLocation id, int processingTime, Ingredient input, ArrayList outputs) { - this.id = id; - this.processingTime = processingTime; - this.input = input; - this.outputs = outputs; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.addProperty("time", this.processingTime); - json.add("input", this.input.toJson()); - - JsonArray products = new JsonArray(); - - for (Product product : this.outputs) { - products.add(JsonUtil.serialize(Product.CODEC, product)); - } - - json.add("products", products); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.CENTRIFUGE.serializer(); - } - - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/FabricatorRecipeBuilder.java b/src/main/java/forestry/core/data/builder/FabricatorRecipeBuilder.java deleted file mode 100644 index 72c2b3f424..0000000000 --- a/src/main/java/forestry/core/data/builder/FabricatorRecipeBuilder.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.advancements.critereon.ImpossibleTrigger; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.data.recipes.ShapedRecipeBuilder; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.fluids.FluidStack; -import org.apache.commons.lang3.mutable.MutableObject; - -import java.util.function.Consumer; - -public class FabricatorRecipeBuilder { - private Ingredient plan; - private FluidStack molten; - private ShapedRecipeBuilder.Result recipe; - - public FabricatorRecipeBuilder setPlan(Ingredient plan) { - this.plan = plan; - return this; - } - - public FabricatorRecipeBuilder setMolten(FluidStack molten) { - this.molten = molten; - return this; - } - - public FabricatorRecipeBuilder recipe(ShapedRecipeBuilder recipe) { - MutableObject holder = new MutableObject<>(); - recipe.unlockedBy("impossible", new ImpossibleTrigger.TriggerInstance()).save(holder::setValue); - this.recipe = (ShapedRecipeBuilder.Result) holder.getValue(); - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.plan, this.molten, this.recipe)); - } - - public static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final Ingredient plan; - private final FluidStack molten; - private final ShapedRecipeBuilder.Result recipe; - - public Result(ResourceLocation id, Ingredient plan, FluidStack molten, ShapedRecipeBuilder.Result recipe) { - this.id = id; - this.plan = plan; - this.molten = molten; - this.recipe = recipe; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.add("plan", this.plan.toJson()); - json.add("molten", RecipeSerializers.serializeFluid(this.molten)); - json.add("recipe", this.recipe.serializeRecipe()); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.FABRICATOR.serializer(); - } - - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/FabricatorSmeltingRecipeBuilder.java b/src/main/java/forestry/core/data/builder/FabricatorSmeltingRecipeBuilder.java deleted file mode 100644 index 7626d6d7c9..0000000000 --- a/src/main/java/forestry/core/data/builder/FabricatorSmeltingRecipeBuilder.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.fluids.FluidStack; - -import java.util.function.Consumer; - -public class FabricatorSmeltingRecipeBuilder { - - private int meltingPoint; - private Ingredient resource; - private FluidStack product; - - public FabricatorSmeltingRecipeBuilder setMeltingPoint(int meltingPoint) { - this.meltingPoint = meltingPoint; - return this; - } - - public FabricatorSmeltingRecipeBuilder setResource(Ingredient resource) { - this.resource = resource; - return this; - } - - public FabricatorSmeltingRecipeBuilder setProduct(FluidStack product) { - this.product = product; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.meltingPoint, this.resource, this.product)); - } - - public static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final int meltingPoint; - private final Ingredient resource; - private final FluidStack product; - - public Result(ResourceLocation id, int meltingPoint, Ingredient resource, FluidStack product) { - this.id = id; - this.meltingPoint = meltingPoint; - this.resource = resource; - this.product = product; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.addProperty("melting", this.meltingPoint); - json.add("resource", this.resource.toJson()); - json.add("product", RecipeSerializers.serializeFluid(this.product)); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.FABRICATOR_SMELTING.serializer(); - } - - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/FermenterRecipeBuilder.java b/src/main/java/forestry/core/data/builder/FermenterRecipeBuilder.java deleted file mode 100644 index 16d464a409..0000000000 --- a/src/main/java/forestry/core/data/builder/FermenterRecipeBuilder.java +++ /dev/null @@ -1,101 +0,0 @@ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.core.utils.ModUtil; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.Nullable; -import java.util.function.Consumer; - -public class FermenterRecipeBuilder { - private Ingredient resource; - private int fermentationValue; - private float modifier = 1.0f; - private Fluid output; - private FluidStack fluidResource; - - public FermenterRecipeBuilder setResource(Ingredient resource) { - this.resource = resource; - return this; - } - - public FermenterRecipeBuilder setFermentationValue(int fermentationValue) { - this.fermentationValue = fermentationValue; - return this; - } - - public FermenterRecipeBuilder setModifier(float modifier) { - this.modifier = modifier; - return this; - } - - public FermenterRecipeBuilder setOutput(Fluid output) { - this.output = output; - return this; - } - - public FermenterRecipeBuilder setFluidResource(FluidStack fluidResource) { - this.fluidResource = fluidResource; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.resource, this.fermentationValue, this.modifier, this.output, this.fluidResource)); - } - - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final Ingredient resource; - private final int fermentationValue; - private final float modifier; - private final Fluid output; - private final FluidStack fluidResource; - - public Result(ResourceLocation id, Ingredient resource, int fermentationValue, float modifier, Fluid output, FluidStack fluidResource) { - this.id = id; - this.resource = resource; - this.fermentationValue = fermentationValue; - this.modifier = modifier; - this.output = output; - this.fluidResource = fluidResource; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.add("resource", this.resource.toJson()); - json.addProperty("fermentationValue", this.fermentationValue); - json.addProperty("modifier", this.modifier); - json.addProperty("output", ModUtil.getRegistryName(this.output).toString()); - json.add("fluidResource", RecipeSerializers.serializeFluid(this.fluidResource)); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.FERMENTER.serializer(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/HygroregulatorRecipeBuilder.java b/src/main/java/forestry/core/data/builder/HygroregulatorRecipeBuilder.java deleted file mode 100644 index 49ca88d845..0000000000 --- a/src/main/java/forestry/core/data/builder/HygroregulatorRecipeBuilder.java +++ /dev/null @@ -1,89 +0,0 @@ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.Nullable; -import java.util.function.Consumer; - -public class HygroregulatorRecipeBuilder { - private FluidStack liquid; - private int humiditySteps; - private int temperatureSteps; - private int retainTime; - - public HygroregulatorRecipeBuilder setLiquid(FluidStack liquid) { - this.liquid = liquid; - return this; - } - - public HygroregulatorRecipeBuilder setHumiditySteps(int humiditySteps) { - this.humiditySteps = humiditySteps; - return this; - } - - public HygroregulatorRecipeBuilder setTemperatureSteps(int temperatureSteps) { - this.temperatureSteps = temperatureSteps; - return this; - } - - public HygroregulatorRecipeBuilder setRetainTime(int retainTime) { - this.retainTime = retainTime; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.liquid, this.retainTime, this.humiditySteps, this.temperatureSteps)); - } - - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final FluidStack liquid; - private final byte humiditySteps; - private final byte temperatureSteps; - private final int retainTime; - - public Result(ResourceLocation id, FluidStack liquid, int retainTime, int humiditySteps, int temperatureSteps) { - this.id = id; - this.liquid = liquid; - this.retainTime = retainTime; - this.humiditySteps = (byte) humiditySteps; - this.temperatureSteps = (byte) temperatureSteps; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.add("liquid", RecipeSerializers.serializeFluid(this.liquid)); - json.addProperty("time", this.retainTime); - json.addProperty("humidity_steps", this.humiditySteps); - json.addProperty("temperature_steps", this.temperatureSteps); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.HYGROREGULATOR.serializer(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/MoistenerRecipeBuilder.java b/src/main/java/forestry/core/data/builder/MoistenerRecipeBuilder.java deleted file mode 100644 index 7b682aa963..0000000000 --- a/src/main/java/forestry/core/data/builder/MoistenerRecipeBuilder.java +++ /dev/null @@ -1,82 +0,0 @@ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; - -import javax.annotation.Nullable; -import java.util.function.Consumer; - -public class MoistenerRecipeBuilder { - - private int timePerItem; - private Ingredient resource; - private ItemStack product; - - public MoistenerRecipeBuilder setTimePerItem(int timePerItem) { - this.timePerItem = timePerItem; - return this; - } - - public MoistenerRecipeBuilder setResource(Ingredient resource) { - this.resource = resource; - return this; - } - - public MoistenerRecipeBuilder setProduct(ItemStack product) { - this.product = product; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.timePerItem, this.resource, this.product)); - } - - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final int timePerItem; - private final Ingredient resource; - private final ItemStack product; - - public Result(ResourceLocation id, int timePerItem, Ingredient resource, ItemStack product) { - this.id = id; - this.timePerItem = timePerItem; - this.resource = resource; - this.product = product; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.addProperty("time", this.timePerItem); - json.add("resource", this.resource.toJson()); - json.add("product", RecipeSerializers.item(this.product)); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.MOISTENER.serializer(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/SqueezerContainerRecipeBuilder.java b/src/main/java/forestry/core/data/builder/SqueezerContainerRecipeBuilder.java deleted file mode 100644 index e994a42c5f..0000000000 --- a/src/main/java/forestry/core/data/builder/SqueezerContainerRecipeBuilder.java +++ /dev/null @@ -1,89 +0,0 @@ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeSerializer; - -import javax.annotation.Nullable; -import java.util.function.Consumer; - -public class SqueezerContainerRecipeBuilder { - private ItemStack emptyContainer; - private int processingTime; - private ItemStack remnants; - private float remnantsChance; - - public SqueezerContainerRecipeBuilder setEmptyContainer(ItemStack emptyContainer) { - this.emptyContainer = emptyContainer; - return this; - } - - public SqueezerContainerRecipeBuilder setProcessingTime(int processingTime) { - this.processingTime = processingTime; - return this; - } - - public SqueezerContainerRecipeBuilder setRemnants(ItemStack remnants) { - this.remnants = remnants; - return this; - } - - public SqueezerContainerRecipeBuilder setRemnantsChance(float remnantsChance) { - this.remnantsChance = remnantsChance; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.emptyContainer, this.processingTime, this.remnants, this.remnantsChance)); - } - - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final ItemStack emptyContainer; - private final int processingTime; - private final ItemStack remnants; - private final float remnantsChance; - - public Result(ResourceLocation id, ItemStack emptyContainer, int processingTime, ItemStack remnants, float remnantsChance) { - this.id = id; - this.emptyContainer = emptyContainer; - this.processingTime = processingTime; - this.remnants = remnants; - this.remnantsChance = remnantsChance; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.add("container", RecipeSerializers.item(this.emptyContainer)); - json.addProperty("time", this.processingTime); - json.add("remnants", RecipeSerializers.item(this.remnants)); - json.addProperty("remnantsChance", this.remnantsChance); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.SQUEEZER_CONTAINER.serializer(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/SqueezerRecipeBuilder.java b/src/main/java/forestry/core/data/builder/SqueezerRecipeBuilder.java deleted file mode 100644 index fc1ba4a665..0000000000 --- a/src/main/java/forestry/core/data/builder/SqueezerRecipeBuilder.java +++ /dev/null @@ -1,109 +0,0 @@ -package forestry.core.data.builder; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.Nullable; -import java.util.List; -import java.util.function.Consumer; - -public class SqueezerRecipeBuilder { - private int processingTime; - private List resources; - private FluidStack fluidOutput; - private ItemStack remnants = ItemStack.EMPTY; - private float remnantsChance; - - public SqueezerRecipeBuilder setProcessingTime(int processingTime) { - this.processingTime = processingTime; - return this; - } - - public SqueezerRecipeBuilder setResources(List resources) { - this.resources = resources; - return this; - } - - public SqueezerRecipeBuilder setFluidOutput(FluidStack fluidOutput) { - this.fluidOutput = fluidOutput; - return this; - } - - public SqueezerRecipeBuilder setRemnants(ItemStack remnants) { - this.remnants = remnants; - return this; - } - - public SqueezerRecipeBuilder setRemnantsChance(float remnantsChance) { - this.remnantsChance = remnantsChance; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.processingTime, this.resources, this.fluidOutput, this.remnants, this.remnantsChance)); - } - - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final int processingTime; - private final List resources; - private final FluidStack fluidOutput; - private final ItemStack remnants; - private final float remnantsChance; - - public Result(ResourceLocation id, int processingTime, List resources, FluidStack fluidOutput, ItemStack remnants, float remnantsChance) { - this.id = id; - this.processingTime = processingTime; - this.resources = resources; - this.fluidOutput = fluidOutput; - this.remnants = remnants; - this.remnantsChance = remnantsChance; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.addProperty("time", this.processingTime); - - JsonArray resources = new JsonArray(); - - for (Ingredient resource : this.resources) { - resources.add(resource.toJson()); - } - - json.add("resources", resources); - json.add("output", RecipeSerializers.serializeFluid(this.fluidOutput)); - json.add("remnant", RecipeSerializers.item(this.remnants)); - json.addProperty("chance", this.remnantsChance); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.SQUEEZER.serializer(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/StillRecipeBuilder.java b/src/main/java/forestry/core/data/builder/StillRecipeBuilder.java deleted file mode 100644 index 828b57802a..0000000000 --- a/src/main/java/forestry/core/data/builder/StillRecipeBuilder.java +++ /dev/null @@ -1,81 +0,0 @@ -package forestry.core.data.builder; - -import com.google.gson.JsonObject; -import forestry.factory.features.FactoryRecipeTypes; -import forestry.factory.recipes.RecipeSerializers; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.fluids.FluidStack; - -import javax.annotation.Nullable; -import java.util.function.Consumer; - -public class StillRecipeBuilder { - - private int timePerUnit; - private FluidStack input; - private FluidStack output; - - public StillRecipeBuilder setTimePerUnit(int timePerUnit) { - this.timePerUnit = timePerUnit; - return this; - } - - public StillRecipeBuilder setInput(FluidStack input) { - this.input = input; - return this; - } - - public StillRecipeBuilder setOutput(FluidStack output) { - this.output = output; - return this; - } - - public void build(Consumer consumer, ResourceLocation id) { - consumer.accept(new Result(id, this.timePerUnit, this.input, this.output)); - } - - private static class Result implements FinishedRecipe { - private final ResourceLocation id; - private final int timePerUnit; - private final FluidStack input; - private final FluidStack output; - - public Result(ResourceLocation id, int timePerUnit, FluidStack input, FluidStack output) { - this.id = id; - this.timePerUnit = timePerUnit; - this.input = input; - this.output = output; - } - - @Override - public void serializeRecipeData(JsonObject json) { - json.addProperty("time", this.timePerUnit); - json.add("input", RecipeSerializers.serializeFluid(this.input)); - json.add("output", RecipeSerializers.serializeFluid(this.output)); - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getType() { - return FactoryRecipeTypes.STILL.serializer(); - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return null; - } - } -} diff --git a/src/main/java/forestry/core/data/builder/package-info.java b/src/main/java/forestry/core/data/builder/package-info.java deleted file mode 100644 index 688866dad1..0000000000 --- a/src/main/java/forestry/core/data/builder/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault -package forestry.core.data.builder; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/core/data/builder/FilledCrateModelBuilder.java b/src/main/java/forestry/core/data/models/FilledCrateModelBuilder.java similarity index 73% rename from src/main/java/forestry/core/data/builder/FilledCrateModelBuilder.java rename to src/main/java/forestry/core/data/models/FilledCrateModelBuilder.java index 7ccfdfcf67..186caa09af 100644 --- a/src/main/java/forestry/core/data/builder/FilledCrateModelBuilder.java +++ b/src/main/java/forestry/core/data/models/FilledCrateModelBuilder.java @@ -1,15 +1,16 @@ -package forestry.core.data.builder; +package forestry.core.data.models; import com.google.gson.JsonObject; +import forestry.api.ForestryConstants; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.client.model.generators.CustomLoaderBuilder; -import net.minecraftforge.client.model.generators.ModelBuilder; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.client.model.generators.CustomLoaderBuilder; +import net.neoforged.neoforge.client.model.generators.ModelBuilder; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import javax.annotation.Nullable; public class FilledCrateModelBuilder> extends CustomLoaderBuilder { - private static final ResourceLocation ID = new ResourceLocation("forestry:filled_crate"); + private static final ResourceLocation ID = ForestryConstants.forestry("filled_crate"); @Nullable private ResourceLocation layer1; @@ -17,7 +18,8 @@ public class FilledCrateModelBuilder> extends CustomLo private ResourceLocation layer2; public FilledCrateModelBuilder(T parent, ExistingFileHelper helper) { - super(ID, parent, helper); + // idk what allowInlineElements does + super(ID, parent, helper, false); } public static > FilledCrateModelBuilder begin(T parent, ExistingFileHelper helper) { diff --git a/src/main/java/forestry/core/data/models/ForestryBlockStateProvider.java b/src/main/java/forestry/core/data/models/ForestryBlockStateProvider.java index 64418de8ed..af2106c771 100644 --- a/src/main/java/forestry/core/data/models/ForestryBlockStateProvider.java +++ b/src/main/java/forestry/core/data/models/ForestryBlockStateProvider.java @@ -22,11 +22,11 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; -import net.minecraftforge.client.model.generators.BlockModelProvider; -import net.minecraftforge.client.model.generators.BlockStateProvider; -import net.minecraftforge.client.model.generators.ModelFile; -import net.minecraftforge.client.model.generators.loaders.CompositeModelBuilder; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.client.model.generators.BlockModelProvider; +import net.neoforged.neoforge.client.model.generators.loaders.CompositeModelBuilder; +import net.neoforged.neoforge.client.model.generators.BlockStateProvider; +import net.neoforged.neoforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.common.data.ExistingFileHelper; public class ForestryBlockStateProvider extends BlockStateProvider { public ForestryBlockStateProvider(PackOutput output, ExistingFileHelper exFileHelper) { @@ -47,7 +47,7 @@ protected void registerStatesAndModels() { } for (BlockTypePlanter farmType : BlockTypePlanter.values()) { - ModelFile file = models().getExistingFile(modBlock(farmType.getSerializedName())); + ModelFile file = models().getExistingFile(modBlock(farmType.identifier())); horizontalBlock(CultivationBlocks.MANAGED_PLANTER.get(farmType).block(), file); horizontalBlock(CultivationBlocks.MANUAL_PLANTER.get(farmType).block(), file); } @@ -103,9 +103,9 @@ protected void registerStatesAndModels() { BlockBeeHive feature = ApicultureBlocks.BEEHIVE.get(type).block(); String path = path(feature); - ResourceLocation side = modBlock("beehives/" + type.getSerializedName() + ".side"); - ResourceLocation top = modBlock("beehives/" + type.getSerializedName() + ".top"); - ResourceLocation bottom = modBlock("beehives/" + type.getSerializedName() + ".bottom"); + ResourceLocation side = modBlock("beehives/" + type.identifier() + ".side"); + ResourceLocation top = modBlock("beehives/" + type.identifier() + ".top"); + ResourceLocation bottom = modBlock("beehives/" + type.identifier() + ".bottom"); singleModelBlock(this, feature, models().cubeBottomTop(path, side, bottom, top)); generic3d(feature); @@ -123,7 +123,7 @@ public static ModelFile particleOnly(BlockModelProvider models, String path, Res private void singleFarm(FarmBlock block) { EnumFarmMaterial material = block.getFarmMaterial(); Block base = material.getBase(); - ResourceLocation texture = modLoc("block/farm/" + block.getType().getSerializedName()); + ResourceLocation texture = modLoc("block/farm/" + block.getType().identifier()); singleModelBlock(this, block, farmPillar(path(block), base, texture, texture)); } @@ -132,7 +132,6 @@ private void plainFarm(FarmBlock block) { EnumFarmMaterial material = block.getFarmMaterial(); Block base = material.getBase(); - // todo need to use reverse texture getVariantBuilder(block) .partialState().with(FarmBlock.BAND, false) .modelForState().modelFile(farmPillar(path(block), base, modLoc("block/farm/top"), modLoc("block/farm/plain"))).addModel() @@ -178,7 +177,7 @@ public void generic3d(Block block, Block otherParent) { } public void generic3d(Block block, ResourceLocation otherParentId) { - itemModels().withExistingParent(path(block), new ResourceLocation(otherParentId.getNamespace(), "block/" + otherParentId.getPath())); + itemModels().withExistingParent(path(block), otherParentId.withPrefix("block/")); } protected ModelFile existingMcBlock(String path) { @@ -200,10 +199,6 @@ public static ModelFile.UncheckedModelFile file(ResourceLocation resourceLoc) { return new ModelFile.UncheckedModelFile(resourceLoc); } - public ModelFile.UncheckedModelFile modFile(String path) { - return file(this.modBlock(path)); - } - public ModelFile.UncheckedModelFile mcFile(String path) { return file(this.mcBlock(path)); } @@ -228,10 +223,8 @@ public void generic2d(ResourceLocation itemId) { } public void layer0(ResourceLocation itemId, String parentName) { - String path = itemId.getPath(); - - itemModels().getBuilder(path) + itemModels().getBuilder(itemId.getPath()) .parent(new ModelFile.UncheckedModelFile(parentName)) - .texture("layer0", new ResourceLocation(itemId.getNamespace(), "item/" + path)); + .texture("layer0", itemId.withPrefix("item/")); } } diff --git a/src/main/java/forestry/core/data/models/ForestryItemModelProvider.java b/src/main/java/forestry/core/data/models/ForestryItemModelProvider.java deleted file mode 100644 index f8e07adad5..0000000000 --- a/src/main/java/forestry/core/data/models/ForestryItemModelProvider.java +++ /dev/null @@ -1,132 +0,0 @@ -package forestry.core.data.models; - -import com.google.common.collect.Iterables; -import forestry.api.ForestryConstants; -import forestry.api.modules.ForestryModuleIds; -import forestry.apiculture.features.ApicultureItems; -import forestry.core.data.builder.FilledCrateModelBuilder; -import forestry.core.fluids.ForestryFluids; -import forestry.core.utils.ModUtil; -import forestry.cultivation.blocks.BlockPlanter; -import forestry.cultivation.blocks.BlockTypePlanter; -import forestry.cultivation.features.CultivationBlocks; -import forestry.lepidopterology.features.LepidopterologyItems; -import forestry.modules.features.FeatureBlock; -import forestry.modules.features.FeatureItem; -import forestry.modules.features.ModFeatureRegistry; -import forestry.storage.features.CrateItems; -import forestry.storage.items.ItemBackpack; -import forestry.storage.items.ItemCrated; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.BucketItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemNameBlockItem; -import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.model.generators.ItemModelProvider; -import net.minecraftforge.client.model.generators.loaders.DynamicFluidContainerModelBuilder; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.registries.RegistryObject; - -import java.util.Map; - -import static forestry.core.data.models.ForestryBlockStateProvider.file; - -public class ForestryItemModelProvider extends ItemModelProvider { - public ForestryItemModelProvider(PackOutput output, ExistingFileHelper existingFileHelper) { - super(output, ForestryConstants.MOD_ID, existingFileHelper); - } - - @Override - protected void registerModels() { - withExistingParent(LepidopterologyItems.CATERPILLAR_GE.getName(), mcLoc("item/generated")) - .texture("layer0", ForestryConstants.forestry("item/caterpillar.body2")) - .texture("layer1", ForestryConstants.forestry("item/caterpillar.body")); - withExistingParent(LepidopterologyItems.SERUM_GE.getName(), mcLoc("item/generated")) - .texture("layer0", ForestryConstants.forestry("item/liquids/jar.bottle")) - .texture("layer1", ForestryConstants.forestry("item/liquids/jar.contents")); - - for (FeatureItem featureCrated : CrateItems.getCrates()) { - Item containedItem = featureCrated.get().getContained().getItem(); - String id = featureCrated.getName(); - - if (ApicultureItems.BEE_COMBS.itemEqual(containedItem)) { - filledCrateModelLayered(id, modLoc("item/bee_combs.0"), modLoc("item/bee_combs.1")); - } else if (ApicultureItems.POLLEN_CLUSTER.itemEqual(containedItem)) { - filledCrateModelLayered(id, modLoc("item/pollen.0"), modLoc("item/pollen.1")); - } else { - ResourceLocation contained = ModUtil.getRegistryName(containedItem); - ResourceLocation contentsTexture; - - if (containedItem instanceof BlockItem && !(containedItem instanceof ItemNameBlockItem)) { - contentsTexture = new ResourceLocation(contained.getNamespace(), "block/" + contained.getPath()); - } else { - contentsTexture = new ResourceLocation(contained.getNamespace(), "item/" + contained.getPath()); - } - - filledCrateModel(id, contentsTexture); - - } - } - - // 2d items - basicItem(ApicultureItems.FRAME_CREATIVE.get()); - - // manual overrides - filledCrateModel(CrateItems.CRATED_CACTUS.getName(), mcLoc("block/cactus_side")); - filledCrateModel(CrateItems.CRATED_MYCELIUM.getName(), mcLoc("block/mycelium_side")); - filledCrateModel(CrateItems.CRATED_GRASS_BLOCK.getName(), mcLoc("block/grass_block_top")); - filledCrateModel(CrateItems.CRATED_PROPOLIS.getName(), modLoc("item/propolis.0")); - - for (Map.Entry> cell : Iterables.concat(CultivationBlocks.MANAGED_PLANTER.getFeatureByType().entrySet(), CultivationBlocks.MANUAL_PLANTER.getFeatureByType().entrySet())) { - Block block = cell.getValue().block(); - withExistingParent(ForestryBlockStateProvider.path(block), ForestryConstants.forestry("block/" + cell.getKey().getSerializedName())); - } - - // Buckets - for (ForestryFluids fluid : ForestryFluids.values()) { - BucketItem item = fluid.getBucket(); - if (item != null) { - getBuilder(path(item)) - .customLoader(DynamicFluidContainerModelBuilder::begin) - .fluid(fluid.getFluid()) - .end() - .parent(getExistingFile(new ResourceLocation("forge:item/bucket"))); - } - } - - // Backpacks - for (RegistryObject object : ModFeatureRegistry.get(ForestryModuleIds.STORAGE).getRegistry(Registries.ITEM).getEntries()) { - if (object.get() instanceof ItemBackpack) { - String path = object.getId().getPath(); - boolean woven = path.endsWith("woven"); - - withExistingParent(path, woven ? modLoc("item/backpack/woven_neutral") : modLoc("item/backpack/normal_neutral")) - .override().predicate(mcLoc("mode"), 1).model(file(woven ? modLoc("item/backpack/woven_locked") : modLoc("item/backpack/normal_locked"))).end() - .override().predicate(mcLoc("mode"), 2).model(file(woven ? modLoc("item/backpack/woven_receive") : modLoc("item/backpack/normal_receive"))).end() - .override().predicate(mcLoc("mode"), 3).model(file(woven ? modLoc("item/backpack/woven_resupply") : modLoc("item/backpack/normal_resupply"))).end(); - } - } - } - - private static String path(Item block) { - return ModUtil.getRegistryName(block).getPath(); - } - - private void filledCrateModel(String id, ResourceLocation texture) { - getBuilder(id) - .customLoader(FilledCrateModelBuilder::begin) - .layer1(texture) - .end(); - } - - private void filledCrateModelLayered(String id, ResourceLocation layer1, ResourceLocation layer2) { - getBuilder(id) - .customLoader(FilledCrateModelBuilder::begin) - .layer1(layer1) - .layer2(layer2) - .end(); - } -} diff --git a/src/main/java/forestry/core/data/models/ForestryWoodModelProvider.java b/src/main/java/forestry/core/data/models/ForestryWoodModelProvider.java index 4fc5330373..0fc4a51925 100644 --- a/src/main/java/forestry/core/data/models/ForestryWoodModelProvider.java +++ b/src/main/java/forestry/core/data/models/ForestryWoodModelProvider.java @@ -10,8 +10,8 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SlabBlock; import net.minecraft.world.level.block.StairBlock; -import net.minecraftforge.client.model.generators.ModelFile; -import net.minecraftforge.common.data.ExistingFileHelper; +import net.neoforged.neoforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import org.jetbrains.annotations.NotNull; public class ForestryWoodModelProvider extends ForestryBlockStateProvider { diff --git a/src/main/java/forestry/core/data/models/package-info.java b/src/main/java/forestry/core/data/models/package-info.java index ed4fe41c6c..40ec7b0fd4 100644 --- a/src/main/java/forestry/core/data/models/package-info.java +++ b/src/main/java/forestry/core/data/models/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.data.models; diff --git a/src/main/java/forestry/core/data/package-info.java b/src/main/java/forestry/core/data/package-info.java index 7658ed5cd5..84eb329afa 100644 --- a/src/main/java/forestry/core/data/package-info.java +++ b/src/main/java/forestry/core/data/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.data; diff --git a/src/main/java/forestry/core/data/recipe/ApicultureRecipes.java b/src/main/java/forestry/core/data/recipe/ApicultureRecipes.java new file mode 100644 index 0000000000..89e4f484cd --- /dev/null +++ b/src/main/java/forestry/core/data/recipe/ApicultureRecipes.java @@ -0,0 +1,279 @@ +package forestry.core.data.recipe; + +import forestry.api.ForestryTags; +import forestry.apiculture.blocks.BlockAlveary; +import forestry.apiculture.blocks.BlockTypeApiculture; +import forestry.apiculture.blocks.NaturalistChestBlockType; +import forestry.apiculture.features.ApicultureBlocks; +import forestry.apiculture.features.ApicultureItems; +import forestry.apiculture.items.EnumHoneyComb; +import forestry.apiculture.items.EnumPollenCluster; +import forestry.apiculture.items.EnumPropolis; +import forestry.core.features.CoreBlocks; +import forestry.core.features.CoreItems; +import forestry.core.features.FluidsItems; +import forestry.core.items.definitions.EnumContainerType; +import forestry.core.items.definitions.EnumCraftingMaterial; +import forestry.core.items.definitions.EnumElectronTube; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.tags.ItemTags; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; +import net.neoforged.neoforge.common.Tags; +import thedarkcolour.modkit.data.MKRecipeProvider; + +public class ApicultureRecipes { + static void registerApicultureRecipes(MKRecipeProvider recipes) { + registerCombRecipes(recipes); + + // Bee housings + beeHousings(recipes); + + // Apiarist Suit + ItemLike wovenSilk = CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK); + recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_HELMET, recipe -> { + recipe.define('#', wovenSilk); + recipe.pattern("###"); + recipe.pattern("# #"); + recipe.group("apiarist_armour"); + }); + recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_CHEST, recipe -> { + recipe.define('#', wovenSilk); + recipe.pattern("# #"); + recipe.pattern("###"); + recipe.pattern("###"); + recipe.group("apiarist_armour"); + }); + recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_LEGS, recipe -> { + recipe.define('#', wovenSilk); + recipe.pattern("###"); + recipe.pattern("# #"); + recipe.pattern("# #"); + recipe.group("apiarist_armour"); + }); + recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_BOOTS, recipe -> { + recipe.define('#', wovenSilk); + recipe.pattern("# #"); + recipe.pattern("# #"); + recipe.group("apiarist_armour"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.APIARIST_CHEST), recipe -> { + recipe.define('G', Tags.Items.GLASS_BLOCKS); + recipe.define('X', ForestryTags.Items.BEE_COMBS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern(" G "); + recipe.pattern("XYX"); + recipe.pattern("XXX"); + }); + + ItemLike propolis = ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL); + + recipes.shapedCrafting(RecipeCategory.MISC, CoreItems.BITUMINOUS_PEAT, recipe -> { + recipe.define('#', ForestryTags.Items.DUSTS_ASH); + recipe.define('X', CoreItems.PEAT); + recipe.define('Y', propolis); + recipe.pattern(" # "); + recipe.pattern("XYX"); + recipe.pattern(" # "); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, ApicultureItems.FRAME_IMPREGNATED, recipe -> { + recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.IMPREGNATED_STICK)); + recipe.define('S', Tags.Items.STRINGS); + recipe.pattern("###"); + recipe.pattern("#S#"); + recipe.pattern("###"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, ApicultureItems.FRAME_UNTREATED, recipe -> { + recipe.define('#', Tags.Items.RODS_WOODEN); + recipe.define('S', Tags.Items.STRINGS); + recipe.pattern("###"); + recipe.pattern("#S#"); + recipe.pattern("###"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.PULSATING_MESH), recipe -> { + recipe.define('#', ApicultureItems.PROPOLIS.get(EnumPropolis.PULSATING)); + recipe.pattern("# #"); + recipe.pattern(" # "); + recipe.pattern("# #"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, ApicultureItems.SCOOP, recipe -> { + recipe.define('#', Tags.Items.RODS_WOODEN); + recipe.define('X', ItemTags.WOOL); + recipe.pattern("#X#"); + recipe.pattern("###"); + recipe.pattern(" # "); + }); + + recipes.shapedCrafting("slime_from_propolis", RecipeCategory.MISC, Items.SLIME_BALL, recipe -> { + recipe.define('#', propolis); + recipe.define('X', ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL)); + recipe.pattern("#X#"); + recipe.pattern("#X#"); + recipe.pattern("#X#"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, ApicultureItems.SMOKER, recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_TIN); + recipe.define('S', Tags.Items.RODS_WOODEN); + recipe.define('F', Items.FLINT_AND_STEEL); + recipe.define('L', Tags.Items.LEATHERS); + recipe.pattern("LS#"); + recipe.pattern("LF#"); + recipe.pattern("###"); + }); + + recipes.shapedCrafting("glistering_melon_slice", RecipeCategory.MISC, Items.GLISTERING_MELON_SLICE, recipe -> { + recipe.define('#', ApicultureItems.HONEY_DROP); + recipe.define('X', ApicultureItems.HONEYDEW); + recipe.define('Y', Items.MELON_SLICE); + recipe.pattern("#X#"); + recipe.pattern("#Y#"); + recipe.pattern("#X#"); + }); + + ItemLike beesWax = CoreItems.BEESWAX; + recipes.shapedCrafting("torch_from_wax", RecipeCategory.MISC, Items.TORCH, 3, recipe -> { + recipe.define('#', beesWax); + recipe.define('Y', Tags.Items.RODS_WOODEN); + recipe.pattern(" # "); + recipe.pattern(" # "); + recipe.pattern(" Y "); + }); + + recipes.shapelessCrafting("exp_bottle_from_exp_drop", RecipeCategory.MISC, Items.EXPERIENCE_BOTTLE, 1, Items.GLASS_BOTTLE, ApicultureItems.EXPERIENCE_DROP.item()); + } + + private static void registerCombRecipes(MKRecipeProvider recipes) { + for (EnumHoneyComb honeyComb : EnumHoneyComb.values()) { + ItemLike comb = ApicultureItems.BEE_COMBS.get(honeyComb); + Block combBlock = ApicultureBlocks.BEE_COMB.get(honeyComb).block(); + recipes.grid2x2(RecipeCategory.BUILDING_BLOCKS, combBlock, 1, Ingredient.of(comb), "combs"); + } + } + + private static void beeHousings(MKRecipeProvider recipes) { + // Bee House + recipes.shapedCrafting(RecipeCategory.MISC, ApicultureBlocks.BASE.get(BlockTypeApiculture.BEE_HOUSE).block(), recipe -> { + recipe.define('S', ItemTags.WOODEN_SLABS); + recipe.define('P', ItemTags.PLANKS); + recipe.define('C', ForestryTags.Items.BEE_COMBS); + recipe.pattern("SSS"); + recipe.pattern("PCP"); + recipe.pattern("PPP"); + }); + // Apiary + recipes.shapedCrafting(RecipeCategory.MISC, ApicultureBlocks.BASE.get(BlockTypeApiculture.APIARY).block(), recipe -> { + recipe.define('S', ItemTags.WOODEN_SLABS); + recipe.define('P', ItemTags.PLANKS); + recipe.define('C', CoreItems.IMPREGNATED_CASING); + recipe.pattern("SSS"); + recipe.pattern("PCP"); + recipe.pattern("PPP"); + }); + + // Alveary components + BlockAlveary plain = ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.PLAIN).block(); + ItemLike goldElectronTube = CoreItems.ELECTRON_TUBES.get(EnumElectronTube.GOLD); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, plain, recipe -> { + recipe.define('X', CoreItems.IMPREGNATED_CASING); + recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SCENTED_PANELING)); + recipe.pattern("###"); + recipe.pattern("#X#"); + recipe.pattern("###"); + recipe.group("alveary"); + }); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.FAN).block(), recipe -> { + recipe.define('#', goldElectronTube); + recipe.define('X', plain); + recipe.define('I', Tags.Items.INGOTS_IRON); + recipe.pattern("I I"); + recipe.pattern(" X "); + recipe.pattern("I#I"); + recipe.group("alveary"); + }); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.HEATER).block(), recipe -> { + recipe.define('#', goldElectronTube); + recipe.define('I', Tags.Items.INGOTS_IRON); + recipe.define('X', plain); + recipe.define('S', Tags.Items.STONES); + recipe.pattern("#I#"); + recipe.pattern(" X "); + recipe.pattern("SSS"); + recipe.group("alveary"); + }); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.HYGRO).block(), recipe -> { + recipe.define('G', Tags.Items.GLASS_BLOCKS); + recipe.define('X', plain); + recipe.define('I', Tags.Items.INGOTS_IRON); + recipe.pattern("GIG"); + recipe.pattern("GXG"); + recipe.pattern("GIG"); + recipe.group("alveary"); + }); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.SIEVE).block(), recipe -> { + recipe.define('W', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK)); + recipe.define('X', plain); + recipe.define('I', Tags.Items.INGOTS_IRON); + recipe.pattern("III"); + recipe.pattern(" X "); + recipe.pattern("WWW"); + recipe.group("alveary"); + }); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.STABILISER).block(), recipe -> { + recipe.define('X', plain); + recipe.define('G', Tags.Items.GEMS_QUARTZ); + recipe.pattern("G G"); + recipe.pattern("GXG"); + recipe.pattern("G G"); + recipe.group("alveary"); + }); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlveary.Type.SWARMER).block(), recipe -> { + recipe.define('#', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.DIAMOND)); + recipe.define('X', plain); + recipe.define('G', Tags.Items.INGOTS_GOLD); + recipe.pattern("#G#"); + recipe.pattern(" X "); + recipe.pattern("#G#"); + recipe.group("alveary"); + }); + } + + static void registerFoodRecipes(MKRecipeProvider recipes) { + ItemLike waxCapsule = FluidsItems.CONTAINERS.get(EnumContainerType.CAPSULE); + ItemLike honeyDrop = ApicultureItems.HONEY_DROP; + + recipes.shapedCrafting(RecipeCategory.FOOD, ApicultureItems.AMBROSIA, recipe -> { + recipe.define('#', ApicultureItems.HONEYDEW); + recipe.define('X', ApicultureItems.ROYAL_JELLY); + recipe.define('Y', waxCapsule); + recipe.pattern("#Y#"); + recipe.pattern("XXX"); + recipe.pattern("###"); + }); + + recipes.shapedCrafting(RecipeCategory.FOOD, ApicultureItems.HONEYED_SLICE, recipe -> { + recipe.define('#', honeyDrop); + recipe.define('X', Items.BREAD); + recipe.pattern("###"); + recipe.pattern("#X#"); + recipe.pattern("###"); + }); + + recipes.shapelessCrafting("bottled_honey_drops", RecipeCategory.FOOD, Items.HONEY_BOTTLE, 1, Items.GLASS_BOTTLE, honeyDrop, honeyDrop); + + } +} diff --git a/src/main/java/forestry/core/data/recipe/ArboricultureRecipes.java b/src/main/java/forestry/core/data/recipe/ArboricultureRecipes.java new file mode 100644 index 0000000000..bc5ed3b40b --- /dev/null +++ b/src/main/java/forestry/core/data/recipe/ArboricultureRecipes.java @@ -0,0 +1,196 @@ +package forestry.core.data.recipe; + +import forestry.api.ForestryTags; +import forestry.api.IForestryApi; +import forestry.api.arboriculture.IWoodAccess; +import forestry.api.arboriculture.IWoodType; +import forestry.api.arboriculture.WoodBlockKind; +import forestry.apiculture.blocks.NaturalistChestBlockType; +import forestry.arboriculture.ForestryWoodType; +import forestry.arboriculture.VanillaWoodType; +import forestry.arboriculture.WoodAccess; +import forestry.arboriculture.features.ArboricultureBlocks; +import forestry.arboriculture.features.ArboricultureItems; +import forestry.arboriculture.features.CharcoalBlocks; +import forestry.core.features.CoreBlocks; +import forestry.core.features.CoreItems; +import forestry.core.fluids.ForestryFluids; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.data.recipes.ShapedRecipeBuilder; +import net.minecraft.tags.ItemTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.block.Block; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; +import thedarkcolour.modkit.data.MKRecipeProvider; + +import java.util.List; + +import static forestry.core.data.recipe.CoreRecipes.fabricator; + +class ArboricultureRecipes { + static void registerArboricultureRecipes(RecipeOutput output, MKRecipeProvider recipes) { + registerWoodRecipes(recipes); + + for (ForestryWoodType type : ForestryWoodType.values()) { + addFireproofRecipes(output, recipes, type); + } + + for (VanillaWoodType type : VanillaWoodType.values()) { + addFireproofRecipes(output, recipes, type); + } + + recipes.shapedCrafting(RecipeCategory.TOOLS, ArboricultureItems.GRAFTER, recipe -> { + recipe.define('B', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('#', Tags.Items.RODS_WOODEN); + recipe.pattern(" B"); + recipe.pattern(" # "); + recipe.pattern("# "); + }); + recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST), recipe -> { + recipe.define('X', ItemTags.SAPLINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.pattern(" # "); + recipe.pattern("XYX"); + recipe.pattern("XXX"); + }); + } + + static void registerWoodRecipes(MKRecipeProvider recipes) { + IWoodAccess woodAccess = WoodAccess.INSTANCE; + List woodTypes = woodAccess.getRegisteredWoodTypes(); + + for (IWoodType woodType : woodTypes) { + Block planks = woodAccess.getBlock(woodType, WoodBlockKind.PLANKS, false).getBlock(); + Block fireproofPlanks = woodAccess.getBlock(woodType, WoodBlockKind.PLANKS, true).getBlock(); + Block log = woodAccess.getBlock(woodType, WoodBlockKind.LOG, false).getBlock(); + Block fireproofLog = woodAccess.getBlock(woodType, WoodBlockKind.LOG, true).getBlock(); + Block wood = woodAccess.getBlock(woodType, WoodBlockKind.WOOD, false).getBlock(); + Block fireproofWood = woodAccess.getBlock(woodType, WoodBlockKind.WOOD, true).getBlock(); + Block strippedLog = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_LOG, false).getBlock(); + Block fireproofStrippedLog = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_LOG, true).getBlock(); + Block strippedWood = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_WOOD, false).getBlock(); + Block fireproofStrippedWood = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_WOOD, true).getBlock(); + Block door = woodAccess.getBlock(woodType, WoodBlockKind.DOOR, false).getBlock(); + Block trapdoor = woodAccess.getBlock(woodType, WoodBlockKind.TRAPDOOR, false).getBlock(); + Block fence = woodAccess.getBlock(woodType, WoodBlockKind.FENCE, false).getBlock(); + Block fireproofFence = woodAccess.getBlock(woodType, WoodBlockKind.FENCE, true).getBlock(); + Block fenceGate = woodAccess.getBlock(woodType, WoodBlockKind.FENCE_GATE, false).getBlock(); + Block fireproofFenceGate = woodAccess.getBlock(woodType, WoodBlockKind.FENCE_GATE, true).getBlock(); + Block slab = woodAccess.getBlock(woodType, WoodBlockKind.SLAB, false).getBlock(); + Block fireproofSlab = woodAccess.getBlock(woodType, WoodBlockKind.SLAB, true).getBlock(); + Block stairs = woodAccess.getBlock(woodType, WoodBlockKind.STAIRS, false).getBlock(); + Block fireproofStairs = woodAccess.getBlock(woodType, WoodBlockKind.STAIRS, true).getBlock(); + + TagKey logTag = woodAccess.getLogItemTag(woodType, false); + TagKey fireproofLogTag = woodAccess.getLogItemTag(woodType, true); + + recipes.woodenDoor(door, woodType instanceof VanillaWoodType ? Ingredient.of(fireproofPlanks) : Ingredient.of(planks, fireproofPlanks)); + + // Regular (Forestry) + if (woodType instanceof ForestryWoodType type) { + makeCommonWoodenSet(recipes, planks, log, logTag, wood, strippedLog, strippedWood, fence, fenceGate, slab, stairs); + + recipes.shapelessCrafting(RecipeCategory.MISC, ArboricultureItems.CHEST_BOAT.item(type), 1, ArboricultureItems.BOAT.item(type), Tags.Items.CHESTS_WOODEN); + recipes.shapedCrafting(RecipeCategory.MISC, ArboricultureItems.BOAT.item(type), recipe -> { + recipe.define('P', Ingredient.of(planks, fireproofPlanks)); + recipe.pattern("P P"); + recipe.pattern("PPP"); + }); + + recipes.woodenTrapdoor(trapdoor, Ingredient.of(planks, fireproofPlanks)); + + recipes.shapedCrafting(RecipeCategory.MISC, ArboricultureBlocks.SIGN.get(type), recipe -> { + recipe.define('P', Ingredient.of(planks, fireproofPlanks)); + recipe.define('S', Tags.Items.RODS_WOODEN); + recipe.pattern("PPP"); + recipe.pattern("PPP"); + recipe.pattern(" S "); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, ArboricultureBlocks.HANGING_SIGN.get(type), recipe -> { + recipe.define('X', Items.CHAIN); + recipe.define('#', Ingredient.of(strippedLog, fireproofStrippedLog)); + recipe.pattern("X X"); + recipe.pattern("###"); + recipe.pattern("###"); + }); + + recipes.shapelessCrafting(RecipeCategory.REDSTONE, ArboricultureBlocks.BUTTON.get(type), 1, Ingredient.of(planks, fireproofPlanks)); + recipes.shapedCrafting(RecipeCategory.REDSTONE, ArboricultureBlocks.PRESSURE_PLATE.get(type), recipe -> { + recipe.define('P', Ingredient.of(planks, fireproofPlanks)); + recipe.pattern("PP"); + }); + } + + // Fireproof (Vanilla & Forestry) + makeCommonWoodenSet(recipes, fireproofPlanks, fireproofLog, fireproofLogTag, fireproofWood, fireproofStrippedLog, fireproofStrippedWood, fireproofFence, fireproofFenceGate, fireproofSlab, fireproofStairs); + } + } + + // Shared between regular and fireproof recipes + static void makeCommonWoodenSet(MKRecipeProvider recipes, Block planks, Block log, TagKey logTag, Block wood, Block strippedLog, Block strippedWood, Block fence, Block fenceGate, Block slab, Block stairs) { + recipes.shapelessCrafting(RecipeCategory.BUILDING_BLOCKS, planks, 4, "planks", logTag); + recipes.woodenFence(fence, planks); + recipes.woodenFenceGate(fenceGate, planks); + recipes.woodenSlab(slab, planks); + recipes.woodenStairs(stairs, planks); + recipes.grid2x2(RecipeCategory.BUILDING_BLOCKS, wood, 3, Ingredient.of(log), "bark"); + recipes.grid2x2(RecipeCategory.BUILDING_BLOCKS, strippedWood, 3, Ingredient.of(strippedLog), "bark"); + } + + static void registerCharcoalRecipes(MKRecipeProvider recipes) { + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.CHARCOAL.block(), recipe -> { + recipe.define('#', Items.CHARCOAL); + recipe.pattern("###"); + recipe.pattern("###"); + recipe.pattern("###"); + }); + + recipes.shapelessCrafting("charcoal_from_block", RecipeCategory.MISC, Items.CHARCOAL, 9, ForestryTags.Items.CHARCOAL_BLOCK); + + recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.LOG_PILE.block(), recipe -> { + recipe.define('L', ItemTags.LOGS); + recipe.pattern(" L "); + recipe.pattern("L L"); + recipe.pattern(" L "); + }); + + recipes.shapelessCrafting(RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.DECORATIVE_LOG_PILE.block(), 1, CharcoalBlocks.LOG_PILE.block()); + + recipes.shapelessCrafting("wood_pile_from_decorative", RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.LOG_PILE.block(), 1, CharcoalBlocks.DECORATIVE_LOG_PILE.block()); + } + + static void addFireproofRecipes(RecipeOutput consumer, MKRecipeProvider recipes, IWoodType type) { + SizedFluidIngredient liquidGlass = ForestryFluids.GLASS.ingredient(500); + + List logLike = List.of(WoodBlockKind.LOG, WoodBlockKind.WOOD, WoodBlockKind.STRIPPED_LOG, WoodBlockKind.STRIPPED_WOOD); + IWoodAccess woodAccess = IForestryApi.INSTANCE.getTreeManager().getWoodAccess(); + + for (WoodBlockKind woodKind : logLike) { + try { + fabricator(consumer, recipes, liquidGlass, woodAccess.getBlock(type, woodKind, true), 2, recipe -> { + recipe.pattern(" "); + recipe.pattern("X#X"); + recipe.pattern(" "); + recipe.define('#', CoreItems.REFRACTORY_WAX); + recipe.define('X', woodAccess.getBlock(type, woodKind, false).getBlock())); + }); + } catch (IllegalStateException ignored) { + } + } + + fabricator(consumer, recipes, liquidGlass, woodAccess.getBlock(type, WoodBlockKind.PLANKS, true), 8, recipe -> { + recipe.pattern("XXX"); + recipe.pattern("X#X"); + recipe.pattern("XXX"); + recipe.define('#', CoreItems.REFRACTORY_WAX); + recipe.define('X', woodAccess.getBlock(type, WoodBlockKind.PLANKS, false).getBlock())); + }); + } +} diff --git a/src/main/java/forestry/core/data/recipe/CoreRecipes.java b/src/main/java/forestry/core/data/recipe/CoreRecipes.java new file mode 100644 index 0000000000..e1dff58003 --- /dev/null +++ b/src/main/java/forestry/core/data/recipe/CoreRecipes.java @@ -0,0 +1,917 @@ +package forestry.core.data.recipe; + +import forestry.api.ForestryConstants; +import forestry.api.ForestryTags; +import forestry.api.core.Product; +import forestry.apiculture.blocks.NaturalistChestBlockType; +import forestry.apiculture.features.ApicultureItems; +import forestry.apiculture.items.EnumHoneyComb; +import forestry.apiculture.items.EnumPollenCluster; +import forestry.apiculture.items.EnumPropolis; +import forestry.apiculture.recipes.HygroregulatorRecipe; +import forestry.core.blocks.BlockTypeCoreTesr; +import forestry.core.blocks.EnumResourceType; +import forestry.core.circuits.CircuitBoard; +import forestry.core.circuits.EnumCircuitBoardType; +import forestry.core.config.Constants; +import forestry.core.features.CoreBlocks; +import forestry.core.features.CoreDataComponents; +import forestry.core.features.CoreItems; +import forestry.core.features.FluidsItems; +import forestry.core.fluids.ForestryFluids; +import forestry.core.items.definitions.EnumContainerType; +import forestry.core.items.definitions.EnumCraftingMaterial; +import forestry.core.items.definitions.EnumElectronTube; +import forestry.energy.blocks.EngineBlockType; +import forestry.energy.features.EnergyBlocks; +import forestry.factory.recipes.*; +import forestry.lepidopterology.features.LepidopterologyItems; +import forestry.lepidopterology.recipe.ButterflyMatingRecipe; +import forestry.mail.blocks.BlockTypeMail; +import forestry.mail.features.MailBlocks; +import forestry.mail.features.MailItems; +import forestry.mail.items.EnumStampDefinition; +import forestry.mail.items.ItemLetter; +import forestry.mail.items.ItemStamp; +import forestry.modules.features.FeatureItem; +import forestry.sorting.features.SortingBlocks; +import forestry.storage.features.CrateItems; +import forestry.worktable.features.WorktableBlocks; +import it.unimi.dsi.fastutil.objects.ObjectIntPair; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.data.recipes.ShapedRecipeBuilder; +import net.minecraft.data.recipes.ShapelessRecipeBuilder; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.FluidTags; +import net.minecraft.tags.ItemTags; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.material.Fluid; +import net.minecraft.world.level.material.Fluids; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.common.NeoForgeMod; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.common.crafting.DataComponentIngredient; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; +import net.neoforged.neoforge.fluids.crafting.FluidIngredient; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; +import thedarkcolour.modkit.data.MKRecipeProvider; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import static thedarkcolour.modkit.data.MKRecipeProvider.ingredient; + +public class CoreRecipes { + // todo it might be cool to have a custom ingredient that checks for the fluid capability, so stuff like Thermal tanks could be used + static Ingredient getContainer(EnumContainerType type, Fluid fluid) { + ItemStack container = FluidsItems.CONTAINERS.stack(type); + IFluidHandlerItem fluidHandlerCap = container.getCapability(Capabilities.FluidHandler.ITEM); + fluidHandlerCap.fill(new FluidStack(fluid, Integer.MAX_VALUE), IFluidHandler.FluidAction.EXECUTE); + return DataComponentIngredient.of(false, container); + } + + public static void addRecipes(RecipeOutput output, MKRecipeProvider recipes) { + // Vanilla recipe types + ArboricultureRecipes.registerArboricultureRecipes(output, recipes); + ApicultureRecipes.registerApicultureRecipes(recipes); + ApicultureRecipes.registerFoodRecipes(recipes); + StorageRecipes.registerBackpackRecipes(output, recipes); + ArboricultureRecipes.registerCharcoalRecipes(recipes); + registerCoreRecipes(recipes); + CultivationRecipes.registerCultivationRecipes(recipes); + FactoryRecipes.registerFactoryRecipes(recipes); + CultivationRecipes.registerFarmingRecipes(recipes); + registerFluidsRecipes(recipes); + registerLepidopterologyRecipes(recipes); + registerMailRecipes(recipes); + registerSortingRecipes(recipes); + registerWorktableRecipes(recipes); + registerEnergyRecipes(recipes); + + // Forestry recipe types + registerCarpenter(output, recipes); + registerCentrifuge(output); + FactoryRecipes.registerFabricator(output, recipes); + FactoryRecipes.registerFabricatorSmelting(output); + registerFermenter(output); + registerHygroregulator(output); + CultivationRecipes.registerMoistener(output); + registerSqueezerContainer(output); + registerSqueezer(output); + registerStill(output); + } + + private static void registerCoreRecipes(MKRecipeProvider recipes) { + recipes.oreSmelting(ingredient(CoreBlocks.APATITE_ORE.get(), CoreBlocks.DEEPSLATE_APATITE_ORE.get()), CoreItems.APATITE, 0.5f, 200); + recipes.oreSmelting(ingredient(CoreBlocks.TIN_ORE.get(), CoreBlocks.DEEPSLATE_TIN_ORE.get(), CoreItems.RAW_TIN), CoreItems.INGOT_TIN, 0.5f, 200); + recipes.smelting(Ingredient.of(CoreItems.PEAT.item()), CoreItems.ASH, 0.0f, 200); + recipes.storage3x3(CoreBlocks.RAW_TIN_BLOCK, CoreItems.RAW_TIN); + + recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.BASE.get(BlockTypeCoreTesr.ANALYZER), recipe -> { + recipe.define('T', CoreItems.PORTABLE_ALYZER); + recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("XTX"); + recipe.pattern(" Y "); + recipe.pattern("X X"); + }); + recipes.storage3x3(CoreBlocks.RESOURCE_STORAGE.get(EnumResourceType.APATITE), CoreItems.APATITE); + recipes.storage3x3(CoreBlocks.RESOURCE_STORAGE.get(EnumResourceType.BRONZE), CoreItems.INGOT_BRONZE); + recipes.storage3x3(CoreBlocks.RESOURCE_STORAGE.get(EnumResourceType.TIN), CoreItems.INGOT_TIN); + recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.BRONZE_PICKAXE, recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('X', Tags.Items.RODS_WOODEN); + recipe.pattern("###"); + recipe.pattern(" X "); + recipe.pattern(" X "); + }); + recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.BRONZE_SHOVEL, recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('X', Tags.Items.RODS_WOODEN); + recipe.pattern(" # "); + recipe.pattern(" X "); + recipe.pattern(" X "); + }); + + gear(recipes, CoreItems.GEAR_BRONZE, ForestryTags.Items.INGOTS_BRONZE); + gear(recipes, CoreItems.GEAR_TIN, ForestryTags.Items.INGOTS_TIN); + gear(recipes, CoreItems.GEAR_COPPER, Tags.Items.INGOTS_COPPER); + + recipes.shapelessCrafting("ingot_bronze_alloying", RecipeCategory.MISC, CoreItems.INGOT_BRONZE, 4, ForestryTags.Items.INGOTS_TIN, ObjectIntPair.of(Items.COPPER_INGOT, 3)); + recipes.shapelessCrafting(RecipeCategory.TOOLS, CoreItems.KIT_PICKAXE, 1, CoreItems.BRONZE_PICKAXE, CoreItems.CARTON); + recipes.shapelessCrafting(RecipeCategory.TOOLS, CoreItems.KIT_SHOVEL, 1, CoreItems.BRONZE_SHOVEL, CoreItems.CARTON); + recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.SPECTACLES, recipe -> { + recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('Y', Tags.Items.GLASS_PANES); + recipe.pattern(" X "); + recipe.pattern("Y Y"); + }); + recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.PIPETTE, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('X', Tags.Items.GLASS_PANES); + recipe.pattern(" #"); + recipe.pattern(" X "); + recipe.pattern("X "); + }); + recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.PORTABLE_ALYZER, recipe -> { + recipe.define('#', Tags.Items.GLASS_PANES); + recipe.define('X', ForestryTags.Items.INGOTS_TIN); + recipe.define('R', Tags.Items.DUSTS_REDSTONE); + recipe.define('D', Tags.Items.GEMS_DIAMOND); + recipe.pattern("X#X"); + recipe.pattern("X#X"); + recipe.pattern("RDR"); + }); + + recipes.shapedCrafting("string_from_wisp", RecipeCategory.MISC, Items.STRING, recipe -> { + recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP)); + recipe.pattern(" # "); + recipe.pattern(" # "); + recipe.pattern(" # "); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, CoreItems.STURDY_CASING, recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); + recipe.pattern("###"); + recipe.pattern("# #"); + recipe.pattern("###"); + }); + + recipes.shapedCrafting("cobweb_from_wisp", RecipeCategory.MISC, Items.COBWEB, 4, recipe -> { + recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP)); + recipe.pattern("# #"); + recipe.pattern(" # "); + recipe.pattern("# #"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.WRENCH, recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); + recipe.pattern("# #"); + recipe.pattern(" # "); + recipe.pattern(" # "); + }); + + recipes.shapedCrafting("can", RecipeCategory.MISC, FluidsItems.CONTAINERS.get(EnumContainerType.CAN), 12, recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_TIN); + recipe.pattern(" # "); + recipe.pattern("# #"); + }); + + recipes.shapedCrafting("capsule", RecipeCategory.MISC, FluidsItems.CONTAINERS.get(EnumContainerType.CAPSULE), 4, recipe -> { + recipe.define('#', CoreItems.BEESWAX); + recipe.pattern(" # "); + recipe.pattern("# #"); + }); + + recipes.shapedCrafting("refractory_capsule", RecipeCategory.MISC, FluidsItems.CONTAINERS.get(EnumContainerType.REFRACTORY), 4, recipe -> { + recipe.define('#', CoreItems.REFRACTORY_WAX); + recipe.pattern(" # "); + recipe.pattern("# #"); + }); + + recipes.shapedCrafting("compressed_ice_shards", RecipeCategory.MISC, Items.ICE, 1, recipe -> { + recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)); + recipe.pattern("##"); + recipe.pattern("##"); + }); + + recipes.shapedCrafting("honey_drop_block", RecipeCategory.MISC, Items.HONEY_BLOCK, 1, recipe -> { + recipe.define('V', ApicultureItems.HONEY_DROP); + recipe.pattern("VVV"); + recipe.pattern("V V"); + recipe.pattern("VVV"); + }); + + recipes.shapedCrafting("phosphor_torches", RecipeCategory.MISC, Items.TORCH, 6, recipe -> { + recipe.define('P', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.PHOSPHOR)); + recipe.define('|', Tags.Items.RODS_WOODEN); + recipe.pattern(" P "); + recipe.pattern(" | "); + }); + + recipes.shapedCrafting("beeswax_candles", RecipeCategory.MISC, Items.CANDLE, 1, recipe -> { + recipe.define('|', Tags.Items.STRINGS); + recipe.define('^', CoreItems.BEESWAX); + recipe.pattern(" | "); + recipe.pattern(" ^ "); + }); + + // Books + recipes.shapelessCrafting("foresters_manual_honeydrop", RecipeCategory.MISC, CoreItems.FORESTERS_MANUAL, 1, Items.BOOK, ApicultureItems.HONEY_DROP); + recipes.shapelessCrafting("foresters_manual_sapling", RecipeCategory.MISC, CoreItems.FORESTERS_MANUAL, 1, Items.BOOK, ItemTags.SAPLINGS); + recipes.shapelessCrafting("foresters_manual_butterfly", RecipeCategory.MISC, CoreItems.FORESTERS_MANUAL, 1, Items.BOOK, LepidopterologyItems.BUTTERFLY_GE); + } + + private static void gear(MKRecipeProvider recipes, ItemLike gear, TagKey ingot) { + // In old versions, these gears were upgrades of BuildCraft's stone gears (which are tiered) + // Might bring this back if anything comes out of that BuildCraft port. + // For now, just have the same recipes as Thermal. + recipes.shapedCrafting(RecipeCategory.MISC, gear, recipe -> { + recipe.define('#', ingot); + recipe.define('X', Tags.Items.NUGGETS_IRON); + recipe.pattern(" # "); + recipe.pattern("#X#"); + recipe.pattern(" # "); + }); + } + + private static void registerFluidsRecipes(MKRecipeProvider recipes) { + for (EnumContainerType containerType : EnumContainerType.values()) { + recipes.shapedCrafting("cake_" + containerType.identifier(), RecipeCategory.FOOD, Items.CAKE, recipe -> { + recipe.define('A', getContainer(containerType, NeoForgeMod.MILK.get())); + recipe.define('B', Items.SUGAR); + recipe.define('C', Items.WHEAT); + recipe.define('E', Items.EGG); + recipe.pattern("AAA"); + recipe.pattern("BEB"); + recipe.pattern("CCC"); + }); + } + } + + private static void registerLepidopterologyRecipes(MKRecipeProvider recipes) { + recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.LEPIDOPTERIST_CHEST), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', LepidopterologyItems.BUTTERFLY_GE); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern(" # "); + recipe.pattern("XYX"); + recipe.pattern("XXX"); + }); + recipes.special("butterfly_mating", ButterflyMatingRecipe::new); + } + + private static void registerMailRecipes(MKRecipeProvider recipes) { + recipes.shapelessCrafting(RecipeCategory.MISC, MailItems.CATALOGUE, 1, Items.BOOK, ForestryTags.Items.STAMPS); + Ingredient sealant = Ingredient.fromValues(Stream.of(new Ingredient.TagValue(ForestryTags.Items.PROPOLIS), new Ingredient.TagValue(Tags.Items.SLIME_BALLS))); + recipes.shapelessCrafting(RecipeCategory.MISC, MailItems.LETTERS.get(ItemLetter.Size.EMPTY, ItemLetter.State.FRESH), 1, Items.PAPER, sealant); + + recipes.shapedCrafting(RecipeCategory.MISC, MailBlocks.BASE.get(BlockTypeMail.MAILBOX).block(), recipe -> { + recipe.define('#', ForestryTags.Items.INGOTS_TIN); + recipe.define('X', Tags.Items.CHESTS_WOODEN); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern(" # "); + recipe.pattern("#Y#"); + recipe.pattern("XXX"); + }); + + Ingredient emptiedLetter = Ingredient.fromValues(MailItems.LETTERS.getRowFeatures(ItemLetter.Size.EMPTY).stream().map(feature -> new Ingredient.ItemValue(feature.stack()))); + recipes.shapedCrafting("paper_from_letters", RecipeCategory.MISC, Items.PAPER, recipe -> { + recipe.define('#', emptiedLetter); + recipe.pattern(" # "); + recipe.pattern(" # "); + recipe.pattern(" # "); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, MailBlocks.BASE.get(BlockTypeMail.TRADE_STATION).block(), recipe -> { + recipe.define('#', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.BRONZE)); + recipe.define('X', Tags.Items.CHESTS_WOODEN); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.define('Z', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.IRON)); + recipe.define('W', DataComponentIngredient.of(false, CoreDataComponents.CIRCUIT_BOARD.value(), CircuitBoard.empty(EnumCircuitBoardType.REFINED), CoreItems.CIRCUITBOARDS.item(EnumCircuitBoardType.REFINED))); + recipe.pattern("Z#Z"); + recipe.pattern("#Y#"); + recipe.pattern("XWX"); + }); + + Ingredient glue = Ingredient.fromValues(Stream.of( + new Ingredient.TagValue(ForestryTags.Items.DROP_HONEY), + new Ingredient.TagValue(Tags.Items.SLIME_BALLS) + )); + + for (EnumStampDefinition stampDefinition : EnumStampDefinition.VALUES) { + recipes.shapedCrafting(RecipeCategory.MISC, MailItems.STAMPS.get(stampDefinition), 9, recipe -> { + recipe.define('X', stampDefinition.getCraftingIngredient()); + recipe.define('#', Items.PAPER); + recipe.define('Z', glue); + recipe.pattern("XXX"); + recipe.pattern("###"); + recipe.pattern("ZZZ"); + }); + } + } + + private static void registerSortingRecipes(MKRecipeProvider recipes) { + Ingredient ing = Ingredient.fromValues(Stream.of( + new Ingredient.ItemValue(LepidopterologyItems.CATERPILLAR.stack()), + new Ingredient.ItemValue(ApicultureItems.PROPOLIS.stack(EnumPropolis.NORMAL)), + new Ingredient.TagValue(ForestryTags.Items.FORESTRY_FRUITS) + )); + + recipes.shapedCrafting(RecipeCategory.MISC, SortingBlocks.FILTER.block(), 2, recipe -> { + recipe.define('B', ForestryTags.Items.GEARS_BRONZE); + recipe.define('D', Tags.Items.GEMS_DIAMOND); + recipe.define('F', ing); + recipe.define('W', ItemTags.PLANKS); + recipe.define('G', Tags.Items.GLASS_BLOCKS); + recipe.pattern("WDW"); + recipe.pattern("FGF"); + recipe.pattern("BDB"); + }); + } + + private static void registerWorktableRecipes(MKRecipeProvider recipes) { + recipes.shapedCrafting(RecipeCategory.MISC, WorktableBlocks.WORKTABLE.block(), recipe -> { + recipe.define('B', Items.BOOK); + recipe.define('T', Tags.Items.PLAYER_WORKSTATIONS_CRAFTING_TABLES); + recipe.define('C', Tags.Items.CHESTS_WOODEN); + recipe.pattern("B"); + recipe.pattern("T"); + recipe.pattern("C"); + }); + } + + private static void registerEnergyRecipes(MKRecipeProvider recipes) { + recipes.shapedCrafting(RecipeCategory.MISC, EnergyBlocks.ENGINES.get(EngineBlockType.CLOCKWORK), recipe -> { + recipe.define('P', ItemTags.PLANKS); + recipe.define('I', Tags.Items.GLASS_BLOCKS); + recipe.define('Q', ForestryTags.Items.GEARS_COPPER); + recipe.define('D', Items.PISTON); + recipe.define('C', Items.CLOCK); + recipe.pattern("PPP"); + recipe.pattern(" I "); + recipe.pattern("QDC"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, EnergyBlocks.ENGINES.get(EngineBlockType.BIOGAS), recipe -> { + recipe.define('P', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('I', Tags.Items.GLASS_BLOCKS); + recipe.define('Q', ForestryTags.Items.GEARS_BRONZE); + recipe.define('D', Items.PISTON); + recipe.pattern("PPP"); + recipe.pattern(" I "); + recipe.pattern("QDQ"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, EnergyBlocks.ENGINES.get(EngineBlockType.PEAT), recipe -> { + recipe.define('P', Tags.Items.INGOTS_COPPER); + recipe.define('I', Tags.Items.GLASS_BLOCKS); + recipe.define('Q', ForestryTags.Items.GEARS_COPPER); + recipe.define('D', Items.PISTON); + recipe.pattern("PPP"); + recipe.pattern(" I "); + recipe.pattern("QDQ"); + }); + } + + private static void registerCarpenter(RecipeOutput output, MKRecipeProvider recipes) { + carpenter(output, recipes, 50, ForestryFluids.SEED_OIL.ingredient(250), Ingredient.EMPTY, CoreItems.IMPREGNATED_CASING, 1, recipe -> { + recipe.pattern("###"); + recipe.pattern("# #"); + recipe.pattern("###"); + recipe.define('#', ItemTags.LOGS); + }); + carpenter(output, recipes, 50, ForestryFluids.SEED_OIL.ingredient(250), Ingredient.EMPTY, CoreBlocks.BASE.get(BlockTypeCoreTesr.ESCRITOIRE).item(), 1, recipe -> { + recipe.pattern("# "); + recipe.pattern("###"); + recipe.pattern("# #"); + recipe.define('#', ItemTags.PLANKS); + }); + carpenter(output, recipes, 50, ForestryFluids.SEED_OIL.ingredient(100), Ingredient.EMPTY, CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.IMPREGNATED_STICK), 2, recipe -> { + recipe.pattern("#"); + recipe.pattern("#"); + recipe.define('#', ItemTags.LOGS); + }); + carpenterShapeless(output, recipes, 5, SizedFluidIngredient.of(Fluids.WATER, 250), Ingredient.EMPTY, CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.WOOD_PULP), 4, shapeless -> shapeless); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 250)) + .setBox(Ingredient.EMPTY) + .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.WOOD_PULP), 4) + .requires(ItemTags.LOGS)) + .build(output, id("carpenter", "wood_pulp")); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreBlocks.HUMUS, 9) + .pattern("###") + .pattern("#X#") + .pattern("###") + .define('#', Items.DIRT) + .define('X', CoreItems.MULCH)) + .build(output, id("carpenter", "humus")); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreBlocks.BOG_EARTH, 8) + .pattern("#X#") + .pattern("XYX") + .pattern("#X#") + .define('#', Items.DIRT) + .define('X', Tags.Items.SANDS) + .define('Y', CoreItems.MULCH)) + .build(output, id("carpenter", "bog_earth")); + new CarpenterRecipeBuilder() + .setPackagingTime(75) + .setLiquid(new FluidStack(Fluids.WATER, 5000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.HARDENED_CASING) + .pattern("X X") + .pattern(" Y ") + .pattern("X X") + .define('X', Tags.Items.GEMS_DIAMOND) + .define('Y', CoreItems.STURDY_CASING)) + .build(output, id("carpenter", "hardened_casing")); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.IODINE_CHARGE) + .pattern("Z#Z") + .pattern("#Y#") + .pattern("X#X") + .define('#', ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL)) + .define('X', Items.GUNPOWDER) + .define('Y', FluidsItems.CONTAINERS.get(EnumContainerType.CAN)) + .define('Z', ApicultureItems.HONEY_DROP)) + .build(output, id("carpenter", "iodine_charge")); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.DISSIPATION_CHARGE) + .pattern("Z#Z") + .pattern("#Y#") + .pattern("X#X") + .define('#', ApicultureItems.ROYAL_JELLY) + .define('X', Items.GUNPOWDER) + .define('Y', FluidsItems.CONTAINERS.get(EnumContainerType.CAN)) + .define('Z', ApicultureItems.HONEYDEW)) + .build(output, id("carpenter", "dissipation_charge")); + new CarpenterRecipeBuilder() + .setPackagingTime(100) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, Items.ENDER_PEARL) + .pattern(" # ") + .pattern("###") + .pattern(" # ") + .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.PULSATING_MESH))) + .build(output, id("carpenter", "ender_pearl")); + new CarpenterRecipeBuilder() + .setPackagingTime(10) + .setLiquid(new FluidStack(Fluids.WATER, 500)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK)) + .pattern("XX") + .pattern("XX") + .define('X', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP))) + .build(output, id("carpenter", "woven_silk")); + new CarpenterRecipeBuilder() + .setBox(Ingredient.EMPTY) + .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, CoreItems.INGOT_BRONZE, 2) + .requires(CoreItems.BROKEN_BRONZE_PICKAXE)) + .build(output, id("carpenter", "reclaim_bronze_pickaxe")); + new CarpenterRecipeBuilder() + .setBox(Ingredient.EMPTY) + .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, CoreItems.INGOT_BRONZE, 1) + .requires(CoreItems.BROKEN_BRONZE_SHOVEL)) + .build(output, id("carpenter", "reclaim_bronze_shovel")); + // todo conditional recipe for Create honey fluid 1.20 + new CarpenterRecipeBuilder() + .setPackagingTime(50) + .setLiquid(ForestryFluids.HONEY.getFluid(500)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SCENTED_PANELING)) + .pattern(" J ") + .pattern("###") + .pattern("WPW") + .define('#', ItemTags.PLANKS) + .define('J', ApicultureItems.ROYAL_JELLY) + .define('W', CoreItems.BEESWAX) + .define('P', ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL))) + .build(output, id("carpenter", "scented_paneling")); + new CarpenterRecipeBuilder() + .setPackagingTime(100) + .setLiquid(new FluidStack(Fluids.WATER, 2000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.PORTABLE_ALYZER) + .pattern("X#X") + .pattern("X#X") + .pattern("RDR") + .define('#', Tags.Items.GLASS_PANES) + .define('X', ForestryTags.Items.INGOTS_TIN) + .define('R', Tags.Items.DUSTS_REDSTONE) + .define('D', Tags.Items.GEMS_DIAMOND)) + .build(output, id("carpenter", "portable_analyzer")); + new CarpenterRecipeBuilder() + .setPackagingTime(20) + .setBox(Ingredient.of(CoreItems.CARTON)) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.KIT_PICKAXE) + .pattern("###") + .pattern(" X ") + .pattern(" X ") + .define('#', ForestryTags.Items.INGOTS_BRONZE) + .define('X', Items.STICK)) + .build(output, id("carpenter", "kit_pickaxe")); + new CarpenterRecipeBuilder() + .setPackagingTime(20) + .setBox(Ingredient.of(CoreItems.CARTON)) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.KIT_SHOVEL) + .pattern(" # ") + .pattern(" X ") + .pattern(" X ") + .define('#', ForestryTags.Items.INGOTS_BRONZE) + .define('X', Items.STICK)) + .build(output, id("carpenter", "kit_shovel")); + new CarpenterRecipeBuilder() + .setPackagingTime(40) + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.SOLDERING_IRON) + .pattern(" # ") + .pattern("# #") + .pattern(" B") + .define('#', Tags.Items.INGOTS_IRON) + .define('B', ForestryTags.Items.INGOTS_BRONZE)) + .build(output, id("carpenter", "soldering_iron")); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 250)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, Items.PAPER) + .pattern("#") + .pattern("#") + .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOOD_PULP))) + .build(output, id("carpenter", "paper")); + new CarpenterRecipeBuilder() + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CARTON, 2) + .pattern(" # ") + .pattern("# #") + .pattern(" # ") + .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOOD_PULP))) + .build(output, id("carpenter", "carton")); + + for (EnumStampDefinition stamp : EnumStampDefinition.VALUES) { + FeatureItem item = MailItems.STAMPS.get(stamp); + + new CarpenterRecipeBuilder() + .setLiquid(ForestryFluids.SEED_OIL.getFluid(300)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, item, 9) + .pattern("###") + .pattern("PPP") + .define('#', stamp.getCraftingIngredient()) + .define('P', Items.PAPER)) + .build(output, id("carpenter", item.getName())); + } + + ItemStack basic = CoreItems.CIRCUITBOARDS.stack(EnumCircuitBoardType.BASIC); + ItemStack enhanced = CoreItems.CIRCUITBOARDS.stack(EnumCircuitBoardType.ENHANCED); + ItemStack refined = CoreItems.CIRCUITBOARDS.stack(EnumCircuitBoardType.REFINED); + ItemStack intricate = CoreItems.CIRCUITBOARDS.stack(EnumCircuitBoardType.INTRICATE); + + new CarpenterRecipeBuilder() + .setPackagingTime(20) + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .override(basic) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.BASIC)) + .pattern("R R") + .pattern("R#R") + .pattern("R R") + .define('#', ForestryTags.Items.INGOTS_TIN) + .define('R', Tags.Items.DUSTS_REDSTONE)) + .build(output, id("carpenter", "circuits", "basic")); + new CarpenterRecipeBuilder() + .setPackagingTime(40) + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .override(enhanced) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.ENHANCED)) + .pattern("R#R") + .pattern("R#R") + .pattern("R#R") + .define('#', ForestryTags.Items.INGOTS_BRONZE) + .define('R', Tags.Items.DUSTS_REDSTONE)) + .build(output, id("carpenter", "circuits", "enhanced")); + new CarpenterRecipeBuilder() + .setPackagingTime(80) + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .override(refined) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.REFINED)) + .pattern("R#R") + .pattern("R#R") + .pattern("R#R") + .define('#', Tags.Items.INGOTS_IRON) + .define('R', Tags.Items.DUSTS_REDSTONE)) + .build(output, id("carpenter", "circuits", "refined")); + new CarpenterRecipeBuilder() + .setPackagingTime(80) + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .override(intricate) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.INTRICATE)) + .pattern("R#R") + .pattern("R#R") + .pattern("R#R") + .define('#', Tags.Items.INGOTS_GOLD) + .define('R', Tags.Items.DUSTS_REDSTONE)) + .build(output, id("carpenter", "circuits", "intricate")); + new CarpenterRecipeBuilder() + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.DECORATIONS, Items.CANDLE, 4) + .pattern("# #") + .pattern(" X ") + .pattern("# #") + .define('#', CoreItems.BEESWAX) + .define('X', Items.STRING)) + .build(output, id("carpenter", "candles")); + + // Crates + new CarpenterRecipeBuilder() + .setPackagingTime(20) + .setLiquid(new FluidStack(Fluids.WATER, 1000)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CrateItems.CRATE, 24) + .pattern(" # ") + .pattern("# #") + .pattern(" # ") + .define('#', ItemTags.LOGS)) + .build(output, id("carpenter", "crates", "empty")); + + new CarpenterRecipeBuilder() + .setPackagingTime(10) + .setLiquid(new FluidStack(Fluids.WATER, 250)) + .setBox(Ingredient.EMPTY) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, MailItems.LETTERS.get(ItemLetter.Size.EMPTY, ItemLetter.State.FRESH).item()) + .pattern("###") + .pattern("###") + .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOOD_PULP))) + .build(output, id("carpenter", "letter_pulp")); + } + + protected static void carpenter(RecipeOutput output, MKRecipeProvider recipes, int packingTime, @Nullable SizedFluidIngredient inputFluid, Ingredient box, ItemLike result, int resultCount, Consumer pattern) { + recipes.pushRecipeOutput( + // the recipe is passed in by newOutput, letting us obtain the finished recipe instance from ModKit + (id, recipe) -> output.accept(id("carpenter", MKRecipeProvider.path(result)), new CarpenterRecipe(packingTime, Optional.ofNullable(inputFluid), box, (CraftingRecipe) recipe), null), + // create a shaped recipe with the new output, which ModKit will pass into the above function + newOutput -> recipes.shapedCrafting(RecipeCategory.MISC, result, resultCount, pattern) + ); + } + + private static void carpenterShapeless(RecipeOutput output, MKRecipeProvider recipes, int packingTime, @Nullable SizedFluidIngredient inputFluid, Ingredient box, ItemLike result, int resultCount, Consumer shapeless) { + recipes.pushRecipeOutput( + (id, recipe) -> output.accept(id("carpenter", MKRecipeProvider.path(recipe.getResultItem(null).getItem())), new CarpenterRecipe(packingTime, Optional.ofNullable(inputFluid), box, (CraftingRecipe) recipe), null), + newOutput -> shapeless.accept(recipes) + ); + } + + private static void registerCentrifuge(RecipeOutput output) { + Item honeyDrop = ApicultureItems.HONEY_DROP.item(); + + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.HONEY), products -> { + products.accept(1.0f, CoreItems.BEESWAX); + products.accept(0.9f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.COCOA), products -> { + products.accept(1.0f, CoreItems.BEESWAX); + products.accept(0.5f, Items.COCOA_BEANS); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.SIMMERING), products -> { + products.accept(1.0f, CoreItems.REFRACTORY_WAX); + products.accept(0.7f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.STRINGY), products -> { + products.accept(1.0f, ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL)); + products.accept(0.4f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.DRIPPING), products -> { + products.accept(1.0f, ApicultureItems.HONEYDEW); + products.accept(0.4f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.FROZEN), products -> { + products.accept(0.8f, CoreItems.BEESWAX); + products.accept(0.7f, honeyDrop); + products.accept(0.4f, Items.SNOWBALL); + products.accept(0.2f, ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.CRYSTALLINE)); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.SILKY), products -> { + products.accept(1.0f, honeyDrop); + products.accept(0.8f, ApicultureItems.PROPOLIS.get(EnumPropolis.SILKY)); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.PARCHED), products -> { + products.accept(1.0f, CoreItems.BEESWAX); + products.accept(0.9f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.MYSTERIOUS), products -> { + products.accept(1.0f, ApicultureItems.PROPOLIS.get(EnumPropolis.PULSATING)); + products.accept(0.4f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.POWDERY), products -> { + products.accept(0.2f, honeyDrop); + products.accept(0.2f, CoreItems.BEESWAX); + products.accept(0.9f, Items.GUNPOWDER); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.WHEATEN), products -> { + products.accept(0.2f, honeyDrop); + products.accept(0.2f, CoreItems.BEESWAX); + products.accept(0.8f, Items.WHEAT); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.MOSSY), products -> { + products.accept(1.0f, CoreItems.BEESWAX); + products.accept(0.9f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.KAOLIN), products -> { + products.accept(1.0f, Items.CLAY_BALL); + products.accept(0.9f, honeyDrop); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.MELLOW), products -> { + products.accept(0.6f, ApicultureItems.HONEYDEW); + products.accept(0.2f, CoreItems.BEESWAX); + products.accept(0.3f, Items.QUARTZ); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.VINTAGE), products -> { + products.accept(1.0f, CoreItems.BEESWAX); + products.accept(0.9f, ApicultureItems.HONEYDEW); + }); + centrifuge(output, 20, ApicultureItems.BEE_COMBS.get(EnumHoneyComb.SCULKEN), products -> { + products.accept(1.0f, CoreItems.BEESWAX); + products.accept(0.9f, ApicultureItems.EXPERIENCE_DROP); + products.accept(0.2f, Items.SCULK); + }); + centrifuge(output, 5, ApicultureItems.PROPOLIS.get(EnumPropolis.SILKY), products -> { + products.accept(0.6f, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP)); + products.accept(0.1f, ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL)); + }); + + centrifuge(output, 20, Items.HONEYCOMB, products -> { + products.accept(1.0f, CoreItems.BEESWAX); + }); + } + + private static void centrifuge(RecipeOutput output, int processingTime, ItemLike input, Consumer> products) { + ArrayList productsList = new ArrayList<>(); + products.accept((chance, item) -> productsList.add(Product.of(item.asItem(), chance))); + output.accept(id("centrifuge", MKRecipeProvider.path(input)), new CentrifugeRecipe(processingTime, Ingredient.of(input), productsList), null); + } + + private static void registerFermenter(RecipeOutput output) { + // Apiculture + fermenter(output, "honeydew", Ingredient.of(ApicultureItems.HONEYDEW), FluidIngredient.tag(Tags.Fluids.HONEY), 500, 1f, ForestryFluids.HONEY.getFluid()); + // Arboriculture + addFermenterRecipes(output, "sapling", Ingredient.of(ItemTags.SAPLINGS), 250); + // Factory + addFermenterRecipes(output, "cactus", Ingredient.of(Items.CACTUS), 50); + addFermenterRecipes(output, "wheat", Ingredient.of(Tags.Items.CROPS_WHEAT), 50); + addFermenterRecipes(output, "potato", Ingredient.of(Tags.Items.CROPS_POTATO), 100); + addFermenterRecipes(output, "sugar_cane", Ingredient.of(Items.SUGAR_CANE), 50); + addFermenterRecipes(output, "mushroom", Ingredient.of(Tags.Items.MUSHROOMS), 50); + } + + private static void addFermenterRecipes(RecipeOutput output, String name, Ingredient input, int fermentationValue) { + Fluid outputFluid = ForestryFluids.BIOMASS.getFluid(); + + fermenter(output, name, input, FluidIngredient.tag(FluidTags.WATER), fermentationValue, 1f, outputFluid); + // todo Juice tag? + fermenter(output, name + "_juice", input, FluidIngredient.single(ForestryFluids.JUICE.getFluid()), fermentationValue, 1.5f, outputFluid); + fermenter(output, name + "_honey", input, FluidIngredient.tag(Tags.Fluids.HONEY), fermentationValue, 1.5f, outputFluid); + } + + private static void fermenter(RecipeOutput output, String name, Ingredient input, FluidIngredient fluidInput, int fermentationValue, float modifier, Fluid result) { + output.accept(id("fermenter", name), new FermenterRecipe(input, fluidInput, fermentationValue, modifier, result), null); + } + + private static void registerHygroregulator(RecipeOutput output) { + hygroregulator(output, "water", FluidIngredient.tag(FluidTags.WATER), 0, -1, 1); + hygroregulator(output, "lava", FluidIngredient.tag(FluidTags.LAVA), 0, 1, -1); + hygroregulator(output, "ice", FluidIngredient.single(ForestryFluids.ICE.getFluid()), 10, -2, 2); + } + + private static void hygroregulator(RecipeOutput output, String name, FluidIngredient input, int retainTime, int temperatureSteps, int humiditySteps) { + output.accept(id("hygroregulator", name), new HygroregulatorRecipe(new SizedFluidIngredient(input, 1), retainTime, (byte) temperatureSteps, (byte) humiditySteps), null); + } + + private static void registerSqueezerContainer(RecipeOutput output) { + squeezerContainer(output, EnumContainerType.CAN, CoreItems.INGOT_TIN, 0.05f); + squeezerContainer(output, EnumContainerType.CAPSULE, CoreItems.BEESWAX, 0.10f); + squeezerContainer(output, EnumContainerType.REFRACTORY, CoreItems.REFRACTORY_WAX, 0.10f); + } + + private static void squeezerContainer(RecipeOutput output, EnumContainerType type, ItemLike remnants, float remnantsChance) { + output.accept(id("squeezer_container", type.identifier()), new SqueezerContainerRecipe(FluidsItems.CONTAINERS.stack(type), 10, new ItemStack(remnants), remnantsChance), null); + } + + private static void registerSqueezer(RecipeOutput output) { + FluidStack honeyDropFluid = ForestryFluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); + FluidStack honeyBlockFluid = ForestryFluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP * 8); + + squeezer(output, "honey_drop", 10, List.of(Ingredient.of(ApicultureItems.HONEY_DROP)), honeyDropFluid, ApicultureItems.PROPOLIS.stack(EnumPropolis.NORMAL, 1), 5 / 100f); + squeezer(output, "sponge_comb", 10, List.of(Ingredient.of(ApicultureItems.BEE_COMBS.stack(EnumHoneyComb.SPONGE))), honeyDropFluid, new ItemStack(Items.SPONGE), 2 / 100f); + squeezer(output, "honey_block", 60, List.of(Ingredient.of(Items.HONEY_BLOCK)), honeyBlockFluid); + squeezer(output, "honey_dew", 10, List.of(Ingredient.of(ApicultureItems.HONEYDEW)), honeyDropFluid); + squeezer(output, "lava_sand", 20, List.of(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.VOLCANIC)), Ingredient.of(Items.SAND, Items.RED_SAND)), new FluidStack(Fluids.LAVA, 500)); + squeezer(output, "lava", 30, List.of(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.VOLCANIC)), Ingredient.of(Items.COBBLESTONE)), new FluidStack(Fluids.LAVA, 500)); + squeezer(output, "lava_magma", 20, List.of(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.VOLCANIC)), Ingredient.of(Items.MAGMA_BLOCK)), new FluidStack(Fluids.LAVA, 1000)); + + int seedOilAmount = 10; + + squeezer(output, "seeds", 10, List.of(Ingredient.of(Tags.Items.SEEDS)), ForestryFluids.SEED_OIL.getFluid(seedOilAmount)); + + float mulchMultiplier = 0.2f; + int juiceMultiplier = 200; + + squeezer(output, "mulch", 10, List.of(Ingredient.of(Items.APPLE, Items.CARROT)), ForestryFluids.JUICE.getFluid(juiceMultiplier), CoreItems.MULCH.stack(), mulchMultiplier); + squeezer(output, "cactus", 10, List.of(Ingredient.of(Items.CACTUS)), new FluidStack(Fluids.WATER, 500)); + squeezer(output, "ice", 10, List.of(Ingredient.of(Items.SNOWBALL), Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)), Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)), Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)), Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD))), ForestryFluids.ICE.getFluid(4000)); + + int seedOilMultiplier = 10; + + ItemStack mulch = new ItemStack(CoreItems.MULCH); + Fluid seedOil = ForestryFluids.SEED_OIL.getFluid(); + Fluid juice = ForestryFluids.JUICE.getFluid(); + + squeezer(output, "cherry", 20, List.of(Ingredient.of(ForestryTags.Items.CHERRY)), new FluidStack(seedOil, seedOilMultiplier * 5), mulch, 0.05F); + squeezer(output, "walnut", 60, List.of(Ingredient.of(ForestryTags.Items.WALNUT)), new FluidStack(seedOil, seedOilMultiplier * 18), mulch, 0.05F); + squeezer(output, "chestnut", 70, List.of(Ingredient.of(ForestryTags.Items.CHESTNUT)), new FluidStack(seedOil, seedOilMultiplier * 22), mulch, 0.02F); + squeezer(output, "lemon", 10, List.of(Ingredient.of(ForestryTags.Items.LEMON)), new FluidStack(juice, juiceMultiplier * 2), mulch, mulchMultiplier / 2f); + squeezer(output, "plum", 10, List.of(Ingredient.of(ForestryTags.Items.PLUM)), new FluidStack(juice, juiceMultiplier / 2), mulch, mulchMultiplier * 3f); + squeezer(output, "papaya", 10, List.of(Ingredient.of(ForestryTags.Items.PAPAYA)), new FluidStack(juice, juiceMultiplier * 3), mulch, mulchMultiplier / 2f); + squeezer(output, "dates", 10, List.of(Ingredient.of(ForestryTags.Items.DATE)), new FluidStack(juice, juiceMultiplier / 4), mulch, mulchMultiplier); + } + + private static void squeezer(RecipeOutput output, String id, int processingTime, List inputs, FluidStack result) { + squeezer(output, id, processingTime, inputs, result, ItemStack.EMPTY, 0f); + } + + private static void squeezer(RecipeOutput output, String id, int processingTime, List inputs, FluidStack result, ItemStack remnants, float remnantsChance) { + output.accept(id("squeezer", id), new SqueezerRecipe(processingTime, inputs, result, remnants, remnantsChance), null); + } + + private static void registerStill(RecipeOutput output) { + output.accept(id("still", "ethanol"), new StillRecipe( + 100, + ForestryFluids.BIOMASS.ingredient(10), + ForestryFluids.BIO_ETHANOL.getFluid(3) + ), null); + } + + static ResourceLocation id(String... path) { + return ForestryConstants.forestry(String.join("/", path)); + } + + static void fabricator(RecipeOutput output, MKRecipeProvider recipes, @Nullable SizedFluidIngredient inputFluid, ItemLike result, int resultCount, Consumer pattern) { + recipes.pushRecipeOutput( + // the recipe is passed in by newOutput, letting us obtain the finished recipe instance from ModKit + (id, recipe) -> output.accept(id("carpenter", MKRecipeProvider.path(result)), new FabricatorRecipe(Ingredient.EMPTY, Optional.ofNullable(inputFluid), (CraftingRecipe) recipe), null), + // create a shaped recipe with the new output, which ModKit will pass into the above function + newOutput -> recipes.shapedCrafting(RecipeCategory.MISC, result, resultCount, pattern) + ); + } + + static void fabricatorSmelting(RecipeOutput output, String id, Ingredient input, FluidStack result, int meltingPoint) { + output.accept(id("fabricator_smelting", id), new FabricatorSmeltingRecipe(input, result, meltingPoint), null); + } +} diff --git a/src/main/java/forestry/core/data/recipe/CultivationRecipes.java b/src/main/java/forestry/core/data/recipe/CultivationRecipes.java new file mode 100644 index 0000000000..67b8f376f9 --- /dev/null +++ b/src/main/java/forestry/core/data/recipe/CultivationRecipes.java @@ -0,0 +1,183 @@ +package forestry.core.data.recipe; + +import forestry.api.ForestryTags; +import forestry.core.circuits.EnumCircuitBoardType; +import forestry.core.features.CoreBlocks; +import forestry.core.features.CoreDataComponents; +import forestry.core.features.CoreItems; +import forestry.core.items.definitions.EnumContainerType; +import forestry.core.items.definitions.EnumElectronTube; +import forestry.cultivation.blocks.BlockTypePlanter; +import forestry.cultivation.features.CultivationBlocks; +import forestry.factory.recipes.MoistenerRecipe; +import forestry.farming.blocks.EnumFarmBlockType; +import forestry.farming.blocks.EnumFarmMaterial; +import forestry.farming.features.FarmingBlocks; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.tags.ItemTags; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.material.Fluids; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.common.crafting.DataComponentIngredient; +import thedarkcolour.modkit.data.MKRecipeProvider; + +import static thedarkcolour.modkit.data.MKRecipeProvider.path; + +class CultivationRecipes { + static void registerCultivationRecipes(MKRecipeProvider recipes) { + for (BlockTypePlanter planter : BlockTypePlanter.values()) { + Block managed = CultivationBlocks.MANAGED_PLANTER.get(planter).block(); + Block manual = CultivationBlocks.MANUAL_PLANTER.get(planter).block(); + + recipes.shapedCrafting(RecipeCategory.MISC, managed, recipe -> { + recipe.define('G', Tags.Items.GLASS_BLOCKS); + recipe.define('T', CoreItems.ELECTRON_TUBES.get(getElectronTube(planter))); + recipe.define('C', CoreItems.FLEXIBLE_CASING); + recipe.define('B', CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.BASIC)); + recipe.pattern("GTG"); + recipe.pattern("TCT"); + recipe.pattern("GBG"); + }); + recipes.shapelessCrafting(RecipeCategory.MISC, manual, 1, managed); + recipes.shapelessCrafting(path(managed) + "_from_manual", RecipeCategory.MISC, managed, 1, manual); + } + + // Manure and Fertilizer + recipes.shapedCrafting("compost_wheat", RecipeCategory.MISC, CoreItems.COMPOST, 4, recipe -> { + recipe.define('#', Blocks.DIRT); + recipe.define('X', Tags.Items.CROPS_WHEAT); + recipe.pattern(" X "); + recipe.pattern("X#X"); + recipe.pattern(" X "); + }); + + recipes.shapedCrafting("compost_ash", RecipeCategory.MISC, CoreItems.COMPOST, 1, recipe -> { + recipe.define('#', Blocks.DIRT); + recipe.define('X', ForestryTags.Items.DUSTS_ASH); + recipe.pattern(" X "); + recipe.pattern("X#X"); + recipe.pattern(" X "); + }); + + recipes.shapedCrafting("fertilizer_apatite", RecipeCategory.MISC, CoreItems.FERTILIZER_COMPOUND, 8, recipe -> { + recipe.define('#', ItemTags.SAND); + recipe.define('X', ForestryTags.Items.GEMS_APATITE); + recipe.pattern(" # "); + recipe.pattern(" X "); + recipe.pattern(" # "); + }); + + recipes.shapedCrafting("fertilizer_ash", RecipeCategory.MISC, CoreItems.FERTILIZER_COMPOUND, 16, recipe -> { + recipe.define('#', ForestryTags.Items.DUSTS_ASH); + recipe.define('X', ForestryTags.Items.GEMS_APATITE); + recipe.pattern("###"); + recipe.pattern("#X#"); + recipe.pattern("###"); + }); + + // Humus + recipes.shapedCrafting("humus_compost", RecipeCategory.BUILDING_BLOCKS, CoreBlocks.HUMUS, 8, recipe -> { + recipe.define('#', Blocks.DIRT); + recipe.define('X', CoreItems.COMPOST); + recipe.pattern("###"); + recipe.pattern("#X#"); + recipe.pattern("###"); + }); + + recipes.shapedCrafting("humus_fertilizer", RecipeCategory.BUILDING_BLOCKS, CoreBlocks.HUMUS, 8, recipe -> { + recipe.define('#', Blocks.DIRT); + recipe.define('X', CoreItems.FERTILIZER_COMPOUND); + recipe.pattern("###"); + recipe.pattern("#X#"); + recipe.pattern("###"); + }); + + // Bog earth + bogEarth(recipes, 8, CoreRecipes.getContainer(EnumContainerType.CAN, Fluids.WATER), "can"); + bogEarth(recipes, 8, CoreRecipes.getContainer(EnumContainerType.CAPSULE, Fluids.WATER), "wax_capsule"); + bogEarth(recipes, 8, CoreRecipes.getContainer(EnumContainerType.REFRACTORY, Fluids.WATER), "refractory"); + bogEarth(recipes, 6, Ingredient.of(Items.WATER_BUCKET), "bucket"); + } + + static EnumElectronTube getElectronTube(BlockTypePlanter planter) { + return switch (planter) { + case ARBORETUM -> EnumElectronTube.GOLD; + case FARM_CROPS -> EnumElectronTube.BRONZE; + case PEAT_POG -> EnumElectronTube.OBSIDIAN; + case FARM_MUSHROOM -> EnumElectronTube.APATITE; + case FARM_GOURD -> EnumElectronTube.LAPIS; + case FARM_NETHER -> EnumElectronTube.BLAZE; + case FARM_ENDER -> EnumElectronTube.ENDER; + }; + } + + static void registerFarmingRecipes(MKRecipeProvider recipes) { + for (EnumFarmMaterial material : EnumFarmMaterial.values()) { + Item base = material.getBase().asItem(); + recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.PLAIN, material), recipe -> { + recipe.define('I', Items.COPPER_INGOT); + recipe.define('#', base); + recipe.define('C', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.TIN)); + recipe.define('W', ItemTags.WOODEN_SLABS); + recipe.pattern("I#I"); + recipe.pattern("WCW"); + }); + recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.GEARBOX, material), recipe -> { + recipe.define('T', ForestryTags.Items.GEARS_TIN); + recipe.define('#', base); + recipe.pattern(" # "); + recipe.pattern("TTT"); + }); + recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.HATCH, material), recipe -> { + recipe.define('T', ForestryTags.Items.GEARS_TIN); + recipe.define('#', base); + recipe.define('D', ItemTags.WOODEN_TRAPDOORS); + recipe.pattern(" # "); + recipe.pattern("TDT"); + }); + recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.VALVE, material), recipe -> { + recipe.define('T', ForestryTags.Items.GEARS_TIN); + recipe.define('#', base); + recipe.define('X', Tags.Items.GLASS_BLOCKS); + recipe.pattern(" # "); + recipe.pattern("XTX"); + }); + recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.CONTROL, material), recipe -> { + recipe.define('T', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.GOLD)); + recipe.define('#', base); + recipe.define('X', Tags.Items.DUSTS_REDSTONE); + recipe.pattern(" # "); + recipe.pattern("XTX"); + }); + } + } + + static void registerMoistener(RecipeOutput output) { + moistener(output, Items.MYCELIUM, Ingredient.of(Items.WHEAT_SEEDS), 5000); + moistener(output, Items.MOSSY_COBBLESTONE, Ingredient.of(Items.COBBLESTONE), 20000); + moistener(output, Items.MOSSY_STONE_BRICKS, Ingredient.of(Items.STONE_BRICKS), 20000); + moistener(output, Items.PODZOL, Ingredient.of(Items.SPRUCE_LEAVES), 5000); + } + + private static void moistener(RecipeOutput output, ItemLike result, Ingredient input, int time) { + output.accept(CoreRecipes.id("moistener", path(result)), new MoistenerRecipe(time, input, new ItemStack(result)), null); + } + + private static void bogEarth(MKRecipeProvider recipes, int amount, Ingredient container, String name) { + recipes.shapedCrafting("bog_earth_" + name, RecipeCategory.BUILDING_BLOCKS, CoreBlocks.BOG_EARTH, amount, recipe -> { + recipe.define('#', Blocks.DIRT); + recipe.define('X', container); + recipe.define('Y', ItemTags.SAND); + recipe.pattern("#Y#"); + recipe.pattern("YXY"); + recipe.pattern("#Y#"); + }); + } +} diff --git a/src/main/java/forestry/core/data/recipe/FactoryRecipes.java b/src/main/java/forestry/core/data/recipe/FactoryRecipes.java new file mode 100644 index 0000000000..bbe99abca9 --- /dev/null +++ b/src/main/java/forestry/core/data/recipe/FactoryRecipes.java @@ -0,0 +1,226 @@ +package forestry.core.data.recipe; + +import forestry.api.ForestryTags; +import forestry.core.features.CoreItems; +import forestry.core.features.FluidsItems; +import forestry.core.fluids.ForestryFluids; +import forestry.core.items.definitions.EnumContainerType; +import forestry.core.items.definitions.EnumElectronTube; +import forestry.factory.blocks.BlockTypeFactoryPlain; +import forestry.factory.blocks.BlockTypeFactoryTesr; +import forestry.factory.features.FactoryBlocks; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; +import thedarkcolour.modkit.data.MKRecipeProvider; + +class FactoryRecipes { + static void registerFactoryRecipes(MKRecipeProvider recipes) { + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.BOTTLER).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', FluidsItems.CONTAINERS.get(EnumContainerType.CAN)); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("#Y#"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.CARPENTER).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("XYX"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.CENTRIFUGE).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', Items.COPPER_INGOT); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("XYX"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.PLAIN.get(BlockTypeFactoryPlain.FABRICATOR).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', Tags.Items.INGOTS_GOLD); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.define('Z', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("#Y#"); + recipe.pattern("XZX"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.FERMENTER).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', ForestryTags.Items.GEARS_BRONZE); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("#Y#"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.MOISTENER).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', ForestryTags.Items.GEARS_COPPER); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("#Y#"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.RAINMAKER).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', ForestryTags.Items.GEARS_TIN); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("#Y#"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.PLAIN.get(BlockTypeFactoryPlain.RAINTANK).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', Tags.Items.INGOTS_IRON); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("XYX"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.SQUEEZER).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', ForestryTags.Items.INGOTS_TIN); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("XYX"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.STILL).block(), recipe -> { + recipe.define('#', Tags.Items.GLASS_BLOCKS); + recipe.define('X', Tags.Items.DUSTS_REDSTONE); + recipe.define('Y', CoreItems.STURDY_CASING); + recipe.pattern("X#X"); + recipe.pattern("#Y#"); + recipe.pattern("X#X"); + }); + } + + static void registerFabricator(RecipeOutput output, MKRecipeProvider recipes) { + SizedFluidIngredient liquidGlass = ForestryFluids.GLASS.ingredient(500); + + // Electron tubes + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.IRON), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Tags.Items.INGOTS_IRON); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.GOLD), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Tags.Items.INGOTS_GOLD); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.DIAMOND), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Tags.Items.GEMS_DIAMOND); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.OBSIDIAN), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Items.OBSIDIAN); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.BLAZE), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Items.BLAZE_POWDER); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.EMERALD), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Tags.Items.GEMS_EMERALD); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.LAPIS), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Tags.Items.GEMS_LAPIS); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.ENDER), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Items.ENDER_EYE); + recipe.define('X', Items.END_STONE); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.COPPER), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', Items.COPPER_INGOT); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.TIN), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', ForestryTags.Items.INGOTS_TIN); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.BRONZE), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); + }); + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.APATITE), 4, recipe -> { + recipe.pattern(" X "); + recipe.pattern("#X#"); + recipe.pattern("XXX"); + recipe.define('#', Tags.Items.DUSTS_REDSTONE); + recipe.define('X', ForestryTags.Items.GEMS_APATITE); + }); + + // Flexible casing + CoreRecipes.fabricator(output, recipes, liquidGlass, CoreItems.FLEXIBLE_CASING, 1, recipe -> { + recipe.pattern("#E#"); + recipe.pattern("B B"); + recipe.pattern("#E#"); + recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); + recipe.define('B', Tags.Items.SLIME_BALLS); + recipe.define('E', Tags.Items.GEMS_EMERALD); + }); + } + + static void registerFabricatorSmelting(RecipeOutput consumer) { + FluidStack liquidGlassBucket = ForestryFluids.GLASS.getFluid(FluidType.BUCKET_VOLUME); + FluidStack liquidGlassX4 = ForestryFluids.GLASS.getFluid(FluidType.BUCKET_VOLUME * 4); + FluidStack liquidGlass375 = ForestryFluids.GLASS.getFluid(375); + + CoreRecipes.fabricatorSmelting(consumer, "glass", Ingredient.of(Tags.Items.GLASS_BLOCKS_CHEAP), liquidGlassBucket, 1000); + CoreRecipes.fabricatorSmelting(consumer, "glass_pane", Ingredient.of(Tags.Items.GLASS_PANES), liquidGlass375, 1000); + CoreRecipes.fabricatorSmelting(consumer, "sand", Ingredient.of(Tags.Items.SANDS), liquidGlassBucket, 3000); + CoreRecipes.fabricatorSmelting(consumer, "sandstone", Ingredient.of(Tags.Items.SANDSTONE_BLOCKS), liquidGlassX4, 4800); + } +} diff --git a/src/main/java/forestry/core/data/recipe/ForestryRecipeProvider.java b/src/main/java/forestry/core/data/recipe/ForestryRecipeProvider.java deleted file mode 100644 index 5ba05546ec..0000000000 --- a/src/main/java/forestry/core/data/recipe/ForestryRecipeProvider.java +++ /dev/null @@ -1,2136 +0,0 @@ -package forestry.core.data.recipe; - -import forestry.api.ForestryTags; -import forestry.api.IForestryApi; -import forestry.api.arboriculture.IWoodAccess; -import forestry.api.arboriculture.IWoodType; -import forestry.api.arboriculture.WoodBlockKind; -import forestry.api.circuits.ICircuit; -import forestry.apiculture.blocks.BlockAlveary; -import forestry.apiculture.blocks.BlockAlvearyType; -import forestry.apiculture.blocks.BlockTypeApiculture; -import forestry.apiculture.blocks.NaturalistChestBlockType; -import forestry.apiculture.features.ApicultureBlocks; -import forestry.apiculture.features.ApicultureItems; -import forestry.apiculture.items.EnumHoneyComb; -import forestry.apiculture.items.EnumPollenCluster; -import forestry.apiculture.items.EnumPropolis; -import forestry.arboriculture.ForestryWoodType; -import forestry.arboriculture.VanillaWoodType; -import forestry.arboriculture.WoodAccess; -import forestry.arboriculture.features.ArboricultureBlocks; -import forestry.arboriculture.features.ArboricultureItems; -import forestry.arboriculture.features.CharcoalBlocks; -import forestry.core.blocks.BlockTypeCoreTesr; -import forestry.core.blocks.EnumResourceType; -import forestry.core.circuits.EnumCircuitBoardType; -import forestry.core.circuits.ItemCircuitBoard; -import forestry.core.config.Constants; -import forestry.core.config.Preference; -import forestry.core.data.builder.*; -import forestry.core.features.CoreBlocks; -import forestry.core.features.CoreItems; -import forestry.core.features.FluidsItems; -import forestry.core.fluids.ForestryFluids; -import forestry.core.items.definitions.EnumContainerType; -import forestry.core.items.definitions.EnumCraftingMaterial; -import forestry.core.items.definitions.EnumElectronTube; -import forestry.core.utils.ModUtil; -import forestry.cultivation.blocks.BlockTypePlanter; -import forestry.cultivation.features.CultivationBlocks; -import forestry.energy.blocks.EngineBlockType; -import forestry.energy.features.EnergyBlocks; -import forestry.factory.blocks.BlockTypeFactoryPlain; -import forestry.factory.blocks.BlockTypeFactoryTesr; -import forestry.factory.features.FactoryBlocks; -import forestry.farming.blocks.EnumFarmBlockType; -import forestry.farming.blocks.EnumFarmMaterial; -import forestry.farming.features.FarmingBlocks; -import forestry.lepidopterology.features.LepidopterologyItems; -import forestry.lepidopterology.features.LepidopterologyRecipes; -import forestry.mail.blocks.BlockTypeMail; -import forestry.mail.features.MailBlocks; -import forestry.mail.features.MailItems; -import forestry.mail.items.EnumStampDefinition; -import forestry.mail.items.ItemLetter; -import forestry.mail.items.ItemStamp; -import forestry.modules.features.FeatureItem; -import forestry.sorting.features.SortingBlocks; -import forestry.storage.features.BackpackItems; -import forestry.storage.features.CrateItems; -import forestry.storage.items.ItemCrated; -import forestry.worktable.features.WorktableBlocks; -import it.unimi.dsi.fastutil.objects.ObjectIntPair; -import net.minecraft.Util; -import net.minecraft.core.NonNullList; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.data.recipes.RecipeCategory; -import net.minecraft.data.recipes.ShapedRecipeBuilder; -import net.minecraft.data.recipes.ShapelessRecipeBuilder; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.common.Tags; -import net.minecraftforge.common.crafting.StrictNBTIngredient; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import thedarkcolour.modkit.data.MKRecipeProvider; - -import java.util.List; -import java.util.function.Consumer; - -import static thedarkcolour.modkit.data.MKRecipeProvider.ingredient; -import static thedarkcolour.modkit.data.MKRecipeProvider.path; - -// todo split into smaller classes so that my computer doesn't die -public class ForestryRecipeProvider { - public static final int STILL_DESTILLATION_DURATION = 100; - public static final int STILL_DESTILLATION_INPUT = 10; - public static final int STILL_DESTILLATION_OUTPUT = 3; - - public static ItemStack getContainer(EnumContainerType type, ForestryFluids fluid) { - return getContainer(type, fluid.getFluid()); - } - - public static ItemStack getContainer(EnumContainerType type, Fluid fluid) { - ItemStack container = FluidsItems.CONTAINERS.stack(type); - LazyOptional fluidHandlerCap = FluidUtil.getFluidHandler(container); - return fluidHandlerCap.map(handler -> { - handler.fill(new FluidStack(fluid, Integer.MAX_VALUE), IFluidHandler.FluidAction.EXECUTE); - return container; - }).orElse(ItemStack.EMPTY); - } - - public static void addRecipes(Consumer consumer, MKRecipeProvider recipes) { - // Vanilla recipe types - registerArboricultureRecipes(recipes); - registerApicultureRecipes(recipes); - registerFoodRecipes(recipes); - registerBackpackRecipes(recipes); - registerCharcoalRecipes(recipes); - registerCoreRecipes(recipes); - registerCultivationRecipes(recipes); - registerFactoryRecipes(recipes); - registerFarmingRecipes(recipes); - registerFluidsRecipes(recipes); - registerLepidopterologyRecipes(recipes); - registerMailRecipes(recipes); - registerSortingRecipes(recipes); - registerWorktableRecipes(recipes); - registerEnergyRecipes(recipes); - - // Forestry recipe types - registerCarpenter(consumer); - registerCentrifuge(consumer); - registerFabricator(consumer); - registerFabricatorSmelting(consumer); - registerFermenter(consumer); - registerHygroregulator(consumer); - registerMoistener(consumer); - registerSqueezerContainer(consumer); - registerSqueezer(consumer); - registerStill(consumer); - } - - private static void registerApicultureRecipes(MKRecipeProvider recipes) { - registerCombRecipes(recipes); - - BlockAlveary plain = ApicultureBlocks.ALVEARY.get(BlockAlvearyType.PLAIN).block(); - ItemLike goldElectronTube = CoreItems.ELECTRON_TUBES.get(EnumElectronTube.GOLD); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, plain, recipe -> { - recipe.define('X', CoreItems.IMPREGNATED_CASING); - recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SCENTED_PANELING)); - recipe.pattern("###"); - recipe.pattern("#X#"); - recipe.pattern("###"); - recipe.group("alveary"); - }); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlvearyType.FAN).block(), recipe -> { - recipe.define('#', goldElectronTube); - recipe.define('X', plain); - recipe.define('I', Tags.Items.INGOTS_IRON); - recipe.pattern("I I"); - recipe.pattern(" X "); - recipe.pattern("I#I"); - recipe.group("alveary"); - }); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlvearyType.HEATER).block(), recipe -> { - recipe.define('#', goldElectronTube); - recipe.define('I', Tags.Items.INGOTS_IRON); - recipe.define('X', plain); - recipe.define('S', Tags.Items.STONE); - recipe.pattern("#I#"); - recipe.pattern(" X "); - recipe.pattern("SSS"); - recipe.group("alveary"); - }); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlvearyType.HYGRO).block(), recipe -> { - recipe.define('G', Tags.Items.GLASS); - recipe.define('X', plain); - recipe.define('I', Tags.Items.INGOTS_IRON); - recipe.pattern("GIG"); - recipe.pattern("GXG"); - recipe.pattern("GIG"); - recipe.group("alveary"); - }); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlvearyType.SIEVE).block(), recipe -> { - recipe.define('W', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK)); - recipe.define('X', plain); - recipe.define('I', Tags.Items.INGOTS_IRON); - recipe.pattern("III"); - recipe.pattern(" X "); - recipe.pattern("WWW"); - recipe.group("alveary"); - }); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlvearyType.STABILISER).block(), recipe -> { - recipe.define('X', plain); - recipe.define('G', Tags.Items.GEMS_QUARTZ); - recipe.pattern("G G"); - recipe.pattern("GXG"); - recipe.pattern("G G"); - recipe.group("alveary"); - }); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, ApicultureBlocks.ALVEARY.get(BlockAlvearyType.SWARMER).block(), recipe -> { - recipe.define('#', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.DIAMOND)); - recipe.define('X', plain); - recipe.define('G', Tags.Items.INGOTS_GOLD); - recipe.pattern("#G#"); - recipe.pattern(" X "); - recipe.pattern("#G#"); - recipe.group("alveary"); - }); - - ItemLike wovenSilk = CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK); - - recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_HELMET, recipe -> { - recipe.define('#', wovenSilk); - recipe.pattern("###"); - recipe.pattern("# #"); - recipe.group("apiarist_armour"); - }); - - recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_CHEST, recipe -> { - recipe.define('#', wovenSilk); - recipe.pattern("# #"); - recipe.pattern("###"); - recipe.pattern("###"); - recipe.group("apiarist_armour"); - }); - - recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_LEGS, recipe -> { - recipe.define('#', wovenSilk); - recipe.pattern("###"); - recipe.pattern("# #"); - recipe.pattern("# #"); - recipe.group("apiarist_armour"); - }); - - recipes.shapedCrafting(RecipeCategory.COMBAT, ApicultureItems.APIARIST_BOOTS, recipe -> { - recipe.define('#', wovenSilk); - recipe.pattern("# #"); - recipe.pattern("# #"); - recipe.group("apiarist_armour"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, ApicultureBlocks.BASE.get(BlockTypeApiculture.APIARY).block(), recipe -> { - recipe.define('S', ItemTags.WOODEN_SLABS); - recipe.define('P', ItemTags.PLANKS); - recipe.define('C', CoreItems.IMPREGNATED_CASING); - recipe.pattern("SSS"); - recipe.pattern("PCP"); - recipe.pattern("PPP"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, ApicultureBlocks.BASE.get(BlockTypeApiculture.BEE_HOUSE).block(), recipe -> { - recipe.define('S', ItemTags.WOODEN_SLABS); - recipe.define('P', ItemTags.PLANKS); - recipe.define('C', ForestryTags.Items.BEE_COMBS); - recipe.pattern("SSS"); - recipe.pattern("PCP"); - recipe.pattern("PPP"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.APIARIST_CHEST), recipe -> { - recipe.define('G', Tags.Items.GLASS); - recipe.define('X', ForestryTags.Items.BEE_COMBS); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern(" G "); - recipe.pattern("XYX"); - recipe.pattern("XXX"); - }); - - ItemLike propolis = ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL); - - recipes.shapedCrafting(RecipeCategory.MISC, CoreItems.BITUMINOUS_PEAT, recipe -> { - recipe.define('#', ForestryTags.Items.DUSTS_ASH); - recipe.define('X', CoreItems.PEAT); - recipe.define('Y', propolis); - recipe.pattern(" # "); - recipe.pattern("XYX"); - recipe.pattern(" # "); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, ApicultureItems.FRAME_IMPREGNATED, recipe -> { - recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.IMPREGNATED_STICK)); - recipe.define('S', Tags.Items.STRING); - recipe.pattern("###"); - recipe.pattern("#S#"); - recipe.pattern("###"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, ApicultureItems.FRAME_UNTREATED, recipe -> { - recipe.define('#', Tags.Items.RODS_WOODEN); - recipe.define('S', Tags.Items.STRING); - recipe.pattern("###"); - recipe.pattern("#S#"); - recipe.pattern("###"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.PULSATING_MESH), recipe -> { - recipe.define('#', ApicultureItems.PROPOLIS.get(EnumPropolis.PULSATING)); - recipe.pattern("# #"); - recipe.pattern(" # "); - recipe.pattern("# #"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, ApicultureItems.SCOOP, recipe -> { - recipe.define('#', Tags.Items.RODS_WOODEN); - recipe.define('X', ItemTags.WOOL); - recipe.pattern("#X#"); - recipe.pattern("###"); - recipe.pattern(" # "); - }); - - recipes.shapedCrafting("slime_from_propolis", RecipeCategory.MISC, Items.SLIME_BALL, recipe -> { - recipe.define('#', propolis); - recipe.define('X', ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL)); - recipe.pattern("#X#"); - recipe.pattern("#X#"); - recipe.pattern("#X#"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, ApicultureItems.SMOKER, recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_TIN); - recipe.define('S', Tags.Items.RODS_WOODEN); - recipe.define('F', Items.FLINT_AND_STEEL); - recipe.define('L', Tags.Items.LEATHER); - recipe.pattern("LS#"); - recipe.pattern("LF#"); - recipe.pattern("###"); - }); - - recipes.shapedCrafting("glistering_melon_slice", RecipeCategory.MISC, Items.GLISTERING_MELON_SLICE, recipe -> { - recipe.define('#', ApicultureItems.HONEY_DROP); - recipe.define('X', ApicultureItems.HONEYDEW); - recipe.define('Y', Items.MELON_SLICE); - recipe.pattern("#X#"); - recipe.pattern("#Y#"); - recipe.pattern("#X#"); - }); - - ItemLike beesWax = CoreItems.BEESWAX; - recipes.shapedCrafting("torch_from_wax", RecipeCategory.MISC, Items.TORCH, 3, recipe -> { - recipe.define('#', beesWax); - recipe.define('Y', Tags.Items.RODS_WOODEN); - recipe.pattern(" # "); - recipe.pattern(" # "); - recipe.pattern(" Y "); - }); - - recipes.shapelessCrafting("exp_bottle_from_exp_drop", RecipeCategory.MISC, Items.EXPERIENCE_BOTTLE, 1, Items.GLASS_BOTTLE, ApicultureItems.EXPERIENCE_DROP.item()); - } - - private static void registerCombRecipes(MKRecipeProvider recipes) { - for (EnumHoneyComb honeyComb : EnumHoneyComb.VALUES) { - ItemLike comb = ApicultureItems.BEE_COMBS.get(honeyComb); - Block combBlock = ApicultureBlocks.BEE_COMB.get(honeyComb).block(); - recipes.grid2x2(RecipeCategory.BUILDING_BLOCKS, combBlock, 1, Ingredient.of(comb), "combs"); - } - } - - private static void registerArboricultureRecipes(MKRecipeProvider recipes) { - registerWoodRecipes(recipes); - - recipes.shapedCrafting(RecipeCategory.TOOLS, ArboricultureItems.GRAFTER, recipe -> { - recipe.define('B', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('#', Tags.Items.RODS_WOODEN); - recipe.pattern(" B"); - recipe.pattern(" # "); - recipe.pattern("# "); - }); - recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST), recipe -> { - recipe.define('X', ItemTags.SAPLINGS); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.define('#', Tags.Items.GLASS); - recipe.pattern(" # "); - recipe.pattern("XYX"); - recipe.pattern("XXX"); - }); - } - - private static void registerWoodRecipes(MKRecipeProvider recipes) { - IWoodAccess woodAccess = WoodAccess.INSTANCE; - List woodTypes = woodAccess.getRegisteredWoodTypes(); - - for (IWoodType woodType : woodTypes) { - Block planks = woodAccess.getBlock(woodType, WoodBlockKind.PLANKS, false).getBlock(); - Block fireproofPlanks = woodAccess.getBlock(woodType, WoodBlockKind.PLANKS, true).getBlock(); - Block log = woodAccess.getBlock(woodType, WoodBlockKind.LOG, false).getBlock(); - Block fireproofLog = woodAccess.getBlock(woodType, WoodBlockKind.LOG, true).getBlock(); - Block wood = woodAccess.getBlock(woodType, WoodBlockKind.WOOD, false).getBlock(); - Block fireproofWood = woodAccess.getBlock(woodType, WoodBlockKind.WOOD, true).getBlock(); - Block strippedLog = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_LOG, false).getBlock(); - Block fireproofStrippedLog = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_LOG, true).getBlock(); - Block strippedWood = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_WOOD, false).getBlock(); - Block fireproofStrippedWood = woodAccess.getBlock(woodType, WoodBlockKind.STRIPPED_WOOD, true).getBlock(); - Block door = woodAccess.getBlock(woodType, WoodBlockKind.DOOR, false).getBlock(); - Block trapdoor = woodAccess.getBlock(woodType, WoodBlockKind.TRAPDOOR, false).getBlock(); - Block fence = woodAccess.getBlock(woodType, WoodBlockKind.FENCE, false).getBlock(); - Block fireproofFence = woodAccess.getBlock(woodType, WoodBlockKind.FENCE, true).getBlock(); - Block fenceGate = woodAccess.getBlock(woodType, WoodBlockKind.FENCE_GATE, false).getBlock(); - Block fireproofFenceGate = woodAccess.getBlock(woodType, WoodBlockKind.FENCE_GATE, true).getBlock(); - Block slab = woodAccess.getBlock(woodType, WoodBlockKind.SLAB, false).getBlock(); - Block fireproofSlab = woodAccess.getBlock(woodType, WoodBlockKind.SLAB, true).getBlock(); - Block stairs = woodAccess.getBlock(woodType, WoodBlockKind.STAIRS, false).getBlock(); - Block fireproofStairs = woodAccess.getBlock(woodType, WoodBlockKind.STAIRS, true).getBlock(); - - TagKey logTag = woodAccess.getLogItemTag(woodType, false); - TagKey fireproofLogTag = woodAccess.getLogItemTag(woodType, true); - - recipes.woodenDoor(door, woodType instanceof VanillaWoodType ? Ingredient.of(fireproofPlanks) : Ingredient.of(planks, fireproofPlanks)); - - // Regular (Forestry) - if (woodType instanceof ForestryWoodType type) { - makeCommonWoodenSet(recipes, planks, log, logTag, wood, strippedLog, strippedWood, fence, fenceGate, slab, stairs); - - recipes.shapelessCrafting(RecipeCategory.MISC, ArboricultureItems.CHEST_BOAT.item(type), 1, ArboricultureItems.BOAT.item(type), Tags.Items.CHESTS_WOODEN); - recipes.shapedCrafting(RecipeCategory.MISC, ArboricultureItems.BOAT.item(type), recipe -> { - recipe.define('P', Ingredient.of(planks, fireproofPlanks)); - recipe.pattern("P P"); - recipe.pattern("PPP"); - }); - - recipes.woodenTrapdoor(trapdoor, Ingredient.of(planks, fireproofPlanks)); - - recipes.shapedCrafting(RecipeCategory.MISC, ArboricultureBlocks.SIGN.get(type), recipe -> { - recipe.define('P', Ingredient.of(planks, fireproofPlanks)); - recipe.define('S', Tags.Items.RODS_WOODEN); - recipe.pattern("PPP"); - recipe.pattern("PPP"); - recipe.pattern(" S "); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, ArboricultureBlocks.HANGING_SIGN.get(type), recipe -> { - recipe.define('X', Items.CHAIN); - recipe.define('#', Ingredient.of(strippedLog, fireproofStrippedLog)); - recipe.pattern("X X"); - recipe.pattern("###"); - recipe.pattern("###"); - }); - - recipes.shapelessCrafting(RecipeCategory.REDSTONE, ArboricultureBlocks.BUTTON.get(type), 1, Ingredient.of(planks, fireproofPlanks)); - recipes.shapedCrafting(RecipeCategory.REDSTONE, ArboricultureBlocks.PRESSURE_PLATE.get(type), recipe -> { - recipe.define('P', Ingredient.of(planks, fireproofPlanks)); - recipe.pattern("PP"); - }); - } - - // Fireproof (Vanilla & Forestry) - makeCommonWoodenSet(recipes, fireproofPlanks, fireproofLog, fireproofLogTag, fireproofWood, fireproofStrippedLog, fireproofStrippedWood, fireproofFence, fireproofFenceGate, fireproofSlab, fireproofStairs); - } - } - - // Shared between regular and fireproof recipes - private static void makeCommonWoodenSet(MKRecipeProvider recipes, Block planks, Block log, TagKey logTag, Block wood, Block strippedLog, Block strippedWood, Block fence, Block fenceGate, Block slab, Block stairs) { - recipes.shapelessCrafting(RecipeCategory.BUILDING_BLOCKS, planks, 4, "planks", logTag); - recipes.woodenFence(fence, planks); - recipes.woodenFenceGate(fenceGate, planks); - recipes.woodenSlab(slab, planks); - recipes.woodenStairs(stairs, planks); - recipes.grid2x2(RecipeCategory.BUILDING_BLOCKS, wood, 3, Ingredient.of(log), "bark"); - recipes.grid2x2(RecipeCategory.BUILDING_BLOCKS, strippedWood, 3, Ingredient.of(strippedLog), "bark"); - } - - private static void registerFoodRecipes(MKRecipeProvider recipes) { - ItemLike waxCapsule = FluidsItems.CONTAINERS.get(EnumContainerType.CAPSULE); - ItemLike honeyDrop = ApicultureItems.HONEY_DROP; - - recipes.shapedCrafting(RecipeCategory.FOOD, ApicultureItems.AMBROSIA, recipe -> { - recipe.define('#', ApicultureItems.HONEYDEW); - recipe.define('X', ApicultureItems.ROYAL_JELLY); - recipe.define('Y', waxCapsule); - recipe.pattern("#Y#"); - recipe.pattern("XXX"); - recipe.pattern("###"); - }); - - recipes.shapedCrafting(RecipeCategory.FOOD, ApicultureItems.HONEYED_SLICE, recipe -> { - recipe.define('#', honeyDrop); - recipe.define('X', Items.BREAD); - recipe.pattern("###"); - recipe.pattern("#X#"); - recipe.pattern("###"); - }); - - recipes.shapelessCrafting("bottled_honey_drops", RecipeCategory.FOOD, Items.HONEY_BOTTLE, 1, Items.GLASS_BOTTLE, honeyDrop, honeyDrop); - - } - - private static void registerBackpackRecipes(MKRecipeProvider recipes) { - recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.ADVENTURER_BACKPACK, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', Tags.Items.BONES); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.BUILDER_BACKPACK, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', Items.CLAY_BALL); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.DIGGER_BACKPACK, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', Tags.Items.STONE); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.FORESTER_BACKPACK, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', ItemTags.LOGS); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.HUNTER_BACKPACK, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', Tags.Items.FEATHERS); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.MINER_BACKPACK, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', Tags.Items.INGOTS_IRON); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - - // Naturalist backpacks - naturalistBackpack(recipes, BackpackItems.APIARIST_BACKPACK, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.APIARIST_CHEST)); - naturalistBackpack(recipes, BackpackItems.LEPIDOPTERIST_BACKPACK, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.LEPIDOPTERIST_CHEST)); - naturalistBackpack(recipes, BackpackItems.ARBORIST_BACKPACK, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST)); - } - - private static void naturalistBackpack(MKRecipeProvider recipes, ItemLike backpack, ItemLike chest) { - recipes.shapedCrafting(RecipeCategory.TOOLS, backpack, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('V', Tags.Items.RODS_WOODEN); - recipe.define('X', Tags.Items.STRING); - recipe.define('Y', chest); - recipe.pattern("X#X"); - recipe.pattern("VYV"); - recipe.pattern("X#X"); - }); - } - - private static void registerCharcoalRecipes(MKRecipeProvider recipes) { - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.CHARCOAL.block(), recipe -> { - recipe.define('#', Items.CHARCOAL); - recipe.pattern("###"); - recipe.pattern("###"); - recipe.pattern("###"); - }); - - // todo custom IDs - recipes.shapelessCrafting("charcoal_from_block", RecipeCategory.MISC, Items.CHARCOAL, 9, ForestryTags.Items.CHARCOAL_BLOCK); - - recipes.shapedCrafting(RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.LOG_PILE.block(), recipe -> { - recipe.define('L', ItemTags.LOGS); - recipe.pattern(" L "); - recipe.pattern("L L"); - recipe.pattern(" L "); - }); - - recipes.shapelessCrafting(RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.DECORATIVE_LOG_PILE.block(), 1, CharcoalBlocks.LOG_PILE.block()); - - recipes.shapelessCrafting("wood_pile_from_decorative", RecipeCategory.BUILDING_BLOCKS, CharcoalBlocks.LOG_PILE.block(), 1, CharcoalBlocks.DECORATIVE_LOG_PILE.block()); - } - - private static void registerCoreRecipes(MKRecipeProvider recipes) { - recipes.oreSmelting(ingredient(CoreBlocks.APATITE_ORE.get(), CoreBlocks.DEEPSLATE_APATITE_ORE.get()), CoreItems.APATITE, 0.5f, 200); - recipes.oreSmelting(ingredient(CoreBlocks.TIN_ORE.get(), CoreBlocks.DEEPSLATE_TIN_ORE.get(), CoreItems.RAW_TIN), CoreItems.INGOT_TIN, 0.5f, 200); - recipes.smelting(Ingredient.of(CoreItems.PEAT.item()), CoreItems.ASH, 0.0f, 200); - recipes.storage3x3(CoreBlocks.RAW_TIN_BLOCK, CoreItems.RAW_TIN); - - recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.BASE.get(BlockTypeCoreTesr.ANALYZER), recipe -> { - recipe.define('T', CoreItems.PORTABLE_ALYZER); - recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("XTX"); - recipe.pattern(" Y "); - recipe.pattern("X X"); - }); - recipes.storage3x3(CoreBlocks.RESOURCE_STORAGE.get(EnumResourceType.APATITE), CoreItems.APATITE); - recipes.storage3x3(CoreBlocks.RESOURCE_STORAGE.get(EnumResourceType.BRONZE), CoreItems.INGOT_BRONZE); - recipes.storage3x3(CoreBlocks.RESOURCE_STORAGE.get(EnumResourceType.TIN), CoreItems.INGOT_TIN); - recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.BRONZE_PICKAXE, recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('X', Tags.Items.RODS_WOODEN); - recipe.pattern("###"); - recipe.pattern(" X "); - recipe.pattern(" X "); - }); - recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.BRONZE_SHOVEL, recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('X', Tags.Items.RODS_WOODEN); - recipe.pattern(" # "); - recipe.pattern(" X "); - recipe.pattern(" X "); - }); - - gear(recipes, CoreItems.GEAR_BRONZE, ForestryTags.Items.INGOTS_BRONZE); - gear(recipes, CoreItems.GEAR_TIN, ForestryTags.Items.INGOTS_TIN); - gear(recipes, CoreItems.GEAR_COPPER, Tags.Items.INGOTS_COPPER); - - recipes.shapelessCrafting("ingot_bronze_alloying", RecipeCategory.MISC, CoreItems.INGOT_BRONZE, 4, ForestryTags.Items.INGOTS_TIN, ObjectIntPair.of(Items.COPPER_INGOT, 3)); - recipes.shapelessCrafting(RecipeCategory.TOOLS, CoreItems.KIT_PICKAXE, 1, CoreItems.BRONZE_PICKAXE, CoreItems.CARTON); - recipes.shapelessCrafting(RecipeCategory.TOOLS, CoreItems.KIT_SHOVEL, 1, CoreItems.BRONZE_SHOVEL, CoreItems.CARTON); - recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.SPECTACLES, recipe -> { - recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('Y', Tags.Items.GLASS_PANES); - recipe.pattern(" X "); - recipe.pattern("Y Y"); - }); - recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.PIPETTE, recipe -> { - recipe.define('#', ItemTags.WOOL); - recipe.define('X', Tags.Items.GLASS_PANES); - recipe.pattern(" #"); - recipe.pattern(" X "); - recipe.pattern("X "); - }); - recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.PORTABLE_ALYZER, recipe -> { - recipe.define('#', Tags.Items.GLASS_PANES); - recipe.define('X', ForestryTags.Items.INGOTS_TIN); - recipe.define('R', Tags.Items.DUSTS_REDSTONE); - recipe.define('D', Tags.Items.GEMS_DIAMOND); - recipe.pattern("X#X"); - recipe.pattern("X#X"); - recipe.pattern("RDR"); - }); - - recipes.shapedCrafting("string_from_wisp", RecipeCategory.MISC, Items.STRING, recipe -> { - recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP)); - recipe.pattern(" # "); - recipe.pattern(" # "); - recipe.pattern(" # "); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, CoreItems.STURDY_CASING, recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); - recipe.pattern("###"); - recipe.pattern("# #"); - recipe.pattern("###"); - }); - - recipes.shapedCrafting("cobweb_from_wisp", RecipeCategory.MISC, Items.COBWEB, 4, recipe -> { - recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP)); - recipe.pattern("# #"); - recipe.pattern(" # "); - recipe.pattern("# #"); - }); - - recipes.shapedCrafting(RecipeCategory.TOOLS, CoreItems.WRENCH, recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_BRONZE); - recipe.pattern("# #"); - recipe.pattern(" # "); - recipe.pattern(" # "); - }); - - // Manure and Fertilizer - recipes.shapedCrafting("compost_wheat", RecipeCategory.MISC, CoreItems.COMPOST, 4, recipe -> { - recipe.define('#', Blocks.DIRT); - recipe.define('X', Tags.Items.CROPS_WHEAT); - recipe.pattern(" X "); - recipe.pattern("X#X"); - recipe.pattern(" X "); - }); - - recipes.shapedCrafting("compost_ash", RecipeCategory.MISC, CoreItems.COMPOST, 1, recipe -> { - recipe.define('#', Blocks.DIRT); - recipe.define('X', ForestryTags.Items.DUSTS_ASH); - recipe.pattern(" X "); - recipe.pattern("X#X"); - recipe.pattern(" X "); - }); - - recipes.shapedCrafting("fertilizer_apatite", RecipeCategory.MISC, CoreItems.FERTILIZER_COMPOUND, 8, recipe -> { - recipe.define('#', ItemTags.SAND); - recipe.define('X', ForestryTags.Items.GEMS_APATITE); - recipe.pattern(" # "); - recipe.pattern(" X "); - recipe.pattern(" # "); - }); - - recipes.shapedCrafting("fertilizer_ash", RecipeCategory.MISC, CoreItems.FERTILIZER_COMPOUND, 16, recipe -> { - recipe.define('#', ForestryTags.Items.DUSTS_ASH); - recipe.define('X', ForestryTags.Items.GEMS_APATITE); - recipe.pattern("###"); - recipe.pattern("#X#"); - recipe.pattern("###"); - }); - - // Humus - recipes.shapedCrafting("humus_compost", RecipeCategory.BUILDING_BLOCKS, CoreBlocks.HUMUS, 8, recipe -> { - recipe.define('#', Blocks.DIRT); - recipe.define('X', CoreItems.COMPOST); - recipe.pattern("###"); - recipe.pattern("#X#"); - recipe.pattern("###"); - }); - - recipes.shapedCrafting("humus_fertilizer", RecipeCategory.BUILDING_BLOCKS, CoreBlocks.HUMUS, 8, recipe -> { - recipe.define('#', Blocks.DIRT); - recipe.define('X', CoreItems.FERTILIZER_COMPOUND); - recipe.pattern("###"); - recipe.pattern("#X#"); - recipe.pattern("###"); - }); - - // Bog earth - bogRecipe(recipes, 8, getContainer(EnumContainerType.CAN, Fluids.WATER), "can"); - bogRecipe(recipes, 8, getContainer(EnumContainerType.CAPSULE, Fluids.WATER), "wax_capsule"); - bogRecipe(recipes, 8, getContainer(EnumContainerType.REFRACTORY, Fluids.WATER), "refractory"); - bogRecipe(recipes, 6, new ItemStack(Items.WATER_BUCKET), "bucket"); - - recipes.shapedCrafting("can", RecipeCategory.MISC, FluidsItems.CONTAINERS.get(EnumContainerType.CAN), 12, recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_TIN); - recipe.pattern(" # "); - recipe.pattern("# #"); - }); - - recipes.shapedCrafting("capsule", RecipeCategory.MISC, FluidsItems.CONTAINERS.get(EnumContainerType.CAPSULE), 4, recipe -> { - recipe.define('#', CoreItems.BEESWAX); - recipe.pattern(" # "); - recipe.pattern("# #"); - }); - - recipes.shapedCrafting("refractory_capsule", RecipeCategory.MISC, FluidsItems.CONTAINERS.get(EnumContainerType.REFRACTORY), 4, recipe -> { - recipe.define('#', CoreItems.REFRACTORY_WAX); - recipe.pattern(" # "); - recipe.pattern("# #"); - }); - - recipes.shapedCrafting("compressed_ice_shards", RecipeCategory.MISC, Items.ICE, 1, recipe -> { - recipe.define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)); - recipe.pattern("##"); - recipe.pattern("##"); - }); - - recipes.shapedCrafting("honey_drop_block", RecipeCategory.MISC, Items.HONEY_BLOCK, 1, recipe -> { - recipe.define('V', ApicultureItems.HONEY_DROP); - recipe.pattern("VVV"); - recipe.pattern("V V"); - recipe.pattern("VVV"); - }); - - recipes.shapedCrafting("phosphor_torches", RecipeCategory.MISC, Items.TORCH, 6, recipe -> { - recipe.define('P', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.PHOSPHOR)); - recipe.define('|', Tags.Items.RODS_WOODEN); - recipe.pattern(" P "); - recipe.pattern(" | "); - }); - - recipes.shapedCrafting("beeswax_candles", RecipeCategory.MISC, Items.CANDLE, 1, recipe -> { - recipe.define('|', Tags.Items.STRING); - recipe.define('^', CoreItems.BEESWAX); - recipe.pattern(" | "); - recipe.pattern(" ^ "); - }); - - // Books - recipes.shapelessCrafting("foresters_manual_honeydrop", RecipeCategory.MISC, CoreItems.FORESTERS_MANUAL, 1, Items.BOOK, ApicultureItems.HONEY_DROP); - recipes.shapelessCrafting("foresters_manual_sapling", RecipeCategory.MISC, CoreItems.FORESTERS_MANUAL, 1, Items.BOOK, ItemTags.SAPLINGS); - recipes.shapelessCrafting("foresters_manual_butterfly", RecipeCategory.MISC, CoreItems.FORESTERS_MANUAL, 1, Items.BOOK, LepidopterologyItems.BUTTERFLY_GE); - } - - private static void bogRecipe(MKRecipeProvider recipes, int amount, ItemStack container, String name) { - recipes.shapedCrafting("bog_earth_" + name, RecipeCategory.BUILDING_BLOCKS, CoreBlocks.BOG_EARTH, amount, recipe -> { - recipe.define('#', Blocks.DIRT); - recipe.define('X', StrictNBTIngredient.of(container)); - recipe.define('Y', ItemTags.SAND); - recipe.pattern("#Y#"); - recipe.pattern("YXY"); - recipe.pattern("#Y#"); - }); - } - - private static void gear(MKRecipeProvider recipes, ItemLike gear, TagKey ingot) { - // In old versions, these gears were upgrades of BuildCraft's stone gears (which are tiered) - // Might bring this back if anything comes out of that BuildCraft port. - // For now, just have the same recipes as Thermal. - recipes.shapedCrafting(RecipeCategory.MISC, gear, recipe -> { - recipe.define('#', ingot); - recipe.define('X', Tags.Items.NUGGETS_IRON); - recipe.pattern(" # "); - recipe.pattern("#X#"); - recipe.pattern(" # "); - }); - } - - private static EnumElectronTube getElectronTube(BlockTypePlanter planter) { - return switch (planter) { - case ARBORETUM -> EnumElectronTube.GOLD; - case FARM_CROPS -> EnumElectronTube.BRONZE; - case PEAT_POG -> EnumElectronTube.OBSIDIAN; - case FARM_MUSHROOM -> EnumElectronTube.APATITE; - case FARM_GOURD -> EnumElectronTube.LAPIS; - case FARM_NETHER -> EnumElectronTube.BLAZE; - case FARM_ENDER -> EnumElectronTube.ENDER; - }; - } - - private static void registerCultivationRecipes(MKRecipeProvider recipes) { - for (BlockTypePlanter planter : BlockTypePlanter.VALUES) { - Block managed = CultivationBlocks.MANAGED_PLANTER.get(planter).block(); - Block manual = CultivationBlocks.MANUAL_PLANTER.get(planter).block(); - - recipes.shapedCrafting(RecipeCategory.MISC, managed, recipe -> { - recipe.define('G', Tags.Items.GLASS); - recipe.define('T', CoreItems.ELECTRON_TUBES.get(getElectronTube(planter))); - recipe.define('C', CoreItems.FLEXIBLE_CASING); - recipe.define('B', CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.BASIC)); - recipe.pattern("GTG"); - recipe.pattern("TCT"); - recipe.pattern("GBG"); - }); - recipes.shapelessCrafting(RecipeCategory.MISC, manual, 1, managed); - recipes.shapelessCrafting(path(managed) + "_from_manual", RecipeCategory.MISC, managed, 1, manual); - } - } - - private static void registerFactoryRecipes(MKRecipeProvider recipes) { - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.BOTTLER).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', FluidsItems.CONTAINERS.get(EnumContainerType.CAN)); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("#Y#"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.CARPENTER).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("XYX"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.CENTRIFUGE).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', Items.COPPER_INGOT); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("XYX"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.PLAIN.get(BlockTypeFactoryPlain.FABRICATOR).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', Tags.Items.INGOTS_GOLD); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.define('Z', Tags.Items.CHESTS_WOODEN); - recipe.pattern("X#X"); - recipe.pattern("#Y#"); - recipe.pattern("XZX"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.FERMENTER).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', ForestryTags.Items.GEARS_BRONZE); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("#Y#"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.MOISTENER).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', ForestryTags.Items.GEARS_COPPER); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("#Y#"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.RAINMAKER).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', ForestryTags.Items.GEARS_TIN); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("#Y#"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.PLAIN.get(BlockTypeFactoryPlain.RAINTANK).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', Tags.Items.INGOTS_IRON); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("XYX"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.SQUEEZER).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', ForestryTags.Items.INGOTS_TIN); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("XYX"); - recipe.pattern("X#X"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, FactoryBlocks.TESR.get(BlockTypeFactoryTesr.STILL).block(), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', Tags.Items.DUSTS_REDSTONE); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern("X#X"); - recipe.pattern("#Y#"); - recipe.pattern("X#X"); - }); - } - - private static void registerFarmingRecipes(MKRecipeProvider recipes) { - for (EnumFarmMaterial material : EnumFarmMaterial.values()) { - Item base = material.getBase().asItem(); - recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.PLAIN, material), recipe -> { - recipe.define('I', Items.COPPER_INGOT); - recipe.define('#', base); - recipe.define('C', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.TIN)); - recipe.define('W', ItemTags.WOODEN_SLABS); - recipe.pattern("I#I"); - recipe.pattern("WCW"); - }); - recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.GEARBOX, material), recipe -> { - recipe.define('T', ForestryTags.Items.GEARS_TIN); - recipe.define('#', base); - recipe.pattern(" # "); - recipe.pattern("TTT"); - }); - recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.HATCH, material), recipe -> { - recipe.define('T', ForestryTags.Items.GEARS_TIN); - recipe.define('#', base); - recipe.define('D', ItemTags.WOODEN_TRAPDOORS); - recipe.pattern(" # "); - recipe.pattern("TDT"); - }); - recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.VALVE, material), recipe -> { - recipe.define('T', ForestryTags.Items.GEARS_TIN); - recipe.define('#', base); - recipe.define('X', Tags.Items.GLASS); - recipe.pattern(" # "); - recipe.pattern("XTX"); - }); - recipes.shapedCrafting(RecipeCategory.MISC, FarmingBlocks.FARM.get(EnumFarmBlockType.CONTROL, material), recipe -> { - recipe.define('T', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.GOLD)); - recipe.define('#', base); - recipe.define('X', Tags.Items.DUSTS_REDSTONE); - recipe.pattern(" # "); - recipe.pattern("XTX"); - }); - } - } - - private static void registerFluidsRecipes(MKRecipeProvider recipes) { - for (EnumContainerType containerType : EnumContainerType.values()) { - recipes.shapedCrafting("cake_" + containerType.getSerializedName(), RecipeCategory.FOOD, Items.CAKE, recipe -> { - recipe.define('A', StrictNBTIngredient.of(getContainer(containerType, ForgeMod.MILK.get()))); - recipe.define('B', Items.SUGAR); - recipe.define('C', Items.WHEAT); - recipe.define('E', Items.EGG); - recipe.pattern("AAA"); - recipe.pattern("BEB"); - recipe.pattern("CCC"); - }); - } - } - - private static void registerLepidopterologyRecipes(MKRecipeProvider recipes) { - recipes.shapedCrafting(RecipeCategory.MISC, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.LEPIDOPTERIST_CHEST), recipe -> { - recipe.define('#', Tags.Items.GLASS); - recipe.define('X', LepidopterologyItems.BUTTERFLY_GE); - recipe.define('Y', Tags.Items.CHESTS_WOODEN); - recipe.pattern(" # "); - recipe.pattern("XYX"); - recipe.pattern("XXX"); - }); - recipes.special("butterfly_mating", LepidopterologyRecipes.MATING_SERIALIZER); - } - - private static void registerMailRecipes(MKRecipeProvider recipes) { - recipes.shapelessCrafting(RecipeCategory.MISC, MailItems.CATALOGUE, 1, Items.BOOK, ForestryTags.Items.STAMPS); - Ingredient sealant = Ingredient.merge(List.of(Ingredient.of(ForestryTags.Items.PROPOLIS), Ingredient.of(Tags.Items.SLIMEBALLS))); - recipes.shapelessCrafting(RecipeCategory.MISC, MailItems.LETTERS.get(ItemLetter.Size.EMPTY, ItemLetter.State.FRESH), 1, Items.PAPER, sealant); - - recipes.shapedCrafting(RecipeCategory.MISC, MailBlocks.BASE.get(BlockTypeMail.MAILBOX).block(), recipe -> { - recipe.define('#', ForestryTags.Items.INGOTS_TIN); - recipe.define('X', Tags.Items.CHESTS_WOODEN); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.pattern(" # "); - recipe.pattern("#Y#"); - recipe.pattern("XXX"); - }); - - Item[] emptiedLetter = MailItems.LETTERS.getRowFeatures(ItemLetter.Size.EMPTY).stream() - .map(FeatureItem::item) - .toArray(Item[]::new); - recipes.shapedCrafting("paper_from_letters", RecipeCategory.MISC, Items.PAPER, recipe -> { - recipe.define('#', Ingredient.of(emptiedLetter)); - recipe.pattern(" # "); - recipe.pattern(" # "); - recipe.pattern(" # "); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, MailBlocks.BASE.get(BlockTypeMail.TRADE_STATION).block(), recipe -> { - recipe.define('#', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.BRONZE)); - recipe.define('X', Tags.Items.CHESTS_WOODEN); - recipe.define('Y', CoreItems.STURDY_CASING); - recipe.define('Z', CoreItems.ELECTRON_TUBES.get(EnumElectronTube.IRON)); - recipe.define('W', StrictNBTIngredient.of(ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{}))); - recipe.pattern("Z#Z"); - recipe.pattern("#Y#"); - recipe.pattern("XWX"); - }); - - Ingredient glue = Ingredient.merge(List.of( - Ingredient.of(ForestryTags.Items.DROP_HONEY), - Ingredient.of(Items.SLIME_BALL) - )); - - for (EnumStampDefinition stampDefinition : EnumStampDefinition.VALUES) { - recipes.shapedCrafting(RecipeCategory.MISC, MailItems.STAMPS.get(stampDefinition), 9, recipe -> { - recipe.define('X', stampDefinition.getCraftingIngredient()); - recipe.define('#', Items.PAPER); - recipe.define('Z', glue); - recipe.pattern("XXX"); - recipe.pattern("###"); - recipe.pattern("ZZZ"); - }); - } - } - - private static void registerSortingRecipes(MKRecipeProvider recipes) { - Ingredient ing = Ingredient.merge(List.of(Ingredient.of(LepidopterologyItems.CATERPILLAR_GE, ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL)), Ingredient.of(ForestryTags.Items.FORESTRY_FRUITS))); - - recipes.shapedCrafting(RecipeCategory.MISC, SortingBlocks.FILTER.block(), 2, recipe -> { - recipe.define('B', ForestryTags.Items.GEARS_BRONZE); - recipe.define('D', Tags.Items.GEMS_DIAMOND); - recipe.define('F', ing); - recipe.define('W', ItemTags.PLANKS); - recipe.define('G', Tags.Items.GLASS); - recipe.pattern("WDW"); - recipe.pattern("FGF"); - recipe.pattern("BDB"); - }); - } - - private static void registerWorktableRecipes(MKRecipeProvider recipes) { - recipes.shapedCrafting(RecipeCategory.MISC, WorktableBlocks.WORKTABLE.block(), recipe -> { - recipe.define('B', Items.BOOK); - recipe.define('T', ForestryTags.Items.CRAFTING_TABLES); - recipe.define('C', Tags.Items.CHESTS_WOODEN); - recipe.pattern("B"); - recipe.pattern("T"); - recipe.pattern("C"); - }); - } - - private static void registerEnergyRecipes(MKRecipeProvider recipes) { - recipes.shapedCrafting(RecipeCategory.MISC, EnergyBlocks.ENGINES.get(EngineBlockType.CLOCKWORK), recipe -> { - recipe.define('P', ItemTags.PLANKS); - recipe.define('I', Tags.Items.GLASS); - recipe.define('Q', ForestryTags.Items.GEARS_COPPER); - recipe.define('D', Items.PISTON); - recipe.define('C', Items.CLOCK); - recipe.pattern("PPP"); - recipe.pattern(" I "); - recipe.pattern("QDC"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, EnergyBlocks.ENGINES.get(EngineBlockType.BIOGAS), recipe -> { - recipe.define('P', ForestryTags.Items.INGOTS_BRONZE); - recipe.define('I', Tags.Items.GLASS); - recipe.define('Q', ForestryTags.Items.GEARS_BRONZE); - recipe.define('D', Items.PISTON); - recipe.pattern("PPP"); - recipe.pattern(" I "); - recipe.pattern("QDQ"); - }); - - recipes.shapedCrafting(RecipeCategory.MISC, EnergyBlocks.ENGINES.get(EngineBlockType.PEAT), recipe -> { - recipe.define('P', Tags.Items.INGOTS_COPPER); - recipe.define('I', Tags.Items.GLASS); - recipe.define('Q', ForestryTags.Items.GEARS_COPPER); - recipe.define('D', Items.PISTON); - recipe.pattern("PPP"); - recipe.pattern(" I "); - recipe.pattern("QDQ"); - }); - } - - private static void registerCarpenter(Consumer consumer) { - new CarpenterRecipeBuilder() - .setPackagingTime(50) - .setLiquid(ForestryFluids.SEED_OIL.getFluid(250)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.IMPREGNATED_CASING) - .pattern("###") - .pattern("# #") - .pattern("###") - .define('#', ItemTags.LOGS)) - .build(consumer, id("carpenter", "impregnated_casing")); - new CarpenterRecipeBuilder() - .setPackagingTime(50) - .setLiquid(ForestryFluids.SEED_OIL.getFluid(500)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreBlocks.BASE.get(BlockTypeCoreTesr.ESCRITOIRE).item()) - .pattern("# ") - .pattern("###") - .pattern("# #") - .define('#', ItemTags.PLANKS)) - .build(consumer, id("carpenter", "escritoire")); - new CarpenterRecipeBuilder() - .setPackagingTime(50) - .setLiquid(ForestryFluids.SEED_OIL.getFluid(100)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.IMPREGNATED_STICK), 2) - .pattern("#") - .pattern("#") - .define('#', ItemTags.LOGS)) - .build(consumer, id("carpenter", "impregnated_stick")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 250)) - .setBox(Ingredient.EMPTY) - .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.WOOD_PULP), 4) - .requires(ItemTags.LOGS)) - .build(consumer, id("carpenter", "wood_pulp")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreBlocks.HUMUS, 9) - .pattern("###") - .pattern("#X#") - .pattern("###") - .define('#', Items.DIRT) - .define('X', CoreItems.MULCH)) - .build(consumer, id("carpenter", "humus")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreBlocks.BOG_EARTH, 8) - .pattern("#X#") - .pattern("XYX") - .pattern("#X#") - .define('#', Items.DIRT) - .define('X', Tags.Items.SAND) - .define('Y', CoreItems.MULCH)) - .build(consumer, id("carpenter", "bog_earth")); - new CarpenterRecipeBuilder() - .setPackagingTime(75) - .setLiquid(new FluidStack(Fluids.WATER, 5000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.HARDENED_CASING) - .pattern("X X") - .pattern(" Y ") - .pattern("X X") - .define('X', Tags.Items.GEMS_DIAMOND) - .define('Y', CoreItems.STURDY_CASING)) - .build(consumer, id("carpenter", "hardened_casing")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.IODINE_CHARGE) - .pattern("Z#Z") - .pattern("#Y#") - .pattern("X#X") - .define('#', ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL)) - .define('X', Items.GUNPOWDER) - .define('Y', FluidsItems.CONTAINERS.get(EnumContainerType.CAN)) - .define('Z', ApicultureItems.HONEY_DROP)) - .build(consumer, id("carpenter", "iodine_charge")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.DISSIPATION_CHARGE) - .pattern("Z#Z") - .pattern("#Y#") - .pattern("X#X") - .define('#', ApicultureItems.ROYAL_JELLY) - .define('X', Items.GUNPOWDER) - .define('Y', FluidsItems.CONTAINERS.get(EnumContainerType.CAN)) - .define('Z', ApicultureItems.HONEYDEW)) - .build(consumer, id("carpenter", "dissipation_charge")); - new CarpenterRecipeBuilder() - .setPackagingTime(100) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, Items.ENDER_PEARL) - .pattern(" # ") - .pattern("###") - .pattern(" # ") - .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.PULSATING_MESH))) - .build(consumer, id("carpenter", "ender_pearl")); - new CarpenterRecipeBuilder() - .setPackagingTime(10) - .setLiquid(new FluidStack(Fluids.WATER, 500)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOVEN_SILK)) - .pattern("XX") - .pattern("XX") - .define('X', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SILK_WISP))) - .build(consumer, id("carpenter", "woven_silk")); - new CarpenterRecipeBuilder() - .setBox(Ingredient.EMPTY) - .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, CoreItems.INGOT_BRONZE, 2) - .requires(CoreItems.BROKEN_BRONZE_PICKAXE)) - .build(consumer, id("carpenter", "reclaim_bronze_pickaxe")); - new CarpenterRecipeBuilder() - .setBox(Ingredient.EMPTY) - .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, CoreItems.INGOT_BRONZE, 1) - .requires(CoreItems.BROKEN_BRONZE_SHOVEL)) - .build(consumer, id("carpenter", "reclaim_bronze_shovel")); - // todo conditional recipe for Create honey fluid 1.20 - new CarpenterRecipeBuilder() - .setPackagingTime(50) - .setLiquid(ForestryFluids.HONEY.getFluid(500)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.SCENTED_PANELING)) - .pattern(" J ") - .pattern("###") - .pattern("WPW") - .define('#', ItemTags.PLANKS) - .define('J', ApicultureItems.ROYAL_JELLY) - .define('W', CoreItems.BEESWAX) - .define('P', ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL))) - .build(consumer, id("carpenter", "scented_paneling")); - new CarpenterRecipeBuilder() - .setPackagingTime(100) - .setLiquid(new FluidStack(Fluids.WATER, 2000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.PORTABLE_ALYZER) - .pattern("X#X") - .pattern("X#X") - .pattern("RDR") - .define('#', Tags.Items.GLASS_PANES) - .define('X', ForestryTags.Items.INGOTS_TIN) - .define('R', Tags.Items.DUSTS_REDSTONE) - .define('D', Tags.Items.GEMS_DIAMOND)) - .build(consumer, id("carpenter", "portable_analyzer")); - new CarpenterRecipeBuilder() - .setPackagingTime(20) - .setBox(Ingredient.of(CoreItems.CARTON)) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.KIT_PICKAXE) - .pattern("###") - .pattern(" X ") - .pattern(" X ") - .define('#', ForestryTags.Items.INGOTS_BRONZE) - .define('X', Items.STICK)) - .build(consumer, id("carpenter", "kit_pickaxe")); - new CarpenterRecipeBuilder() - .setPackagingTime(20) - .setBox(Ingredient.of(CoreItems.CARTON)) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.KIT_SHOVEL) - .pattern(" # ") - .pattern(" X ") - .pattern(" X ") - .define('#', ForestryTags.Items.INGOTS_BRONZE) - .define('X', Items.STICK)) - .build(consumer, id("carpenter", "kit_shovel")); - new CarpenterRecipeBuilder() - .setPackagingTime(40) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, CoreItems.SOLDERING_IRON) - .pattern(" # ") - .pattern("# #") - .pattern(" B") - .define('#', Tags.Items.INGOTS_IRON) - .define('B', ForestryTags.Items.INGOTS_BRONZE)) - .build(consumer, id("carpenter", "soldering_iron")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 250)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, Items.PAPER) - .pattern("#") - .pattern("#") - .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOOD_PULP))) - .build(consumer, id("carpenter", "paper")); - new CarpenterRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CARTON, 2) - .pattern(" # ") - .pattern("# #") - .pattern(" # ") - .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOOD_PULP))) - .build(consumer, id("carpenter", "carton")); - - for (EnumStampDefinition stamp : EnumStampDefinition.VALUES) { - FeatureItem item = MailItems.STAMPS.get(stamp); - - new CarpenterRecipeBuilder() - .setLiquid(ForestryFluids.SEED_OIL.getFluid(300)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, item, 9) - .pattern("###") - .pattern("PPP") - .define('#', stamp.getCraftingIngredient()) - .define('P', Items.PAPER)) - .build(consumer, id("carpenter", item.getName())); - } - - ItemStack basic = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.BASIC, null, new ICircuit[]{}); - ItemStack enhanced = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.ENHANCED, null, new ICircuit[]{}); - ItemStack refined = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{}); - ItemStack intricate = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.INTRICATE, null, new ICircuit[]{}); - - new CarpenterRecipeBuilder() - .setPackagingTime(20) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .override(basic) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.BASIC)) - .pattern("R R") - .pattern("R#R") - .pattern("R R") - .define('#', ForestryTags.Items.INGOTS_TIN) - .define('R', Tags.Items.DUSTS_REDSTONE)) - .build(consumer, id("carpenter", "circuits", "basic")); - new CarpenterRecipeBuilder() - .setPackagingTime(40) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .override(enhanced) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.ENHANCED)) - .pattern("R#R") - .pattern("R#R") - .pattern("R#R") - .define('#', ForestryTags.Items.INGOTS_BRONZE) - .define('R', Tags.Items.DUSTS_REDSTONE)) - .build(consumer, id("carpenter", "circuits", "enhanced")); - new CarpenterRecipeBuilder() - .setPackagingTime(80) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .override(refined) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.REFINED)) - .pattern("R#R") - .pattern("R#R") - .pattern("R#R") - .define('#', Tags.Items.INGOTS_IRON) - .define('R', Tags.Items.DUSTS_REDSTONE)) - .build(consumer, id("carpenter", "circuits", "refined")); - new CarpenterRecipeBuilder() - .setPackagingTime(80) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .override(intricate) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.CIRCUITBOARDS.get(EnumCircuitBoardType.INTRICATE)) - .pattern("R#R") - .pattern("R#R") - .pattern("R#R") - .define('#', Tags.Items.INGOTS_GOLD) - .define('R', Tags.Items.DUSTS_REDSTONE)) - .build(consumer, id("carpenter", "circuits", "intricate")); - new CarpenterRecipeBuilder() - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.DECORATIONS, Items.CANDLE, 4) - .pattern("# #") - .pattern(" X ") - .pattern("# #") - .define('#', CoreItems.BEESWAX) - .define('X', Items.STRING)) - .build(consumer, id("carpenter", "candles")); - - // Crates - new CarpenterRecipeBuilder() - .setPackagingTime(20) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CrateItems.CRATE, 24) - .pattern(" # ") - .pattern("# #") - .pattern(" # ") - .define('#', ItemTags.LOGS)) - .build(consumer, id("carpenter", "crates", "empty")); - - crate(consumer, CrateItems.CRATED_PEAT.get(), Ingredient.of(CoreItems.PEAT)); - crate(consumer, CrateItems.CRATED_APATITE.get(), Ingredient.of(ForestryTags.Items.GEMS_APATITE)); - crate(consumer, CrateItems.CRATED_FERTILIZER_COMPOUND.get(), Ingredient.of(CoreItems.FERTILIZER_COMPOUND)); - crate(consumer, CrateItems.CRATED_MULCH.get(), Ingredient.of(CoreItems.MULCH)); - crate(consumer, CrateItems.CRATED_PHOSPHOR.get(), Ingredient.of(CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.PHOSPHOR))); - crate(consumer, CrateItems.CRATED_ASH.get(), Ingredient.of(CoreItems.ASH)); - crate(consumer, CrateItems.CRATED_TIN.get(), Ingredient.of(ForestryTags.Items.INGOTS_TIN)); - crate(consumer, CrateItems.CRATED_COPPER.get(), Ingredient.of(Items.COPPER_INGOT)); - crate(consumer, CrateItems.CRATED_BRONZE.get(), Ingredient.of(ForestryTags.Items.INGOTS_BRONZE)); - - crate(consumer, CrateItems.CRATED_HUMUS.get(), Ingredient.of(CoreBlocks.HUMUS)); - crate(consumer, CrateItems.CRATED_BOG_EARTH.get(), Ingredient.of(CoreBlocks.BOG_EARTH)); - - crate(consumer, CrateItems.CRATED_WHEAT.get(), Ingredient.of(Tags.Items.CROPS_WHEAT)); - crate(consumer, CrateItems.CRATED_COOKIE.get(), Ingredient.of(Items.COOKIE)); - crate(consumer, CrateItems.CRATED_REDSTONE.get(), Ingredient.of(Tags.Items.DUSTS_REDSTONE)); - crate(consumer, CrateItems.CRATED_LAPIS.get(), Ingredient.of(Tags.Items.GEMS_LAPIS)); - crate(consumer, CrateItems.CRATED_SUGAR_CANE.get(), Ingredient.of(Items.SUGAR_CANE)); - crate(consumer, CrateItems.CRATED_CLAY_BALL.get(), Ingredient.of(Items.CLAY_BALL)); - crate(consumer, CrateItems.CRATED_GLOWSTONE.get(), Ingredient.of(Tags.Items.DUSTS_GLOWSTONE)); - crate(consumer, CrateItems.CRATED_APPLE.get(), Ingredient.of(Items.APPLE)); - crate(consumer, CrateItems.CRATED_COAL.get(), Ingredient.of(Items.COAL)); - crate(consumer, CrateItems.CRATED_CHARCOAL.get(), Ingredient.of(Items.CHARCOAL)); - crate(consumer, CrateItems.CRATED_SEEDS.get(), Ingredient.of(Items.WHEAT_SEEDS)); - crate(consumer, CrateItems.CRATED_POTATO.get(), Ingredient.of(Tags.Items.CROPS_POTATO)); - crate(consumer, CrateItems.CRATED_CARROT.get(), Ingredient.of(Tags.Items.CROPS_CARROT)); - crate(consumer, CrateItems.CRATED_BEETROOT.get(), Ingredient.of(Tags.Items.CROPS_BEETROOT)); - crate(consumer, CrateItems.CRATED_NETHER_WART.get(), Ingredient.of(Tags.Items.CROPS_NETHER_WART)); - - crate(consumer, CrateItems.CRATED_OAK_LOG.get(), Ingredient.of(Items.OAK_LOG)); - crate(consumer, CrateItems.CRATED_BIRCH_LOG.get(), Ingredient.of(Items.BIRCH_LOG)); - crate(consumer, CrateItems.CRATED_JUNGLE_LOG.get(), Ingredient.of(Items.JUNGLE_LOG)); - crate(consumer, CrateItems.CRATED_SPRUCE_LOG.get(), Ingredient.of(Items.SPRUCE_LOG)); - crate(consumer, CrateItems.CRATED_ACACIA_LOG.get(), Ingredient.of(Items.ACACIA_LOG)); - crate(consumer, CrateItems.CRATED_DARK_OAK_LOG.get(), Ingredient.of(Items.DARK_OAK_LOG)); - crate(consumer, CrateItems.CRATED_COBBLESTONE.get(), Ingredient.of(Tags.Items.COBBLESTONE)); - crate(consumer, CrateItems.CRATED_DIRT.get(), Ingredient.of(Items.DIRT)); - crate(consumer, CrateItems.CRATED_GRASS_BLOCK.get(), Ingredient.of(Items.GRASS_BLOCK)); - crate(consumer, CrateItems.CRATED_STONE.get(), Ingredient.of(Tags.Items.STONE)); - crate(consumer, CrateItems.CRATED_GRANITE.get(), Ingredient.of(Items.GRANITE)); - crate(consumer, CrateItems.CRATED_DIORITE.get(), Ingredient.of(Items.DIORITE)); - crate(consumer, CrateItems.CRATED_ANDESITE.get(), Ingredient.of(Items.ANDESITE)); - crate(consumer, CrateItems.CRATED_PRISMARINE.get(), Ingredient.of(Items.PRISMARINE)); - crate(consumer, CrateItems.CRATED_PRISMARINE_BRICKS.get(), Ingredient.of(Items.PRISMARINE_BRICKS)); - crate(consumer, CrateItems.CRATED_DARK_PRISMARINE.get(), Ingredient.of(Items.DARK_PRISMARINE)); - crate(consumer, CrateItems.CRATED_BRICKS.get(), Ingredient.of(Items.BRICKS)); - crate(consumer, CrateItems.CRATED_CACTUS.get(), Ingredient.of(Items.CACTUS)); - crate(consumer, CrateItems.CRATED_SAND.get(), Ingredient.of(Items.SAND)); - crate(consumer, CrateItems.CRATED_RED_SAND.get(), Ingredient.of(Items.RED_SAND)); - crate(consumer, CrateItems.CRATED_OBSIDIAN.get(), Ingredient.of(Tags.Items.OBSIDIAN)); - crate(consumer, CrateItems.CRATED_NETHERRACK.get(), Ingredient.of(Tags.Items.NETHERRACK)); - crate(consumer, CrateItems.CRATED_SOUL_SAND.get(), Ingredient.of(Items.SOUL_SAND)); - crate(consumer, CrateItems.CRATED_SANDSTONE.get(), Ingredient.of(Tags.Items.SANDSTONE)); - crate(consumer, CrateItems.CRATED_NETHER_BRICKS.get(), Ingredient.of(Items.NETHER_BRICKS)); - crate(consumer, CrateItems.CRATED_MYCELIUM.get(), Ingredient.of(Items.MYCELIUM)); - crate(consumer, CrateItems.CRATED_GRAVEL.get(), Ingredient.of(Tags.Items.GRAVEL)); - crate(consumer, CrateItems.CRATED_OAK_SAPLING.get(), Ingredient.of(Items.OAK_SAPLING)); - crate(consumer, CrateItems.CRATED_BIRCH_SAPLING.get(), Ingredient.of(Items.BIRCH_SAPLING)); - crate(consumer, CrateItems.CRATED_JUNGLE_SAPLING.get(), Ingredient.of(Items.JUNGLE_SAPLING)); - crate(consumer, CrateItems.CRATED_SPRUCE_SAPLING.get(), Ingredient.of(Items.SPRUCE_SAPLING)); - crate(consumer, CrateItems.CRATED_ACACIA_SAPLING.get(), Ingredient.of(Items.ACACIA_SAPLING)); - crate(consumer, CrateItems.CRATED_DARK_OAK_SAPLING.get(), Ingredient.of(Items.DARK_OAK_SAPLING)); - - crate(consumer, CrateItems.CRATED_BEESWAX.get(), Ingredient.of(CoreItems.BEESWAX)); - crate(consumer, CrateItems.CRATED_REFRACTORY_WAX.get(), Ingredient.of(CoreItems.REFRACTORY_WAX)); - - crate(consumer, CrateItems.CRATED_POLLEN_CLUSTER_NORMAL.get(), Ingredient.of(ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL))); - crate(consumer, CrateItems.CRATED_POLLEN_CLUSTER_CRYSTALLINE.get(), Ingredient.of(ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.CRYSTALLINE))); - crate(consumer, CrateItems.CRATED_PROPOLIS.get(), Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL))); - crate(consumer, CrateItems.CRATED_HONEYDEW.get(), Ingredient.of(ApicultureItems.HONEYDEW)); - crate(consumer, CrateItems.CRATED_ROYAL_JELLY.get(), Ingredient.of(ApicultureItems.ROYAL_JELLY)); - - for (EnumHoneyComb comb : EnumHoneyComb.VALUES) { - crate(consumer, CrateItems.CRATED_BEE_COMBS.get(comb).get(), Ingredient.of(ApicultureItems.BEE_COMBS.get(comb))); - } - - new CarpenterRecipeBuilder() - .setPackagingTime(10) - .setLiquid(new FluidStack(Fluids.WATER, 250)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, MailItems.LETTERS.get(ItemLetter.Size.EMPTY, ItemLetter.State.FRESH).item()) - .pattern("###") - .pattern("###") - .define('#', CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.WOOD_PULP))) - .build(consumer, id("carpenter", "letter_pulp")); - - wovenBackpack(consumer, "miner", BackpackItems.MINER_BACKPACK, BackpackItems.MINER_BACKPACK_T_2); - wovenBackpack(consumer, "digger", BackpackItems.DIGGER_BACKPACK, BackpackItems.DIGGER_BACKPACK_T_2); - wovenBackpack(consumer, "forester", BackpackItems.FORESTER_BACKPACK, BackpackItems.FORESTER_BACKPACK_T_2); - wovenBackpack(consumer, "hunter", BackpackItems.HUNTER_BACKPACK, BackpackItems.HUNTER_BACKPACK_T_2); - wovenBackpack(consumer, "adventurer", BackpackItems.ADVENTURER_BACKPACK, BackpackItems.ADVENTURER_BACKPACK_T_2); - wovenBackpack(consumer, "builder", BackpackItems.BUILDER_BACKPACK, BackpackItems.BUILDER_BACKPACK_T_2); - } - - private static void wovenBackpack(Consumer consumer, String id, FeatureItem tier1, FeatureItem tier2) { - new CarpenterRecipeBuilder() - .setPackagingTime(200) - .setLiquid(new FluidStack(Fluids.WATER, 1000)) - .setBox(Ingredient.EMPTY) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.TOOLS, tier2) - .pattern("WXW") - .pattern("WTW") - .pattern("WWW") - .define('W', CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.WOVEN_SILK).getItem()) - .define('X', Items.DIAMOND) - .define('T', tier1)) - .build(consumer, id("woven_backpack", id)); - } - - private static void crate(Consumer consumer, ItemCrated crated, Ingredient ingredient) { - ItemStack contained = crated.getContained(); - ResourceLocation name = ModUtil.getRegistryName(contained.getItem()); - - new CarpenterRecipeBuilder() - .setPackagingTime(Constants.CARPENTER_CRATING_CYCLES) - .setLiquid(new FluidStack(Fluids.WATER, Constants.CARPENTER_CRATING_LIQUID_QUANTITY)) - .setBox(Ingredient.of(CrateItems.CRATE)) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, crated, 1) - .pattern("###") - .pattern("###") - .pattern("###") - .define('#', ingredient)) - .build(consumer, id("carpenter", "crates", "pack", name.getNamespace(), name.getPath())); - new CarpenterRecipeBuilder() - .setPackagingTime(Constants.CARPENTER_UNCRATING_CYCLES) - .setBox(Ingredient.EMPTY) - .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, contained.getItem(), 9).requires(crated)) - .build(consumer, id("carpenter", "crates", "unpack", name.getNamespace(), name.getPath())); - } - - private static void registerCentrifuge(Consumer consumer) { - - ItemStack honeyDrop = ApicultureItems.HONEY_DROP.stack(); - - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.HONEY))) - .product(1.0f, CoreItems.BEESWAX.stack()) - .product(0.9F, honeyDrop) - .build(consumer, id("centrifuge", "honey_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.COCOA))) - .product(1.0f, CoreItems.BEESWAX.stack()) - .product(0.5f, new ItemStack(Items.COCOA_BEANS)) - .build(consumer, id("centrifuge", "cocoa_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.SIMMERING))) - .product(1.0f, CoreItems.REFRACTORY_WAX.stack()) - .product(0.7f, honeyDrop) - .build(consumer, id("centrifuge", "simmering_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.STRINGY))) - .product(1.0f, ApicultureItems.PROPOLIS.stack(EnumPropolis.NORMAL, 1)) - .product(0.4f, honeyDrop) - .build(consumer, id("centrifuge", "stringy_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.DRIPPING))) - .product(1.0f, ApicultureItems.HONEYDEW.stack()) - .product(0.4f, honeyDrop) - .build(consumer, id("centrifuge", "dripping_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.FROZEN))) - .product(0.8f, CoreItems.BEESWAX.stack()) - .product(0.7f, honeyDrop) - .product(0.4f, new ItemStack(Items.SNOWBALL)) - .product(0.2f, ApicultureItems.POLLEN_CLUSTER.stack(EnumPollenCluster.CRYSTALLINE, 1)) - .build(consumer, id("centrifuge", "frozen_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.SILKY))) - .product(1.0f, honeyDrop) - .product(0.8f, ApicultureItems.PROPOLIS.stack(EnumPropolis.SILKY, 1)) - .build(consumer, id("centrifuge", "silky_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.PARCHED))) - .product(1.0f, CoreItems.BEESWAX.stack()) - .product(0.9f, honeyDrop) - .build(consumer, id("centrifuge", "parched_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.MYSTERIOUS))) - .product(1.0f, ApicultureItems.PROPOLIS.stack(EnumPropolis.PULSATING, 1)) - .product(0.4f, honeyDrop) - .build(consumer, id("centrifuge", "mysterious_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.POWDERY))) - .product(0.2f, honeyDrop) - .product(0.2f, CoreItems.BEESWAX.stack()) - .product(0.9f, new ItemStack(Items.GUNPOWDER)) - .build(consumer, id("centrifuge", "powdery_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.WHEATEN))) - .product(0.2f, honeyDrop) - .product(0.2f, CoreItems.BEESWAX.stack()) - .product(0.8f, new ItemStack(Items.WHEAT)) - .build(consumer, id("centrifuge", "wheaten_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.MOSSY))) - .product(1.0f, CoreItems.BEESWAX.stack()) - .product(0.9f, honeyDrop) - .build(consumer, id("centrifuge", "mossy_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.KAOLIN))) - .product(1.0f, new ItemStack(Items.CLAY_BALL)) - .product(0.9f, honeyDrop) - .build(consumer, id("centrifuge", "kaolin_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.MELLOW))) - .product(0.6f, ApicultureItems.HONEYDEW.stack()) - .product(0.2f, CoreItems.BEESWAX.stack()) - .product(0.3f, new ItemStack(Items.QUARTZ)) - .build(consumer, id("centrifuge", "mellow_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.VINTAGE))) - .product(1.0f, CoreItems.BEESWAX.stack()) - .product(0.9f, ApicultureItems.HONEYDEW.stack()) - .build(consumer, id("centrifuge", "vintage_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(ApicultureItems.BEE_COMBS.get(EnumHoneyComb.SCULKEN))) - .product(1.0f, CoreItems.BEESWAX.stack()) - .product(0.9f, ApicultureItems.EXPERIENCE_DROP.stack()) - .product(0.2F, new ItemStack(Items.SCULK)) - .build(consumer, id("centrifuge", "sculken_comb")); - new CentrifugeRecipeBuilder() - .setProcessingTime(5) - .setInput(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.SILKY))) - .product(0.6f, CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.SILK_WISP, 1)) - .product(0.1f, ApicultureItems.PROPOLIS.stack(EnumPropolis.NORMAL, 1)) - .build(consumer, id("centrifuge", "silky_propolis")); - - - new CentrifugeRecipeBuilder() - .setProcessingTime(20) - .setInput(Ingredient.of(Items.HONEYCOMB)) - .product(1.0f, CoreItems.BEESWAX.stack()) - .build(consumer, id("centrifuge", "comb_to_wax")); - } - - private static void registerFabricator(Consumer consumer) { - FluidStack liquidGlass = ForestryFluids.GLASS.getFluid(500); - - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.IRON), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Tags.Items.INGOTS_IRON)) - .build(consumer, id("fabricator", "electron_tubes", "iron")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.GOLD), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Tags.Items.INGOTS_GOLD)) - .build(consumer, id("fabricator", "electron_tubes", "gold")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.DIAMOND), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Tags.Items.GEMS_DIAMOND)) - .build(consumer, id("fabricator", "electron_tubes", "diamond")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.OBSIDIAN), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Items.OBSIDIAN)) - .build(consumer, id("fabricator", "electron_tubes", "obsidian")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.BLAZE), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Items.BLAZE_POWDER)) - .build(consumer, id("fabricator", "electron_tubes", "blaze")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.EMERALD), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Tags.Items.GEMS_EMERALD)) - .build(consumer, id("fabricator", "electron_tubes", "emerald")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.LAPIS), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Tags.Items.GEMS_LAPIS)) - .build(consumer, id("fabricator", "electron_tubes", "lapis")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.ENDER), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Items.ENDER_EYE) - .define('X', Items.END_STONE)) - .build(consumer, id("fabricator", "electron_tubes", "ender")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.COPPER), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', Items.COPPER_INGOT)) - .build(consumer, id("fabricator", "electron_tubes", "copper")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.TIN), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', ForestryTags.Items.INGOTS_TIN)) - .build(consumer, id("fabricator", "electron_tubes", "tin")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.BRONZE), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', ForestryTags.Items.INGOTS_BRONZE)) - .build(consumer, id("fabricator", "electron_tubes", "bronze")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.ELECTRON_TUBES.get(EnumElectronTube.APATITE), 4) - .pattern(" X ") - .pattern("#X#") - .pattern("XXX") - .define('#', Tags.Items.DUSTS_REDSTONE) - .define('X', ForestryTags.Items.GEMS_APATITE)) - .build(consumer, id("fabricator", "electron_tubes", "apatite")); - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, CoreItems.FLEXIBLE_CASING) - .pattern("#E#") - .pattern("B B") - .pattern("#E#") - .define('#', ForestryTags.Items.INGOTS_BRONZE) - .define('B', Tags.Items.SLIMEBALLS) - .define('E', Tags.Items.GEMS_EMERALD)) - .build(consumer, id("fabricator", "electron_tubes", "flexible_casing")); - - for (ForestryWoodType type : ForestryWoodType.values()) { - addFireproofRecipes(consumer, type); - } - - for (VanillaWoodType type : VanillaWoodType.values()) { - addFireproofRecipes(consumer, type); - } - } - - private static void addFireproofRecipes(Consumer consumer, IWoodType type) { - FluidStack liquidGlass = ForestryFluids.GLASS.getFluid(500); - - List logLike = List.of(WoodBlockKind.LOG, WoodBlockKind.WOOD, WoodBlockKind.STRIPPED_LOG, WoodBlockKind.STRIPPED_WOOD); - IWoodAccess woodAccess = IForestryApi.INSTANCE.getTreeManager().getWoodAccess(); - - for (WoodBlockKind woodKind : logLike) { - try { - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.BUILDING_BLOCKS, woodAccess.getBlock(type, woodKind, true).getBlock(), 2) - .pattern(" ") - .pattern("X#X") - .pattern(" ") - .define('#', CoreItems.REFRACTORY_WAX) - .define('X', woodAccess.getBlock(type, woodKind, false).getBlock())) - .build(consumer, id("fabricator", "fireproof", woodKind.getSerializedName(), type.toString())); - } catch (IllegalStateException ignored) { - } - } - - new FabricatorRecipeBuilder() - .setPlan(Ingredient.EMPTY) - .setMolten(liquidGlass) - .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.BUILDING_BLOCKS, woodAccess.getBlock(type, WoodBlockKind.PLANKS, true).getBlock(), 8) - .pattern("XXX") - .pattern("X#X") - .pattern("XXX") - .define('#', CoreItems.REFRACTORY_WAX) - .define('X', woodAccess.getBlock(type, WoodBlockKind.PLANKS, false).getBlock())) - .build(consumer, id("fabricator", "fireproof", "planks", type.toString())); - } - - private static void registerFabricatorSmelting(Consumer consumer) { - FluidStack liquidGlassBucket = ForestryFluids.GLASS.getFluid(FluidType.BUCKET_VOLUME); - FluidStack liquidGlassX4 = ForestryFluids.GLASS.getFluid(FluidType.BUCKET_VOLUME * 4); - FluidStack liquidGlass375 = ForestryFluids.GLASS.getFluid(375); - - new FabricatorSmeltingRecipeBuilder() - .setResource(Ingredient.of(Items.GLASS)) - .setProduct(liquidGlassBucket) - .setMeltingPoint(1000) - .build(consumer, id("fabricator", "smelting", "glass")); - new FabricatorSmeltingRecipeBuilder() - .setResource(Ingredient.of(Items.GLASS_PANE)) - .setProduct(liquidGlass375) - .setMeltingPoint(1000) - .build(consumer, id("fabricator", "smelting", "glass_pane")); - new FabricatorSmeltingRecipeBuilder() - .setResource(Ingredient.of(Items.SAND, Items.RED_SAND)) - .setProduct(liquidGlassBucket) - .setMeltingPoint(3000) - .build(consumer, id("fabricator", "smelting", "sand")); - new FabricatorSmeltingRecipeBuilder() - .setResource(Ingredient.of(Items.SANDSTONE, Items.SMOOTH_SANDSTONE, Items.CHISELED_SANDSTONE)) - .setProduct(liquidGlassX4) - .setMeltingPoint(4800) - .build(consumer, id("fabricator", "smelting", "sandstone")); - } - - private static void registerFermenter(Consumer consumer) { - // Apiculture - new FermenterRecipeBuilder() - .setResource(Ingredient.of(ApicultureItems.HONEYDEW)) - .setFermentationValue(500) - .setOutput(ForestryFluids.SHORT_MEAD.getFluid()) - .setFluidResource(ForestryFluids.HONEY.getFluid(1)) - .build(consumer, id("fermenter", "honeydew")); - // Arboriculture - addFermenterRecipes(consumer, "sapling", Ingredient.of(ItemTags.SAPLINGS), 250, ForestryFluids.BIOMASS); - // Factory - addFermenterRecipes(consumer, "cactus", Ingredient.of(Items.CACTUS), 50, ForestryFluids.BIOMASS); - addFermenterRecipes(consumer, "wheat", Ingredient.of(Tags.Items.CROPS_WHEAT), 50, ForestryFluids.BIOMASS); - addFermenterRecipes(consumer, "potato", Ingredient.of(Tags.Items.CROPS_POTATO), 100, ForestryFluids.BIOMASS); - addFermenterRecipes(consumer, "sugar_cane", Ingredient.of(Items.SUGAR_CANE), 50, ForestryFluids.BIOMASS); - addFermenterRecipes(consumer, "mushroom", Ingredient.of(Tags.Items.MUSHROOMS), 50, ForestryFluids.BIOMASS); - } - - private static void addFermenterRecipes(Consumer writer, String name, Ingredient resource, int fermentationValue, ForestryFluids output) { - Fluid outputFluid = output.getFluid(); - - new FermenterRecipeBuilder() - .setResource(resource) - .setFermentationValue(fermentationValue) - .setFluidResource(new FluidStack(Fluids.WATER, 1)) - .setOutput(outputFluid) - .build(writer, id("fermenter", name)); - new FermenterRecipeBuilder() - .setResource(resource) - .setFermentationValue(fermentationValue) - .setFluidResource(ForestryFluids.JUICE.getFluid(1)) - .setOutput(outputFluid) - .setModifier(1.5f) - .build(writer, id("fermenter", name + "_juice")); - new FermenterRecipeBuilder() - .setResource(resource) - .setFermentationValue(fermentationValue) - .setFluidResource(ForestryFluids.HONEY.getFluid(1)) - .setOutput(outputFluid) - .setModifier(1.5f) - .build(writer, id("fermenter", name + "_honey")); - } - - private static void registerHygroregulator(Consumer consumer) { - new HygroregulatorRecipeBuilder() - .setLiquid(new FluidStack(Fluids.WATER, 1)) - .setTemperatureSteps(-1) - .setHumiditySteps(1) - .build(consumer, id("hygroregulator", "water")); - new HygroregulatorRecipeBuilder() - .setLiquid(new FluidStack(Fluids.LAVA, 1)) - .setTemperatureSteps(1) - .setHumiditySteps(-1) - .build(consumer, id("hygroregulator", "lava")); - new HygroregulatorRecipeBuilder() - .setLiquid(ForestryFluids.ICE.getFluid(1)) - .setRetainTime(10) - .setTemperatureSteps(-2) - .setHumiditySteps(2) - .build(consumer, id("hygroregulator", "ice")); - } - - private static void registerMoistener(Consumer consumer) { - new MoistenerRecipeBuilder() - .setResource(Ingredient.of(Items.WHEAT_SEEDS)) - .setProduct(new ItemStack(Items.MYCELIUM)) - .setTimePerItem(5000) - .build(consumer, id("moistener", "mycelium")); - new MoistenerRecipeBuilder() - .setResource(Ingredient.of(Items.COBBLESTONE)) - .setProduct(new ItemStack(Items.MOSSY_COBBLESTONE)) - .setTimePerItem(20000) - .build(consumer, id("moistener", "mossy_cobblestone")); - new MoistenerRecipeBuilder() - .setResource(Ingredient.of(Items.STONE_BRICKS)) - .setProduct(new ItemStack(Items.MOSSY_STONE_BRICKS)) - .setTimePerItem(20000) - .build(consumer, id("moistener", "mossy_stone_bricks")); - new MoistenerRecipeBuilder() - .setResource(Ingredient.of(Items.SPRUCE_LEAVES)) - .setProduct(new ItemStack(Items.PODZOL)) - .setTimePerItem(5000) - .build(consumer, id("moistener", "podzol")); - } - - private static void registerSqueezerContainer(Consumer consumer) { - new SqueezerContainerRecipeBuilder() - .setProcessingTime(10) - .setEmptyContainer(FluidsItems.CONTAINERS.stack(EnumContainerType.CAN)) - .setRemnants(CoreItems.INGOT_TIN.stack()) - .setRemnantsChance(0.05f) - .build(consumer, id("squeezer", "container", "can")); - new SqueezerContainerRecipeBuilder() - .setProcessingTime(10) - .setEmptyContainer(FluidsItems.CONTAINERS.stack(EnumContainerType.CAPSULE)) - .setRemnants(CoreItems.BEESWAX.stack()) - .setRemnantsChance(0.10f) - .build(consumer, id("squeezer", "container", "capsule")); - new SqueezerContainerRecipeBuilder() - .setProcessingTime(10) - .setEmptyContainer(FluidsItems.CONTAINERS.stack(EnumContainerType.REFRACTORY)) - .setRemnants(CoreItems.REFRACTORY_WAX.stack()) - .setRemnantsChance(0.10f) - .build(consumer, id("squeezer", "container", "refractory")); - } - - private static void registerSqueezer(Consumer consumer) { - FluidStack honeyDropFluid = ForestryFluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); - FluidStack honeyBlockFluid = ForestryFluids.HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP * 8); - - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ApicultureItems.HONEY_DROP))) - .setFluidOutput(honeyDropFluid) - .setRemnants(ApicultureItems.PROPOLIS.stack(EnumPropolis.NORMAL, 1)) - .setRemnantsChance(5 / 100f) - .build(consumer, id("squeezer", "honey_drop")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ApicultureItems.BEE_COMBS.stack(EnumHoneyComb.SPONGE)))) - .setFluidOutput(honeyDropFluid) - .setRemnants(new ItemStack(Items.SPONGE)) - .setRemnantsChance(2 / 100f) - .build(consumer, id("squeezer", "sponge_comb")); - - new SqueezerRecipeBuilder() - .setProcessingTime(60) - .setResources(NonNullList.withSize(1, Ingredient.of(Items.HONEY_BLOCK))) - .setFluidOutput(honeyBlockFluid) - .build(consumer, id("squeezer", "honey_block")); - - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ApicultureItems.HONEYDEW))) - .setFluidOutput(honeyDropFluid) - .build(consumer, id("squeezer", "honey_dew")); - - new SqueezerRecipeBuilder() - .setProcessingTime(20) - .setResources(Util.make(NonNullList.create(), (ingredients) -> { - ingredients.add(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.VOLCANIC))); - ingredients.add(Ingredient.of(Items.SAND, Items.RED_SAND)); - })) - .setFluidOutput(new FluidStack(Fluids.LAVA, 500)) - .build(consumer, id("squeezer", "lava_sand")); - - new SqueezerRecipeBuilder() - .setProcessingTime(30) - .setResources(Util.make(NonNullList.create(), (ingredients) -> { - ingredients.add(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.VOLCANIC))); - ingredients.add(Ingredient.of(Items.COBBLESTONE)); - })) - .setFluidOutput(new FluidStack(Fluids.LAVA, 500)) - .build(consumer, id("squeezer", "lava")); - - new SqueezerRecipeBuilder() - .setProcessingTime(20) - .setResources(Util.make(NonNullList.create(), (ingredients) -> { - ingredients.add(Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.VOLCANIC))); - ingredients.add(Ingredient.of(Items.MAGMA_BLOCK)); - })) - .setFluidOutput(new FluidStack(Fluids.LAVA, 1000)) - .build(consumer, id("squeezer", "lava_magma")); - - int seedOilAmount = Preference.SQUEEZED_LIQUID_SEED; - - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(Tags.Items.SEEDS))) - .setFluidOutput(ForestryFluids.SEED_OIL.getFluid(seedOilAmount)) - .build(consumer, id("squeezer", "seeds")); - - float mulchMultiplier = Preference.SQUEEZED_MULCH_APPLE; - int juiceMultiplier = Preference.SQUEEZED_LIQUID_APPLE; - - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(Items.APPLE, Items.CARROT))) - .setFluidOutput(ForestryFluids.JUICE.getFluid(juiceMultiplier)) - .setRemnants(CoreItems.MULCH.stack()) - .setRemnantsChance(mulchMultiplier) - .build(consumer, id("squeezer", "mulch")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(Items.CACTUS))) - .setFluidOutput(new FluidStack(Fluids.WATER, 500)) - .build(consumer, id("squeezer", "cactus")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(List.of( - Ingredient.of(Items.SNOWBALL), - Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)), - Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)), - Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)), - Ingredient.of(CoreItems.CRAFTING_MATERIALS.get(EnumCraftingMaterial.ICE_SHARD)) - )) - .setFluidOutput(ForestryFluids.ICE.getFluid(4000)) - .build(consumer, id("squeezer", "ice")); - - int seedOilMultiplier = Preference.SQUEEZED_LIQUID_SEED; - - ItemStack mulch = new ItemStack(CoreItems.MULCH); - Fluid seedOil = ForestryFluids.SEED_OIL.getFluid(); - Fluid juice = ForestryFluids.JUICE.getFluid(); - - new SqueezerRecipeBuilder() - .setProcessingTime(20) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.CHERRY))) - .setFluidOutput(new FluidStack(seedOil, seedOilMultiplier * 5)) - .setRemnants(mulch) - .setRemnantsChance(0.05F) - .build(consumer, id("squeezer", "fruit", "cherry")); - new SqueezerRecipeBuilder() - .setProcessingTime(60) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.WALNUT))) - .setFluidOutput(new FluidStack(seedOil, seedOilMultiplier * 18)) - .setRemnants(mulch) - .setRemnantsChance(0.05F) - .build(consumer, id("squeezer", "fruit", "walnut")); - new SqueezerRecipeBuilder() - .setProcessingTime(70) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.CHESTNUT))) - .setFluidOutput(new FluidStack(seedOil, seedOilMultiplier * 22)) - .setRemnants(mulch) - .setRemnantsChance(0.02F) - .build(consumer, id("squeezer", "fruit", "chestnut")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.LEMON))) - .setFluidOutput(new FluidStack(juice, juiceMultiplier * 2)) - .setRemnants(mulch) - .setRemnantsChance(mulchMultiplier / 2f) - .build(consumer, id("squeezer", "fruit", "lemon")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.PLUM))) - .setFluidOutput(new FluidStack(juice, juiceMultiplier / 2)) - .setRemnants(mulch) - .setRemnantsChance(mulchMultiplier * 3f) - .build(consumer, id("squeezer", "fruit", "plum")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.PAPAYA))) - .setFluidOutput(new FluidStack(juice, juiceMultiplier * 3)) - .setRemnants(mulch) - .setRemnantsChance(mulchMultiplier / 2f) - .build(consumer, id("squeezer", "fruit", "papaya")); - new SqueezerRecipeBuilder() - .setProcessingTime(10) - .setResources(NonNullList.withSize(1, Ingredient.of(ForestryTags.Items.DATE))) - .setFluidOutput(new FluidStack(juice, juiceMultiplier / 4)) - .setRemnants(mulch) - .setRemnantsChance(mulchMultiplier) - .build(consumer, id("squeezer", "fruit", "dates")); - } - - private static void registerStill(Consumer consumer) { - FluidStack biomass = ForestryFluids.BIOMASS.getFluid(STILL_DESTILLATION_INPUT); - FluidStack ethanol = ForestryFluids.BIO_ETHANOL.getFluid(STILL_DESTILLATION_OUTPUT); - - new StillRecipeBuilder() - .setTimePerUnit(STILL_DESTILLATION_DURATION) - .setInput(biomass) - .setOutput(ethanol) - .build(consumer, id("still", "ethanol")); - } - - private static ResourceLocation id(String... path) { - return new ResourceLocation("forestry", String.join("/", path)); - } -} diff --git a/src/main/java/forestry/core/data/recipe/StorageRecipes.java b/src/main/java/forestry/core/data/recipe/StorageRecipes.java new file mode 100644 index 0000000000..a49880225e --- /dev/null +++ b/src/main/java/forestry/core/data/recipe/StorageRecipes.java @@ -0,0 +1,228 @@ +package forestry.core.data.recipe; + +import forestry.api.ForestryTags; +import forestry.apiculture.blocks.NaturalistChestBlockType; +import forestry.apiculture.features.ApicultureItems; +import forestry.apiculture.items.EnumHoneyComb; +import forestry.apiculture.items.EnumPollenCluster; +import forestry.apiculture.items.EnumPropolis; +import forestry.core.config.Constants; +import forestry.core.features.CoreBlocks; +import forestry.core.features.CoreItems; +import forestry.core.items.definitions.EnumCraftingMaterial; +import forestry.core.utils.ModUtil; +import forestry.modules.features.FeatureItem; +import forestry.storage.features.BackpackItems; +import forestry.storage.features.CrateItems; +import forestry.storage.items.ItemCrated; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.data.recipes.ShapedRecipeBuilder; +import net.minecraft.data.recipes.ShapelessRecipeBuilder; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.ItemTags; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.material.Fluids; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; +import thedarkcolour.modkit.data.MKRecipeProvider; + +public class StorageRecipes { + static void registerBackpackRecipes(RecipeOutput output, MKRecipeProvider recipes) { + recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.ADVENTURER_BACKPACK, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', Tags.Items.BONES); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.BUILDER_BACKPACK, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', Items.CLAY_BALL); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.DIGGER_BACKPACK, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', Tags.Items.STONES); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.FORESTER_BACKPACK, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', ItemTags.LOGS); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.HUNTER_BACKPACK, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', Tags.Items.FEATHERS); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + + recipes.shapedCrafting(RecipeCategory.TOOLS, BackpackItems.MINER_BACKPACK, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', Tags.Items.INGOTS_IRON); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', Tags.Items.CHESTS_WOODEN); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + + wovenBackpack(output, "miner", BackpackItems.MINER_BACKPACK, BackpackItems.MINER_BACKPACK_T_2); + wovenBackpack(output, "digger", BackpackItems.DIGGER_BACKPACK, BackpackItems.DIGGER_BACKPACK_T_2); + wovenBackpack(output, "forester", BackpackItems.FORESTER_BACKPACK, BackpackItems.FORESTER_BACKPACK_T_2); + wovenBackpack(output, "hunter", BackpackItems.HUNTER_BACKPACK, BackpackItems.HUNTER_BACKPACK_T_2); + wovenBackpack(output, "adventurer", BackpackItems.ADVENTURER_BACKPACK, BackpackItems.ADVENTURER_BACKPACK_T_2); + wovenBackpack(output, "builder", BackpackItems.BUILDER_BACKPACK, BackpackItems.BUILDER_BACKPACK_T_2); + + // Naturalist backpacks + naturalistBackpack(recipes, BackpackItems.APIARIST_BACKPACK, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.APIARIST_CHEST)); + naturalistBackpack(recipes, BackpackItems.LEPIDOPTERIST_BACKPACK, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.LEPIDOPTERIST_CHEST)); + naturalistBackpack(recipes, BackpackItems.ARBORIST_BACKPACK, CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST)); + + crate(output, CrateItems.CRATED_PEAT.get(), Ingredient.of(CoreItems.PEAT)); + crate(output, CrateItems.CRATED_APATITE.get(), Ingredient.of(ForestryTags.Items.GEMS_APATITE)); + crate(output, CrateItems.CRATED_FERTILIZER_COMPOUND.get(), Ingredient.of(CoreItems.FERTILIZER_COMPOUND)); + crate(output, CrateItems.CRATED_MULCH.get(), Ingredient.of(CoreItems.MULCH)); + crate(output, CrateItems.CRATED_PHOSPHOR.get(), Ingredient.of(CoreItems.CRAFTING_MATERIALS.item(EnumCraftingMaterial.PHOSPHOR))); + crate(output, CrateItems.CRATED_ASH.get(), Ingredient.of(CoreItems.ASH)); + crate(output, CrateItems.CRATED_TIN.get(), Ingredient.of(ForestryTags.Items.INGOTS_TIN)); + crate(output, CrateItems.CRATED_COPPER.get(), Ingredient.of(Items.COPPER_INGOT)); + crate(output, CrateItems.CRATED_BRONZE.get(), Ingredient.of(ForestryTags.Items.INGOTS_BRONZE)); + + crate(output, CrateItems.CRATED_HUMUS.get(), Ingredient.of(CoreBlocks.HUMUS)); + crate(output, CrateItems.CRATED_BOG_EARTH.get(), Ingredient.of(CoreBlocks.BOG_EARTH)); + + crate(output, CrateItems.CRATED_WHEAT.get(), Ingredient.of(Tags.Items.CROPS_WHEAT)); + crate(output, CrateItems.CRATED_COOKIE.get(), Ingredient.of(Items.COOKIE)); + crate(output, CrateItems.CRATED_REDSTONE.get(), Ingredient.of(Tags.Items.DUSTS_REDSTONE)); + crate(output, CrateItems.CRATED_LAPIS.get(), Ingredient.of(Tags.Items.GEMS_LAPIS)); + crate(output, CrateItems.CRATED_SUGAR_CANE.get(), Ingredient.of(Items.SUGAR_CANE)); + crate(output, CrateItems.CRATED_CLAY_BALL.get(), Ingredient.of(Items.CLAY_BALL)); + crate(output, CrateItems.CRATED_GLOWSTONE.get(), Ingredient.of(Tags.Items.DUSTS_GLOWSTONE)); + crate(output, CrateItems.CRATED_APPLE.get(), Ingredient.of(Items.APPLE)); + crate(output, CrateItems.CRATED_COAL.get(), Ingredient.of(Items.COAL)); + crate(output, CrateItems.CRATED_CHARCOAL.get(), Ingredient.of(Items.CHARCOAL)); + crate(output, CrateItems.CRATED_SEEDS.get(), Ingredient.of(Items.WHEAT_SEEDS)); + crate(output, CrateItems.CRATED_POTATO.get(), Ingredient.of(Tags.Items.CROPS_POTATO)); + crate(output, CrateItems.CRATED_CARROT.get(), Ingredient.of(Tags.Items.CROPS_CARROT)); + crate(output, CrateItems.CRATED_BEETROOT.get(), Ingredient.of(Tags.Items.CROPS_BEETROOT)); + crate(output, CrateItems.CRATED_NETHER_WART.get(), Ingredient.of(Tags.Items.CROPS_NETHER_WART)); + + crate(output, CrateItems.CRATED_OAK_LOG.get(), Ingredient.of(Items.OAK_LOG)); + crate(output, CrateItems.CRATED_BIRCH_LOG.get(), Ingredient.of(Items.BIRCH_LOG)); + crate(output, CrateItems.CRATED_JUNGLE_LOG.get(), Ingredient.of(Items.JUNGLE_LOG)); + crate(output, CrateItems.CRATED_SPRUCE_LOG.get(), Ingredient.of(Items.SPRUCE_LOG)); + crate(output, CrateItems.CRATED_ACACIA_LOG.get(), Ingredient.of(Items.ACACIA_LOG)); + crate(output, CrateItems.CRATED_DARK_OAK_LOG.get(), Ingredient.of(Items.DARK_OAK_LOG)); + crate(output, CrateItems.CRATED_COBBLESTONE.get(), Ingredient.of(Tags.Items.COBBLESTONES)); + crate(output, CrateItems.CRATED_DIRT.get(), Ingredient.of(Items.DIRT)); + crate(output, CrateItems.CRATED_GRASS_BLOCK.get(), Ingredient.of(Items.GRASS_BLOCK)); + crate(output, CrateItems.CRATED_STONE.get(), Ingredient.of(Tags.Items.STONES)); + crate(output, CrateItems.CRATED_GRANITE.get(), Ingredient.of(Items.GRANITE)); + crate(output, CrateItems.CRATED_DIORITE.get(), Ingredient.of(Items.DIORITE)); + crate(output, CrateItems.CRATED_ANDESITE.get(), Ingredient.of(Items.ANDESITE)); + crate(output, CrateItems.CRATED_PRISMARINE.get(), Ingredient.of(Items.PRISMARINE)); + crate(output, CrateItems.CRATED_PRISMARINE_BRICKS.get(), Ingredient.of(Items.PRISMARINE_BRICKS)); + crate(output, CrateItems.CRATED_DARK_PRISMARINE.get(), Ingredient.of(Items.DARK_PRISMARINE)); + crate(output, CrateItems.CRATED_BRICKS.get(), Ingredient.of(Items.BRICKS)); + crate(output, CrateItems.CRATED_CACTUS.get(), Ingredient.of(Items.CACTUS)); + crate(output, CrateItems.CRATED_SAND.get(), Ingredient.of(Items.SAND)); + crate(output, CrateItems.CRATED_RED_SAND.get(), Ingredient.of(Items.RED_SAND)); + crate(output, CrateItems.CRATED_OBSIDIAN.get(), Ingredient.of(Tags.Items.OBSIDIANS)); + crate(output, CrateItems.CRATED_NETHERRACK.get(), Ingredient.of(Tags.Items.NETHERRACKS)); + crate(output, CrateItems.CRATED_SOUL_SAND.get(), Ingredient.of(Items.SOUL_SAND)); + crate(output, CrateItems.CRATED_SANDSTONE.get(), Ingredient.of(Tags.Items.SANDSTONE_BLOCKS)); + crate(output, CrateItems.CRATED_NETHER_BRICKS.get(), Ingredient.of(Items.NETHER_BRICKS)); + crate(output, CrateItems.CRATED_MYCELIUM.get(), Ingredient.of(Items.MYCELIUM)); + crate(output, CrateItems.CRATED_GRAVEL.get(), Ingredient.of(Tags.Items.GRAVELS)); + crate(output, CrateItems.CRATED_OAK_SAPLING.get(), Ingredient.of(Items.OAK_SAPLING)); + crate(output, CrateItems.CRATED_BIRCH_SAPLING.get(), Ingredient.of(Items.BIRCH_SAPLING)); + crate(output, CrateItems.CRATED_JUNGLE_SAPLING.get(), Ingredient.of(Items.JUNGLE_SAPLING)); + crate(output, CrateItems.CRATED_SPRUCE_SAPLING.get(), Ingredient.of(Items.SPRUCE_SAPLING)); + crate(output, CrateItems.CRATED_ACACIA_SAPLING.get(), Ingredient.of(Items.ACACIA_SAPLING)); + crate(output, CrateItems.CRATED_DARK_OAK_SAPLING.get(), Ingredient.of(Items.DARK_OAK_SAPLING)); + + crate(output, CrateItems.CRATED_BEESWAX.get(), Ingredient.of(CoreItems.BEESWAX)); + crate(output, CrateItems.CRATED_REFRACTORY_WAX.get(), Ingredient.of(CoreItems.REFRACTORY_WAX)); + + crate(output, CrateItems.CRATED_POLLEN_CLUSTER_NORMAL.get(), Ingredient.of(ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.NORMAL))); + crate(output, CrateItems.CRATED_POLLEN_CLUSTER_CRYSTALLINE.get(), Ingredient.of(ApicultureItems.POLLEN_CLUSTER.get(EnumPollenCluster.CRYSTALLINE))); + crate(output, CrateItems.CRATED_PROPOLIS.get(), Ingredient.of(ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL))); + crate(output, CrateItems.CRATED_HONEYDEW.get(), Ingredient.of(ApicultureItems.HONEYDEW)); + crate(output, CrateItems.CRATED_ROYAL_JELLY.get(), Ingredient.of(ApicultureItems.ROYAL_JELLY)); + + for (EnumHoneyComb comb : EnumHoneyComb.values()) { + crate(output, CrateItems.CRATED_BEE_COMBS.get(comb).get(), Ingredient.of(ApicultureItems.BEE_COMBS.get(comb))); + } + } + + private static void naturalistBackpack(MKRecipeProvider recipes, ItemLike backpack, ItemLike chest) { + recipes.shapedCrafting(RecipeCategory.TOOLS, backpack, recipe -> { + recipe.define('#', ItemTags.WOOL); + recipe.define('V', Tags.Items.RODS_WOODEN); + recipe.define('X', Tags.Items.STRINGS); + recipe.define('Y', chest); + recipe.pattern("X#X"); + recipe.pattern("VYV"); + recipe.pattern("X#X"); + }); + } + + static void wovenBackpack(RecipeOutput consumer, MKRecipeProvider recipes, String id, FeatureItem tier1, FeatureItem tier2) { + CoreRecipes.carpenter(consumer, recipes, 200, SizedFluidIngredient.of(Fluids.WATER, 1000), Ingredient.EMPTY, tier2, 1, recipe -> { + recipe.pattern("WXW"); + recipe.pattern("WTW"); + recipe.pattern("WWW"); + recipe.define('W', CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.WOVEN_SILK).getItem()); + recipe.define('X', Items.DIAMOND); + recipe.define('T', tier1); + }); + } + + static void crate(RecipeOutput consumer, ItemCrated crated, Ingredient ingredient) { + ItemStack contained = crated.getContained(); + ResourceLocation name = ModUtil.getRegistryName(contained.getItem()); + + new CarpenterRecipeBuilder() + .setPackagingTime(Constants.CARPENTER_CRATING_CYCLES) + .setLiquid(new FluidStack(Fluids.WATER, Constants.CARPENTER_CRATING_LIQUID_QUANTITY)) + .setBox(Ingredient.of(CrateItems.CRATE)) + .recipe(ShapedRecipeBuilder.shaped(RecipeCategory.MISC, crated, 1) + .pattern("###") + .pattern("###") + .pattern("###") + .define('#', ingredient)) + .build(consumer, CoreRecipes.id("carpenter", "crates", "pack", name.getNamespace(), name.getPath())); + new CarpenterRecipeBuilder() + .setPackagingTime(Constants.CARPENTER_UNCRATING_CYCLES) + .setBox(Ingredient.EMPTY) + .recipe(ShapelessRecipeBuilder.shapeless(RecipeCategory.MISC, contained.getItem(), 9).requires(crated)) + .build(consumer, CoreRecipes.id("carpenter", "crates", "unpack", name.getNamespace(), name.getPath())); + } +} diff --git a/src/main/java/forestry/core/data/recipe/package-info.java b/src/main/java/forestry/core/data/recipe/package-info.java index 9fb719c6d2..8a75192b33 100644 --- a/src/main/java/forestry/core/data/recipe/package-info.java +++ b/src/main/java/forestry/core/data/recipe/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.data.recipe; diff --git a/src/main/java/forestry/core/entities/ParticleClimate.java b/src/main/java/forestry/core/entities/ParticleClimate.java deleted file mode 100644 index 66b1a0c4ea..0000000000 --- a/src/main/java/forestry/core/entities/ParticleClimate.java +++ /dev/null @@ -1,27 +0,0 @@ -//package forestry.core.entities; -// -//import net.minecraft.client.particle.RedstoneParticle; -//import net.minecraft.world.World; -// -//import forestry.core.utils.ColourUtil; -// TODO particles -//public class ParticleClimate extends RedstoneParticle { -// -// public ParticleClimate(World world, double x, double y, double z) { -// this(world, x, y, z, 0x37485a); -// } -// -// //TODO redstone constructor private but has factory method, and I can't get the AT to work -// public ParticleClimate(World worldIn, double x, double y, double z, int color) { -// super(worldIn, x, y, z, 0.0F, 0.0F, 0.0F); -// particleRed = ColourUtil.getRedAsFloat(color); -// particleGreen = ColourUtil.getGreenAsFloat(color); -// particleBlue = ColourUtil.getBlueAsFloat(color); -// } -// -// //TODO - use particle factory here. -// public static ParticleClimate create(World worldIn, double x, double y, double z, int color) { -//// return RedstoneParticle.Factory. -// return null; -// } -//} diff --git a/src/main/java/forestry/core/entities/ParticleIgnition.java b/src/main/java/forestry/core/entities/ParticleIgnition.java index 95ba7f7cd9..c84ea41efa 100755 --- a/src/main/java/forestry/core/entities/ParticleIgnition.java +++ b/src/main/java/forestry/core/entities/ParticleIgnition.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.entities; import com.mojang.blaze3d.vertex.VertexConsumer; @@ -16,8 +6,8 @@ import net.minecraft.client.particle.Particle; import net.minecraft.client.particle.ParticleRenderType; import net.minecraft.core.particles.ParticleTypes; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; //TODO particles @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/forestry/core/entities/ParticleSmoke.java b/src/main/java/forestry/core/entities/ParticleSmoke.java index db6b7e7eb1..bb97dd4b16 100755 --- a/src/main/java/forestry/core/entities/ParticleSmoke.java +++ b/src/main/java/forestry/core/entities/ParticleSmoke.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.entities; import com.mojang.blaze3d.vertex.VertexConsumer; @@ -16,8 +6,8 @@ import net.minecraft.client.particle.Particle; import net.minecraft.client.particle.ParticleRenderType; import net.minecraft.core.particles.ParticleTypes; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class ParticleSmoke extends Particle { diff --git a/src/main/java/forestry/core/entities/package-info.java b/src/main/java/forestry/core/entities/package-info.java index bad07d23f2..fe483ed233 100644 --- a/src/main/java/forestry/core/entities/package-info.java +++ b/src/main/java/forestry/core/entities/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.entities; diff --git a/src/main/java/forestry/core/errors/package-info.java b/src/main/java/forestry/core/errors/package-info.java index 29de144470..ce302f7cf2 100644 --- a/src/main/java/forestry/core/errors/package-info.java +++ b/src/main/java/forestry/core/errors/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.errors; diff --git a/src/main/java/forestry/core/features/CoreBlocks.java b/src/main/java/forestry/core/features/CoreBlocks.java index 244b2aa7b0..4b9dff94ea 100644 --- a/src/main/java/forestry/core/features/CoreBlocks.java +++ b/src/main/java/forestry/core/features/CoreBlocks.java @@ -21,18 +21,14 @@ public class CoreBlocks { public static final FeatureBlockGroup BASE = REGISTRY.blockGroup(BlockCore::new, BlockTypeCoreTesr.values()).item(ItemBlockTesr::new).create(); public static final FeatureBlock> BOG_EARTH = REGISTRY.block(BlockBogEarth::new, ItemBlockForestry::new, "bog_earth"); - public static final FeatureBlock> PEAT = REGISTRY.block(() -> new Block(Block.Properties.of() - .strength(0.5f) - .sound(SoundType.GRAVEL)), "peat"); + public static final FeatureBlock> PEAT = REGISTRY.block(() -> new Block(Block.Properties.of().strength(0.5f).sound(SoundType.GRAVEL)), "peat"); public static final FeatureBlock> HUMUS = REGISTRY.block(BlockHumus::new, ItemBlockForestry::new, "humus"); - public static final FeatureBlockGroup RESOURCE_STORAGE = REGISTRY.blockGroup(BlockResourceStorage::new, EnumResourceType.values()).item(ItemBlockForestry::new).identifier("resource_storage").create(); - public static final FeatureBlock APATITE_ORE = REGISTRY.block(() -> new DropExperienceBlock(BlockBehaviour.Properties.copy(Blocks.COAL_ORE), UniformInt.of(0, 4)), ItemBlockForestry::new, "apatite_ore"); - public static final FeatureBlock DEEPSLATE_APATITE_ORE = REGISTRY.block(() -> new DropExperienceBlock(BlockBehaviour.Properties.copy(APATITE_ORE.block()).mapColor(MapColor.DEEPSLATE).strength(4.5f, 3.0f).sound(SoundType.DEEPSLATE), UniformInt.of(0, 4)), ItemBlockForestry::new, "deepslate_apatite_ore"); - public static final FeatureBlock TIN_ORE = REGISTRY.block(() -> new Block(BlockBehaviour.Properties.copy(Blocks.COPPER_ORE)), ItemBlockForestry::new, "tin_ore"); - public static final FeatureBlock DEEPSLATE_TIN_ORE = REGISTRY.block(() -> new Block(BlockBehaviour.Properties.copy(TIN_ORE.block()).mapColor(MapColor.DEEPSLATE).strength(4.5f, 3.0f).sound(SoundType.DEEPSLATE)), ItemBlockForestry::new, "deepslate_tin_ore"); - public static final FeatureBlock RAW_TIN_BLOCK = REGISTRY.block(() -> new Block(BlockBehaviour.Properties.copy(Blocks.RAW_COPPER_BLOCK)), ItemBlockForestry::new, "raw_tin_block"); + public static final FeatureBlockGroup RESOURCE_STORAGE = REGISTRY.blockGroup(type -> new BlockResourceStorage(), EnumResourceType.values()).item(ItemBlockForestry::new).identifier("resource_storage").create(); + public static final FeatureBlock APATITE_ORE = REGISTRY.block(() -> new DropExperienceBlock(UniformInt.of(0, 4), BlockBehaviour.Properties.ofFullCopy(Blocks.COAL_ORE)), ItemBlockForestry::new, "apatite_ore"); + public static final FeatureBlock DEEPSLATE_APATITE_ORE = REGISTRY.block(() -> new DropExperienceBlock(UniformInt.of(0, 4), BlockBehaviour.Properties.ofFullCopy(APATITE_ORE.block()).mapColor(MapColor.DEEPSLATE).strength(4.5f, 3.0f).sound(SoundType.DEEPSLATE)), ItemBlockForestry::new, "deepslate_apatite_ore"); + public static final FeatureBlock TIN_ORE = REGISTRY.block(() -> new Block(BlockBehaviour.Properties.ofFullCopy(Blocks.COPPER_ORE)), ItemBlockForestry::new, "tin_ore"); + public static final FeatureBlock DEEPSLATE_TIN_ORE = REGISTRY.block(() -> new Block(BlockBehaviour.Properties.ofFullCopy(TIN_ORE.block()).mapColor(MapColor.DEEPSLATE).strength(4.5f, 3.0f).sound(SoundType.DEEPSLATE)), ItemBlockForestry::new, "deepslate_tin_ore"); + public static final FeatureBlock RAW_TIN_BLOCK = REGISTRY.block(() -> new Block(BlockBehaviour.Properties.ofFullCopy(Blocks.RAW_COPPER_BLOCK)), ItemBlockForestry::new, "raw_tin_block"); - public static final FeatureBlockGroup, NaturalistChestBlockType> NATURALIST_CHEST = REGISTRY.blockGroup(type -> { - return new BlockTesr<>(type, Block.Properties.of().sound(SoundType.WOOD)); - }, NaturalistChestBlockType.values()).item(ItemBlockTesr::new).create(); + public static final FeatureBlockGroup, NaturalistChestBlockType> NATURALIST_CHEST = REGISTRY.blockGroup(BlockTesr::new, NaturalistChestBlockType.values()).item(ItemBlockTesr::new).create(); } diff --git a/src/main/java/forestry/core/commands/CommandArgumentTypes.java b/src/main/java/forestry/core/features/CoreCommandArgumentTypes.java similarity index 87% rename from src/main/java/forestry/core/commands/CommandArgumentTypes.java rename to src/main/java/forestry/core/features/CoreCommandArgumentTypes.java index 74d3c0d6c0..60771bd3e8 100644 --- a/src/main/java/forestry/core/commands/CommandArgumentTypes.java +++ b/src/main/java/forestry/core/features/CoreCommandArgumentTypes.java @@ -1,15 +1,16 @@ -package forestry.core.commands; +package forestry.core.features; import forestry.api.modules.ForestryModuleIds; +import forestry.core.commands.*; import forestry.modules.features.FeatureProvider; import forestry.modules.features.ModFeatureRegistry; import net.minecraft.commands.synchronization.ArgumentTypeInfo; import net.minecraft.commands.synchronization.ArgumentTypeInfos; import net.minecraft.core.registries.Registries; -import net.minecraftforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider -public class CommandArgumentTypes { +public class CoreCommandArgumentTypes { static { DeferredRegister> registry = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(Registries.COMMAND_ARGUMENT_TYPE); diff --git a/src/main/java/forestry/core/damage/CoreDamageTypes.java b/src/main/java/forestry/core/features/CoreDamageTypes.java similarity index 97% rename from src/main/java/forestry/core/damage/CoreDamageTypes.java rename to src/main/java/forestry/core/features/CoreDamageTypes.java index fd12f8e1ed..fa2d0eebcf 100644 --- a/src/main/java/forestry/core/damage/CoreDamageTypes.java +++ b/src/main/java/forestry/core/features/CoreDamageTypes.java @@ -1,4 +1,4 @@ -package forestry.core.damage; +package forestry.core.features; import forestry.api.ForestryConstants; import net.minecraft.core.registries.Registries; diff --git a/src/main/java/forestry/core/features/CoreDataComponents.java b/src/main/java/forestry/core/features/CoreDataComponents.java new file mode 100644 index 0000000000..809fcc8203 --- /dev/null +++ b/src/main/java/forestry/core/features/CoreDataComponents.java @@ -0,0 +1,32 @@ +package forestry.core.features; + +import com.mojang.serialization.Codec; +import forestry.api.IForestryApi; +import forestry.api.genetics.IIndividual; +import forestry.api.mail.ILetter; +import forestry.api.modules.ForestryModuleIds; +import forestry.core.circuits.CircuitBoard; +import forestry.modules.features.FeatureProvider; +import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.registries.Registries; +import net.neoforged.neoforge.fluids.SimpleFluidContent; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; + +import java.util.function.UnaryOperator; + +@FeatureProvider +public class CoreDataComponents { + private static final DeferredRegister> REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(Registries.DATA_COMPONENT_TYPE); + + public static final DeferredHolder, DataComponentType> CIRCUIT_BOARD = type("circuit_board", builder -> builder.persistent(CircuitBoard.CODEC)); + public static final DeferredHolder, DataComponentType> FLUID_CONTENTS = type("fluid_contents", builder -> builder.persistent(SimpleFluidContent.CODEC)); + public static final DeferredHolder, DataComponentType> ANALYZER_CHARGES = type("analyzer_charges", builder -> builder.persistent(Codec.INT)); + public static final DeferredHolder, DataComponentType> LETTER = type("letter", builder -> builder.persistent(IDK)); + public static final DeferredHolder, DataComponentType> INDIVIDUAL = type("individual", builder -> builder.persistent(IIndividual.CODEC)); + + private static DeferredHolder, DataComponentType> type(String name, UnaryOperator> configure) { + return REGISTRY.register(name, () -> configure.apply(DataComponentType.builder()).build()); + } +} diff --git a/src/main/java/forestry/core/features/CoreFeatures.java b/src/main/java/forestry/core/features/CoreFeatures.java index 95066cbf15..d9a3105e6b 100644 --- a/src/main/java/forestry/core/features/CoreFeatures.java +++ b/src/main/java/forestry/core/features/CoreFeatures.java @@ -1,6 +1,6 @@ package forestry.core.features; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import forestry.api.ForestryConstants; import forestry.api.modules.ForestryModuleIds; import forestry.core.worldgen.ForestryBiomeModifier; @@ -10,14 +10,14 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraftforge.common.world.BiomeModifier; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.common.world.BiomeModifier; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; @FeatureProvider public class CoreFeatures { - private static final DeferredRegister> BIOME_MODIFIERS = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS); + private static final DeferredRegister> BIOME_MODIFIERS = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(NeoForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS); public static final ResourceKey> ORE_APATITE = ResourceKey.create(Registries.CONFIGURED_FEATURE, ForestryConstants.forestry("ore_apatite")); public static final ResourceKey> ORE_TIN = ResourceKey.create(Registries.CONFIGURED_FEATURE, ForestryConstants.forestry("ore_tin")); @@ -26,5 +26,5 @@ public class CoreFeatures { public static final ResourceKey PLACED_TIN = ResourceKey.create(Registries.PLACED_FEATURE, ForestryConstants.forestry("ore_tin")); // Responsible for hives + trees - private static final RegistryObject> FORESTRY = BIOME_MODIFIERS.register("forestry", () -> ForestryBiomeModifier.CODEC); + private static final DeferredHolder, MapCodec> FORESTRY = BIOME_MODIFIERS.register("forestry", () -> ForestryBiomeModifier.CODEC); } diff --git a/src/main/java/forestry/core/features/CoreItems.java b/src/main/java/forestry/core/features/CoreItems.java index c4234aa21e..1b2846af01 100644 --- a/src/main/java/forestry/core/features/CoreItems.java +++ b/src/main/java/forestry/core/features/CoreItems.java @@ -1,7 +1,6 @@ package forestry.core.features; import forestry.api.modules.ForestryModuleIds; -import forestry.apiculture.items.ItemBeesWax; import forestry.apiculture.items.ItemRefractoryWax; import forestry.core.circuits.EnumCircuitBoardType; import forestry.core.circuits.ItemCircuitBoard; @@ -11,6 +10,7 @@ import forestry.core.items.definitions.EnumElectronTube; import forestry.core.items.definitions.ToolTier; import forestry.modules.features.*; +import net.minecraft.world.item.HoneycombItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.ShovelItem; @@ -34,7 +34,7 @@ public class CoreItems { public static final FeatureItem RESEARCH_NOTE = REGISTRY.item(ItemResearchNote::new, "research_note"); /* Alyzer */ - public static final FeatureItem PORTABLE_ALYZER = REGISTRY.item(ItemAlyzer::new, "portable_alyzer"); + public static final FeatureItem PORTABLE_ALYZER = REGISTRY.item(ItemPortableAnalyzer::new, "portable_alyzer"); /* Ingots */ public static final FeatureItem INGOT_TIN = REGISTRY.item(ItemForestry::new, "ingot_tin"); @@ -87,6 +87,6 @@ public class CoreItems { /* Misc */ public static final FeatureItemGroup CRAFTING_MATERIALS = REGISTRY.itemGroup(ItemCraftingMaterial::new, EnumCraftingMaterial.values()).create(); public static final FeatureItemGroup FRUITS = REGISTRY.itemGroup(ItemFruit::new, "fruit", ItemFruit.EnumFruit.values()); - public static final FeatureItem BEESWAX = REGISTRY.item(ItemBeesWax::new, "beeswax"); + public static final FeatureItem BEESWAX = REGISTRY.item(() -> new HoneycombItem(new Item.Properties()), "beeswax"); public static final FeatureItem REFRACTORY_WAX = REGISTRY.item(ItemRefractoryWax::new, "refractory_wax"); } diff --git a/src/main/java/forestry/core/features/CoreLootModifiers.java b/src/main/java/forestry/core/features/CoreLootModifiers.java new file mode 100644 index 0000000000..fc3e1e7a1b --- /dev/null +++ b/src/main/java/forestry/core/features/CoreLootModifiers.java @@ -0,0 +1,20 @@ +package forestry.core.features; + +import com.mojang.serialization.MapCodec; +import forestry.api.modules.ForestryModuleIds; +import forestry.arboriculture.loot.GrafterLootModifier; +import forestry.core.loot.ConditionLootModifier; +import forestry.modules.features.FeatureProvider; +import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.core.Holder; +import net.neoforged.neoforge.common.loot.IGlobalLootModifier; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; + +@FeatureProvider +public class CoreLootModifiers { + private static final DeferredRegister> REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(NeoForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS); + + public static final Holder> CONDITION_MODIFIER = REGISTRY.register("condition_modifier", () -> ConditionLootModifier.CODEC); + public static final Holder> GRAFTER_MODIFIER = REGISTRY.register("grafter_modifier", () -> GrafterLootModifier.CODEC); +} diff --git a/src/main/java/forestry/core/features/CoreMenuTypes.java b/src/main/java/forestry/core/features/CoreMenuTypes.java index abcd4f0ed5..be21378bbc 100644 --- a/src/main/java/forestry/core/features/CoreMenuTypes.java +++ b/src/main/java/forestry/core/features/CoreMenuTypes.java @@ -1,11 +1,11 @@ package forestry.core.features; import forestry.api.modules.ForestryModuleIds; -import forestry.core.circuits.ContainerSolderingIron; -import forestry.core.gui.ContainerAlyzer; -import forestry.core.gui.ContainerAnalyzer; -import forestry.core.gui.ContainerEscritoire; -import forestry.core.gui.ContainerNaturalistInventory; +import forestry.core.circuits.SolderingIronMenu; +import forestry.core.gui.PortableAnalyzerMenu; +import forestry.core.gui.AnalyzerMenu; +import forestry.core.gui.EscritoireMenu; +import forestry.core.gui.NaturalistInventoryMenu; import forestry.modules.features.FeatureMenuType; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; @@ -15,9 +15,9 @@ public class CoreMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE); - public static final FeatureMenuType ALYZER = REGISTRY.menuType(ContainerAlyzer::fromNetwork, "alyzer"); - public static final FeatureMenuType ANALYZER = REGISTRY.menuType(ContainerAnalyzer::fromNetwork, "analyzer"); - public static final FeatureMenuType ESCRITOIRE = REGISTRY.menuType(ContainerEscritoire::fromNetwork, "escritoire"); - public static final FeatureMenuType NATURALIST_INVENTORY = REGISTRY.menuType(ContainerNaturalistInventory::fromNetwork, "naturalist_inventory"); - public static final FeatureMenuType SOLDERING_IRON = REGISTRY.menuType(ContainerSolderingIron::fromNetwork, "soldering_iron"); + public static final FeatureMenuType ALYZER = REGISTRY.menuType(PortableAnalyzerMenu::fromNetwork, "alyzer"); + public static final FeatureMenuType ANALYZER = REGISTRY.menuType(AnalyzerMenu::fromNetwork, "analyzer"); + public static final FeatureMenuType ESCRITOIRE = REGISTRY.menuType(EscritoireMenu::fromNetwork, "escritoire"); + public static final FeatureMenuType NATURALIST_INVENTORY = REGISTRY.menuType(NaturalistInventoryMenu::fromNetwork, "naturalist_inventory"); + public static final FeatureMenuType SOLDERING_IRON = REGISTRY.menuType(SolderingIronMenu::fromNetwork, "soldering_iron"); } diff --git a/src/main/java/forestry/core/features/CorePaintings.java b/src/main/java/forestry/core/features/CorePaintings.java index f1ee12c969..4ea74a84e3 100644 --- a/src/main/java/forestry/core/features/CorePaintings.java +++ b/src/main/java/forestry/core/features/CorePaintings.java @@ -2,26 +2,24 @@ import forestry.api.modules.ForestryModuleIds; import forestry.modules.features.FeatureProvider; -import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.world.entity.decoration.PaintingVariant; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class CorePaintings { - private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE); - private static final DeferredRegister PAINTINGS = REGISTRY.getRegistry(Registries.PAINTING_VARIANT); + private static final DeferredRegister PAINTINGS = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(Registries.PAINTING_VARIANT); - public static final RegistryObject MOUSETREE = PAINTINGS.register("mousetree", () -> new PaintingVariant(48, 48)); - public static final RegistryObject WASPHOL = PAINTINGS.register("wasphol", () -> new PaintingVariant(32, 32)); - public static final RegistryObject CAGE = PAINTINGS.register("cage", () -> new PaintingVariant(32, 32)); - public static final RegistryObject LEWIS = PAINTINGS.register("lewis", () -> new PaintingVariant(32, 48)); - public static final RegistryObject SITEBEE = PAINTINGS.register("site_bee", () -> new PaintingVariant(32, 32)); - public static final RegistryObject ALEXBLOOME = PAINTINGS.register("alex_bloome", () -> new PaintingVariant(64, 32)); - public static final RegistryObject SUSPICIOUS_LOOKING_TREE = PAINTINGS.register("suspicious_looking_tree", () -> new PaintingVariant(32, 48)); - public static final RegistryObject WISDOM = PAINTINGS.register("wisdom", () -> new PaintingVariant(32, 32)); - public static final RegistryObject MYSTICAL_TREE = PAINTINGS.register("mystical_tree", () -> new PaintingVariant(32, 32)); - public static final RegistryObject DEKU = PAINTINGS.register("deku", () -> new PaintingVariant(64, 32)); + public static final DeferredHolder MOUSETREE = PAINTINGS.register("mousetree", () -> new PaintingVariant(48, 48, CorePaintings.MOUSETREE.getId())); + public static final DeferredHolder WASPHOL = PAINTINGS.register("wasphol", () -> new PaintingVariant(32, 32, CorePaintings.WASPHOL.getId())); + public static final DeferredHolder CAGE = PAINTINGS.register("cage", () -> new PaintingVariant(32, 32, CorePaintings.CAGE.getId())); + public static final DeferredHolder LEWIS = PAINTINGS.register("lewis", () -> new PaintingVariant(32, 48, CorePaintings.LEWIS.getId())); + public static final DeferredHolder SITEBEE = PAINTINGS.register("site_bee", () -> new PaintingVariant(32, 32, CorePaintings.SITEBEE.getId())); + public static final DeferredHolder ALEXBLOOME = PAINTINGS.register("alex_bloome", () -> new PaintingVariant(64, 32, CorePaintings.ALEXBLOOME.getId())); + public static final DeferredHolder SUSPICIOUS_LOOKING_TREE = PAINTINGS.register("suspicious_looking_tree", () -> new PaintingVariant(32, 48, CorePaintings.SUSPICIOUS_LOOKING_TREE.getId())); + public static final DeferredHolder WISDOM = PAINTINGS.register("wisdom", () -> new PaintingVariant(32, 32, CorePaintings.WISDOM.getId())); + public static final DeferredHolder MYSTICAL_TREE = PAINTINGS.register("mystical_tree", () -> new PaintingVariant(32, 32, CorePaintings.MYSTICAL_TREE.getId())); + public static final DeferredHolder DEKU = PAINTINGS.register("deku", () -> new PaintingVariant(64, 32, CorePaintings.DEKU.getId())); } diff --git a/src/main/java/forestry/core/particles/CoreParticles.java b/src/main/java/forestry/core/features/CoreParticles.java similarity index 62% rename from src/main/java/forestry/core/particles/CoreParticles.java rename to src/main/java/forestry/core/features/CoreParticles.java index d73614e908..eee5dd7678 100644 --- a/src/main/java/forestry/core/particles/CoreParticles.java +++ b/src/main/java/forestry/core/features/CoreParticles.java @@ -1,4 +1,4 @@ -package forestry.core.particles; +package forestry.core.features; import forestry.api.modules.ForestryModuleIds; import forestry.modules.features.FeatureProvider; @@ -6,12 +6,12 @@ import net.minecraft.core.particles.ParticleType; import net.minecraft.core.particles.SimpleParticleType; import net.minecraft.core.registries.Registries; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class CoreParticles { private static final DeferredRegister> PARTICLE_TYPES = ModFeatureRegistry.get(ForestryModuleIds.APICULTURE).getRegistry(Registries.PARTICLE_TYPE); - public static final RegistryObject REFRACTORY_WAX = PARTICLE_TYPES.register("refractory_wax", () -> new SimpleParticleType(true)); + public static final DeferredHolder, SimpleParticleType> REFRACTORY_WAX = PARTICLE_TYPES.register("refractory_wax", () -> new SimpleParticleType(true)); } diff --git a/src/main/java/forestry/core/features/CoreSpeciesTypes.java b/src/main/java/forestry/core/features/CoreSpeciesTypes.java new file mode 100644 index 0000000000..f6deb0bc54 --- /dev/null +++ b/src/main/java/forestry/core/features/CoreSpeciesTypes.java @@ -0,0 +1,137 @@ +package forestry.core.features; + +import forestry.api.ForestryRegistries; +import forestry.api.apiculture.ForestryBeeSpecies; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBeeSpeciesType; +import forestry.api.arboriculture.ForestryTreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpeciesType; +import forestry.api.arboriculture.genetics.TreeLifeStage; +import forestry.api.genetics.ISpeciesType; +import forestry.api.genetics.alleles.BeeChromosomes; +import forestry.api.genetics.alleles.ButterflyChromosomes; +import forestry.api.genetics.alleles.ForestryAlleles; +import forestry.api.genetics.alleles.TreeChromosomes; +import forestry.api.lepidopterology.ForestryButterflySpecies; +import forestry.api.lepidopterology.genetics.ButterflyLifeStage; +import forestry.api.lepidopterology.genetics.IButterflySpeciesType; +import forestry.api.modules.ForestryModuleIds; +import forestry.apiculture.genetics.BeeSpeciesType; +import forestry.apiimpl.plugin.SpeciesTypeBuilder; +import forestry.arboriculture.genetics.TreeSpeciesType; +import forestry.lepidopterology.genetics.ButterflySpeciesType; +import forestry.modules.features.FeatureProvider; +import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.world.item.Items; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; + +@FeatureProvider +public class CoreSpeciesTypes { + private static final DeferredRegister> REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE).getRegistry(ForestryRegistries.Keys.SPECIES_TYPE); + + public static final DeferredHolder, IBeeSpeciesType> BEE = REGISTRY.register("bee", CoreSpeciesTypes::bee); + public static final DeferredHolder, ITreeSpeciesType> TREE = REGISTRY.register("tree", CoreSpeciesTypes::tree); + public static final DeferredHolder, IButterflySpeciesType> BUTTERFLY = REGISTRY.register("butterfly", CoreSpeciesTypes::butterfly); + + private static BeeSpeciesType bee() { + SpeciesTypeBuilder builder = new SpeciesTypeBuilder<>(BeeSpeciesType::new); + + builder.setKaryotype(karyotype -> { + karyotype.setSpecies(BeeChromosomes.SPECIES, ForestryBeeSpecies.FOREST); + karyotype.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWEST) + .addAlleles(ForestryAlleles.DEFAULT_SPEEDS); + karyotype.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORTER) + .addAlleles(ForestryAlleles.DEFAULT_LIFESPANS); + karyotype.set(BeeChromosomes.FERTILITY, ForestryAlleles.FERTILITY_2) + .addAlleles(ForestryAlleles.DEFAULT_BEE_FERTILITIES); + karyotype.set(BeeChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) + .addAlleles(ForestryAlleles.DEFAULT_TEMPERATURE_TOLERANCES) + .setWeaklyInherited(true); + karyotype.set(BeeChromosomes.HUMIDITY_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) + .addAlleles(ForestryAlleles.DEFAULT_HUMIDITY_TOLERANCES) + .setWeaklyInherited(true); + karyotype.set(BeeChromosomes.ACTIVITY, ForestryAlleles.ACTIVITY_DIURNAL) + .setWeaklyInherited(true); + karyotype.set(BeeChromosomes.CAVE_DWELLING, false) + .setWeaklyInherited(true); + karyotype.set(BeeChromosomes.TOLERATES_RAIN, false) + .setWeaklyInherited(true); + karyotype.set(BeeChromosomes.FLOWER_TYPE, ForestryAlleles.FLOWER_TYPE_VANILLA); + karyotype.set(BeeChromosomes.TERRITORY, ForestryAlleles.TERRITORY_AVERAGE) + .addAlleles(ForestryAlleles.DEFAULT_TERRITORIES); + karyotype.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_NONE); + karyotype.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOWEST) + .addAlleles(ForestryAlleles.DEFAULT_POLLINATIONS); + }); + + builder.addStages(BeeLifeStage.DRONE, BeeLifeStage.PRINCESS, BeeLifeStage.QUEEN, BeeLifeStage.LARVAE); + builder.setDefaultStage(BeeLifeStage.DRONE); + + return builder.build(); + } + + private static TreeSpeciesType tree() { + SpeciesTypeBuilder builder = new SpeciesTypeBuilder<>(TreeSpeciesType::new); + + builder.setKaryotype(karyotype -> { + karyotype.setSpecies(TreeChromosomes.SPECIES, ForestryTreeSpecies.OAK); + karyotype.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_SMALL) + .addAlleles(ForestryAlleles.DEFAULT_HEIGHTS); + karyotype.set(TreeChromosomes.SAPLINGS, ForestryAlleles.SAPLINGS_LOWER) + .addAlleles(ForestryAlleles.DEFAULT_SAPLINGS); + karyotype.set(TreeChromosomes.FRUIT, ForestryAlleles.FRUIT_NONE); + karyotype.set(TreeChromosomes.YIELD, ForestryAlleles.YIELD_LOWEST) + .addAlleles(ForestryAlleles.DEFAULT_YIELDS); + karyotype.set(TreeChromosomes.SAPPINESS, ForestryAlleles.SAPPINESS_LOWEST) + .addAlleles(ForestryAlleles.DEFAULT_SAPPINESSES); + karyotype.set(TreeChromosomes.EFFECT, ForestryAlleles.TREE_EFFECT_NONE); + karyotype.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_AVERAGE) + .addAlleles(ForestryAlleles.DEFAULT_MATURATIONS); + karyotype.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_1) + .addAlleles(ForestryAlleles.DEFAULT_GIRTHS); + karyotype.set(TreeChromosomes.FIREPROOF, false); + }); + builder.addStages(TreeLifeStage.SAPLING, TreeLifeStage.POLLEN); + builder.setDefaultStage(TreeLifeStage.SAPLING); + + return builder.build(); + } + + private static ButterflySpeciesType butterfly() { + SpeciesTypeBuilder builder = new SpeciesTypeBuilder<>(ButterflySpeciesType::new); + + builder.setKaryotype(karyotype -> { + karyotype.setSpecies(ButterflyChromosomes.SPECIES, ForestryButterflySpecies.MONARCH); + karyotype.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALL) + .addAlleles(ForestryAlleles.DEFAULT_SIZES); + karyotype.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWEST) + .addAlleles(ForestryAlleles.DEFAULT_SPEEDS); + karyotype.set(ButterflyChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORTER) + .addAlleles(ForestryAlleles.DEFAULT_LIFESPANS); + karyotype.set(ButterflyChromosomes.METABOLISM, ForestryAlleles.METABOLISM_SLOWER) + .addAlleles(ForestryAlleles.DEFAULT_METABOLISMS); + karyotype.set(ButterflyChromosomes.FERTILITY, ForestryAlleles.FERTILITY_3) + .addAlleles(ForestryAlleles.DEFAULT_BUTTERFLY_FERTILITIES); + karyotype.set(ButterflyChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) + .addAlleles(ForestryAlleles.DEFAULT_TEMPERATURE_TOLERANCES) + .setWeaklyInherited(true); + karyotype.set(ButterflyChromosomes.HUMIDITY_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) + .addAlleles(ForestryAlleles.DEFAULT_HUMIDITY_TOLERANCES) + .setWeaklyInherited(true); + karyotype.set(ButterflyChromosomes.NEVER_SLEEPS, false) + .setWeaklyInherited(true); + karyotype.set(ButterflyChromosomes.TOLERATES_RAIN, false) + .setWeaklyInherited(true); + karyotype.set(ButterflyChromosomes.FIREPROOF, false); + karyotype.set(ButterflyChromosomes.FLOWER_TYPE, ForestryAlleles.FLOWER_TYPE_VANILLA); + karyotype.set(ButterflyChromosomes.EFFECT, ForestryAlleles.BUTTERFLY_EFFECT_NONE); + karyotype.set(ButterflyChromosomes.COCOON, ForestryAlleles.COCOON_DEFAULT); + }); + builder.addStages(ButterflyLifeStage.BUTTERFLY, ButterflyLifeStage.SERUM, ButterflyLifeStage.CATERPILLAR, ButterflyLifeStage.COCOON); + builder.setDefaultStage(ButterflyLifeStage.BUTTERFLY); + builder.addResearchMaterials(map -> map.put(Items.GLASS_BOTTLE, 0.9f)); + + return builder.build(); + } +} diff --git a/src/main/java/forestry/core/features/CoreTiles.java b/src/main/java/forestry/core/features/CoreTiles.java index b453daedd1..1ecd3b4266 100644 --- a/src/main/java/forestry/core/features/CoreTiles.java +++ b/src/main/java/forestry/core/features/CoreTiles.java @@ -18,5 +18,4 @@ public class CoreTiles { public static final FeatureTileType APIARIST_CHEST = REGISTRY.tile(TileApiaristChest::new, "apiarist_chest", () -> CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.APIARIST_CHEST).collect()); public static final FeatureTileType ARBORIST_CHEST = REGISTRY.tile(TileArboristChest::new, "arborist_chest", () -> CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.ARBORIST_CHEST).collect()); public static final FeatureTileType LEPIDOPTERIST_CHEST = REGISTRY.tile(TileLepidopteristChest::new, "lepidopterist_chest", () -> CoreBlocks.NATURALIST_CHEST.get(NaturalistChestBlockType.LEPIDOPTERIST_CHEST).collect()); - } diff --git a/src/main/java/forestry/core/features/FluidsItems.java b/src/main/java/forestry/core/features/FluidsItems.java index 0e86fc17c5..91499d560d 100644 --- a/src/main/java/forestry/core/features/FluidsItems.java +++ b/src/main/java/forestry/core/features/FluidsItems.java @@ -10,7 +10,7 @@ @FeatureProvider public class FluidsItems { - private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.FLUIDS); + private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE); public static final FeatureItemGroup CONTAINERS = REGISTRY.itemGroup(ItemFluidContainerForestry::new, EnumContainerType.values()).create(); } diff --git a/src/main/java/forestry/core/tab/ForestryCreativeTabs.java b/src/main/java/forestry/core/features/ForestryCreativeTabs.java similarity index 95% rename from src/main/java/forestry/core/tab/ForestryCreativeTabs.java rename to src/main/java/forestry/core/features/ForestryCreativeTabs.java index 6229b6f9f5..e524afdedd 100644 --- a/src/main/java/forestry/core/tab/ForestryCreativeTabs.java +++ b/src/main/java/forestry/core/features/ForestryCreativeTabs.java @@ -1,8 +1,8 @@ -package forestry.core.tab; +package forestry.core.features; import forestry.api.ForestryConstants; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.arboriculture.ForestryTreeSpecies; import forestry.api.arboriculture.IWoodAccess; import forestry.api.arboriculture.IWoodType; @@ -23,9 +23,6 @@ import forestry.arboriculture.features.ArboricultureItems; import forestry.arboriculture.features.CharcoalBlocks; import forestry.core.blocks.BlockTypeCoreTesr; -import forestry.core.features.CoreBlocks; -import forestry.core.features.CoreItems; -import forestry.core.features.FluidsItems; import forestry.core.fluids.ForestryFluids; import forestry.core.items.definitions.EnumContainerType; import forestry.core.items.definitions.FluidHandlerItemForestry; @@ -55,11 +52,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; @FeatureProvider public class ForestryCreativeTabs { @@ -213,10 +209,8 @@ private static void addApicultureItems(CreativeModeTab.ItemDisplayParameters par items.accept(ApicultureItems.FRAME_UNTREATED); items.accept(ApicultureItems.FRAME_IMPREGNATED); items.accept(ApicultureItems.FRAME_PROVEN); - ItemStack creativeFrameMaxMutation = ApicultureItems.FRAME_CREATIVE.stack(); - creativeFrameMaxMutation.addTagElement(ItemCreativeHiveFrame.NBT_FORCE_MUTATIONS, ByteTag.valueOf((byte) 1)); - items.accept(ApicultureItems.FRAME_CREATIVE); - items.accept(creativeFrameMaxMutation); + items.accept(ApicultureItems.FRAME_CREATIVE.get(ItemCreativeHiveFrame.Variant.FRAME_CREATIVE)); + items.accept(ApicultureItems.FRAME_CREATIVE.get(ItemCreativeHiveFrame.Variant.FRAME_CREATIVE_FORCE_MUTATIONS)); // Food items.accept(ApicultureItems.HONEYED_SLICE); diff --git a/src/main/java/forestry/core/features/package-info.java b/src/main/java/forestry/core/features/package-info.java index d8aba8fc5d..097a2d73da 100644 --- a/src/main/java/forestry/core/features/package-info.java +++ b/src/main/java/forestry/core/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.features; diff --git a/src/main/java/forestry/core/fluids/BlockForestryFluid.java b/src/main/java/forestry/core/fluids/BlockForestryFluid.java index add854c49b..6a17726712 100644 --- a/src/main/java/forestry/core/fluids/BlockForestryFluid.java +++ b/src/main/java/forestry/core/fluids/BlockForestryFluid.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import forestry.modules.features.FeatureFluid; @@ -30,18 +20,16 @@ public class BlockForestryFluid extends LiquidBlock { private final boolean spreadsFire; private final int flammability; - private final int color; private final boolean freezing; private final boolean burning; private final float explosionPower; private final boolean explodes; public BlockForestryFluid(FeatureFluid feature) { - super(feature::fluid, Block.Properties.of().liquid().noCollission().noLootTable().replaceable()); + super(feature.fluid(), Block.Properties.of().liquid().noCollission().noLootTable().replaceable()); FluidProperties properties = feature.properties(); this.flammability = properties.flammability; this.spreadsFire = properties.spreadsFire; - this.color = properties.particleColor; this.freezing = properties.temperature < 270; this.burning = properties.temperature > 505; // Explosion size is determined by flammability, up to size 4. @@ -54,7 +42,7 @@ public void entityInside(BlockState pState, Level pLevel, BlockPos pPos, Entity if (this.freezing) { entity.setIsInPowderSnow(true); } else if (this.burning) { - entity.setSecondsOnFire(5); + entity.igniteForSeconds(5); entity.hurt(pLevel.damageSources().lava(), 1); } } diff --git a/src/main/java/forestry/core/fluids/ContainerFiller.java b/src/main/java/forestry/core/fluids/ContainerFiller.java index 3d83e6c399..315d31a188 100644 --- a/src/main/java/forestry/core/fluids/ContainerFiller.java +++ b/src/main/java/forestry/core/fluids/ContainerFiller.java @@ -4,8 +4,8 @@ import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.templates.FluidTank; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.templates.FluidTank; import javax.annotation.Nullable; @@ -35,8 +35,8 @@ public ContainerFiller(FluidTank fluidTank, int fillingTime, Container inventory public void updateServerSide() { ItemStack input = this.inventory.getItem(this.inputSlot); if (this.usedInput == null || !ItemStackUtil.isIdenticalItem(this.usedInput, input)) { - this.fillingProgress = 0; - this.usedInput = input; + this.fillingProgress = 0; + this.usedInput = input; } if (this.usedInput != null) { @@ -46,15 +46,15 @@ public void updateServerSide() { Fluid tankFluid = tankContents.getFluid(); FluidHelper.FillStatus canFill = FluidHelper.fillContainers(this.fluidTank, this.inventory, this.inputSlot, this.outputSlot, tankFluid, false); if (canFill == FluidHelper.FillStatus.SUCCESS) { - this.fillingProgress = 1; + this.fillingProgress = 1; } } else { - this.fillingProgress++; + this.fillingProgress++; if (this.fillingProgress >= this.fillingTime) { Fluid tankFluid = tankContents.getFluid(); FluidHelper.FillStatus filled = FluidHelper.fillContainers(this.fluidTank, this.inventory, this.inputSlot, this.outputSlot, tankFluid, true); if (filled == FluidHelper.FillStatus.SUCCESS) { - this.fillingProgress = 0; + this.fillingProgress = 0; } } } diff --git a/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java b/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java index e1be22e60b..1a1581e06b 100644 --- a/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java +++ b/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java @@ -1,7 +1,7 @@ package forestry.core.fluids; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nonnull; diff --git a/src/main/java/forestry/core/fluids/FakeTankManager.java b/src/main/java/forestry/core/fluids/FakeTankManager.java index 8615e8d9d1..0d094fb858 100644 --- a/src/main/java/forestry/core/fluids/FakeTankManager.java +++ b/src/main/java/forestry/core/fluids/FakeTankManager.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.templates.EmptyFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.templates.EmptyFluidHandler; import javax.annotation.Nullable; diff --git a/src/main/java/forestry/core/fluids/FilteredTank.java b/src/main/java/forestry/core/fluids/FilteredTank.java index 08f5e5d779..0ded30b60b 100644 --- a/src/main/java/forestry/core/fluids/FilteredTank.java +++ b/src/main/java/forestry/core/fluids/FilteredTank.java @@ -1,31 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import com.google.common.base.Preconditions; -import com.google.common.base.Suppliers; import forestry.api.core.tooltips.ToolTip; import forestry.core.utils.ModUtil; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Rarity; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; import java.util.Collection; import java.util.HashSet; @@ -33,7 +22,7 @@ import java.util.function.Supplier; public class FilteredTank extends StandardTank { - private Supplier> filters = Suppliers.ofInstance(Set.of()); + private Supplier> filters = Set::of; public FilteredTank(int capacity) { super(capacity); @@ -77,14 +66,11 @@ protected void refreshTooltip() { if (Screen.hasShiftDown() || filters.size() < 5) { for (ResourceLocation filterName : filters) { - Fluid fluidFilter = ForgeRegistries.FLUIDS.getValue(filterName); + Fluid fluidFilter = BuiltInRegistries.FLUID.get(filterName); FluidType attributes = fluidFilter.getFluidType(); Rarity rarity = attributes.getRarity(); - if (rarity == null) { - rarity = Rarity.COMMON; - } FluidStack filterFluidStack = new FluidStack(fluidFilter, 1); - toolTip.add(filterFluidStack.getDisplayName(), rarity.color); + toolTip.add(filterFluidStack.getHoverName().copy().withStyle(rarity.getStyleModifier())); } } else { Component tmiComponent = Component.literal("<") diff --git a/src/main/java/forestry/core/fluids/FluidHelper.java b/src/main/java/forestry/core/fluids/FluidHelper.java index a3c1f14e42..feb8dc81c6 100644 --- a/src/main/java/forestry/core/fluids/FluidHelper.java +++ b/src/main/java/forestry/core/fluids/FluidHelper.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import forestry.core.utils.ItemStackUtil; @@ -17,46 +7,31 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidActionResult; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; - -import javax.annotation.Nullable; - +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidActionResult; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; + +// todo nah wtf is this //TODO: Fix isFillable's -public final class FluidHelper { - - private FluidHelper() { - } - - public static boolean areFluidStacksEqual(@Nullable FluidStack fluidStack1, @Nullable FluidStack fluidStack2) { - if (fluidStack1 == null) { - return fluidStack2 == null; - } else { - return fluidStack1.isFluidStackIdentical(fluidStack2); +public class FluidHelper { + public static boolean canAcceptFluid(Level level, BlockPos pos, Direction facing, FluidStack fluid) { + IFluidHandler handler = level.getCapability(Capabilities.FluidHandler.BLOCK, pos, facing); + if (handler == null) { + return false; } - } - public static boolean canAcceptFluid(Level world, BlockPos pos, Direction facing, FluidStack fluid, boolean checkSpace) { - LazyOptional capability = FluidUtil.getFluidHandler(world, pos, facing); - return capability.filter((handler) -> { - for (int tank = 0; tank < handler.getTanks(); tank++) { - int amountFilled = handler.fill(fluid, IFluidHandler.FluidAction.SIMULATE); - if (amountFilled > 0 && (!checkSpace || amountFilled >= fluid.getAmount())) { - return true; - } - } - return false; - }) - .isPresent(); - } + for (int tank = 0; tank < handler.getTanks(); tank++) { + int amountFilled = handler.fill(fluid, IFluidHandler.FluidAction.SIMULATE); + if (amountFilled > 0) { + return true; + } + } - public static boolean canAcceptFluid(Level world, BlockPos pos, Direction facing, FluidStack fluid) { - return canAcceptFluid(world, pos, facing, fluid, false); + return false; } public enum FillStatus { @@ -81,15 +56,12 @@ public static FillStatus fillContainers(IFluidHandler fluidHandler, Container in emptyStack = filled; } - LazyOptional fluidFilledHandlerCap = FluidUtil.getFluidHandler(filled); - LazyOptional fluidEmptyHandlerCap = FluidUtil.getFluidHandler(emptyStack); - if (!fluidFilledHandlerCap.isPresent() || !fluidEmptyHandlerCap.isPresent()) { + IFluidHandlerItem fluidFilledHandler = filled.getCapability(Capabilities.FluidHandler.ITEM); + IFluidHandlerItem fluidEmptyHandler = emptyStack.getCapability(Capabilities.FluidHandler.ITEM); + if (fluidFilledHandler == null || fluidEmptyHandler == null) { return FillStatus.INVALID_INPUT; } - IFluidHandlerItem fluidFilledHandler = fluidFilledHandlerCap.orElse(null); - IFluidHandlerItem fluidEmptyHandler = fluidEmptyHandlerCap.orElse(null); - int containerEmptyCapacity = fluidEmptyHandler.fill(new FluidStack(fluidToFill, Integer.MAX_VALUE), IFluidHandler.FluidAction.SIMULATE); int containerCapacity = fluidFilledHandler.fill(new FluidStack(fluidToFill, Integer.MAX_VALUE), IFluidHandler.FluidAction.SIMULATE); if (containerCapacity <= 0 && containerEmptyCapacity <= 0) { @@ -214,32 +186,23 @@ public static FillStatus drainContainers(IFluidHandler fluidHandler, Container i } public static boolean isFillableContainer(ItemStack container, FluidStack content) { - LazyOptional fluidHandlerCap = FluidUtil.getFluidHandler(container); - if (!fluidHandlerCap.isPresent()) { - return false; - } + IFluidHandlerItem handler = container.getCapability(Capabilities.FluidHandler.ITEM); - return fluidHandlerCap.filter(handler -> handler.fill(new FluidStack(content, 1), IFluidHandler.FluidAction.SIMULATE) > 0).isPresent(); + return handler != null && (handler.fill(content.copyWithAmount(1), IFluidHandler.FluidAction.SIMULATE) > 0); } public static boolean isFillableContainerAndEmpty(ItemStack container, FluidStack content) { - LazyOptional fluidHandlerCap = FluidUtil.getFluidHandler(container); - if (!fluidHandlerCap.isPresent()) { - return false; - } + IFluidHandlerItem handler = container.getCapability(Capabilities.FluidHandler.ITEM); - return fluidHandlerCap.filter(handler -> handler.fill(new FluidStack(content, 1), IFluidHandler.FluidAction.SIMULATE) > 0 && handler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE).isEmpty()).isPresent(); + return handler != null && (handler.fill(content.copyWithAmount(1), IFluidHandler.FluidAction.SIMULATE) > 0) && (handler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE).isEmpty()); } public static ItemStack getEmptyContainer(ItemStack container) { ItemStack empty = container.copy(); empty.setCount(1); - LazyOptional fluidHandlerCap = FluidUtil.getFluidHandler(empty); - if (!fluidHandlerCap.isPresent()) { - return ItemStack.EMPTY; - } + IFluidHandlerItem handler = empty.getCapability(Capabilities.FluidHandler.ITEM); - return fluidHandlerCap.filter(fluidHandler -> fluidHandler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.EXECUTE) != null).isPresent() ? empty : ItemStack.EMPTY; + return (handler != null && handler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.EXECUTE).isEmpty()) ? empty : ItemStack.EMPTY; } public static boolean isFillableContainerWithRoom(ItemStack container) { diff --git a/src/main/java/forestry/core/fluids/FluidRecipeFilter.java b/src/main/java/forestry/core/fluids/FluidRecipeFilter.java index 327937e0ec..a4cd87efc1 100644 --- a/src/main/java/forestry/core/fluids/FluidRecipeFilter.java +++ b/src/main/java/forestry/core/fluids/FluidRecipeFilter.java @@ -1,24 +1,28 @@ package forestry.core.fluids; import forestry.api.recipes.*; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryRecipeTypes; +import forestry.factory.recipes.FabricatorSmeltingRecipe; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.RecipeManager; +import net.neoforged.neoforge.fluids.crafting.FluidIngredient; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; import java.util.Set; import java.util.function.Function; +import java.util.stream.Stream; public class FluidRecipeFilter extends ReloadableFluidFilter { - public static final FluidRecipeFilter HYGROREGULATOR_INPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluidsFromStacks(manager, FactoryRecipeTypes.HYGROREGULATOR.type(), IHygroregulatorRecipe::getInputFluid)); - public static final FluidRecipeFilter CARPENTER_INPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluidsFromStacks(manager, FactoryRecipeTypes.CARPENTER.type(), ICarpenterRecipe::getInputFluid)); - public static final FluidRecipeFilter FERMENTER_INPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluidsFromStacks(manager, FactoryRecipeTypes.FERMENTER.type(), IFermenterRecipe::getInputFluid)); - public static final FluidRecipeFilter FERMENTER_OUTPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluids(manager, FactoryRecipeTypes.FERMENTER.type(), IFermenterRecipe::getOutput)); - public static final FluidRecipeFilter FABRICATOR_SMELTING_OUTPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluidsFromStacks(manager, FactoryRecipeTypes.FABRICATOR_SMELTING.type(), IFabricatorSmeltingRecipe::getResultFluid)); - public static final FluidRecipeFilter STILL_INPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluidsFromStacks(manager, FactoryRecipeTypes.STILL.type(), IStillRecipe::getInput)); - public static final FluidRecipeFilter STILL_OUTPUT = new FluidRecipeFilter(manager -> RecipeUtils.getTargetFluidsFromStacks(manager, FactoryRecipeTypes.STILL.type(), IStillRecipe::getOutput)); + public static final FluidRecipeFilter HYGROREGULATOR_INPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluidsFromIngredients(manager, FactoryRecipeTypes.HYGROREGULATOR.type(), recipe -> recipe.getInputFluid().ingredient())); + public static final FluidRecipeFilter CARPENTER_INPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluidsFromIngredients(manager, FactoryRecipeTypes.CARPENTER.type(), recipe -> recipe.getInputFluid().map(SizedFluidIngredient::ingredient).orElse(FluidIngredient.empty()))); + public static final FluidRecipeFilter FERMENTER_INPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluidsFromIngredients(manager, FactoryRecipeTypes.FERMENTER.type(), IFermenterRecipe::getInputFluid)); + public static final FluidRecipeFilter FERMENTER_OUTPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluids(manager, FactoryRecipeTypes.FERMENTER.type(), IFermenterRecipe::getOutputFluid)); + public static final FluidRecipeFilter FABRICATOR_SMELTING_OUTPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluidsFromIngredients(manager, FactoryRecipeTypes.FABRICATOR_SMELTING.type(), FabricatorSmeltingRecipe::result)); + public static final FluidRecipeFilter STILL_INPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluidsFromIngredients(manager, FactoryRecipeTypes.STILL.type(), IStillRecipe::getInput)); + public static final FluidRecipeFilter STILL_OUTPUT = new FluidRecipeFilter(manager -> RecipeUtil.getTargetFluids(manager, FactoryRecipeTypes.STILL.type(), recipe -> Stream.of(recipe.getOutput().getFluid()))); public FluidRecipeFilter(Function> filters) { - super(() -> filters.apply(RecipeUtils.getRecipeManager())); + super(() -> filters.apply(RecipeUtil.getRecipeManager())); } } diff --git a/src/main/java/forestry/core/fluids/FluidTagFilter.java b/src/main/java/forestry/core/fluids/FluidTagFilter.java index 7eb94b0153..8369e23ea2 100644 --- a/src/main/java/forestry/core/fluids/FluidTagFilter.java +++ b/src/main/java/forestry/core/fluids/FluidTagFilter.java @@ -1,13 +1,13 @@ package forestry.core.fluids; -import forestry.api.ForestryTags; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.FluidTags; import net.minecraft.tags.TagKey; import net.minecraft.world.level.material.Fluid; +import net.neoforged.neoforge.common.Tags; import java.util.HashSet; import java.util.Set; @@ -15,11 +15,11 @@ public class FluidTagFilter extends ReloadableFluidFilter { public static final FluidTagFilter WATER = new FluidTagFilter(FluidTags.WATER); public static final FluidTagFilter LAVA = new FluidTagFilter(FluidTags.LAVA); - public static final FluidTagFilter HONEY = new FluidTagFilter(ForestryTags.Fluids.HONEY); + public static final FluidTagFilter HONEY = new FluidTagFilter(Tags.Fluids.HONEY); public FluidTagFilter(TagKey tag) { super(() -> { - HolderSet.Named set = RecipeUtils.getFluidRegistry().getTag(tag).orElse(null); + HolderSet.Named set = RecipeUtil.getFluidRegistry().getTag(tag).orElse(null); if (set == null || set.size() == 0) { return Set.of(); } diff --git a/src/main/java/forestry/core/fluids/ForestryFluids.java b/src/main/java/forestry/core/fluids/ForestryFluids.java index 264bfb1100..ebd2efac53 100644 --- a/src/main/java/forestry/core/fluids/ForestryFluids.java +++ b/src/main/java/forestry/core/fluids/ForestryFluids.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import forestry.api.ForestryConstants; @@ -16,13 +6,14 @@ import forestry.core.items.definitions.DrinkProperties; import forestry.core.utils.ModUtil; import forestry.modules.features.*; +import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BucketItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; import javax.annotation.Nullable; import java.util.HashMap; @@ -80,11 +71,11 @@ public enum ForestryFluids { .drinkProperties(1, 0.2f, 32) ); - private static final Map tagToFluid = new HashMap<>(); + private static final Map BY_ID = new HashMap<>(); static { for (ForestryFluids fluidDefinition : ForestryFluids.values()) { - tagToFluid.put(ForestryConstants.forestry(fluidDefinition.feature.getName()), fluidDefinition); + BY_ID.put(ForestryConstants.forestry(fluidDefinition.feature.getName()), fluidDefinition); } } @@ -93,13 +84,13 @@ public enum ForestryFluids { private final FeatureItem bucket; ForestryFluids(UnaryOperator properties) { - IFeatureRegistry registry = ModFeatureRegistry.get(ForestryModuleIds.FLUIDS); + IFeatureRegistry registry = ModFeatureRegistry.get(ForestryModuleIds.CORE); this.feature = properties.apply(registry .fluid(name().toLowerCase(Locale.ENGLISH))) .bucket(this::getBucket) .create(); this.bucket = registry - .item(() -> new BucketItem(this::getFluid, new Item.Properties() + .item(() -> new BucketItem(getFluid(), new Item.Properties() .craftRemainder(Items.BUCKET) .stacksTo(1)), "bucket_" + name().toLowerCase(Locale.ENGLISH) @@ -133,12 +124,13 @@ public final Fluid getFlowing() { public final FluidStack getFluid(int mb) { Fluid fluid = getFluid(); - if (fluid == Fluids.EMPTY) { - return FluidStack.EMPTY; - } return new FluidStack(fluid, mb); } + public final SizedFluidIngredient ingredient(int mb) { + return SizedFluidIngredient.of(getFluid(), mb); + } + public final int getParticleColor() { return this.feature.properties().particleColor; } @@ -151,22 +143,13 @@ public final boolean is(FluidStack fluidStack) { return getFluid() == fluidStack.getFluid(); } - public static boolean areEqual(Fluid fluid, FluidStack fluidStack) { + public static boolean areEqual(@Nullable Fluid fluid, FluidStack fluidStack) { return fluid == fluidStack.getFluid(); } @Nullable public static ForestryFluids getFluidDefinition(Fluid fluid) { - return tagToFluid.get(ModUtil.getRegistryName(fluid)); - } - - @Nullable - public static ForestryFluids getFluidDefinition(FluidStack stack) { - if (!stack.isEmpty()) { - return getFluidDefinition(stack.getFluid()); - } - - return null; + return BY_ID.get(ModUtil.getRegistryName(fluid)); } /** @@ -176,4 +159,9 @@ public static ForestryFluids getFluidDefinition(FluidStack stack) { public DrinkProperties getDrinkProperties() { return this.feature.properties().properties; } + + @SuppressWarnings("deprecation") + public Holder holder() { + return getFluid().builtInRegistryHolder(); + } } diff --git a/src/main/java/forestry/core/fluids/ITankManager.java b/src/main/java/forestry/core/fluids/ITankManager.java index 1b4085bb3f..849fe16300 100644 --- a/src/main/java/forestry/core/fluids/ITankManager.java +++ b/src/main/java/forestry/core/fluids/ITankManager.java @@ -1,22 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; @@ -38,6 +26,5 @@ public interface ITankManager extends IFluidHandler { /** * For updating tanks on the client */ - @OnlyIn(Dist.CLIENT) - void processTankUpdate(int tankIndex, @Nullable FluidStack contents); + void processTankUpdate(int tankIndex, FluidStack contents); } diff --git a/src/main/java/forestry/core/fluids/ITankUpdateHandler.java b/src/main/java/forestry/core/fluids/ITankUpdateHandler.java index cbf4b82022..2300f507c9 100644 --- a/src/main/java/forestry/core/fluids/ITankUpdateHandler.java +++ b/src/main/java/forestry/core/fluids/ITankUpdateHandler.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; public interface ITankUpdateHandler { diff --git a/src/main/java/forestry/core/fluids/PipetteContents.java b/src/main/java/forestry/core/fluids/PipetteContents.java deleted file mode 100644 index 1cb3b01a9c..0000000000 --- a/src/main/java/forestry/core/fluids/PipetteContents.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.fluids; - -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.FluidUtil; - -import javax.annotation.Nullable; -import java.util.List; - -public class PipetteContents { - private final FluidStack contents; - - @Nullable - public static PipetteContents create(ItemStack itemStack) { - FluidStack contents = FluidUtil.getFluidContained(itemStack).orElse(FluidStack.EMPTY); - if (contents.isEmpty()) { - return null; - } - return new PipetteContents(contents); - } - - public PipetteContents(FluidStack contents) { - this.contents = contents; - } - - public FluidStack getContents() { - return this.contents; - } - - public boolean isFull() { - return this.contents.getAmount() >= FluidType.BUCKET_VOLUME; - } - - public void addTooltip(List list) { - list.add(this.contents.getDisplayName().copy().append(" (" + this.contents.getAmount() + " mb)").withStyle(ChatFormatting.GRAY)); - } -} diff --git a/src/main/java/forestry/core/fluids/StandardTank.java b/src/main/java/forestry/core/fluids/StandardTank.java index ccd4d73433..58844cee0c 100644 --- a/src/main/java/forestry/core/fluids/StandardTank.java +++ b/src/main/java/forestry/core/fluids/StandardTank.java @@ -1,30 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import forestry.api.core.tooltips.ToolTip; import forestry.core.network.IStreamable; import forestry.core.utils.ModUtil; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Rarity; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.capability.templates.FluidTank; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.capability.templates.FluidTank; -import javax.annotation.Nonnull; import javax.annotation.Nullable; public class StandardTank extends FluidTank implements IStreamable { @@ -36,7 +25,7 @@ public class StandardTank extends FluidTank implements IStreamable { //Used to bypass a second validator test private boolean internalTest; - @OnlyIn(Dist.CLIENT) + // used on client only @Nullable protected ToolTip toolTip; @@ -103,16 +92,15 @@ public int fill(FluidStack resource, FluidAction action) { } public int fillInternal(FluidStack resource, FluidAction action) { - this.internalTest = true; + this.internalTest = true; int filled = super.fill(resource, action); if (action == FluidAction.EXECUTE && filled > 0) { - this.tankUpdateHandler.updateTankLevels(this); + this.tankUpdateHandler.updateTankLevels(this); } - this.internalTest = false; + this.internalTest = false; return filled; } - @Nonnull @Override public FluidStack drain(int maxDrain, FluidAction action) { if (!this.canDrain) { @@ -121,16 +109,15 @@ public FluidStack drain(int maxDrain, FluidAction action) { return drainInternal(maxDrain, action); } - @Nonnull + // ignores "canDrain" property public FluidStack drainInternal(int maxDrain, FluidAction action) { FluidStack drained = super.drain(maxDrain, action); if (action == FluidAction.EXECUTE && !drained.isEmpty() && drained.getAmount() > 0) { - this.tankUpdateHandler.updateTankLevels(this); + this.tankUpdateHandler.updateTankLevels(this); } return drained; } - @Nonnull @Override public FluidStack drain(FluidStack resource, FluidAction action) { if (!this.canDrain) { @@ -139,11 +126,11 @@ public FluidStack drain(FluidStack resource, FluidAction action) { return drainInternal(resource, action); } - @Nonnull + // ignores "canDrain" property public FluidStack drainInternal(FluidStack resource, FluidAction action) { FluidStack drained = super.drain(resource, action); if (action == FluidAction.EXECUTE && !drained.isEmpty() && drained.getAmount() > 0) { - this.tankUpdateHandler.updateTankLevels(this); + this.tankUpdateHandler.updateTankLevels(this); } return drained; } @@ -159,24 +146,23 @@ protected boolean hasFluid() { } @Override - public void writeData(FriendlyByteBuf data) { - data.writeFluidStack(this.fluid); + public void writeData(RegistryFriendlyByteBuf buffer) { + FluidStack.STREAM_CODEC.encode(buffer, this.fluid); } @Override - public void readData(FriendlyByteBuf data) { - this.fluid = data.readFluidStack(); + public void readData(RegistryFriendlyByteBuf buffer) { + this.fluid = FluidStack.STREAM_CODEC.decode(buffer); } @OnlyIn(Dist.CLIENT) public ToolTip getToolTip() { if (this.toolTip == null) { - this.toolTip = new TankToolTip(this); + this.toolTip = new TankToolTip(this); } return this.toolTip; } - @OnlyIn(Dist.CLIENT) protected void refreshTooltip() { ToolTip toolTip = getToolTip(); toolTip.clear(); @@ -186,17 +172,13 @@ protected void refreshTooltip() { Fluid fluidType = fluidStack.getFluid(); FluidType attributes = fluidType.getFluidType(); Rarity rarity = attributes.getRarity(); - if (rarity == null) { - rarity = Rarity.COMMON; - } - toolTip.add(fluidStack.getDisplayName(), rarity.color); + toolTip.add(fluidStack.getHoverName().copy().withStyle(rarity.getStyleModifier())); amount = getFluid().getAmount(); } Component liquidAmount = Component.translatable("for.gui.tooltip.liquid.amount", amount, getCapacity()); toolTip.add(liquidAmount); } - @OnlyIn(Dist.CLIENT) private static class TankToolTip extends ToolTip { private final StandardTank standardTank; @@ -206,7 +188,7 @@ public TankToolTip(StandardTank standardTank) { @Override public void refresh() { - this.standardTank.refreshTooltip(); + this.standardTank.refreshTooltip(); } } } diff --git a/src/main/java/forestry/core/fluids/TankManager.java b/src/main/java/forestry/core/fluids/TankManager.java index 9f90057591..d2e1998c4b 100644 --- a/src/main/java/forestry/core/fluids/TankManager.java +++ b/src/main/java/forestry/core/fluids/TankManager.java @@ -1,33 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.fluids; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; +import forestry.api.modules.IForestryPacketClient; import forestry.core.network.IStreamable; import forestry.core.network.packets.PacketTankLevelUpdate; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.IRenderableTile; import forestry.core.utils.NetworkUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -64,14 +57,14 @@ public void add(StandardTank tank) { } @Override - public CompoundTag write(CompoundTag data) { + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { ListTag tagList = new ListTag(); for (byte slot = 0; slot < this.tanks.size(); slot++) { StandardTank tank = this.tanks.get(slot); if (!tank.getFluid().isEmpty()) { CompoundTag tag = new CompoundTag(); tag.putByte("tank", slot); - tank.writeToNBT(tag); + tank.writeToNBT(registries, tag); tagList.add(tag); } } @@ -80,29 +73,29 @@ public CompoundTag write(CompoundTag data) { } @Override - public void read(CompoundTag data) { + public void read(CompoundTag data, HolderLookup.Provider registries) { for (Tag tag : data.getList("tanks", Tag.TAG_COMPOUND)) { CompoundTag compound = (CompoundTag) tag; int slot = compound.getByte("tank"); if (slot >= 0 && slot < this.tanks.size()) { StandardTank tank = this.tanks.get(slot); - tank.readFromNBT(compound); + tank.readFromNBT(registries, compound); updateTankLevels(tank); } } } @Override - public void writeData(FriendlyByteBuf data) { + public void writeData(RegistryFriendlyByteBuf buffer) { for (StandardTank tank : this.tanks) { - tank.writeData(data); + tank.writeData(buffer); } } @Override - public void readData(FriendlyByteBuf data) { + public void readData(RegistryFriendlyByteBuf buffer) { for (StandardTank tank : this.tanks) { - tank.readData(data); + tank.readData(buffer); } } @@ -116,7 +109,7 @@ public void sendAllTanks(AbstractContainerMenu container, ServerPlayer player) { @Override public void onClosed(AbstractContainerMenu container) { for (StandardTank tank : this.tanks) { - this.prevFluidStacks.remove(container, tank.getTankIndex()); + this.prevFluidStacks.remove(container, tank.getTankIndex()); } } @@ -138,7 +131,7 @@ private void sendTankUpdate(AbstractContainerMenu container, ServerPlayer player if (prev == null) { prev = FluidStack.EMPTY; } - if (FluidHelper.areFluidStacksEqual(fluidStack, prev)) { + if (FluidStack.matches(fluidStack, prev)) { return; } @@ -149,18 +142,19 @@ private void sendTankUpdate(AbstractContainerMenu container, ServerPlayer player if (this.tile != null) { int tankIndex = tank.getTankIndex(); FluidStack fluid = tank.getFluid(); - NetworkUtil.sendToPlayer(new PacketTankLevelUpdate(this.tile, tankIndex, fluid), player); + IForestryPacketClient packet = new PacketTankLevelUpdate(this.tile.getBlockPos(), tankIndex, fluid); + PacketDistributor.sendToPlayer(player, packet); if (fluid.isEmpty()) { - this.prevFluidStacks.remove(container, tankIndex); + this.prevFluidStacks.remove(container, tankIndex); } else { - this.prevFluidStacks.put(container, tankIndex, fluid.copy()); + this.prevFluidStacks.put(container, tankIndex, fluid.copy()); } } } @Override - public void processTankUpdate(int tankIndex, @Nullable FluidStack contents) { + public void processTankUpdate(int tankIndex, FluidStack contents) { if (tankIndex < 0 || tankIndex > this.tanks.size()) { return; } @@ -236,13 +230,13 @@ public void updateTankLevels(StandardTank tank) { return; } - Level world = this.tile.getWorldObj(); - if (world == null || world.isClientSide) - return; + if (!(this.tile.getLevel() instanceof ServerLevel serverLevel)) { + return; + } int tankIndex = tank.getTankIndex(); - PacketTankLevelUpdate tankLevelUpdate = new PacketTankLevelUpdate(this.tile, tankIndex, tank.getFluid()); - NetworkUtil.sendNetworkPacket(tankLevelUpdate, this.tile.getCoordinates(), world); + PacketTankLevelUpdate tankLevelUpdate = new PacketTankLevelUpdate(this.tile.getBlockPos(), tankIndex, tank.getFluid()); + NetworkUtil.sendToPlayersTrackingPos(tankLevelUpdate, this.tile.getBlockPos(), serverLevel); } @Override @@ -308,7 +302,6 @@ private static boolean tankCanDrain(StandardTank tank) { } private static boolean tankCanDrainFluid(StandardTank tank, FluidStack fluidStack) { - return ForestryFluids.areEqual(tank.getFluidType(), fluidStack) && - tankCanDrain(tank); + return ForestryFluids.areEqual(tank.getFluidType(), fluidStack) && tankCanDrain(tank); } } diff --git a/src/main/java/forestry/core/fluids/package-info.java b/src/main/java/forestry/core/fluids/package-info.java index eba0259574..c70185f805 100644 --- a/src/main/java/forestry/core/fluids/package-info.java +++ b/src/main/java/forestry/core/fluids/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.fluids; diff --git a/src/main/java/forestry/core/genetics/AlleleUtil.java b/src/main/java/forestry/core/genetics/AlleleUtil.java deleted file mode 100644 index 28db3a1134..0000000000 --- a/src/main/java/forestry/core/genetics/AlleleUtil.java +++ /dev/null @@ -1,21 +0,0 @@ -package forestry.core.genetics; - -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpecies; -import forestry.api.genetics.ISpeciesType; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; - -import javax.annotation.Nullable; - -public class AlleleUtil { - @Nullable - public static , I extends IIndividual> S getSpecies(ISpeciesType speciesType, CompoundTag nbt, String key) { - String idString = nbt.getString(key); - if (idString.isEmpty()) { - return null; - } - ResourceLocation id = new ResourceLocation(idString); - return speciesType.getSpecies(id); - } -} diff --git a/src/main/java/forestry/core/genetics/BreedingTracker.java b/src/main/java/forestry/core/genetics/BreedingTracker.java index 6259d10b94..1768761b60 100755 --- a/src/main/java/forestry/core/genetics/BreedingTracker.java +++ b/src/main/java/forestry/core/genetics/BreedingTracker.java @@ -1,25 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics; import com.google.common.collect.Iterables; import com.mojang.authlib.GameProfile; import forestry.api.IForestryApi; -import forestry.api.core.ForestryEvent; +import forestry.api.event.BreedingTrackerEvent; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpecies; import forestry.api.genetics.ISpeciesType; import forestry.core.network.packets.PacketGenomeTrackerSync; -import forestry.core.utils.NetworkUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.StringTag; @@ -27,10 +17,11 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.saveddata.SavedData; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.FakePlayer; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; @@ -55,7 +46,7 @@ public abstract class BreedingTracker extends SavedData implements IBreedingTrac private final Set researchedMutations = new HashSet<>(); @Nullable - private GameProfile username; + private ResolvableProfile username; @Nullable private Level level; @@ -63,7 +54,7 @@ protected BreedingTracker(ResourceLocation typeId) { this.typeId = typeId; } - public void setUsername(@Nullable GameProfile username) { + public void setUsername(@Nullable ResolvableProfile username) { this.username = username; } @@ -73,31 +64,31 @@ public void setLevel(@Nullable Level level) { @Override public void syncToPlayer(Player player) { - if (player instanceof ServerPlayer && !(player instanceof FakePlayer)) { + if (player instanceof ServerPlayer && !player.isFakePlayer()) { CompoundTag nbt = new CompoundTag(); writeToNbt(nbt); PacketGenomeTrackerSync packet = new PacketGenomeTrackerSync(nbt); - NetworkUtil.sendToPlayer(packet, (ServerPlayer) player); - } + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); + } } // Sends the given species and mutations to client. Use to sync serverside breeding updates to the client. private void sendUpdate(Collection discoveredSpecies, Collection discoveredMutations, Collection researchedMutations) { - if (this.level != null && this.username != null && this.username.getName() != null) { - Player player = this.level.getPlayerByUUID(this.username.getId()); + if (this.level != null && this.username != null && this.username.id().isPresent()) { + Player player = this.level.getPlayerByUUID(this.username.id().get()); - if (player instanceof ServerPlayer && !(player instanceof FakePlayer)) { + if (player instanceof ServerPlayer && !player.isFakePlayer()) { CompoundTag nbt = new CompoundTag(); writeAllValues(nbt, discoveredSpecies, discoveredMutations, researchedMutations); writeUpdateData(nbt); PacketGenomeTrackerSync packet = new PacketGenomeTrackerSync(nbt); - NetworkUtil.sendToPlayer(packet, (ServerPlayer) player); - } + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); + } } } @Override - public final CompoundTag save(CompoundTag nbt) { + public final CompoundTag save(CompoundTag nbt, HolderLookup.Provider registries) { writeToNbt(nbt); return nbt; } @@ -115,8 +106,13 @@ protected void writeUpdateData(CompoundTag nbt) { @OverridingMethodsMustInvokeSuper @Override - public void readFromNbt(CompoundTag nbt) { - readValuesFromNBT(nbt, value -> this.discoveredSpecies.add(new ResourceLocation(value)), SPECIES_KEY); + public void readFromNbt(CompoundTag nbt, HolderLookup.Provider registries) { + readValuesFromNBT(nbt, value -> { + ResourceLocation id = ResourceLocation.tryParse(value); + if (id != null) { + this.discoveredSpecies.add(id); + } + }, SPECIES_KEY); readValuesFromNBT(nbt, this.discoveredMutations::add, MUTATIONS_KEY); readValuesFromNBT(nbt, this.researchedMutations::add, RESEARCHED_KEY); } @@ -166,8 +162,8 @@ public void registerMutation(IMutation mutation) { setDirty(); ISpeciesType speciesRoot = IForestryApi.INSTANCE.getGeneticManager().getSpeciesType(this.typeId); - ForestryEvent event = new ForestryEvent.MutationDiscovered(speciesRoot, this.username, mutation, this); - MinecraftForge.EVENT_BUS.post(event); + BreedingTrackerEvent.MutationDiscovered event = new BreedingTrackerEvent.MutationDiscovered(speciesRoot, this.username, mutation, this); + NeoForge.EVENT_BUS.post(event); sendUpdate(List.of(), List.of(mutationString), List.of()); } @@ -207,8 +203,8 @@ public void registerSpecies(ISpecies species) { this.discoveredSpecies.add(speciesId); ISpeciesType speciesType = IForestryApi.INSTANCE.getGeneticManager().getSpeciesType(this.typeId); - ForestryEvent event = new ForestryEvent.SpeciesDiscovered(speciesType, this.username, species, this); - MinecraftForge.EVENT_BUS.post(event); + BreedingTrackerEvent.SpeciesDiscovered event = new BreedingTrackerEvent.SpeciesDiscovered(speciesType, this.username, species, this); + NeoForge.EVENT_BUS.post(event); sendUpdate(List.of(speciesId), List.of(), List.of()); } diff --git a/src/main/java/forestry/core/genetics/EffectData.java b/src/main/java/forestry/core/genetics/EffectData.java index bb96f1f30c..ccdb8390da 100755 --- a/src/main/java/forestry/core/genetics/EffectData.java +++ b/src/main/java/forestry/core/genetics/EffectData.java @@ -11,6 +11,7 @@ package forestry.core.genetics; import forestry.api.genetics.IEffectData; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public class EffectData implements IEffectData { @@ -47,11 +48,11 @@ public int getIntSize() { } @Override - public void read(CompoundTag CompoundNBT) { + public void read(CompoundTag CompoundNBT, HolderLookup.Provider registries) { } @Override - public CompoundTag write(CompoundTag CompoundNBT) { + public CompoundTag write(CompoundTag CompoundNBT, HolderLookup.Provider registries) { return CompoundNBT; } } diff --git a/src/main/java/forestry/core/genetics/ItemGE.java b/src/main/java/forestry/core/genetics/ItemGE.java index 7e22ea14e4..2136c0c4c6 100755 --- a/src/main/java/forestry/core/genetics/ItemGE.java +++ b/src/main/java/forestry/core/genetics/ItemGE.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics; import forestry.Forestry; @@ -18,30 +8,22 @@ import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.core.config.ForestryConfig; -import forestry.core.genetics.capability.SerializableIndividualHandlerItem; +import forestry.core.features.CoreDataComponents; import forestry.core.items.ItemForestry; -import forestry.core.utils.GeneticsUtil; -import forestry.core.utils.SpeciesUtil; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.screens.Screen; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import org.apache.commons.lang3.mutable.MutableBoolean; -import javax.annotation.Nullable; import java.util.List; public abstract class ItemGE extends ItemForestry { protected final ILifeStage stage; protected ItemGE(Item.Properties properties, ILifeStage stage) { - super(properties.setNoRepair()); + super(properties.setNoRepair().component(CoreDataComponents.INDIVIDUAL)); this.stage = stage; } @@ -50,67 +32,43 @@ protected ItemGE(Item.Properties properties, ILifeStage stage) { protected abstract ISpeciesType getType(); - @Override - public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) { - Tag parent; - - if (nbt != null && nbt.contains("Parent")) { - // serializable caps returned by this method are saved under "Parent". I love undocumented Forge code!!! - parent = nbt.get("Parent"); - } else if (stack.getTag() != null && stack.getTagElement("ForgeCaps") != null && stack.getTagElement("ForgeCaps").contains("Parent")) { - // Individual.saveToStack saves to NBT manually to bypass the cap nbt being null without setting the field - parent = stack.getTagElement("ForgeCaps").get("Parent"); - } else { - parent = null; - } - - if (parent == null) { - return new SerializableIndividualHandlerItem(getType(), stack, getType().getDefaultSpecies().createIndividual(), this.stage); - } - - return new SerializableIndividualHandlerItem(getType(), stack, SpeciesUtil.deserializeIndividual(getType(), parent), this.stage); - } - @Override public Component getName(ItemStack stack) { - return stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM) - .map(handler -> GeneticsUtil.getItemName(handler.getStage(), handler.getIndividual().getSpecies())) - .orElseGet(() -> super.getName(stack)); + IIndividualHandlerItem handler = stack.getCapability(ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM); + if (handler == null) { + return super.getName(stack); + } + return handler.getIndividual().getSpecies().getItemDisplayName(handler.getStage()); } @Override public boolean isFoil(ItemStack stack) { - if (!stack.hasTag()) { // villager trade wildcard bees - return false; - } ISpecies species = getSpecies(stack); return species.hasGlint() && ForestryConfig.CLIENT.enableGlints.get(); } public static void appendGeneticsTooltip(ItemStack stack, List tooltip) { - if (!stack.hasTag()) { - return; - } + boolean analyzed = false; + IIndividual individual = IIndividualHandlerItem.getIndividual(stack); - MutableBoolean analyzed = new MutableBoolean(); - IIndividualHandlerItem.ifPresent(stack, individual -> { + if (individual != null) { if (individual.isAnalyzed()) { if (Screen.hasShiftDown()) { - ((ISpecies) individual.getSpecies()).addTooltip(individual, tooltip); + individual.getSpecies().addTooltip(individual.cast(), tooltip); } else { tooltip.add(Component.translatable("for.gui.tooltip.tmi", "< %s >").withStyle(style -> style.withColor(ChatFormatting.GRAY).withItalic(true))); } - analyzed.setTrue(); + analyzed = true; } - }); - if (analyzed.isFalse()) { + } + if (!analyzed) { tooltip.add(Component.translatable("for.gui.unknown", "< %s >").withStyle(ChatFormatting.GRAY)); } } @Override - public void appendHoverText(ItemStack stack, @Nullable Level level, List tooltip, TooltipFlag flag) { + public void appendHoverText(ItemStack stack, TooltipContext context, List tooltip, TooltipFlag flag) { appendGeneticsTooltip(stack, tooltip); } diff --git a/src/main/java/forestry/core/genetics/ItemResearchNote.java b/src/main/java/forestry/core/genetics/ItemResearchNote.java index 47c3fb29d9..c31845dbe6 100755 --- a/src/main/java/forestry/core/genetics/ItemResearchNote.java +++ b/src/main/java/forestry/core/genetics/ItemResearchNote.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics; -import com.mojang.authlib.GameProfile; import forestry.api.IForestryApi; import forestry.api.genetics.*; import forestry.core.features.CoreItems; @@ -27,6 +16,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import javax.annotation.Nullable; @@ -47,6 +37,15 @@ public ItemResearchNote() { super(new Item.Properties()); } + @Nullable + public static , I extends IIndividual> S getSpecies(ISpeciesType speciesType, CompoundTag nbt, String key) { + String idString = nbt.getString(key); + if (idString.isEmpty()) { + return null; + } + return speciesType.getSpeciesSafe(ResourceLocation.tryParse(idString)); + } + @Override public Component getName(ItemStack itemstack) { ResearchNote note = new ResearchNote(itemstack.getTag()); @@ -88,15 +87,15 @@ private static IMutation getEncodedMutation(CompoundTag compound) { return null; } - ISpecies parent0 = AlleleUtil.getSpecies(type, compound, PARENT_0_KEY); - ISpecies parent1 = AlleleUtil.getSpecies(type, compound, PARENT_1_KEY); + ISpecies parent0 = getSpecies(type, compound, PARENT_0_KEY); + ISpecies parent1 = getSpecies(type, compound, PARENT_1_KEY); if (parent0 == null || parent1 == null) { return null; } ISpecies result = null; if (compound.contains(RESULT_KEY)) { - result = AlleleUtil.getSpecies(type, compound, RESULT_KEY); + result = getSpecies(type, compound, RESULT_KEY); } IMutation encoded = null; @@ -171,7 +170,7 @@ public static boolean registerResults(Level level, Player player, CompoundTag co return true; } - public static ResearchNote createMutationNote(GameProfile researcher, IMutation mutation) { + public static ResearchNote createMutationNote(ResolvableProfile researcher, IMutation mutation) { CompoundTag compound = new CompoundTag(); compound.putString(TYPE_KEY, mutation.getType().id().toString()); compound.putString(PARENT_0_KEY, mutation.getFirstParent().id().toString()); @@ -180,7 +179,7 @@ public static ResearchNote createMutationNote(GameProfile researcher, IMutation< return new ResearchNote(researcher, compound); } - public static ItemStack createMutationNoteStack(GameProfile researcher, IMutation mutation) { + public static ItemStack createMutationNoteStack(ResolvableProfile researcher, IMutation mutation) { ResearchNote note = createMutationNote(researcher, mutation); CompoundTag compound = new CompoundTag(); note.writeToNBT(compound); @@ -191,10 +190,10 @@ public static ItemStack createMutationNoteStack(GameProfile researcher, IMutatio public static class ResearchNote { @Nullable - private final GameProfile researcher; + private final ResolvableProfile researcher; private final CompoundTag inner; - public ResearchNote(GameProfile researcher, CompoundTag inner) { + public ResearchNote(ResolvableProfile researcher, CompoundTag inner) { this.researcher = researcher; this.inner = inner; } diff --git a/src/main/java/forestry/core/genetics/Karyotype.java b/src/main/java/forestry/core/genetics/Karyotype.java index 0e4404c2fd..c58e8a297a 100644 --- a/src/main/java/forestry/core/genetics/Karyotype.java +++ b/src/main/java/forestry/core/genetics/Karyotype.java @@ -27,9 +27,10 @@ public class Karyotype implements IKaryotype { private final Codec genomeCodec; // Used in Karyotype.Builder + @SuppressWarnings("unchecked") public Karyotype(ImmutableMap, ImmutableSet> chromosomes, ImmutableMap, ? extends IAllele> defaultAlleles, ResourceLocation defaultSpecies, Set> weaklyInheritedChromosomes) { this.chromosomes = chromosomes; - this.speciesChromosome = (IRegistryChromosome>) chromosomes.keySet().asList().get(0); + this.speciesChromosome = (IRegistryChromosome>) chromosomes.keySet().asList().getFirst(); this.defaultAlleles = defaultAlleles; this.defaultSpecies = defaultSpecies; this.weaklyInheritedChromosomes = weaklyInheritedChromosomes; @@ -61,7 +62,7 @@ public int size() { } @Override - public boolean isAlleleValid(IChromosome chromosome, A allele) { + public boolean isAlleleValid(IChromosome chromosome, B allele) { ImmutableSet validAlleles = this.chromosomes.get(chromosome); if (validAlleles != null) { @@ -156,7 +157,6 @@ public IChromosomeBuilder get(IChromosome chromosome) return (IChromosomeBuilder) this.chromosomes.computeIfAbsent(chromosome, key -> new ChromosomeBuilder<>(chromosome)); } - @SuppressWarnings("UnstableApiUsage") public Karyotype build() { Preconditions.checkState(this.defaultSpeciesId != null && this.speciesChromosome != null, "IKaryotypeBuilder is missing a species chromosome."); diff --git a/src/main/java/forestry/core/genetics/SpeciesType.java b/src/main/java/forestry/core/genetics/SpeciesType.java index 53f266bfda..1691b0a9ec 100644 --- a/src/main/java/forestry/core/genetics/SpeciesType.java +++ b/src/main/java/forestry/core/genetics/SpeciesType.java @@ -2,17 +2,18 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.mojang.authlib.GameProfile; import forestry.api.genetics.*; import forestry.api.genetics.alleles.IKaryotype; import forestry.api.plugin.ISpeciesTypeBuilder; import it.unimi.dsi.fastutil.objects.Reference2FloatOpenHashMap; import net.minecraft.Util; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import javax.annotation.Nullable; @@ -58,8 +59,7 @@ public ResourceLocation id() { } @Override - @SuppressWarnings("unchecked") - public S getDefaultSpecies() { + public S getDefaultSpecies() { return (S) this.karyotype.getDefaultAllele(this.karyotype.getSpeciesChromosome()).value(); } @@ -127,7 +127,7 @@ public S getSpecies(ResourceLocation id) { } @Override - public S getSpeciesSafe(ResourceLocation id) { + public S getSpeciesSafe(@Nullable ResourceLocation id) { checkSpecies(); return this.allSpecies.get(id); @@ -165,7 +165,7 @@ public float getResearchSuitability(S species, ItemStack stack) { } @Override - public List getResearchBounty(S species, Level level, GameProfile researcher, I individual, int bountyLevel) { + public List getResearchBounty(S species, Level level, ResolvableProfile researcher, I individual, int bountyLevel) { ArrayList list = new ArrayList<>(); if (level.random.nextFloat() < bountyLevel / 16f) { @@ -218,9 +218,9 @@ public I createRandomIndividual(RandomSource rand) { } @Override - public IBreedingTracker createBreedingTracker(CompoundTag nbt) { + public IBreedingTracker createBreedingTracker(CompoundTag nbt, HolderLookup.Provider registries) { IBreedingTracker tracker = createBreedingTracker(); - tracker.readFromNbt(nbt); + tracker.readFromNbt(nbt, registries); return tracker; } diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleManager.java b/src/main/java/forestry/core/genetics/alleles/AlleleManager.java index a18bdede5d..3d438004ff 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleManager.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleManager.java @@ -108,9 +108,9 @@ public IFloatAllele floatAllele(float value, boolean dominant) { @SuppressWarnings("unchecked") @Override - public IRegistryAllele registryAllele(ResourceLocation id, IRegistryChromosome chromosome) { + public IRegistryAllele registryAllele(ResourceLocation id, IRegistryChromosome chromosome) { checkAlleleRegistration(); - return (IRegistryAllele) this.allelesByName.computeIfAbsent(id, key -> new RegistryAllele<>(key, chromosome)); + return (IRegistryAllele) this.allelesByName.computeIfAbsent(id, key -> new RegistryAllele<>(key, chromosome)); } @Override diff --git a/src/main/java/forestry/core/genetics/alleles/RegistryChromosome.java b/src/main/java/forestry/core/genetics/alleles/RegistryChromosome.java index 1e2ae3933b..62ad7ff22a 100644 --- a/src/main/java/forestry/core/genetics/alleles/RegistryChromosome.java +++ b/src/main/java/forestry/core/genetics/alleles/RegistryChromosome.java @@ -41,8 +41,9 @@ public V get(ResourceLocation id) { @Nullable @Override - public V getSafe(ResourceLocation id) { + public V getSafe(@Nullable ResourceLocation id) { Preconditions.checkState(this.registry != null, "Registry not yet populated"); + return this.registry.get(id); } diff --git a/src/main/java/forestry/core/genetics/alleles/package-info.java b/src/main/java/forestry/core/genetics/alleles/package-info.java index 8d3164f334..b56492bbcf 100644 --- a/src/main/java/forestry/core/genetics/alleles/package-info.java +++ b/src/main/java/forestry/core/genetics/alleles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.genetics.alleles; diff --git a/src/main/java/forestry/core/genetics/capability/IndividualHandlerItem.java b/src/main/java/forestry/core/genetics/capability/IndividualHandlerItem.java index 31705b3d50..7892574347 100644 --- a/src/main/java/forestry/core/genetics/capability/IndividualHandlerItem.java +++ b/src/main/java/forestry/core/genetics/capability/IndividualHandlerItem.java @@ -1,22 +1,16 @@ package forestry.core.genetics.capability; -import forestry.api.ForestryCapabilities; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ILifeStage; import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.capability.IIndividualHandlerItem; -import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; +import net.neoforged.neoforge.capabilities.ICapabilityProvider; import javax.annotation.Nullable; // Used for Vanilla sapling items. -public class IndividualHandlerItem implements ICapabilityProvider, IIndividualHandlerItem { - private final LazyOptional holder = LazyOptional.of(() -> this); - +public class IndividualHandlerItem implements ICapabilityProvider, IIndividualHandlerItem { protected final ISpeciesType speciesType; protected final ItemStack container; protected IIndividual individual; @@ -54,7 +48,7 @@ public boolean isGeneticForm() { } @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction side) { - return ForestryCapabilities.INDIVIDUAL_HANDLER_ITEM.orEmpty(capability, this.holder); + public IIndividualHandlerItem getCapability(ItemStack stack, @Nullable Void v) { + return this; } } diff --git a/src/main/java/forestry/core/genetics/capability/SerializableIndividualHandlerItem.java b/src/main/java/forestry/core/genetics/capability/SerializableIndividualHandlerItem.java index 1d1e5d4241..5f1d76e38f 100644 --- a/src/main/java/forestry/core/genetics/capability/SerializableIndividualHandlerItem.java +++ b/src/main/java/forestry/core/genetics/capability/SerializableIndividualHandlerItem.java @@ -4,9 +4,10 @@ import forestry.api.genetics.ILifeStage; import forestry.api.genetics.ISpeciesType; import forestry.core.utils.SpeciesUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.Tag; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.util.INBTSerializable; +import net.neoforged.neoforge.common.util.INBTSerializable; public class SerializableIndividualHandlerItem extends IndividualHandlerItem implements INBTSerializable { public SerializableIndividualHandlerItem(ISpeciesType type, ItemStack container, IIndividual individual, ILifeStage stage) { @@ -14,12 +15,12 @@ public SerializableIndividualHandlerItem(ISpeciesType type, ItemStack cont } @Override - public Tag serializeNBT() { + public Tag serializeNBT(HolderLookup.Provider registries) { return SpeciesUtil.serializeIndividual(this.individual); } @Override - public void deserializeNBT(Tag nbt) { + public void deserializeNBT(HolderLookup.Provider registries, Tag nbt) { this.individual = SpeciesUtil.deserializeIndividual(this.speciesType, nbt); } } diff --git a/src/main/java/forestry/core/genetics/capability/package-info.java b/src/main/java/forestry/core/genetics/capability/package-info.java new file mode 100644 index 0000000000..d11409eeb1 --- /dev/null +++ b/src/main/java/forestry/core/genetics/capability/package-info.java @@ -0,0 +1,4 @@ +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault +package forestry.core.genetics.capability; diff --git a/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java b/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java index cc13718272..ad11c5e86f 100644 --- a/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java +++ b/src/main/java/forestry/core/genetics/mutations/EnumMutateChance.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; public enum EnumMutateChance { diff --git a/src/main/java/forestry/core/genetics/mutations/Mutation.java b/src/main/java/forestry/core/genetics/mutations/Mutation.java index d7cdca5312..1aa365557f 100644 --- a/src/main/java/forestry/core/genetics/mutations/Mutation.java +++ b/src/main/java/forestry/core/genetics/mutations/Mutation.java @@ -1,17 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; import com.google.common.collect.ImmutableList; -import com.mojang.authlib.GameProfile; import forestry.api.climate.IClimateProvider; import forestry.api.genetics.*; import forestry.api.genetics.alleles.AllelePair; @@ -22,6 +11,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import java.util.List; @@ -145,7 +135,7 @@ public boolean isSecret() { } @Override - public ItemStack getMutationNote(GameProfile researcher) { + public ItemStack getMutationNote(ResolvableProfile researcher) { return ItemResearchNote.createMutationNoteStack(researcher, this); } } diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java index 13e0741844..669c9c41c3 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java index 54d8570fc8..3da3cc7c7e 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionDaytime.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java index 1e744bb26b..b86bcac54b 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionHumidity.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java index e92562de2d..dd73a39e7b 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java index b2ae974183..56319c94af 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionTimeLimited.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.genetics.mutations; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/core/genetics/mutations/package-info.java b/src/main/java/forestry/core/genetics/mutations/package-info.java index 99e3d6893e..45303fc01d 100644 --- a/src/main/java/forestry/core/genetics/mutations/package-info.java +++ b/src/main/java/forestry/core/genetics/mutations/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.genetics.mutations; diff --git a/src/main/java/forestry/core/genetics/package-info.java b/src/main/java/forestry/core/genetics/package-info.java index f8a2f21c58..2186534005 100644 --- a/src/main/java/forestry/core/genetics/package-info.java +++ b/src/main/java/forestry/core/genetics/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.genetics; diff --git a/src/main/java/forestry/core/genetics/root/BreedingTrackerManager.java b/src/main/java/forestry/core/genetics/root/BreedingTrackerManager.java index cbe6ed5558..04350745c4 100644 --- a/src/main/java/forestry/core/genetics/root/BreedingTrackerManager.java +++ b/src/main/java/forestry/core/genetics/root/BreedingTrackerManager.java @@ -1,13 +1,13 @@ package forestry.core.genetics.root; -import com.mojang.authlib.GameProfile; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IBreedingTrackerManager; import forestry.api.genetics.ISpeciesType; import forestry.core.ClientsideCode; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.LevelAccessor; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.loading.FMLEnvironment; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; import javax.annotation.Nullable; @@ -17,11 +17,11 @@ public enum BreedingTrackerManager implements IBreedingTrackerManager { private static final SidedHandler BREEDING_HANDLER = FMLEnvironment.dist == Dist.CLIENT ? ClientsideCode.newBreedingHandler() : new ServerBreedingHandler(); @Override - public T getTracker(ISpeciesType type, LevelAccessor level, @Nullable GameProfile profile) { + public T getTracker(ISpeciesType type, LevelAccessor level, @Nullable ResolvableProfile profile) { return BREEDING_HANDLER.getTracker(type, level, profile); } interface SidedHandler { - T getTracker(ISpeciesType type, LevelAccessor level, @Nullable GameProfile profile); + T getTracker(ISpeciesType type, LevelAccessor level, @Nullable ResolvableProfile profile); } } diff --git a/src/main/java/forestry/core/genetics/root/ServerBreedingHandler.java b/src/main/java/forestry/core/genetics/root/ServerBreedingHandler.java index 49034899c6..c08b2d1b03 100644 --- a/src/main/java/forestry/core/genetics/root/ServerBreedingHandler.java +++ b/src/main/java/forestry/core/genetics/root/ServerBreedingHandler.java @@ -4,6 +4,7 @@ import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesType; import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.saveddata.SavedData; @@ -13,10 +14,10 @@ public class ServerBreedingHandler implements BreedingTrackerManager.SidedHandler { @Override @SuppressWarnings("unchecked") - public T getTracker(ISpeciesType type, LevelAccessor level, @Nullable GameProfile profile) { + public T getTracker(ISpeciesType type, LevelAccessor level, @Nullable ResolvableProfile profile) { String filename = type.getBreedingTrackerFile(profile); ServerLevel overworld = level.getServer().getLevel(Level.OVERWORLD); - T tracker = (T) overworld.getDataStorage().computeIfAbsent(tag -> (SavedData) type.createBreedingTracker(tag), () -> (SavedData) type.createBreedingTracker(), filename); + T tracker = (T) overworld.getDataStorage().computeIfAbsent(new SavedData.Factory<>(() -> (SavedData) type.createBreedingTracker(), (nbt, registries) -> (SavedData) type.createBreedingTracker(nbt, registries)), filename); type.initializeBreedingTracker(tracker, overworld, profile); return tracker; } diff --git a/src/main/java/forestry/core/genetics/root/package-info.java b/src/main/java/forestry/core/genetics/root/package-info.java index f1398ff00b..b5d0d0f948 100644 --- a/src/main/java/forestry/core/genetics/root/package-info.java +++ b/src/main/java/forestry/core/genetics/root/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.genetics.root; diff --git a/src/main/java/forestry/core/gui/ContainerAnalyzer.java b/src/main/java/forestry/core/gui/AnalyzerMenu.java old mode 100755 new mode 100644 similarity index 85% rename from src/main/java/forestry/core/gui/ContainerAnalyzer.java rename to src/main/java/forestry/core/gui/AnalyzerMenu.java index 505b606461..f4d4f64a3e --- a/src/main/java/forestry/core/gui/ContainerAnalyzer.java +++ b/src/main/java/forestry/core/gui/AnalyzerMenu.java @@ -21,13 +21,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerAnalyzer extends ContainerLiquidTanks { - public static ContainerAnalyzer fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { +public class AnalyzerMenu extends LiquidTanksMenu { + public static AnalyzerMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { TileAnalyzer analyzer = TileUtil.getTile(playerInv.player.level(), extraData.readBlockPos(), TileAnalyzer.class); - return new ContainerAnalyzer(windowId, playerInv, analyzer); + return new AnalyzerMenu(windowId, playerInv, analyzer); } - public ContainerAnalyzer(int windowId, Inventory player, TileAnalyzer tile) { + public AnalyzerMenu(int windowId, Inventory player, TileAnalyzer tile) { super(windowId, CoreMenuTypes.ANALYZER.menuType(), player, tile, 8, 94); // Input buffer diff --git a/src/main/java/forestry/core/gui/ContainerAlyzer.java b/src/main/java/forestry/core/gui/ContainerAlyzer.java deleted file mode 100644 index c537403190..0000000000 --- a/src/main/java/forestry/core/gui/ContainerAlyzer.java +++ /dev/null @@ -1,35 +0,0 @@ -package forestry.core.gui; - -import forestry.core.features.CoreMenuTypes; -import forestry.core.gui.slots.SlotFiltered; -import forestry.core.inventory.ItemInventoryAlyzer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; - -public class ContainerAlyzer extends ContainerItemInventory { - - public static ContainerAlyzer fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { - InteractionHand hand = extraData.readBoolean() ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; - Player player = playerInv.player; - ItemInventoryAlyzer inv = new ItemInventoryAlyzer(player, player.getItemInHand(hand)); - return new ContainerAlyzer(windowId, inv, player); - } - - public ContainerAlyzer(int windowId, ItemInventoryAlyzer inventory, Player player) { - super(windowId, inventory, player.getInventory(), 43, 156, CoreMenuTypes.ALYZER.menuType()); - - final int xPosLeftSlots = 223; - - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ENERGY, xPosLeftSlots, 8)); - - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_SPECIMEN, xPosLeftSlots, 26)); - - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_1, xPosLeftSlots, 57)); - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_2, xPosLeftSlots, 75)); - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_3, xPosLeftSlots, 93)); - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_4, xPosLeftSlots, 111)); - this.addSlot(new SlotFiltered(inventory, ItemInventoryAlyzer.SLOT_ANALYZE_5, xPosLeftSlots, 129)); - } -} diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java b/src/main/java/forestry/core/gui/ContainerLiquidTanks.java deleted file mode 100755 index 55b1190057..0000000000 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanks.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui; - -import forestry.core.tiles.ILiquidTankTile; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.IFluidTank; - -import javax.annotation.Nullable; - -public abstract class ContainerLiquidTanks extends ContainerTile implements IContainerLiquidTanks { - private final ContainerLiquidTanksHelper helper; - - protected ContainerLiquidTanks(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { - super(windowId, type, playerInventory, tile, xInv, yInv); - - this.helper = new ContainerLiquidTanksHelper<>(tile); - - if (this.player != null) { - this.tile.getTankManager().sendAllTanks(this, this.player); - } - } - - @Override - @OnlyIn(Dist.CLIENT) - public void handlePipetteClickClient(int slot, Player player) { - this.helper.handlePipetteClickClient(slot, player); - } - - @Override - public void handlePipetteClick(int slot, ServerPlayer player) { - this.helper.handlePipetteClick(slot, player); - } - - @Override - public void broadcastChanges() { - super.broadcastChanges(); - - if (this.player != null) { - this.tile.getTankManager().broadcastChanges(this, this.player); - } - } - - @Override - public void removed(Player PlayerEntity) { - super.removed(PlayerEntity); - this.tile.getTankManager().onClosed(this); - } - - @Nullable - @Override - public IFluidTank getTank(int slot) { - return this.tile.getTankManager().getTank(slot); - } -} diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java b/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java index 32678f433c..9138091019 100644 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java @@ -1,35 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import forestry.api.core.IToolPipette; -import forestry.core.fluids.StandardTank; +import forestry.api.modules.IForestryPacketServer; import forestry.core.network.packets.PacketPipetteClick; import forestry.core.tiles.ILiquidTankTile; -import forestry.core.utils.NetworkUtil; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import net.minecraftforge.fluids.capability.templates.FluidTank; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; +import net.neoforged.neoforge.fluids.capability.templates.FluidTank; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; @@ -45,14 +34,15 @@ public ContainerLiquidTanksHelper(T tile) { public void handlePipetteClickClient(int slot, Player player) { ItemStack itemstack = player.containerMenu.getCarried(); if (itemstack.getItem() instanceof IToolPipette) { - NetworkUtil.sendToServer(new PacketPipetteClick(slot)); + IForestryPacketServer packet = new PacketPipetteClick(slot); + PacketDistributor.sendToServer(packet); } } @Override public void handlePipetteClick(int slot, ServerPlayer player) { - ItemStack itemstack = player.containerMenu.getCarried(); - Item held = itemstack.getItem(); + ItemStack stack = player.containerMenu.getCarried(); + Item held = stack.getItem(); if (!(held instanceof IToolPipette pipette)) { return; } @@ -60,22 +50,16 @@ public void handlePipetteClick(int slot, ServerPlayer player) { IFluidTank tank = this.tile.getTankManager().getTank(slot); int liquidAmount = tank.getFluidAmount(); - LazyOptional fluidCap = FluidUtil.getFluidHandler(itemstack); - fluidCap.ifPresent(fluidHandlerItem -> { - if (pipette.canPipette(itemstack) && liquidAmount > 0) { - if (tank instanceof StandardTank standard) { - FluidStack fillAmount = standard.drainInternal(FluidType.BUCKET_VOLUME, IFluidHandler.FluidAction.SIMULATE); - int filled = fluidHandlerItem.fill(fillAmount, IFluidHandler.FluidAction.EXECUTE); - tank.drain(filled, IFluidHandler.FluidAction.EXECUTE); - player.inventoryMenu.setCarried(fluidHandlerItem.getContainer()); - player.inventoryMenu.broadcastChanges(); - } else {//TODO: Test if this works - FluidStack fillAmount = tank.drain(FluidType.BUCKET_VOLUME, IFluidHandler.FluidAction.EXECUTE); - int filled = fluidHandlerItem.fill(fillAmount, IFluidHandler.FluidAction.EXECUTE); - tank.drain(filled, IFluidHandler.FluidAction.EXECUTE); - player.containerMenu.setCarried(fluidHandlerItem.getContainer()); - player.containerMenu.broadcastChanges(); - } + IFluidHandlerItem fluidHandlerItem = stack.getCapability(Capabilities.FluidHandler.ITEM); + if (fluidHandlerItem != null) { + if (pipette.canPipette(stack) && liquidAmount > 0) { + // todo test pipette extraction + FluidStack fillAmount = tank.drain(FluidType.BUCKET_VOLUME, IFluidHandler.FluidAction.SIMULATE); + int filled = fluidHandlerItem.fill(fillAmount, IFluidHandler.FluidAction.EXECUTE); + tank.drain(filled, IFluidHandler.FluidAction.EXECUTE); + player.containerMenu.setCarried(fluidHandlerItem.getContainer()); + player.containerMenu.broadcastChanges(); + } else { FluidStack potential = fluidHandlerItem.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.SIMULATE); if (!potential.isEmpty()) { @@ -87,7 +71,7 @@ public void handlePipetteClick(int slot, ServerPlayer player) { } } } - }); + } } @Nullable diff --git a/src/main/java/forestry/core/gui/ContainerSocketedHelper.java b/src/main/java/forestry/core/gui/ContainerSocketedHelper.java index 7d206b812f..cd15a82e4e 100644 --- a/src/main/java/forestry/core/gui/ContainerSocketedHelper.java +++ b/src/main/java/forestry/core/gui/ContainerSocketedHelper.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; +import forestry.api.ForestryTags; import forestry.api.IForestryApi; import forestry.api.circuits.ICircuitBoard; +import forestry.api.modules.IForestryPacketServer; import forestry.core.circuits.ISocketable; -import forestry.core.circuits.ISolderingIron; +import forestry.core.features.CoreDataComponents; import forestry.core.network.packets.PacketChipsetClick; import forestry.core.network.packets.PacketSocketUpdate; import forestry.core.network.packets.PacketSolderingIronClick; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.NetworkUtil; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.PacketDistributor; public class ContainerSocketedHelper implements IContainerSocketed { @@ -36,7 +29,8 @@ public ContainerSocketedHelper(T tile) { @Override @OnlyIn(Dist.CLIENT) public void handleChipsetClick(int slot) { - NetworkUtil.sendToServer(new PacketChipsetClick(slot)); + IForestryPacketServer packet = new PacketChipsetClick(slot); + PacketDistributor.sendToServer(packet); } @Override @@ -49,7 +43,8 @@ public void handleChipsetClickServer(int slot, ServerPlayer player, ItemStack it return; } - ICircuitBoard circuitBoard = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(itemstack); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard circuitBoard = itemstack.get(CoreDataComponents.CIRCUIT_BOARD); if (circuitBoard == null) { return; } @@ -67,19 +62,20 @@ public void handleChipsetClickServer(int slot, ServerPlayer player, ItemStack it player.containerMenu.broadcastChanges(); PacketSocketUpdate packet = PacketSocketUpdate.create(this.tile); - NetworkUtil.sendToPlayer(packet, player); - } + PacketDistributor.sendToPlayer(player, packet); + } @Override @OnlyIn(Dist.CLIENT) public void handleSolderingIronClick(int slot) { - NetworkUtil.sendToServer(new PacketSolderingIronClick(slot)); + IForestryPacketServer packet = new PacketSolderingIronClick(slot); + PacketDistributor.sendToServer(packet); } @Override - public void handleSolderingIronClickServer(int slot, ServerPlayer player, ItemStack itemstack) { + public void handleSolderingIronClickServer(int slot, ServerPlayer player, ItemStack stack) { ItemStack socket = this.tile.getSocket(slot); - if (socket.isEmpty() || !(itemstack.getItem() instanceof ISolderingIron)) { + if (socket.isEmpty() || !(stack.is(ForestryTags.Items.SOLDERING_IRONS))) { return; } @@ -90,10 +86,10 @@ public void handleSolderingIronClickServer(int slot, ServerPlayer player, ItemSt this.tile.setSocket(slot, ItemStack.EMPTY); InventoryUtil.stowInInventory(socket, player.getInventory(), true); - itemstack.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(p.getUsedItemHand())); //TODO onBreak + stack.hurtAndBreak(1, player, LivingEntity.getSlotForHand(player.getUsedItemHand())); player.inventoryMenu.broadcastChanges(); PacketSocketUpdate packet = PacketSocketUpdate.create(this.tile); - NetworkUtil.sendToPlayer(packet, player); - } + PacketDistributor.sendToPlayer(player, packet); + } } diff --git a/src/main/java/forestry/core/gui/Drawable.java b/src/main/java/forestry/core/gui/Drawable.java index 9104633796..cb211454bd 100644 --- a/src/main/java/forestry/core/gui/Drawable.java +++ b/src/main/java/forestry/core/gui/Drawable.java @@ -3,8 +3,8 @@ import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class Drawable { diff --git a/src/main/java/forestry/core/gui/ContainerEscritoire.java b/src/main/java/forestry/core/gui/EscritoireMenu.java old mode 100755 new mode 100644 similarity index 84% rename from src/main/java/forestry/core/gui/ContainerEscritoire.java rename to src/main/java/forestry/core/gui/EscritoireMenu.java index 466ed26915..b3e5280ba0 --- a/src/main/java/forestry/core/gui/ContainerEscritoire.java +++ b/src/main/java/forestry/core/gui/EscritoireMenu.java @@ -23,11 +23,12 @@ import forestry.core.tiles.EscritoireGame; import forestry.core.tiles.TileEscritoire; import forestry.core.tiles.TileUtil; +import net.minecraft.world.item.component.ResolvableProfile; -public class ContainerEscritoire extends ContainerTile implements IGuiSelectable { +public class EscritoireMenu extends TileMenu implements IGuiSelectable { private long lastUpdate; - public ContainerEscritoire(int id, Inventory playerInv, TileEscritoire tile) { + public EscritoireMenu(int id, Inventory playerInv, TileEscritoire tile) { super(id, CoreMenuTypes.ESCRITOIRE.menuType(), playerInv, tile, 34, 153); // Analyze slot @@ -44,9 +45,9 @@ public ContainerEscritoire(int id, Inventory playerInv, TileEscritoire tile) { } } - public static ContainerEscritoire fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { + public static EscritoireMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { TileEscritoire tile = TileUtil.getTile(playerInv.player.level(), extraData.readBlockPos(), TileEscritoire.class); - return new ContainerEscritoire(windowId, playerInv, tile); + return new EscritoireMenu(windowId, playerInv, tile); } @Override @@ -70,7 +71,7 @@ public void handleSelectionRequest(ServerPlayer player, int primary, int seconda if (primary == -1) { tile.probe(); } else { - tile.choose(player.getGameProfile(), primary); + tile.choose(new ResolvableProfile(player.getGameProfile()), primary); } } } diff --git a/src/main/java/forestry/core/gui/ContainerForestry.java b/src/main/java/forestry/core/gui/ForestryMenu.java similarity index 77% rename from src/main/java/forestry/core/gui/ContainerForestry.java rename to src/main/java/forestry/core/gui/ForestryMenu.java index be476fe56f..ddd85d7b3b 100644 --- a/src/main/java/forestry/core/gui/ContainerForestry.java +++ b/src/main/java/forestry/core/gui/ForestryMenu.java @@ -1,19 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import forestry.api.modules.IForestryPacketClient; import forestry.core.gui.slots.SlotForestry; import forestry.core.gui.slots.SlotLocked; -import forestry.core.utils.NetworkUtil; import forestry.core.utils.SlotUtil; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Inventory; @@ -23,19 +12,20 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; -public abstract class ContainerForestry extends AbstractContainerMenu { +public abstract class ForestryMenu extends AbstractContainerMenu { public static final int PLAYER_HOTBAR_OFFSET = 27; public static final int PLAYER_INV_SLOTS = PLAYER_HOTBAR_OFFSET + 9; - // number of items that have been shift-click-transfered during this click + // number of items that have been shift-click-transferred during this click private int transferCount = 0; // null on client side @Nullable protected final ServerPlayer player; - protected ContainerForestry(int containerId, MenuType type, @Nullable Player player) { + protected ForestryMenu(MenuType type, int containerId, @Nullable Player player) { super(type, containerId); if (player instanceof ServerPlayer serverPlayer) { @@ -120,7 +110,7 @@ public final ItemStack quickMoveStack(Player player, int slotIndex) { protected final void sendPacketToListeners(IForestryPacketClient packet) { if (this.player != null) { - NetworkUtil.sendToPlayer(packet, this.player); - } + PacketDistributor.sendToPlayer(this.player, packet); + } } } diff --git a/src/main/java/forestry/core/gui/GuiAnalyzer.java b/src/main/java/forestry/core/gui/GuiAnalyzer.java index 79cef08da4..2108ba2818 100755 --- a/src/main/java/forestry/core/gui/GuiAnalyzer.java +++ b/src/main/java/forestry/core/gui/GuiAnalyzer.java @@ -19,10 +19,10 @@ import net.minecraft.world.entity.player.Inventory; // The block form of the analyzer -public class GuiAnalyzer extends GuiForestryTitled { +public class GuiAnalyzer extends GuiForestryTitled { private final TileAnalyzer tile; - public GuiAnalyzer(ContainerAnalyzer analyzer, Inventory inventory, Component title) { + public GuiAnalyzer(AnalyzerMenu analyzer, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/alyzer.png", analyzer, inventory, title); this.tile = analyzer.tile; this.imageHeight = 176; diff --git a/src/main/java/forestry/core/gui/GuiEscritoire.java b/src/main/java/forestry/core/gui/GuiEscritoire.java index 0759517065..b80ce2faa7 100755 --- a/src/main/java/forestry/core/gui/GuiEscritoire.java +++ b/src/main/java/forestry/core/gui/GuiEscritoire.java @@ -26,12 +26,12 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -public class GuiEscritoire extends GuiForestry { +public class GuiEscritoire extends GuiForestry { private final ItemStack LEVEL_ITEM = new ItemStack(Items.PAPER); private final EscritoireTextSource textSource = new EscritoireTextSource(); private final TileEscritoire tile; - public GuiEscritoire(ContainerEscritoire container, Inventory inv, Component title) { + public GuiEscritoire(EscritoireMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/escritoire.png", container, inv, title); this.tile = container.getTile(); diff --git a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java index 2e1b345ef8..bd23676c8e 100755 --- a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import com.google.common.collect.ImmutableList; @@ -15,12 +5,11 @@ import forestry.api.genetics.*; import forestry.api.genetics.alleles.IRegistryChromosome; import forestry.api.genetics.capability.IIndividualHandlerItem; +import forestry.api.modules.IForestryPacketServer; import forestry.core.config.Constants; -import forestry.core.gui.buttons.GuiBetterButton; -import forestry.core.gui.buttons.StandardButtonTextureSets; +import forestry.core.gui.widgets.ArrowButton; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.render.ColourProperties; -import forestry.core.utils.NetworkUtil; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -28,6 +17,7 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.Collections; @@ -42,13 +32,14 @@ public class GuiNaturalistInventory { + addRenderableWidget(new ArrowButton(this.leftPos + 99, this.topPos + 7, ArrowButton.Texture.LEFT_BUTTON_SMALL, b -> { if (this.pageCurrent > 0) { flipPage(this.pageCurrent - 1); } })); - addRenderableWidget(new GuiBetterButton(this.leftPos + 180, this.topPos + 7, StandardButtonTextureSets.RIGHT_BUTTON_SMALL, b -> { + addRenderableWidget(new ArrowButton(this.leftPos + 180, this.topPos + 7, ArrowButton.Texture.RIGHT_BUTTON_SMALL, b -> { if (this.pageCurrent < this.pageMax - 1) { flipPage(this.pageCurrent + 1); } @@ -111,8 +102,9 @@ public void init() { private void flipPage(int page) { this.menu.onFlipPage(); - NetworkUtil.sendToServer(new PacketGuiSelectRequest(page, 0)); - } + IForestryPacketServer packet = new PacketGuiSelectRequest(page, 0); + PacketDistributor.sendToServer(packet); + } @Nullable private IIndividual getHoveredIndividual() { @@ -125,10 +117,6 @@ private IIndividual getHoveredIndividual() { return null; } - if (!slot.getItem().hasTag()) { - return null; - } - if (!this.speciesType.isMember(slot.getItem())) { return null; } @@ -174,6 +162,7 @@ private void displaySpeciesInformation(GuiGraphics graphics, boolean analyzed, I @SuppressWarnings("rawtypes") IMutationManager manager = this.speciesType.getMutations(); + @SuppressWarnings("unchecked") List>> mutations = splitMutations(manager.getMutationsFrom(species), maxMutationCount); for (IMutation combination : this.timer.getCycledItem(mutations, Collections::emptyList)) { if (combination.isSecret()) { diff --git a/src/main/java/forestry/core/gui/IContainerLiquidTanks.java b/src/main/java/forestry/core/gui/IContainerLiquidTanks.java index 86d3b5cadc..3f9cd481e4 100644 --- a/src/main/java/forestry/core/gui/IContainerLiquidTanks.java +++ b/src/main/java/forestry/core/gui/IContainerLiquidTanks.java @@ -1,25 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.IFluidTank; import javax.annotation.Nullable; public interface IContainerLiquidTanks { - @OnlyIn(Dist.CLIENT) void handlePipetteClickClient(int slot, Player player); void handlePipetteClick(int slot, ServerPlayer player); diff --git a/src/main/java/forestry/core/gui/IContainerSocketed.java b/src/main/java/forestry/core/gui/IContainerSocketed.java index bfe9dca1a5..2e41e11bef 100644 --- a/src/main/java/forestry/core/gui/IContainerSocketed.java +++ b/src/main/java/forestry/core/gui/IContainerSocketed.java @@ -12,8 +12,8 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public interface IContainerSocketed { @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/forestry/core/gui/IGuiSelectable.java b/src/main/java/forestry/core/gui/IGuiSelectable.java index 3cfd9f6699..4ee0bb5cc7 100755 --- a/src/main/java/forestry/core/gui/IGuiSelectable.java +++ b/src/main/java/forestry/core/gui/IGuiSelectable.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import net.minecraft.server.level.ServerPlayer; diff --git a/src/main/java/forestry/core/gui/ContainerItemInventory.java b/src/main/java/forestry/core/gui/ItemInventoryMenu.java old mode 100755 new mode 100644 similarity index 54% rename from src/main/java/forestry/core/gui/ContainerItemInventory.java rename to src/main/java/forestry/core/gui/ItemInventoryMenu.java index ae440e67f5..5210109491 --- a/src/main/java/forestry/core/gui/ContainerItemInventory.java +++ b/src/main/java/forestry/core/gui/ItemInventoryMenu.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import forestry.core.gui.slots.SlotLocked; @@ -17,14 +7,13 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; -import net.minecraft.world.item.ItemStack; - -public abstract class ContainerItemInventory extends ContainerForestry { +public abstract class ItemInventoryMenu extends ForestryMenu { protected final I inventory; + protected final int slotIndex; - protected ContainerItemInventory(int windowId, I inventory, Inventory playerInventory, int xInv, int yInv, MenuType type) { - super(windowId, type, playerInventory.player); + protected ItemInventoryMenu(MenuType type, int containerId, I inventory, Inventory playerInventory, int xInv, int yInv) { + super(type, containerId, playerInventory.player); this.inventory = inventory; addPlayerInventory(playerInventory, xInv, yInv); @@ -32,9 +21,7 @@ protected ContainerItemInventory(int windowId, I inventory, Inventory playerInve @Override protected void addHotbarSlot(Inventory playerInventory, int slot, int x, int y) { - ItemStack stackInSlot = playerInventory.getItem(slot); - - if (this.inventory.isParentItemInventory(stackInSlot)) { + if (slot == this.slotIndex) { addSlot(new SlotLocked(playerInventory, slot, x, y)); } else { addSlot(new Slot(playerInventory, slot, x, y)); diff --git a/src/main/java/forestry/core/gui/LiquidTanksMenu.java b/src/main/java/forestry/core/gui/LiquidTanksMenu.java new file mode 100644 index 0000000000..41f9dcd68d --- /dev/null +++ b/src/main/java/forestry/core/gui/LiquidTanksMenu.java @@ -0,0 +1,56 @@ +package forestry.core.gui; + +import forestry.core.tiles.ILiquidTankTile; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.fluids.IFluidTank; + +import javax.annotation.Nullable; + +public abstract class LiquidTanksMenu extends TileMenu implements IContainerLiquidTanks { + private final ContainerLiquidTanksHelper helper; + + protected LiquidTanksMenu(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { + super(windowId, type, playerInventory, tile, xInv, yInv); + + this.helper = new ContainerLiquidTanksHelper<>(tile); + + if (this.player != null) { + this.tile.getTankManager().sendAllTanks(this, this.player); + } + } + + @Override + public void handlePipetteClickClient(int slot, Player player) { + this.helper.handlePipetteClickClient(slot, player); + } + + @Override + public void handlePipetteClick(int slot, ServerPlayer player) { + this.helper.handlePipetteClick(slot, player); + } + + @Override + public void broadcastChanges() { + super.broadcastChanges(); + + if (this.player != null) { + this.tile.getTankManager().broadcastChanges(this, this.player); + } + } + + @Override + public void removed(Player player) { + super.removed(player); + this.tile.getTankManager().onClosed(this); + } + + @Nullable + @Override + public IFluidTank getTank(int slot) { + return this.tile.getTankManager().getTank(slot); + } +} diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java b/src/main/java/forestry/core/gui/LiquidTanksSocketedMenu.java similarity index 69% rename from src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java rename to src/main/java/forestry/core/gui/LiquidTanksSocketedMenu.java index f17dc8e702..fb2f65a80c 100644 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanksSocketed.java +++ b/src/main/java/forestry/core/gui/LiquidTanksSocketedMenu.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import forestry.core.circuits.ISocketable; @@ -18,17 +8,17 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.IFluidTank; import javax.annotation.Nullable; -public abstract class ContainerLiquidTanksSocketed extends ContainerTile implements IContainerSocketed, IContainerLiquidTanks { +public abstract class LiquidTanksSocketedMenu extends TileMenu implements IContainerSocketed, IContainerLiquidTanks { private final ContainerSocketedHelper socketedHelper; private final ContainerLiquidTanksHelper tanksHelper; - protected ContainerLiquidTanksSocketed(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { + protected LiquidTanksSocketedMenu(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { super(windowId, type, playerInventory, tile, xInv, yInv); this.socketedHelper = new ContainerSocketedHelper<>(this.tile); this.tanksHelper = new ContainerLiquidTanksHelper<>(this.tile); diff --git a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java b/src/main/java/forestry/core/gui/NaturalistInventoryMenu.java old mode 100755 new mode 100644 similarity index 69% rename from src/main/java/forestry/core/gui/ContainerNaturalistInventory.java rename to src/main/java/forestry/core/gui/NaturalistInventoryMenu.java index 94c11d6abb..e2531fbac3 --- a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/NaturalistInventoryMenu.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import forestry.api.genetics.ISpeciesType; @@ -24,19 +14,19 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ContainerListener; -public class ContainerNaturalistInventory extends ContainerTile implements IGuiSelectable, INaturalistMenu { +public class NaturalistInventoryMenu extends TileMenu implements IGuiSelectable, INaturalistMenu { public static final int MAX_PAGE = 5; private final int page; public boolean closing = true; - public ContainerNaturalistInventory(int windowId, Inventory player, TileNaturalistChest tile, int page) { + public NaturalistInventoryMenu(int windowId, Inventory player, TileNaturalistChest tile, int page) { super(windowId, CoreMenuTypes.NATURALIST_INVENTORY.menuType(), player, tile, 18, 120); this.page = page; addInventory(this, tile, page); } - public static void addInventory(ContainerForestry container, T inventory, int selectedPage) { + public static void addInventory(ForestryMenu container, T inventory, int selectedPage) { int page = Mth.clamp(selectedPage, 0, MAX_PAGE); for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { @@ -47,9 +37,9 @@ public static void addInventory(Cont } } - public static ContainerNaturalistInventory fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { + public static NaturalistInventoryMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { TileNaturalistChest tile = TileUtil.getTile(playerInv.player.level(), extraData.readBlockPos(), TileNaturalistChest.class); - return new ContainerNaturalistInventory(windowId, playerInv, tile, extraData.readVarInt()); + return new NaturalistInventoryMenu(windowId, playerInv, tile, extraData.readVarInt()); } @Override diff --git a/src/main/java/forestry/core/gui/PortableAnalyzerMenu.java b/src/main/java/forestry/core/gui/PortableAnalyzerMenu.java new file mode 100644 index 0000000000..befa7e686c --- /dev/null +++ b/src/main/java/forestry/core/gui/PortableAnalyzerMenu.java @@ -0,0 +1,34 @@ +package forestry.core.gui; + +import forestry.core.features.CoreMenuTypes; +import forestry.core.gui.slots.SlotFiltered; +import forestry.core.inventory.PortableAnalyzerInventory; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; + +public class PortableAnalyzerMenu extends ForestryMenu { + public static PortableAnalyzerMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { + InteractionHand hand = extraData.readBoolean() ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; + Player player = playerInv.player; + PortableAnalyzerInventory inv = new PortableAnalyzerInventory(player, player.getItemInHand(hand)); + return new PortableAnalyzerMenu(windowId, inv, player); + } + + public PortableAnalyzerMenu(int windowId, Inventory playerInv, int slotIndex) { + super(CoreMenuTypes.ALYZER.menuType(), windowId, inventory, playerInv, 43, 156); + + int xPosLeftSlots = 223; + + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_ENERGY, xPosLeftSlots, 8)); + + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_SPECIMEN, xPosLeftSlots, 26)); + + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_ANALYZE_1, xPosLeftSlots, 57)); + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_ANALYZE_2, xPosLeftSlots, 75)); + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_ANALYZE_3, xPosLeftSlots, 93)); + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_ANALYZE_4, xPosLeftSlots, 111)); + addSlot(new SlotFiltered(inventory, PortableAnalyzerInventory.SLOT_ANALYZE_5, xPosLeftSlots, 129)); + } +} diff --git a/src/main/java/forestry/core/gui/GuiAlyzer.java b/src/main/java/forestry/core/gui/PortableAnalyzerScreen.java old mode 100755 new mode 100644 similarity index 86% rename from src/main/java/forestry/core/gui/GuiAlyzer.java rename to src/main/java/forestry/core/gui/PortableAnalyzerScreen.java index d397a311c8..87b4cc6413 --- a/src/main/java/forestry/core/gui/GuiAlyzer.java +++ b/src/main/java/forestry/core/gui/PortableAnalyzerScreen.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import com.mojang.blaze3d.systems.RenderSystem; @@ -19,7 +9,7 @@ import forestry.core.genetics.mutations.EnumMutateChance; import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.WidgetManager; -import forestry.core.inventory.ItemInventoryAlyzer; +import forestry.core.inventory.PortableAnalyzerInventory; import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; import net.minecraft.client.Minecraft; @@ -36,15 +26,15 @@ import java.util.Map; // Portable analyzer -public class GuiAlyzer extends GuiForestry { +public class PortableAnalyzerScreen extends GuiForestry { public static final int COLUMN_0 = 12; public static final int COLUMN_1 = 90; public static final int COLUMN_2 = 155; - private final ItemInventoryAlyzer itemInventory; + private final PortableAnalyzerInventory itemInventory; - public GuiAlyzer(ContainerAlyzer container, Inventory playerInv, Component name) { - super(Constants.TEXTURE_PATH_GUI + "/portablealyzer.png", container, playerInv, Component.literal("GUI_ALYZER_TEST_TITLE")); + public PortableAnalyzerScreen(PortableAnalyzerMenu container, Inventory playerInv, Component name) { + super(Constants.TEXTURE_PATH_GUI + "/portablealyzer.png", container, playerInv, name); this.itemInventory = container.inventory; this.imageWidth = 247; @@ -59,7 +49,7 @@ public static int getColorCoding(boolean dominant) { } } - public final void drawLine(GuiGraphics graphics, String text, int x, IIndividual individual, IChromosome chromosome, boolean inactive) { + public void drawLine(GuiGraphics graphics, String text, int x, IIndividual individual, IChromosome chromosome, boolean inactive) { if (!inactive) { this.textLayout.drawLine(graphics, text, x, getColorCoding(individual.getGenome().getActiveAllele(chromosome).dominant())); } else { @@ -67,7 +57,7 @@ public final void drawLine(GuiGraphics graphics, String text, int x, IIndividual } } - public final void drawSplitLine(GuiGraphics graphics, Component component, int x, int maxWidth, IIndividual individual, IChromosome chromosome, boolean inactive) { + public void drawSplitLine(GuiGraphics graphics, Component component, int x, int maxWidth, IIndividual individual, IChromosome chromosome, boolean inactive) { if (!inactive) { this.textLayout.drawSplitLine(graphics, component, x, maxWidth, getColorCoding(individual.getGenome().getActiveAllele(chromosome).dominant())); } else { @@ -75,12 +65,12 @@ public final void drawSplitLine(GuiGraphics graphics, Component component, int x } } - public final void drawRow(GuiGraphics graphics, Component text0, Component text1, Component text2, IIndividual individual, IChromosome chromosome) { + public void drawRow(GuiGraphics graphics, Component text0, Component text1, Component text2, IIndividual individual, IChromosome chromosome) { this.textLayout.drawRow(graphics, text0, text1, text2, ColourProperties.INSTANCE.get("gui.screen"), getColorCoding(individual.getGenome().getActiveAllele(chromosome).dominant()), getColorCoding(individual.getGenome().getInactiveAllele(chromosome).dominant())); } - public final void drawChromosomeRow(GuiGraphics graphics, IIndividual individual, IChromosome chromosome) { + public void drawChromosomeRow(GuiGraphics graphics, IIndividual individual, IChromosome chromosome) { IAllele active = individual.getGenome().getActiveAllele(chromosome); MutableComponent activeName = chromosome.getDisplayName(active.cast()); IAllele inactive = individual.getGenome().getInactiveAllele(chromosome); @@ -88,20 +78,20 @@ public final void drawChromosomeRow(GuiGraphics graphics, IIndividual individual this.textLayout.drawRow(graphics, chromosome.getChromosomeDisplayName(), activeName, inactiveName, ColourProperties.INSTANCE.get("gui.screen"), getColorCoding(active.dominant()), getColorCoding(inactive.dominant())); } - public final void drawHaploidChromosomeRow(GuiGraphics graphics, IIndividual individual, IChromosome chromosome) { + public void drawHaploidChromosomeRow(GuiGraphics graphics, IIndividual individual, IChromosome chromosome) { IAllele active = individual.getGenome().getActiveAllele(chromosome); MutableComponent activeName = chromosome.getDisplayName(active.cast()); this.textLayout.drawRow(graphics, chromosome.getChromosomeDisplayName(), activeName, ColourProperties.INSTANCE.get("gui.screen"), getColorCoding(active.dominant())); } public > void drawSpeciesRow(GuiGraphics graphics, IIndividual individual, IRegistryChromosome chromosome) { - AllelePair> species = individual.getGenome().getAllelePair(chromosome); + AllelePair> species = individual.getGenome().getAllelePair(chromosome); this.textLayout.drawLine(graphics, chromosome.getChromosomeDisplayName(), this.textLayout.column0); int columnwidth = this.textLayout.column2 - this.textLayout.column1 - 2; - IValueAllele activeSpecies = species.active(); - IValueAllele inactiveSpecies = species.inactive(); + IValueAllele activeSpecies = species.active(); + IValueAllele inactiveSpecies = species.inactive(); Map, ItemStack> iconStacks = activeSpecies.value().getType().getAlyzerPlugin().getIconStacks(); @@ -119,12 +109,12 @@ public > void drawSpeciesRow(GuiGraphics graphics, IIndivi } public > void drawHaploidSpeciesRow(GuiGraphics graphics, IIndividual individual, IRegistryChromosome chromosome) { - AllelePair> species = individual.getGenome().getAllelePair(chromosome); + AllelePair> species = individual.getGenome().getAllelePair(chromosome); this.textLayout.drawLine(graphics, chromosome.getChromosomeDisplayName(), this.textLayout.column0); int columnwidth = this.textLayout.column2 - this.textLayout.column1 - 2; - IValueAllele activeSpecies = species.active(); + IValueAllele activeSpecies = species.active(); Map, ItemStack> iconStacks = activeSpecies.value().getType().getAlyzerPlugin().getIconStacks(); // todo fix Icon Stacks being empty for butterflies GuiUtil.drawItemStack(graphics, this, iconStacks.get(activeSpecies.value()), this.leftPos + this.textLayout.column1 + columnwidth - 20, this.topPos + 10); @@ -139,7 +129,7 @@ protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseX, in this.widgetManager.clear(); int specimenSlot = getSpecimenSlot(); - if (specimenSlot < ItemInventoryAlyzer.SLOT_ANALYZE_1) { + if (specimenSlot < PortableAnalyzerInventory.SLOT_ANALYZE_1) { drawAnalyticsOverview(graphics); return; } @@ -150,21 +140,21 @@ protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseX, in ISpeciesType type = individual.getType(); switch (specimenSlot) { - case ItemInventoryAlyzer.SLOT_ANALYZE_1 -> + case PortableAnalyzerInventory.SLOT_ANALYZE_1 -> type.getAlyzerPlugin().drawAnalyticsPage1(graphics, this, stackInSlot); - case ItemInventoryAlyzer.SLOT_ANALYZE_2 -> + case PortableAnalyzerInventory.SLOT_ANALYZE_2 -> type.getAlyzerPlugin().drawAnalyticsPage2(graphics, this, stackInSlot); - case ItemInventoryAlyzer.SLOT_ANALYZE_3 -> + case PortableAnalyzerInventory.SLOT_ANALYZE_3 -> type.getAlyzerPlugin().drawAnalyticsPage3(graphics, this, stackInSlot); - case ItemInventoryAlyzer.SLOT_ANALYZE_4 -> drawAnalyticsPageMutations(graphics, individual); - case ItemInventoryAlyzer.SLOT_ANALYZE_5 -> drawAnalyticsPageClassification(graphics, individual); + case PortableAnalyzerInventory.SLOT_ANALYZE_4 -> drawAnalyticsPageMutations(graphics, individual); + case PortableAnalyzerInventory.SLOT_ANALYZE_5 -> drawAnalyticsPageClassification(graphics, individual); default -> drawAnalyticsOverview(graphics); } }); } private int getSpecimenSlot() { - for (int k = ItemInventoryAlyzer.SLOT_SPECIMEN; k <= ItemInventoryAlyzer.SLOT_ANALYZE_5; k++) { + for (int k = PortableAnalyzerInventory.SLOT_SPECIMEN; k <= PortableAnalyzerInventory.SLOT_ANALYZE_5; k++) { ItemStack stackInSlot = this.itemInventory.getItem(k); if (!stackInSlot.isEmpty() && IIndividualHandlerItem.filter(stackInSlot, IIndividual::isAnalyzed)) { @@ -345,7 +335,7 @@ private void drawProbabilityArrow(GuiGraphics graphics, IMutation combination } } - public void drawToleranceInfo(GuiGraphics graphics, IValueChromosome chromosome, IValueAllele toleranceAllele, int x) { + public void drawToleranceInfo(GuiGraphics graphics, IValueChromosome chromosome, IValueAllele toleranceAllele, int x) { int textColor = getColorCoding(toleranceAllele.dominant()); ToleranceType tolerance = toleranceAllele.value(); Component text = Component.literal("(").append(chromosome.getDisplayName(toleranceAllele)).append(")"); diff --git a/src/main/java/forestry/core/gui/ContainerSocketed.java b/src/main/java/forestry/core/gui/SocketedMenu.java old mode 100755 new mode 100644 similarity index 83% rename from src/main/java/forestry/core/gui/ContainerSocketed.java rename to src/main/java/forestry/core/gui/SocketedMenu.java index 5bf7015a7b..9fd6447478 --- a/src/main/java/forestry/core/gui/ContainerSocketed.java +++ b/src/main/java/forestry/core/gui/SocketedMenu.java @@ -16,14 +16,14 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; -public abstract class ContainerSocketed extends ContainerTile implements IContainerSocketed { +public abstract class SocketedMenu extends TileMenu implements IContainerSocketed { private final ContainerSocketedHelper helper; - protected ContainerSocketed(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { + protected SocketedMenu(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { super(windowId, type, playerInventory, tile, xInv, yInv); this.helper = new ContainerSocketedHelper<>(this.tile); } diff --git a/src/main/java/forestry/core/gui/ContainerTile.java b/src/main/java/forestry/core/gui/TileMenu.java similarity index 61% rename from src/main/java/forestry/core/gui/ContainerTile.java rename to src/main/java/forestry/core/gui/TileMenu.java index d2d397993e..3ed2293031 100644 --- a/src/main/java/forestry/core/gui/ContainerTile.java +++ b/src/main/java/forestry/core/gui/TileMenu.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui; import forestry.api.core.IError; @@ -23,13 +13,13 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.Set; -public abstract class ContainerTile extends ContainerForestry { +public abstract class TileMenu extends ForestryMenu { protected final T tile; @Nullable private Set previousErrorStates; @@ -37,20 +27,20 @@ public abstract class ContainerTile extends ContainerFore private int previousWorkCounter = 0; private int previousTicksPerWorkCycle = 0; - protected ContainerTile(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { - super(windowId, type, playerInventory.player); + protected TileMenu(int windowId, MenuType type, Inventory playerInventory, T tile, int xInv, int yInv) { + super(type, windowId, playerInventory.player); addPlayerInventory(playerInventory, xInv, yInv); this.tile = tile; } @Deprecated(forRemoval = true) - protected ContainerTile(int windowId, MenuType type, T tile) { - super(windowId, type, null); + protected TileMenu(int windowId, MenuType type, T tile) { + super(type, windowId, null); this.tile = tile; } - protected ContainerTile(int windowId, MenuType type, T tile, Player player) { - super(windowId, type, player); + protected TileMenu(int windowId, MenuType type, T tile, Player player) { + super(type, windowId, player); this.tile = tile; } @@ -76,33 +66,33 @@ public void broadcastChanges() { sendPacketToListeners(packet); } - this.previousErrorStates = Set.copyOf(errorStates); + this.previousErrorStates = Set.copyOf(errorStates); } - if (this.tile instanceof IPowerHandler) { - ForestryEnergyStorage energyStorage = ((IPowerHandler) this.tile).getEnergyManager(); + if (this.tile instanceof IPowerHandler power) { + ForestryEnergyStorage energyStorage = power.getEnergyManager(); int energyManagerData = energyStorage.getEnergyStored(); if (energyManagerData != this.previousEnergyManagerData) { PacketGuiEnergy packet = new PacketGuiEnergy(this.containerId, energyManagerData); sendPacketToListeners(packet); - this.previousEnergyManagerData = energyManagerData; + this.previousEnergyManagerData = energyManagerData; } } if (this.tile instanceof TilePowered tilePowered) { boolean guiNeedsUpdate = false; - int workCounter = tilePowered.getWorkCounter(); + int workCounter = tilePowered.getStepCounter(); if (workCounter != this.previousWorkCounter) { guiNeedsUpdate = true; - this.previousWorkCounter = workCounter; + this.previousWorkCounter = workCounter; } - int ticksPerWorkCycle = tilePowered.getTicksPerWorkCycle(); + int ticksPerWorkCycle = tilePowered.getStepsPerWorkCycle(); if (ticksPerWorkCycle != this.previousTicksPerWorkCycle) { guiNeedsUpdate = true; - this.previousTicksPerWorkCycle = ticksPerWorkCycle; + this.previousTicksPerWorkCycle = ticksPerWorkCycle; } if (guiNeedsUpdate) { diff --git a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java deleted file mode 100755 index a42390b894..0000000000 --- a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.buttons; - -import com.mojang.blaze3d.systems.RenderSystem; -import forestry.api.ForestryConstants; -import forestry.core.config.Constants; -import forestry.core.utils.RenderUtil; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Button; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.Mth; - -public class GuiBetterButton extends Button { - public static final ResourceLocation TEXTURE = ForestryConstants.forestry(Constants.TEXTURE_PATH_GUI + "/buttons.png"); - - protected final IButtonTextureSet texture; - - public GuiBetterButton(int x, int y, IButtonTextureSet texture, OnPress handler) { - super(x, y, texture.getWidth(), texture.getHeight(), Component.empty(), handler, DEFAULT_NARRATION); - this.texture = texture; - } - - @Override - public void renderWidget(GuiGraphics graphics, int mX, int mY, float partialTick) { - int xOffset = this.texture.getX(); - int yOffset = this.texture.getY(); - int h = this.height; - int w = this.width; - - // VANILLA COPY EXCEPT FOR TEXTURE AND COORDINATES - Minecraft minecraft = Minecraft.getInstance(); - graphics.setColor(1.0F, 1.0F, 1.0F, this.alpha); - RenderSystem.enableBlend(); - RenderSystem.enableDepthTest(); - graphics.blit(TEXTURE, getX(), getY(), xOffset, yOffset + RenderUtil.getYImage(this) * h, w, h); - graphics.setColor(1.0F, 1.0F, 1.0F, 1.0F); - int i = getFGColor(); - this.renderString(graphics, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24); - } -} diff --git a/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java b/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java deleted file mode 100755 index 6c733f8a08..0000000000 --- a/src/main/java/forestry/core/gui/buttons/IButtonTextureSet.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.buttons; - -import net.minecraft.resources.ResourceLocation; - -public interface IButtonTextureSet { - int getX(); - - int getY(); - - int getHeight(); - - int getWidth(); - - ResourceLocation getTexture(); -} diff --git a/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java b/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java deleted file mode 100755 index df56f81080..0000000000 --- a/src/main/java/forestry/core/gui/buttons/StandardButtonTextureSets.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.gui.buttons; - -import net.minecraft.resources.ResourceLocation; - -public enum StandardButtonTextureSets implements IButtonTextureSet { - LARGE_BUTTON(0, 0, 20, 200), - SMALL_BUTTON(0, 80, 15, 200), - LOCKED_BUTTON(224, 0, 16, 16), - UNLOCKED_BUTTON(240, 0, 16, 16), - SMALL_BLANK_BUTTON(208, 48, 16, 16), - ARROW_DOWN_BUTTON(224, 48, 16, 16), - ARROW_UP_BUTTON(240, 48, 16, 16), - DOWN_BUTTON(224, 96, 10, 16), - UP_BUTTON(240, 96, 10, 16), - LEFT_BUTTON(204, 0, 16, 10), - RIGHT_BUTTON(214, 0, 16, 10), - LEFT_BUTTON_SMALL(238, 220, 12, 9), - RIGHT_BUTTON_SMALL(247, 220, 12, 9); - private final int x, y, height, width; - - StandardButtonTextureSets(int x, int y, int height, int width) { - this.x = x; - this.y = y; - this.height = height; - this.width = width; - } - - @Override - public int getX() { - return this.x; - } - - @Override - public int getY() { - return this.y; - } - - @Override - public int getHeight() { - return this.height; - } - - @Override - public int getWidth() { - return this.width; - } - - @Override - public ResourceLocation getTexture() { - return GuiBetterButton.TEXTURE; - } -} diff --git a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java index 4b064b03e4..e2fd2950b9 100755 --- a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java +++ b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java @@ -20,8 +20,8 @@ import forestry.core.gui.GuiUtil; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.Rect2i; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.ArrayList; diff --git a/src/main/java/forestry/core/gui/ledgers/package-info.java b/src/main/java/forestry/core/gui/ledgers/package-info.java index 75cacf77fd..6876e61f81 100644 --- a/src/main/java/forestry/core/gui/ledgers/package-info.java +++ b/src/main/java/forestry/core/gui/ledgers/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.gui.ledgers; diff --git a/src/main/java/forestry/core/gui/package-info.java b/src/main/java/forestry/core/gui/package-info.java index 9c3bdc292d..95dfb4d32b 100644 --- a/src/main/java/forestry/core/gui/package-info.java +++ b/src/main/java/forestry/core/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.gui; diff --git a/src/main/java/forestry/core/gui/slots/SlotForestry.java b/src/main/java/forestry/core/gui/slots/SlotForestry.java index 37159c1269..c7e9e961ae 100755 --- a/src/main/java/forestry/core/gui/slots/SlotForestry.java +++ b/src/main/java/forestry/core/gui/slots/SlotForestry.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui.slots; import forestry.api.core.tooltips.IToolTipProvider; @@ -20,7 +10,6 @@ import javax.annotation.Nullable; public class SlotForestry extends Slot implements IToolTipProvider { - private boolean isPhantom; private boolean canAdjustPhantom = true; private boolean canShift = true; diff --git a/src/main/java/forestry/core/gui/slots/SlotLocked.java b/src/main/java/forestry/core/gui/slots/SlotLocked.java index be359a9158..2db6cd1fbc 100755 --- a/src/main/java/forestry/core/gui/slots/SlotLocked.java +++ b/src/main/java/forestry/core/gui/slots/SlotLocked.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui.slots; import net.minecraft.world.Container; @@ -15,7 +5,6 @@ import net.minecraft.world.item.ItemStack; public class SlotLocked extends SlotForestry { - public SlotLocked(Container inventory, int slotIndex, int xPos, int yPos) { super(inventory, slotIndex, xPos, yPos); setCanAdjustPhantom(false); diff --git a/src/main/java/forestry/core/gui/slots/WorktableSlot.java b/src/main/java/forestry/core/gui/slots/WorktableSlot.java index 27416cb647..2798eae11e 100644 --- a/src/main/java/forestry/core/gui/slots/WorktableSlot.java +++ b/src/main/java/forestry/core/gui/slots/WorktableSlot.java @@ -4,7 +4,7 @@ import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.CraftingContainer; -import net.minecraft.world.inventory.RecipeHolder; +import net.minecraft.world.inventory.RecipeCraftingHolder; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; @@ -39,10 +39,10 @@ protected void onQuickCraft(ItemStack pStack, int pAmount) { protected void checkTakeAchievements(ItemStack stack) { if (this.amountCrafted > 0) { stack.onCraftedBy(this.player.level(), this.player, this.amountCrafted); - net.minecraftforge.event.ForgeEventFactory.firePlayerCraftingEvent(this.player, stack, this.craftMatrix); + net.neoforged.neoforge.event.EventHooks.firePlayerCraftingEvent(this.player, stack, this.craftMatrix); } - if (this.container instanceof RecipeHolder holder) { + if (this.container instanceof RecipeCraftingHolder holder) { holder.awardUsedRecipes(this.player, this.craftMatrix.getItems()); } diff --git a/src/main/java/forestry/core/gui/slots/package-info.java b/src/main/java/forestry/core/gui/slots/package-info.java index 3ce0aa75db..41dce8887f 100644 --- a/src/main/java/forestry/core/gui/slots/package-info.java +++ b/src/main/java/forestry/core/gui/slots/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.gui.slots; diff --git a/src/main/java/forestry/core/gui/widgets/ArrowButton.java b/src/main/java/forestry/core/gui/widgets/ArrowButton.java new file mode 100644 index 0000000000..a543284f61 --- /dev/null +++ b/src/main/java/forestry/core/gui/widgets/ArrowButton.java @@ -0,0 +1,46 @@ +package forestry.core.gui.widgets; + +import com.mojang.blaze3d.systems.RenderSystem; +import forestry.api.ForestryConstants; +import forestry.core.config.Constants; +import forestry.core.utils.RenderUtil; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.Mth; + +public class ArrowButton extends Button { + private static final ResourceLocation TEXTURE = ForestryConstants.forestry(Constants.TEXTURE_PATH_GUI + "/buttons.png"); + + protected final Texture texture; + + public ArrowButton(int x, int y, Texture texture, OnPress handler) { + super(x, y, texture.width(), texture.height(), Component.empty(), handler, DEFAULT_NARRATION); + this.texture = texture; + } + + @Override + public void renderWidget(GuiGraphics graphics, int mX, int mY, float partialTick) { + int xOffset = this.texture.x(); + int yOffset = this.texture.y(); + int h = this.height; + int w = this.width; + + // VANILLA COPY EXCEPT FOR TEXTURE AND COORDINATES + Minecraft minecraft = Minecraft.getInstance(); + graphics.setColor(1.0F, 1.0F, 1.0F, this.alpha); + RenderSystem.enableBlend(); + RenderSystem.enableDepthTest(); + graphics.blit(TEXTURE, getX(), getY(), xOffset, yOffset + RenderUtil.getYImage(this) * h, w, h); + graphics.setColor(1.0F, 1.0F, 1.0F, 1.0F); + int i = getFGColor(); + this.renderString(graphics, minecraft.font, i | Mth.ceil(this.alpha * 255.0F) << 24); + } + + public record Texture(int x, int y, int height, int width) { + public static final Texture LEFT_BUTTON_SMALL = new Texture(238, 220, 12, 9); + public static final Texture RIGHT_BUTTON_SMALL = new Texture(247, 220, 12, 9); + } +} diff --git a/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java b/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java index 4abe5cab35..3078402711 100644 --- a/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java +++ b/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java @@ -1,30 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui.widgets; import com.mojang.blaze3d.systems.RenderSystem; import forestry.api.client.ForestrySprites; import forestry.api.client.IForestryClientApi; import forestry.api.core.tooltips.ToolTip; +import forestry.api.modules.IForestryPacketServer; import forestry.core.gui.GuiUtil; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.tiles.EscritoireGame; import forestry.core.tiles.EscritoireGameToken; -import forestry.core.utils.NetworkUtil; import forestry.core.utils.SoundUtil; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; @@ -98,7 +89,8 @@ public ToolTip getToolTip(int mouseX, int mouseY) { @Override public void handleMouseClick(double mouseX, double mouseY, int mouseButton) { this.game.choose(this.index); - NetworkUtil.sendToServer(new PacketGuiSelectRequest(this.index, 0)); - SoundUtil.playButtonClick(); + IForestryPacketServer packet = new PacketGuiSelectRequest(this.index, 0); + PacketDistributor.sendToServer(packet); + SoundUtil.playButtonClick(); } } diff --git a/src/main/java/forestry/core/gui/widgets/IScrollable.java b/src/main/java/forestry/core/gui/widgets/IScrollable.java index 2e23d912d9..d4b376134d 100644 --- a/src/main/java/forestry/core/gui/widgets/IScrollable.java +++ b/src/main/java/forestry/core/gui/widgets/IScrollable.java @@ -1,7 +1,6 @@ package forestry.core.gui.widgets; public interface IScrollable { - void onScroll(int value); /** diff --git a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java index ef0a48c037..7239013bb5 100755 --- a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java +++ b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui.widgets; import forestry.api.core.tooltips.ToolTip; @@ -15,8 +5,6 @@ import forestry.core.utils.ItemTooltipUtil; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; public abstract class ItemStackWidgetBase extends Widget { public ItemStackWidgetBase(WidgetManager widgetManager, int xPos, int yPos) { @@ -33,13 +21,12 @@ public void draw(GuiGraphics graphics, int startX, int startY) { } } - @OnlyIn(Dist.CLIENT) @Override public ToolTip getToolTip(int mouseX, int mouseY) { - ItemStack itemStack = getItemStack(); + ItemStack stack = getItemStack(); ToolTip tip = new ToolTip(); - if (!itemStack.isEmpty()) { - tip.addAll(ItemTooltipUtil.getInformation(itemStack)); + if (!stack.isEmpty()) { + tip.addAll(ItemTooltipUtil.getInformation(stack)); } return tip; } diff --git a/src/main/java/forestry/core/gui/widgets/ProbeButton.java b/src/main/java/forestry/core/gui/widgets/ProbeButton.java index 29a3fa64d7..46bdcb9e65 100644 --- a/src/main/java/forestry/core/gui/widgets/ProbeButton.java +++ b/src/main/java/forestry/core/gui/widgets/ProbeButton.java @@ -11,12 +11,13 @@ package forestry.core.gui.widgets; import forestry.api.core.tooltips.ToolTip; +import forestry.api.modules.IForestryPacketServer; import forestry.core.gui.GuiEscritoire; import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.utils.NetworkUtil; import forestry.core.utils.SoundUtil; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; +import net.neoforged.neoforge.network.PacketDistributor; public class ProbeButton extends Widget { @@ -46,8 +47,9 @@ public ToolTip getToolTip(int mouseX, int mouseY) { @Override public void handleMouseClick(double mouseX, double mouseY, int mouseButton) { this.pressed = true; - NetworkUtil.sendToServer(new PacketGuiSelectRequest(-1, 0)); - SoundUtil.playButtonClick(); + IForestryPacketServer packet = new PacketGuiSelectRequest(-1, 0); + PacketDistributor.sendToServer(packet); + SoundUtil.playButtonClick(); } @Override diff --git a/src/main/java/forestry/core/gui/widgets/SocketWidget.java b/src/main/java/forestry/core/gui/widgets/SocketWidget.java index 1b31f56a7a..dcbef76f1b 100755 --- a/src/main/java/forestry/core/gui/widgets/SocketWidget.java +++ b/src/main/java/forestry/core/gui/widgets/SocketWidget.java @@ -1,21 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui.widgets; import forestry.api.core.tooltips.ToolTip; import forestry.core.circuits.ISocketable; -import forestry.core.circuits.ISolderingIron; import forestry.core.circuits.ItemCircuitBoard; import forestry.core.gui.GuiUtil; import forestry.core.gui.IContainerSocketed; +import forestry.core.items.ItemSolderingIron; import forestry.core.utils.ItemTooltipUtil; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; @@ -24,9 +14,6 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import org.lwjgl.glfw.GLFW; public class SocketWidget extends Widget { @@ -47,7 +34,6 @@ public void draw(GuiGraphics graphics, int startX, int startY) { } } - @OnlyIn(Dist.CLIENT) @Override public ToolTip getToolTip(int mouseX, int mouseY) { return this.toolTip; @@ -55,7 +41,6 @@ public ToolTip getToolTip(int mouseX, int mouseY) { private final ToolTip toolTip = new ToolTip(250) { @Override - @OnlyIn(Dist.CLIENT) public void refresh() { SocketWidget.this.toolTip.clear(); ItemStack stack = SocketWidget.this.tile.getSocket(SocketWidget.this.slot); @@ -73,9 +58,6 @@ public void handleMouseClick(double mouseX, double mouseY, int mouseButton) { ItemStack itemstack = Minecraft.getInstance().player.containerMenu.getCarried(); if (itemstack.isEmpty()) { - if (mouseButton == GLFW.GLFW_MOUSE_BUTTON_MIDDLE) { - - } return; } @@ -89,7 +71,7 @@ public void handleMouseClick(double mouseX, double mouseY, int mouseButton) { // Insert chipsets if (held instanceof ItemCircuitBoard) { containerSocketed.handleChipsetClick(this.slot); - } else if (held instanceof ISolderingIron) { + } else if (held instanceof ItemSolderingIron) { containerSocketed.handleSolderingIronClick(this.slot); } } diff --git a/src/main/java/forestry/core/gui/widgets/TankWidget.java b/src/main/java/forestry/core/gui/widgets/TankWidget.java index a867a667b0..d83b7441f4 100755 --- a/src/main/java/forestry/core/gui/widgets/TankWidget.java +++ b/src/main/java/forestry/core/gui/widgets/TankWidget.java @@ -1,26 +1,13 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.gui.widgets; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.Tesselator; -import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.*; import forestry.api.core.IToolPipette; import forestry.api.core.tooltips.ToolTip; import forestry.core.fluids.StandardTank; import forestry.core.gui.IContainerLiquidTanks; import forestry.core.utils.ResourceUtil; -import forestry.farming.gui.ContainerFarm; +import forestry.farming.gui.FarmMenu; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.GameRenderer; @@ -33,11 +20,11 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; import org.joml.Matrix4f; import javax.annotation.Nullable; @@ -60,8 +47,8 @@ public TankWidget(WidgetManager manager, int xPos, int yPos, int slot) { } public TankWidget setOverlayOrigin(int x, int y) { - this.overlayTexX = x; - this.overlayTexY = y; + this.overlayTexX = x; + this.overlayTexY = y; return this; } @@ -70,7 +57,7 @@ public IFluidTank getTank() { AbstractContainerMenu container = this.manager.gui.getMenu(); if (container instanceof IContainerLiquidTanks tanks) { return tanks.getTank(this.slot); - } else if (container instanceof ContainerFarm farm) { + } else if (container instanceof FarmMenu farm) { return farm.getTank(this.slot); } return null; @@ -179,13 +166,12 @@ private static void drawFluidTexture(Matrix4f matrix, float xCoord, float yCoord vMax = vMax - maskTop / 16.0F * (vMax - vMin); Tesselator tessellator = Tesselator.getInstance(); - BufferBuilder buffer = tessellator.getBuilder(); - buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); - buffer.vertex(matrix, xCoord, yCoord + 16, zLevel).uv(uMin, vMax).endVertex(); - buffer.vertex(matrix, xCoord + 16 - maskRight, yCoord + 16, zLevel).uv(uMax, vMax).endVertex(); - buffer.vertex(matrix, xCoord + 16 - maskRight, yCoord + maskTop, zLevel).uv(uMax, vMin).endVertex(); - buffer.vertex(matrix, xCoord, yCoord + maskTop, zLevel).uv(uMin, vMin).endVertex(); - tessellator.end(); + BufferBuilder buffer = tessellator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); + buffer.addVertex(matrix, xCoord, yCoord + 16, zLevel).setUv(uMin, vMax); + buffer.addVertex(matrix, xCoord + 16 - maskRight, yCoord + 16, zLevel).setUv(uMax, vMax); + buffer.addVertex(matrix, xCoord + 16 - maskRight, yCoord + maskTop, zLevel).setUv(uMax, vMin); + buffer.addVertex(matrix, xCoord, yCoord + maskTop, zLevel).setUv(uMin, vMin); + BufferUploader.drawWithShader(buffer.buildOrThrow()); } @Override diff --git a/src/main/java/forestry/core/gui/widgets/package-info.java b/src/main/java/forestry/core/gui/widgets/package-info.java index 778ee36206..9760b0c90b 100644 --- a/src/main/java/forestry/core/gui/widgets/package-info.java +++ b/src/main/java/forestry/core/gui/widgets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.gui.widgets; diff --git a/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java b/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java index 9f55b12376..4eb114d45b 100644 --- a/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java +++ b/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java @@ -1,33 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.core.tiles.AdjacentTileCache; import forestry.core.tiles.TileUtil; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; import javax.annotation.Nullable; import java.util.*; +import java.util.function.Predicate; -/** - * @author CovertJaguar - */ public final class AdjacentInventoryCache implements AdjacentTileCache.ICacheListener { - - public interface ITileFilter { - boolean matches(BlockEntity tile); - } - private final AdjacentTileCache cache; private boolean changed = true; private final List invs = new LinkedList<>(); @@ -35,17 +18,17 @@ public interface ITileFilter { @Nullable private final Comparator sorter; @Nullable - private final ITileFilter filter; + private final Predicate filter; public AdjacentInventoryCache(BlockEntity tile, AdjacentTileCache cache) { this(tile, cache, null, null); } - public AdjacentInventoryCache(BlockEntity tile, AdjacentTileCache cache, @Nullable ITileFilter filter) { + public AdjacentInventoryCache(BlockEntity tile, AdjacentTileCache cache, @Nullable Predicate filter) { this(tile, cache, filter, null); } - public AdjacentInventoryCache(BlockEntity tile, AdjacentTileCache cache, @Nullable ITileFilter filter, @Nullable Comparator sorter) { + public AdjacentInventoryCache(BlockEntity tile, AdjacentTileCache cache, @Nullable Predicate filter, @Nullable Comparator sorter) { this.cache = cache; this.filter = filter; this.sorter = sorter; @@ -72,34 +55,33 @@ public Collection getAdjacentInventoriesOtherThan(Direction side) @Override public void changed() { - this.changed = true; + this.changed = true; } @Override public void purge() { - this.invs.clear(); + this.invs.clear(); Arrays.fill(this.sides, null); } private void checkChanged() { - this.cache.refresh(); + this.cache.refresh(); if (this.changed) { - this.changed = false; + this.changed = false; purge(); - for (Direction side : Direction.values()) { + for (Direction side : Direction.VALUES) { BlockEntity tile = this.cache.getTileOnSide(side); - if (tile != null && (this.filter == null || this.filter.matches(tile))) { + if (tile != null && (this.filter == null || this.filter.test(tile))) { IItemHandler inv = TileUtil.getInventoryFromTile(tile, side.getOpposite()); if (inv != null) { - this.sides[side.ordinal()] = inv; - this.invs.add(inv); + this.sides[side.ordinal()] = inv; + this.invs.add(inv); } } } if (this.sorter != null) { - this.invs.sort(this.sorter); + this.invs.sort(this.sorter); } } } - } diff --git a/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java b/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java index 566e396500..e186a5f11a 100644 --- a/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java @@ -1,17 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.core.config.Constants; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -101,11 +92,11 @@ public boolean canPlaceItem(int p_94041_1_, ItemStack p_94041_2_) { } @Override - public void read(CompoundTag CompoundNBT) { + public void read(CompoundTag CompoundNBT, HolderLookup.Provider registries) { } @Override - public CompoundTag write(CompoundTag CompoundNBT) { + public CompoundTag write(CompoundTag CompoundNBT, HolderLookup.Provider registries) { return CompoundNBT; } diff --git a/src/main/java/forestry/core/inventory/IInvSlot.java b/src/main/java/forestry/core/inventory/IInvSlot.java index 5e23f46204..24c23593c0 100644 --- a/src/main/java/forestry/core/inventory/IInvSlot.java +++ b/src/main/java/forestry/core/inventory/IInvSlot.java @@ -1,24 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import net.minecraft.world.item.ItemStack; /** * This Interface represents an abstract inventory slot. It provides a unified interface for interfacing with Inventories. - * - * @author CovertJaguar */ public interface IInvSlot { - boolean canPutStackInSlot(ItemStack stack); boolean canTakeStackFromSlot(ItemStack stack); @@ -30,8 +17,6 @@ public interface IInvSlot { */ ItemStack getStackInSlot(); - // void setStackInSlot(ItemStack stack); - int getIndex(); } diff --git a/src/main/java/forestry/core/inventory/IInventoryAdapter.java b/src/main/java/forestry/core/inventory/IInventoryAdapter.java index 857b5563c1..753ed3442f 100644 --- a/src/main/java/forestry/core/inventory/IInventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/IInventoryAdapter.java @@ -6,5 +6,4 @@ import net.minecraft.world.WorldlyContainer; public interface IInventoryAdapter extends WorldlyContainer, IFilterSlotDelegate, INbtWritable, INbtReadable { - } diff --git a/src/main/java/forestry/core/inventory/InvIterator.java b/src/main/java/forestry/core/inventory/InvIterator.java index 5b2be12538..10ee8fd004 100644 --- a/src/main/java/forestry/core/inventory/InvIterator.java +++ b/src/main/java/forestry/core/inventory/InvIterator.java @@ -1,6 +1,6 @@ package forestry.core.inventory; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; import java.util.Iterator; import java.util.NoSuchElementException; diff --git a/src/main/java/forestry/core/inventory/InvSlot.java b/src/main/java/forestry/core/inventory/InvSlot.java index 26d40eb2e6..67576ae1a9 100644 --- a/src/main/java/forestry/core/inventory/InvSlot.java +++ b/src/main/java/forestry/core/inventory/InvSlot.java @@ -1,10 +1,9 @@ package forestry.core.inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; public class InvSlot implements IInvSlot { - private final IItemHandler inv; protected final int slot; diff --git a/src/main/java/forestry/core/inventory/InventoryAdapter.java b/src/main/java/forestry/core/inventory/InventoryAdapter.java index d7144ebbc1..755bd532f4 100755 --- a/src/main/java/forestry/core/inventory/InventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapter.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.core.config.Constants; @@ -15,8 +5,9 @@ import forestry.core.utils.InventoryUtil; import forestry.core.utils.NetworkUtil; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -26,7 +17,6 @@ * With permission from Krapht. */ public class InventoryAdapter implements IInventoryAdapter, IStreamable { - private final InventoryPlain inventory; private boolean allowAutomation = true; @Nullable @@ -126,7 +116,6 @@ public boolean isLocked(int slotIndex) { return false; } - /* ISIDEDINVENTORY */ @Override public int[] getSlotsForFace(Direction side) { if (this.allowAutomation && this.slotMap != null) { @@ -155,24 +144,24 @@ public boolean canTakeItemThroughFace(int slot, ItemStack stack, Direction side) /* SAVING & LOADING */ @Override - public void read(CompoundTag compoundNBT) { + public void read(CompoundTag compoundNBT, HolderLookup.Provider registries) { InventoryUtil.readFromNBT(this, this.inventory.getName(), compoundNBT); } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { InventoryUtil.writeToNBT(this, this.inventory.getName(), compoundNBT); return compoundNBT; } @Override - public void writeData(FriendlyByteBuf data) { - NetworkUtil.writeInventory(data, this.inventory); + public void writeData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.writeInventory(buffer, this.inventory); } @Override - public void readData(FriendlyByteBuf data) { - NetworkUtil.readInventory(data, this.inventory); + public void readData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.readInventory(buffer, this.inventory); } /* FIELDS */ diff --git a/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java b/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java index c0e7ed27b7..038a36b6d0 100644 --- a/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import net.minecraft.core.Direction; diff --git a/src/main/java/forestry/core/inventory/InventoryAdapterTile.java b/src/main/java/forestry/core/inventory/InventoryAdapterTile.java index 823c050955..f7e11b8562 100644 --- a/src/main/java/forestry/core/inventory/InventoryAdapterTile.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapterTile.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import net.minecraft.core.Direction; diff --git a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java index 3a6573fef3..d6e8043545 100644 --- a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java +++ b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.api.genetics.capability.IIndividualHandlerItem; @@ -17,8 +7,8 @@ import forestry.core.utils.SpeciesUtil; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.Optional; diff --git a/src/main/java/forestry/core/inventory/InventoryEscritoire.java b/src/main/java/forestry/core/inventory/InventoryEscritoire.java index 22b8d35b82..e3e47d8157 100644 --- a/src/main/java/forestry/core/inventory/InventoryEscritoire.java +++ b/src/main/java/forestry/core/inventory/InventoryEscritoire.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.api.genetics.IIndividual; diff --git a/src/main/java/forestry/core/inventory/InventoryGhostCrafting.java b/src/main/java/forestry/core/inventory/InventoryGhostCrafting.java index da42268339..99849564d7 100644 --- a/src/main/java/forestry/core/inventory/InventoryGhostCrafting.java +++ b/src/main/java/forestry/core/inventory/InventoryGhostCrafting.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import net.minecraft.world.level.block.entity.BlockEntity; diff --git a/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java b/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java index e42a67bb76..492632a051 100644 --- a/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java +++ b/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.api.genetics.ISpeciesType; @@ -16,9 +6,9 @@ import net.minecraft.world.item.ItemStack; public class InventoryNaturalistChest extends InventoryAdapterTile { - private final ISpeciesType speciesRoot; + private final ISpeciesType speciesRoot; - public InventoryNaturalistChest(TileNaturalistChest tile, ISpeciesType speciesRoot) { + public InventoryNaturalistChest(TileNaturalistChest tile, ISpeciesType speciesRoot) { super(tile, 125, "Items"); this.speciesRoot = speciesRoot; } diff --git a/src/main/java/forestry/core/inventory/InventoryPlain.java b/src/main/java/forestry/core/inventory/InventoryPlain.java index 8c5dd70d81..c8a6809382 100644 --- a/src/main/java/forestry/core/inventory/InventoryPlain.java +++ b/src/main/java/forestry/core/inventory/InventoryPlain.java @@ -1,34 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.core.utils.InventoryUtil; -import net.minecraft.core.NonNullList; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -public class InventoryPlain implements Container, INbtWritable, INbtReadable { +import java.util.Arrays; - private final NonNullList contents; +public class InventoryPlain implements Container, INbtWritable, INbtReadable { + private final ItemStack[] contents; private final String name; private final int stackLimit; public InventoryPlain(int size, String name, int stackLimit) { - this.contents = NonNullList.withSize(size, ItemStack.EMPTY); + this.contents = new ItemStack[size]; this.name = name; this.stackLimit = stackLimit; + Arrays.fill(this.contents, ItemStack.EMPTY); } public String getName() { @@ -45,23 +37,19 @@ public boolean isEmpty() { return true; } - public NonNullList getContents() { - return this.contents; - } - @Override public int getContainerSize() { - return this.contents.size(); + return this.contents.length; } @Override public ItemStack getItem(int slotId) { - return this.contents.get(slotId); + return this.contents[slotId]; } @Override public ItemStack removeItem(int slotId, int count) { - ItemStack itemStack = this.contents.get(slotId); + ItemStack itemStack = this.contents[slotId]; if (itemStack.isEmpty()) { return ItemStack.EMPTY; } @@ -69,8 +57,8 @@ public ItemStack removeItem(int slotId, int count) { } @Override - public void setItem(int slotId, ItemStack itemstack) { - this.contents.set(slotId, itemstack); + public void setItem(int slotId, ItemStack stack) { + this.contents[slotId] = stack; } @Override @@ -83,7 +71,7 @@ public void setChanged() { } @Override - public boolean stillValid(Player PlayerEntity) { + public boolean stillValid(Player player) { return false; } @@ -93,25 +81,18 @@ public ItemStack removeItemNoUpdate(int slotIndex) { } @Override - public boolean canPlaceItem(int i, ItemStack itemstack) { - return true; - } - - /* INBTagable */ - @Override - public void read(CompoundTag CompoundNBT) { - InventoryUtil.readFromNBT(this, this.name, CompoundNBT); + public void read(CompoundTag nbt, HolderLookup.Provider registries) { + InventoryUtil.readFromNBT(this, this.name, nbt); } @Override - public CompoundTag write(CompoundTag CompoundNBT) { - InventoryUtil.writeToNBT(this, this.name, CompoundNBT); - return CompoundNBT; + public CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries) { + InventoryUtil.writeToNBT(this, this.name, nbt); + return nbt; } - /* Fields */ @Override public void clearContent() { - this.contents.clear(); + Arrays.fill(this.contents, ItemStack.EMPTY); } } diff --git a/src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java b/src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java index eba5dfc127..769f104638 100644 --- a/src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java +++ b/src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; import javax.annotation.Nullable; import java.util.ArrayList; @@ -19,11 +9,7 @@ import java.util.List; import java.util.function.Predicate; -/** - * @author CovertJaguar - */ public class ItemHandlerInventoryManipulator implements Iterable { - private final IItemHandler inv; public ItemHandlerInventoryManipulator(IItemHandler inv) { diff --git a/src/main/java/forestry/core/inventory/ItemInventory.java b/src/main/java/forestry/core/inventory/ItemInventory.java index b6b84db43d..5fa827d7ac 100755 --- a/src/main/java/forestry/core/inventory/ItemInventory.java +++ b/src/main/java/forestry/core/inventory/ItemInventory.java @@ -1,69 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; -import com.google.common.base.Preconditions; import forestry.core.tiles.IFilterSlotDelegate; -import net.minecraft.core.Direction; -import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.Container; import net.minecraft.world.ContainerHelper; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.InvWrapper; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.wrapper.InvWrapper; -import javax.annotation.Nullable; -import java.util.Random; +import java.util.Arrays; -public abstract class ItemInventory implements Container, IFilterSlotDelegate, ICapabilityProvider { +/** + * An inventory that belongs to an item, like the Portable Analyzer, or a backpack. + */ +public abstract class ItemInventory implements Container, IFilterSlotDelegate { private static final String KEY_SLOTS = "Slots"; - private static final String KEY_UID = "UID"; - private static final Random rand = new Random(); private final IItemHandler itemHandler = new InvWrapper(this); + private final ItemStack[] slots; + private final int slotIndex; - protected final Player player; - private ItemStack parent; //TODO not final any more. Is this a problem - private final NonNullList inventoryStacks; + public ItemInventory(int size, int slotIndex) { + this.slots = new ItemStack[size]; + this.slotIndex = slotIndex; - public ItemInventory(Player player, int size, ItemStack parent) { - Preconditions.checkArgument(!parent.isEmpty(), "Parent cannot be empty."); + Arrays.fill(slots, ItemStack.EMPTY); - this.player = player; - this.parent = parent; - this.inventoryStacks = NonNullList.withSize(size, ItemStack.EMPTY); - - CompoundTag nbt = parent.getTag(); + CompoundTag nbt = slotIndex.getTag(); if (nbt == null) { nbt = new CompoundTag(); - parent.setTag(nbt); + slotIndex.setTag(nbt); } - setUID(nbt); // Set a uid to identify the itemStack on SMP CompoundTag nbtSlots = nbt.getCompound(KEY_SLOTS); for (int i = 0; i < this.inventoryStacks.size(); i++) { String slotKey = getSlotNBTKey(i); if (nbtSlots.contains(slotKey)) { CompoundTag itemNbt = nbtSlots.getCompound(slotKey); - ItemStack itemStack = ItemStack.of(itemNbt); - this.inventoryStacks.set(i, itemStack); + ItemStack itemStack = ItemStack.parseOptional(registries, itemNbt); + this.inventoryStacks.set(i, itemStack); } else { - this.inventoryStacks.set(i, ItemStack.EMPTY); + this.inventoryStacks.set(i, ItemStack.EMPTY); } } } @@ -78,17 +57,6 @@ public static int getOccupiedSlotCount(ItemStack itemStack) { return slotNbt.size(); } - private void setUID(CompoundTag nbt) { - if (!nbt.contains(KEY_UID)) { - nbt.putInt(KEY_UID, rand.nextInt()); - } - } - - public boolean isParentItemInventory(ItemStack itemStack) { - ItemStack parent = getParent(); - return isSameItemInventory(parent, itemStack); - } - protected ItemStack getParent() { for (InteractionHand hand : InteractionHand.values()) { ItemStack held = this.player.getItemInHand(hand); @@ -103,17 +71,6 @@ protected void setParent(ItemStack parent) { this.parent = parent; } - @Nullable - protected InteractionHand getHand() { - for (InteractionHand hand : InteractionHand.values()) { - ItemStack held = this.player.getItemInHand(hand); - if (isSameItemInventory(held, this.parent)) { - return hand; - } - } - return null; - } - private static boolean isSameItemInventory(ItemStack base, ItemStack comparison) { if (base.isEmpty() || comparison.isEmpty()) { return false; @@ -197,7 +154,7 @@ public ItemStack removeItem(int index, int count) { @Override public void setItem(int index, ItemStack itemstack) { - this.inventoryStacks.set(index, itemstack); + this.inventoryStacks.set(index, itemstack); ItemStack parent = getParent(); @@ -287,16 +244,6 @@ public boolean isLocked(int slotIndex) { return false; } - /* Fields */ - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.ITEM_HANDLER) { - return LazyOptional.of(() -> this.itemHandler).cast(); - } - return LazyOptional.empty(); - } - public IItemHandler getItemHandler() { return this.itemHandler; } diff --git a/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java b/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java index 096681ed29..0ae57bcccb 100644 --- a/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java +++ b/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java @@ -1,19 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import com.google.common.collect.ImmutableSet; import forestry.api.IForestryApi; +import forestry.api.circuits.CircuitLayout; import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; import forestry.api.core.ForestryError; import forestry.api.core.IError; import forestry.api.core.IErrorSource; @@ -23,81 +13,87 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import java.util.Arrays; import java.util.List; public class ItemInventorySolderingIron extends ItemInventory implements IErrorSource { - private final List layouts = IForestryApi.INSTANCE.getCircuitManager().getLayouts(); - private final int layoutCount = this.layouts.size(); - private int layoutIndex; + private static final short INPUT_SLOT = 0; + private static final short OUTPUT_SLOT = 1; + private static final short INGREDIENT_SLOT_START = 2; + private static final short INGREDIENT_SLOT_COUNT = 4; - private static final short inputCircuitBoardSlot = 0; - private static final short finishedCircuitBoardSlot = 1; - private static final short ingredientSlot1 = 2; - private static final short ingredientSlotCount = 4; + private int layoutIndex; - public ItemInventorySolderingIron(Player player, ItemStack itemStack) { - super(player, 6, itemStack); + public ItemInventorySolderingIron(int slotIndex) { + super(6, slotIndex); this.layoutIndex = 0; } + private static List layouts() { + return IForestryApi.INSTANCE.getCircuitManager().getLayouts(); + } + @Override public int getMaxStackSize() { return 1; } - public ICircuitLayout getLayout() { - return this.layouts.get(this.layoutIndex); + public CircuitLayout getLayout() { + return layouts().get(this.layoutIndex); } - public void setLayout(ICircuitLayout layout) { - this.layoutIndex = Math.max(0, this.layouts.indexOf(layout)); + public void setLayout(CircuitLayout layout) { + this.layoutIndex = Math.max(0, layouts().indexOf(layout)); } public void advanceLayout() { - this.layoutIndex = (this.layoutIndex + 1) % this.layoutCount; + int layoutCount = layouts().size(); + this.layoutIndex = (this.layoutIndex + 1) % layoutCount; } public void regressLayout() { if (this.layoutIndex == 0) { - this.layoutIndex = this.layoutCount - 1; + int layoutCount = layouts().size(); + this.layoutIndex = layoutCount - 1; } else { this.layoutIndex--; } } - private ICircuit[] getCircuits(boolean doConsume) { - ICircuit[] circuits = new ICircuit[ingredientSlotCount]; + private List getCircuits(boolean doConsume) { + ICircuit[] circuits = new ICircuit[INGREDIENT_SLOT_COUNT]; - for (short i = 0; i < ingredientSlotCount; i++) { - ItemStack ingredient = getItem(ingredientSlot1 + i); + for (short i = 0; i < INGREDIENT_SLOT_COUNT; i++) { + ItemStack ingredient = getItem(INGREDIENT_SLOT_START + i); if (!ingredient.isEmpty()) { - ICircuit circuit = IForestryApi.INSTANCE.getCircuitManager().getCircuit(this.layouts.get(this.layoutIndex), ingredient); + ICircuit circuit = IForestryApi.INSTANCE.getCircuitManager().getCircuit(layouts().get(this.layoutIndex), ingredient); if (circuit != null) { if (doConsume) { - removeItem(ingredientSlot1 + i, ingredient.getCount()); + removeItem(INGREDIENT_SLOT_START + i, ingredient.getCount()); } circuits[i] = circuit; } } } - return circuits; + return Arrays.asList(circuits); } @Override public void onSlotClick(int slotIndex, Player player) { - if (this.layouts.get(this.layoutIndex) == null) { + List layouts = layouts(); + if (layouts.get(this.layoutIndex) == null) { return; } - ItemStack inputCircuitBoard = getItem(inputCircuitBoardSlot); + ItemStack inputCircuitBoard = getItem(INPUT_SLOT); if (inputCircuitBoard.isEmpty() || inputCircuitBoard.getCount() > 1) { return; } - if (!getItem(finishedCircuitBoardSlot).isEmpty()) { + if (!getItem(OUTPUT_SLOT).isEmpty()) { return; } @@ -116,12 +112,12 @@ public void onSlotClick(int slotIndex, Player player) { return; } - ICircuit[] circuits = getCircuits(true); + List circuits = getCircuits(true); - ItemStack outputCircuitBoard = ItemCircuitBoard.createCircuitboard(type, this.layouts.get(this.layoutIndex), circuits); + ItemStack outputCircuitBoard = ItemCircuitBoard.createCircuitboard(type, layouts.get(this.layoutIndex), circuits); - setItem(finishedCircuitBoardSlot, outputCircuitBoard); - setItem(inputCircuitBoardSlot, ItemStack.EMPTY); + setItem(OUTPUT_SLOT, outputCircuitBoard); + setItem(INPUT_SLOT, ItemStack.EMPTY); } private int getCircuitCount() { @@ -139,11 +135,11 @@ private int getCircuitCount() { public ImmutableSet getErrors() { ImmutableSet.Builder errorStates = ImmutableSet.builder(); - if (this.layouts.get(this.layoutIndex) == null) { + if (layouts().get(this.layoutIndex) == null) { errorStates.add(ForestryError.NO_CIRCUIT_LAYOUT); } - ItemStack blankCircuitBoard = getItem(inputCircuitBoardSlot); + ItemStack blankCircuitBoard = getItem(INPUT_SLOT); if (blankCircuitBoard.isEmpty()) { errorStates.add(ForestryError.NO_CIRCUIT_BOARD); @@ -156,7 +152,7 @@ public ImmutableSet getErrors() { int circuitCount = 0; for (short i = 0; i < type.getSockets(); i++) { - if (!getItem(ingredientSlot1 + i).isEmpty()) { + if (!getItem(INGREDIENT_SLOT_START + i).isEmpty()) { circuitCount++; } } @@ -181,10 +177,10 @@ public boolean canSlotAccept(int slotIndex, ItemStack stack) { } Item item = stack.getItem(); - if (slotIndex == inputCircuitBoardSlot) { + if (slotIndex == INPUT_SLOT) { return item instanceof ItemCircuitBoard; - } else if (slotIndex >= ingredientSlot1 && slotIndex < ingredientSlot1 + ingredientSlotCount) { - return IForestryApi.INSTANCE.getCircuitManager().getCircuit(this.layouts.get(this.layoutIndex), stack) != null; + } else if (slotIndex >= INGREDIENT_SLOT_START && slotIndex < INGREDIENT_SLOT_START + INGREDIENT_SLOT_COUNT) { + return IForestryApi.INSTANCE.getCircuitManager().getCircuit(layouts().get(this.layoutIndex), stack) != null; } return false; } diff --git a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java b/src/main/java/forestry/core/inventory/PortableAnalyzerInventory.java similarity index 76% rename from src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java rename to src/main/java/forestry/core/inventory/PortableAnalyzerInventory.java index d2e7ef6716..0a331c9e59 100644 --- a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java +++ b/src/main/java/forestry/core/inventory/PortableAnalyzerInventory.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory; import forestry.api.ForestryTags; @@ -24,7 +14,7 @@ import java.util.Set; -public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { +public class PortableAnalyzerInventory extends ItemInventory implements IErrorSource { public static final int SLOT_ENERGY = 0; public static final int SLOT_SPECIMEN = 1; public static final int SLOT_ANALYZE_1 = 2; @@ -33,11 +23,14 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource { public static final int SLOT_ANALYZE_4 = 5; public static final int SLOT_ANALYZE_5 = 6; - public ItemInventoryAlyzer(Player player, ItemStack itemstack) { - super(player, 7, itemstack); + private final Player player; + + public PortableAnalyzerInventory(Player player, ItemStack stack) { + super(7, stack); + this.player = player; } - public static boolean isAlyzingFuel(ItemStack stack) { + public static boolean isAnalyzingFuel(ItemStack stack) { if (stack.isEmpty()) { return false; } @@ -48,7 +41,7 @@ public static boolean isAlyzingFuel(ItemStack stack) { @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { if (slotIndex == SLOT_ENERGY) { - return isAlyzingFuel(stack); + return isAnalyzingFuel(stack); } // only allow one slot to be used at a time @@ -93,7 +86,7 @@ private void analyzeSpecimen(ItemStack specimen) { if (individual != null) { if (!individual.isAnalyzed()) { // Requires energy - if (!isAlyzingFuel(getItem(SLOT_ENERGY))) { + if (!isAnalyzingFuel(getItem(SLOT_ENERGY))) { return; } @@ -121,7 +114,7 @@ public Set getErrors() { if (specimen.isEmpty()) { return Set.of(ForestryError.NO_SPECIMEN); } else { - if (IIndividualHandlerItem.isIndividual(specimen) && !isAlyzingFuel(getItem(SLOT_ENERGY))) { + if (IIndividualHandlerItem.isIndividual(specimen) && !isAnalyzingFuel(getItem(SLOT_ENERGY))) { return Set.of(ForestryError.NO_HONEY); } } @@ -145,7 +138,7 @@ public boolean hasSpecimen() { @Override protected void onWriteNBT(CompoundTag nbt) { - ItemStack energy = getItem(ItemInventoryAlyzer.SLOT_ENERGY); + ItemStack energy = getItem(PortableAnalyzerInventory.SLOT_ENERGY); int amount = 0; if (!energy.isEmpty()) { amount = energy.getCount(); diff --git a/src/main/java/forestry/core/inventory/StandardStackFilters.java b/src/main/java/forestry/core/inventory/StandardStackFilters.java deleted file mode 100644 index a1c205584a..0000000000 --- a/src/main/java/forestry/core/inventory/StandardStackFilters.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.entity.FurnaceBlockEntity; - -import java.util.function.Predicate; - -/** - * This interface is used with several of the functions in IItemTransfer to - * provide a convenient means of dealing with entire classes of items without - * having to specify each item individually. - * - * @author CovertJaguar - */ -public enum StandardStackFilters implements Predicate { - - ALL { - @Override - public boolean test(ItemStack stack) { - return true; - } - }, - FUEL { - @Override - public boolean test(ItemStack stack) { - return FurnaceBlockEntity.getFuel().get(stack.getItem()) > 0; - } - }, - //TODO - where is this used? - FEED { - @Override - public boolean test(ItemStack stack) { - //TODO - tag on seeds? - return stack.getItem().getFoodProperties() != null || stack.getItem() == Items.WHEAT || stack.getItem() == Items.WHEAT_SEEDS; - } - } -} diff --git a/src/main/java/forestry/core/inventory/package-info.java b/src/main/java/forestry/core/inventory/package-info.java index 9fb7f16c40..2ec85dd28e 100644 --- a/src/main/java/forestry/core/inventory/package-info.java +++ b/src/main/java/forestry/core/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.inventory; diff --git a/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java b/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java index 923378ffac..6bbc307d9a 100644 --- a/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java @@ -1,17 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory.watchers; import net.minecraft.world.entity.player.Player; +// todo figure out why this isn't used by SlotWatched public interface ISlotPickupWatcher { void onTake(int slotIndex, Player player); } diff --git a/src/main/java/forestry/core/inventory/watchers/package-info.java b/src/main/java/forestry/core/inventory/watchers/package-info.java index 26ee9fd1fa..32cdffb1a2 100644 --- a/src/main/java/forestry/core/inventory/watchers/package-info.java +++ b/src/main/java/forestry/core/inventory/watchers/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.inventory.watchers; diff --git a/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java b/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java index bf7c204ae4..722f2049ca 100644 --- a/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java +++ b/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java @@ -1,26 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory.wrappers; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -/** - * Created by CovertJaguar on 3/6/2016 for Railcraft. - */ public abstract class InvWrapperBase implements Container { - private final Container inv; - private boolean checkItems = true; + private final boolean checkItems; public InvWrapperBase(Container inv) { this(inv, true); diff --git a/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java b/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java index d4fcc53a60..e7d0d65492 100755 --- a/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java +++ b/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.inventory.wrappers; import net.minecraft.world.Container; @@ -17,15 +7,11 @@ * Wrapper class used to specify part of an existing inventory to be treated as * a complete inventory. Used primarily to map a side of an ISidedInventory, but * it is also helpful for complex inventories such as the Tunnel Bore. - * - * @author CovertJaguar */ public class InventoryMapper extends InvWrapperBase implements Container { - private final Container inv; private final int start; private final int size; - private final int stackSizeLimit = -1; public InventoryMapper(Container inv) { this(inv, 0, inv.getContainerSize(), true); @@ -81,12 +67,11 @@ public void setItem(int slot, ItemStack itemstack) { @Override public int getMaxStackSize() { - return this.stackSizeLimit > 0 ? this.stackSizeLimit : this.inv.getMaxStackSize(); + return this.inv.getMaxStackSize(); } @Override public boolean canPlaceItem(int slot, ItemStack stack) { return !checkItems() || this.inv.canPlaceItem(this.start + slot, stack); } - } diff --git a/src/main/java/forestry/core/inventory/wrappers/package-info.java b/src/main/java/forestry/core/inventory/wrappers/package-info.java index be86e6d899..f224442919 100644 --- a/src/main/java/forestry/core/inventory/wrappers/package-info.java +++ b/src/main/java/forestry/core/inventory/wrappers/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.inventory.wrappers; diff --git a/src/main/java/forestry/core/items/ForestersManualItem.java b/src/main/java/forestry/core/items/ForestersManualItem.java index 8799f82347..31386c6e32 100644 --- a/src/main/java/forestry/core/items/ForestersManualItem.java +++ b/src/main/java/forestry/core/items/ForestersManualItem.java @@ -1,5 +1,6 @@ package forestry.core.items; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.InteractionHand; @@ -9,7 +10,6 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.registries.ForgeRegistries; import vazkii.patchouli.api.PatchouliAPI; public class ForestersManualItem extends Item { @@ -22,7 +22,7 @@ public InteractionResultHolder use(Level world, Player player, Intera ItemStack stack = player.getItemInHand(hand); if (player instanceof ServerPlayer) { - PatchouliAPI.get().openBookGUI((ServerPlayer) player, ForgeRegistries.ITEMS.getKey(this)); + PatchouliAPI.get().openBookGUI((ServerPlayer) player, BuiltInRegistries.ITEM.getKey(this)); player.playSound(SoundEvents.BOOK_PAGE_TURN, 1F, (float) (0.7 + Math.random() * 0.4)); } diff --git a/src/main/java/forestry/core/items/HasRemnants.java b/src/main/java/forestry/core/items/HasRemnants.java index 8f81712ab7..cda55445d3 100644 --- a/src/main/java/forestry/core/items/HasRemnants.java +++ b/src/main/java/forestry/core/items/HasRemnants.java @@ -2,11 +2,9 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.PickaxeItem; -import net.minecraft.world.item.ShovelItem; -import net.minecraft.world.item.Tier; +import net.minecraft.world.item.*; +import javax.annotation.Nullable; import java.util.function.Consumer; import java.util.function.Supplier; @@ -15,12 +13,12 @@ class Pickaxe extends PickaxeItem implements HasRemnants { private final Supplier remnants; public Pickaxe(Tier tier, int damageBonus, float speedModifier, Properties properties, Supplier remnants) { - super(tier, damageBonus, speedModifier, properties); + super(tier, properties.attributes(createAttributes(tier, damageBonus, speedModifier))); this.remnants = remnants; } @Override - public int damageItem(ItemStack stack, int amount, T entity, Consumer onBroken) { + public int damageItem(ItemStack stack, int amount, @Nullable T entity, Consumer onBroken) { if (stack.getDamageValue() + amount >= stack.getMaxDamage()) { if (entity instanceof Player player) { // make sure it's really broken @@ -36,12 +34,12 @@ class Shovel extends ShovelItem implements HasRemnants { private final Supplier remnants; public Shovel(Tier tier, float damageBonus, float speedModifier, Properties properties, Supplier remnants) { - super(tier, damageBonus, speedModifier, properties); + super(tier, properties.attributes(createAttributes(tier, damageBonus, speedModifier))); this.remnants = remnants; } @Override - public int damageItem(ItemStack stack, int amount, T entity, Consumer onBroken) { + public int damageItem(ItemStack stack, int amount, @Nullable T entity, Consumer onBroken) { if (stack.getDamageValue() + amount >= stack.getMaxDamage()) { if (entity instanceof Player player) { // make sure it's really broken diff --git a/src/main/java/forestry/core/items/ItemAlyzer.java b/src/main/java/forestry/core/items/ItemAlyzer.java deleted file mode 100644 index aa332f23a5..0000000000 --- a/src/main/java/forestry/core/items/ItemAlyzer.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.items; - -import forestry.core.gui.ContainerAlyzer; -import forestry.core.inventory.ItemInventoryAlyzer; -import net.minecraft.ChatFormatting; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; - -import javax.annotation.Nullable; -import java.util.List; - -public class ItemAlyzer extends ItemWithGui { - public ItemAlyzer() { - super(new Item.Properties().stacksTo(1)); - } - - @Override - public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag advanced) { - super.appendHoverText(stack, world, tooltip, advanced); - int charges = 0; - CompoundTag compound = stack.getTag(); - if (compound != null) { - charges = compound.getInt("Charges"); - } - tooltip.add(Component.translatable(stack.getDescriptionId() + ".charges", charges).withStyle(ChatFormatting.GOLD)); - } - - @Override - public AbstractContainerMenu getContainer(int windowId, Player player, ItemStack heldItem) { - return new ContainerAlyzer(windowId, new ItemInventoryAlyzer(player, heldItem), player); - } -} diff --git a/src/main/java/forestry/core/items/ItemBlockForestry.java b/src/main/java/forestry/core/items/ItemBlockForestry.java index e8b0b352e4..3f9f4f4e29 100755 --- a/src/main/java/forestry/core/items/ItemBlockForestry.java +++ b/src/main/java/forestry/core/items/ItemBlockForestry.java @@ -17,10 +17,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.List; @@ -54,9 +51,8 @@ public int getBurnTime(ItemStack itemStack, @Nullable RecipeType recipeType) } @Override - @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag advanced) { - super.appendHoverText(stack, world, tooltip, advanced); - ItemTooltipUtil.addInformation(stack, world, tooltip, advanced); + public void appendHoverText(ItemStack stack, TooltipContext ctx, List tooltip, TooltipFlag advanced) { + super.appendHoverText(stack, ctx, tooltip, advanced); + ItemTooltipUtil.addInformation(stack, tooltip); } } diff --git a/src/main/java/forestry/core/items/ItemBlockTesr.java b/src/main/java/forestry/core/items/ItemBlockTesr.java index 4aea0b3b45..4090519a9d 100644 --- a/src/main/java/forestry/core/items/ItemBlockTesr.java +++ b/src/main/java/forestry/core/items/ItemBlockTesr.java @@ -3,7 +3,7 @@ import forestry.core.client.CoreClientHandler; import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer; import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; import java.util.function.Consumer; diff --git a/src/main/java/forestry/core/items/ItemElectronTube.java b/src/main/java/forestry/core/items/ItemElectronTube.java index 77993a21ef..cfea9ee656 100755 --- a/src/main/java/forestry/core/items/ItemElectronTube.java +++ b/src/main/java/forestry/core/items/ItemElectronTube.java @@ -1,40 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; import forestry.api.IForestryApi; +import forestry.api.circuits.CircuitLayout; import forestry.api.circuits.ICircuit; -import forestry.api.circuits.ICircuitLayout; import forestry.api.circuits.ICircuitManager; -import forestry.api.core.ItemGroups; import it.unimi.dsi.fastutil.Pair; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class ItemElectronTube extends ItemOverlay { public ItemElectronTube(ItemOverlay.IOverlayInfo type) { - super(ItemGroups.tabForestry, type); + super(type); } @Override - public void appendHoverText(ItemStack itemstack, @Nullable Level world, List list, TooltipFlag flag) { - super.appendHoverText(itemstack, world, list, flag); - ArrayList> circuits = getCircuits(itemstack); + public void appendHoverText(ItemStack itemstack, TooltipContext ctx, List list, TooltipFlag flag) { + super.appendHoverText(itemstack, ctx, list, flag); + ArrayList> circuits = getCircuits(itemstack); if (!circuits.isEmpty()) { for (var entry : circuits) { list.add(entry.left().getUsage().withStyle(ChatFormatting.WHITE, ChatFormatting.UNDERLINE)); @@ -47,11 +34,11 @@ public void appendHoverText(ItemStack itemstack, @Nullable Level world, List> getCircuits(ItemStack stack) { - ArrayList> circuits = new ArrayList<>(); + private static ArrayList> getCircuits(ItemStack stack) { + ArrayList> circuits = new ArrayList<>(); ICircuitManager manager = IForestryApi.INSTANCE.getCircuitManager(); - for (ICircuitLayout layout : manager.getLayouts()) { + for (CircuitLayout layout : manager.getLayouts()) { ICircuit circuit = manager.getCircuit(layout, stack); if (circuit != null) { circuits.add(Pair.of(layout, circuit)); diff --git a/src/main/java/forestry/core/items/ItemFluidContainerForestry.java b/src/main/java/forestry/core/items/ItemFluidContainerForestry.java index b007f7a127..5f418d01e3 100755 --- a/src/main/java/forestry/core/items/ItemFluidContainerForestry.java +++ b/src/main/java/forestry/core/items/ItemFluidContainerForestry.java @@ -1,16 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; import forestry.core.config.Constants; +import forestry.core.features.CoreDataComponents; import forestry.core.fluids.ForestryFluids; import forestry.core.items.definitions.DrinkProperties; import forestry.core.items.definitions.EnumContainerType; @@ -19,7 +10,6 @@ import forestry.core.models.FluidContainerModel; import forestry.core.utils.ModUtil; import forestry.core.utils.Translator; -import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; @@ -37,12 +27,12 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.fluids.FluidActionResult; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.fluids.FluidActionResult; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.SimpleFluidContent; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.items.ItemHandlerHelper; import javax.annotation.Nullable; @@ -50,7 +40,7 @@ public class ItemFluidContainerForestry extends ItemForestry implements IColored private final EnumContainerType type; public ItemFluidContainerForestry(EnumContainerType type) { - super(new Item.Properties()); + super(new Item.Properties().component(CoreDataComponents.FLUID_CONTENTS, SimpleFluidContent.EMPTY)); this.type = type; } @@ -76,7 +66,7 @@ public Component getName(ItemStack stack) { String exactTranslationKey = Constants.TRANSLATION_KEY_ITEM + this.type.getSerializedName() + '.' + ModUtil.getRegistryName(fluid.getFluid()); return Translator.tryTranslate(exactTranslationKey, () -> { String grammarKey = Constants.TRANSLATION_KEY_ITEM + this.type.getSerializedName() + ".grammar"; - return Component.translatable(grammarKey, fluid.getDisplayName()); + return Component.translatable(grammarKey, fluid.getHoverName()); }); } else { String unlocalizedname = Constants.TRANSLATION_KEY_ITEM + this.type.getSerializedName() + ".empty"; @@ -100,7 +90,7 @@ public ItemStack finishUsingItem(ItemStack stack, Level worldIn, LivingEntity en if (!worldIn.isClientSide) { FoodData foodStats = player.getFoodData(); - foodStats.eat(drinkProperties.getHealAmount(), drinkProperties.getSaturationModifier()); + foodStats.eat(drinkProperties.healAmount(), drinkProperties.saturationModifier()); worldIn.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.PLAYER_BURP, SoundSource.PLAYERS, 0.5F, worldIn.random.nextFloat() * 0.1F + 0.9F); } @@ -114,7 +104,7 @@ public ItemStack finishUsingItem(ItemStack stack, Level worldIn, LivingEntity en protected DrinkProperties getDrinkProperties(ItemStack itemStack) { FluidStack contained = getContained(itemStack); if (!contained.isEmpty()) { - ForestryFluids definition = ForestryFluids.getFluidDefinition(contained); + ForestryFluids definition = ForestryFluids.getFluidDefinition(contained.getFluid()); if (definition != null) { return definition.getDrinkProperties(); } @@ -123,12 +113,12 @@ protected DrinkProperties getDrinkProperties(ItemStack itemStack) { } @Override - public int getUseDuration(ItemStack itemstack) { - DrinkProperties drinkProperties = getDrinkProperties(itemstack); + public int getUseDuration(ItemStack stack, LivingEntity living) { + DrinkProperties drinkProperties = getDrinkProperties(stack); if (drinkProperties != null) { - return drinkProperties.getMaxItemUseDuration(); + return drinkProperties.maxItemUseDuration(); } else { - return super.getUseDuration(itemstack); + return super.getUseDuration(stack, living); } } @@ -176,11 +166,6 @@ public InteractionResultHolder use(Level world, Player player, Intera } } - @Override - public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) { - return new FluidHandlerItemForestry(stack, this.type); - } - @Override public int getColorFromItemStack(ItemStack stack, int tintIndex) { return FluidContainerModel.DYNAMIC_COLOR.getColor(stack, tintIndex); diff --git a/src/main/java/forestry/core/items/ItemForestry.java b/src/main/java/forestry/core/items/ItemForestry.java index 2c90201013..10153c18dd 100755 --- a/src/main/java/forestry/core/items/ItemForestry.java +++ b/src/main/java/forestry/core/items/ItemForestry.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; import forestry.core.utils.ItemTooltipUtil; @@ -16,7 +6,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.Level; import javax.annotation.Nullable; import java.util.List; @@ -44,7 +33,7 @@ public int getBurnTime(ItemStack itemStack, @Nullable RecipeType recipeType) } @Override - public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag advanced) { - ItemTooltipUtil.addInformation(stack, world, tooltip, advanced); + public void appendHoverText(ItemStack stack, TooltipContext ctx, List tooltip, TooltipFlag advanced) { + ItemTooltipUtil.addInformation(stack, tooltip); } } diff --git a/src/main/java/forestry/core/items/ItemOverlay.java b/src/main/java/forestry/core/items/ItemOverlay.java index 08002daf87..d2e482ccc0 100755 --- a/src/main/java/forestry/core/items/ItemOverlay.java +++ b/src/main/java/forestry/core/items/ItemOverlay.java @@ -1,18 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; import forestry.api.core.IItemSubtype; import forestry.core.items.definitions.IColoredItem; -import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -20,8 +9,6 @@ * Base class for items with an overlay color and multiple layer models. * * @see forestry.core.items.ItemElectronTube - * @see forestry.apiculture.items.ItemPollenCluster - * @see forestry.apiculture.items.ItemPropolis * @see forestry.mail.items.ItemStamp */ public class ItemOverlay extends ItemForestry implements IColoredItem { @@ -34,7 +21,7 @@ public interface IOverlayInfo extends IItemSubtype { protected final IOverlayInfo overlay; - public ItemOverlay(CreativeModeTab tab, IOverlayInfo overlay) { + public ItemOverlay(IOverlayInfo overlay) { super(new Item.Properties()); this.overlay = overlay; diff --git a/src/main/java/forestry/core/items/ItemPipette.java b/src/main/java/forestry/core/items/ItemPipette.java index 5d89bd23a8..8a84e8bfd7 100755 --- a/src/main/java/forestry/core/items/ItemPipette.java +++ b/src/main/java/forestry/core/items/ItemPipette.java @@ -1,64 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; import forestry.api.core.IToolPipette; -import forestry.core.fluids.PipetteContents; +import forestry.core.features.CoreDataComponents; import forestry.core.items.definitions.IColoredItem; import forestry.core.utils.RenderUtil; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.capability.templates.FluidHandlerItemStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.SimpleFluidContent; -import javax.annotation.Nullable; import java.util.List; public class ItemPipette extends ItemForestry implements IToolPipette, IColoredItem { public ItemPipette() { - super(new Properties().stacksTo(1)); + super(new Properties().component(CoreDataComponents.FLUID_CONTENTS, SimpleFluidContent.EMPTY).stacksTo(1)); } @Override - public boolean canPipette(ItemStack itemstack) { - PipetteContents contained = PipetteContents.create(itemstack); - return contained == null || !contained.isFull(); + public boolean canPipette(ItemStack stack) { + SimpleFluidContent contained = stack.get(CoreDataComponents.FLUID_CONTENTS); + return contained == null || contained.getAmount() < FluidType.BUCKET_VOLUME; } @Override - public void appendHoverText(ItemStack itemstack, @Nullable Level world, List list, TooltipFlag flag) { - super.appendHoverText(itemstack, world, list, flag); + public void appendHoverText(ItemStack stack, TooltipContext ctx, List list, TooltipFlag flag) { + super.appendHoverText(stack, ctx, list, flag); - PipetteContents contained = PipetteContents.create(itemstack); + SimpleFluidContent contained = stack.get(CoreDataComponents.FLUID_CONTENTS); if (contained != null) { - contained.addTooltip(list); + list.add(contained.copy().getHoverName().copy().append(" (" + contained.getAmount() + " mb)").withStyle(ChatFormatting.GRAY)); } } - @Override - public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) { - return new FluidHandlerItemStack(stack, FluidType.BUCKET_VOLUME); - } - @Override public int getColorFromItemStack(ItemStack stack, int tintIndex) { if (tintIndex == 1) { - PipetteContents contents = PipetteContents.create(stack); + SimpleFluidContent contents = stack.get(CoreDataComponents.FLUID_CONTENTS); if (contents != null) { - return RenderUtil.getFluidColor(contents.getContents().getFluid()); + return RenderUtil.getFluidColor(contents.getFluid()); } } return 0xffffff; diff --git a/src/main/java/forestry/core/items/ItemPortableAnalyzer.java b/src/main/java/forestry/core/items/ItemPortableAnalyzer.java new file mode 100644 index 0000000000..a397dc457e --- /dev/null +++ b/src/main/java/forestry/core/items/ItemPortableAnalyzer.java @@ -0,0 +1,37 @@ +package forestry.core.items; + +import forestry.core.features.CoreDataComponents; +import forestry.core.gui.PortableAnalyzerMenu; +import forestry.core.inventory.PortableAnalyzerInventory; +import net.minecraft.ChatFormatting; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.ItemContainerContents; + +import java.util.List; + +public class ItemPortableAnalyzer extends ItemWithGui { + public ItemPortableAnalyzer() { + super(new Item.Properties().stacksTo(1).component(DataComponents.CONTAINER, ItemContainerContents.EMPTY)); + } + + @Override + public void appendHoverText(ItemStack stack, TooltipContext ctx, List tooltip, TooltipFlag advanced) { + super.appendHoverText(stack, ctx, tooltip, advanced); + Integer charges = stack.get(CoreDataComponents.ANALYZER_CHARGES); + if (charges == null) { + charges = 0; + } + tooltip.add(Component.translatable(stack.getDescriptionId() + ".charges", charges).withStyle(ChatFormatting.GOLD)); + } + + @Override + public AbstractContainerMenu createMenu(int containerId, Inventory playerInv, int slotIndex) { + return new PortableAnalyzerMenu(containerId, playerInv, slotIndex); + } +} diff --git a/src/main/java/forestry/core/items/ItemSolderingIron.java b/src/main/java/forestry/core/items/ItemSolderingIron.java index e50637eb5a..d8ebf4b2ce 100644 --- a/src/main/java/forestry/core/items/ItemSolderingIron.java +++ b/src/main/java/forestry/core/items/ItemSolderingIron.java @@ -1,30 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; -import forestry.core.circuits.ContainerSolderingIron; -import forestry.core.circuits.ISolderingIron; +import forestry.core.circuits.SolderingIronMenu; import forestry.core.inventory.ItemInventorySolderingIron; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -public class ItemSolderingIron extends ItemWithGui implements ISolderingIron { +public class ItemSolderingIron extends ItemWithGui { public ItemSolderingIron() { super(new Item.Properties().durability(5)); } @Override - public AbstractContainerMenu getContainer(int windowId, Player player, ItemStack heldItem) { - return new ContainerSolderingIron(windowId, player, new ItemInventorySolderingIron(player, heldItem)); + public AbstractContainerMenu createMenu(int containerId, Inventory playerInv, int slotIndex) { + return new SolderingIronMenu(containerId, playerInv, new ItemInventorySolderingIron(slotIndex)); } } diff --git a/src/main/java/forestry/core/items/ItemSpectacles.java b/src/main/java/forestry/core/items/ItemSpectacles.java index e43c6fa048..8fa6836fa8 100644 --- a/src/main/java/forestry/core/items/ItemSpectacles.java +++ b/src/main/java/forestry/core/items/ItemSpectacles.java @@ -1,36 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; -import forestry.api.ForestryCapabilities; import forestry.api.ForestryConstants; -import forestry.arboriculture.capabilities.ArmorNaturalist; +import forestry.api.core.ISpectacleVision; import forestry.core.config.Constants; -import forestry.core.utils.ItemTooltipUtil; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.*; -import net.minecraft.world.level.Level; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; - -import javax.annotation.Nullable; -import java.util.List; +import net.minecraft.world.item.ArmorItem; +import net.minecraft.world.item.ArmorMaterials; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; public class ItemSpectacles extends ArmorItem { public static final String TEXTURE_NATURALIST_ARMOR_PRIMARY = ForestryConstants.MOD_ID + ":" + Constants.TEXTURE_PATH_ITEM + "/naturalist_armor_1.png"; + public static final ISpectacleVision VISION = (player, armor, execute) -> true; public ItemSpectacles() { super(ArmorMaterials.LEATHER, Type.HELMET, (new Item.Properties()).durability(100)); @@ -40,19 +22,4 @@ public ItemSpectacles() { public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type) { return TEXTURE_NATURALIST_ARMOR_PRIMARY; } - - @Override - public void appendHoverText(ItemStack stack, @Nullable Level level, List tooltip, TooltipFlag advanced) { - ItemTooltipUtil.addInformation(stack, level, tooltip, advanced); - } - - @Override - public @Nullable ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) { - return new ICapabilityProvider() { - @Override - public LazyOptional getCapability(Capability cap, @Nullable Direction side) { - return cap == ForestryCapabilities.ARMOR_NATURALIST ? LazyOptional.of(() -> ArmorNaturalist.INSTANCE).cast() : LazyOptional.empty(); - } - }; - } } diff --git a/src/main/java/forestry/core/items/ItemWithGui.java b/src/main/java/forestry/core/items/ItemWithGui.java index 94beffc5df..095481ece7 100644 --- a/src/main/java/forestry/core/items/ItemWithGui.java +++ b/src/main/java/forestry/core/items/ItemWithGui.java @@ -1,27 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; -import forestry.core.gui.ContainerItemInventory; -import net.minecraft.network.FriendlyByteBuf; +import forestry.core.gui.ItemInventoryMenu; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.SimpleMenuProvider; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.network.NetworkHooks; import javax.annotation.Nullable; @@ -31,31 +21,33 @@ public ItemWithGui(Item.Properties properties) { } @Override - public InteractionResultHolder use(Level worldIn, Player player, InteractionHand handIn) { - ItemStack stack = player.getItemInHand(handIn); - - if (player instanceof ServerPlayer serverPlayer) { - openGui(serverPlayer, stack); + public InteractionResultHolder use(Level level, Player player, InteractionHand hand) { + ItemStack stack = player.getItemInHand(hand); + + if (!level.isClientSide) { + // keep track of the item's slot so we can lock it + int slotIndex = hand == InteractionHand.OFF_HAND ? Inventory.SLOT_OFFHAND : player.getInventory().selected; + + player.openMenu(new SimpleMenuProvider( + (windowId, playerInv, p) -> createMenu(windowId, playerInv, slotIndex), + player.getItemInHand(hand).getHoverName() + ), + buffer -> writeContainerData(buffer, player, stack, slotIndex) + ); + + return InteractionResultHolder.consume(stack); + } else { + return InteractionResultHolder.success(stack); } - - return InteractionResultHolder.success(stack); - } - - protected void openGui(ServerPlayer serverPlayer, ItemStack heldItem) { - NetworkHooks.openScreen(serverPlayer, getMenuProvider(heldItem), buffer -> writeContainerData(serverPlayer, heldItem, buffer)); - } - - public SimpleMenuProvider getMenuProvider(ItemStack heldItem) { - return new SimpleMenuProvider((windowId, playerInv, player) -> getContainer(windowId, player, heldItem), heldItem.getHoverName()); } - protected void writeContainerData(ServerPlayer player, ItemStack stack, FriendlyByteBuf buffer) { - buffer.writeBoolean(player.getUsedItemHand() == InteractionHand.MAIN_HAND); + protected void writeContainerData(RegistryFriendlyByteBuf buffer, Player player, ItemStack stack, int slotIndex) { + buffer.writeByte(slotIndex); } @Override public boolean onDroppedByPlayer(ItemStack itemstack, Player player) { - if (!itemstack.isEmpty() && player instanceof ServerPlayer && player.containerMenu instanceof ContainerItemInventory) { + if (!itemstack.isEmpty() && player instanceof ServerPlayer && player.containerMenu instanceof ItemInventoryMenu) { player.closeContainer(); } @@ -63,5 +55,5 @@ public boolean onDroppedByPlayer(ItemStack itemstack, Player player) { } @Nullable - public abstract AbstractContainerMenu getContainer(int windowId, Player player, ItemStack heldItem); + public abstract AbstractContainerMenu createMenu(int containerId, Inventory playerInv, int slotIndex); } diff --git a/src/main/java/forestry/core/items/ItemWrench.java b/src/main/java/forestry/core/items/ItemWrench.java index 330fd235b0..3bd1acce38 100755 --- a/src/main/java/forestry/core/items/ItemWrench.java +++ b/src/main/java/forestry/core/items/ItemWrench.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items; import net.minecraft.core.BlockPos; @@ -34,13 +24,12 @@ public InteractionResult useOn(UseOnContext context) { if (player == null) { return InteractionResult.FAIL; } - Direction facing = context.getClickedFace(); InteractionHand hand = context.getHand(); BlockState state = worldIn.getBlockState(pos); Block block = state.getBlock(); BlockState rotatedState = block.rotate(state, worldIn, pos, Rotation.CLOCKWISE_90); - if (rotatedState != state) { //TODO - how to rotate based on a direction, might need helper method + if (rotatedState != state) { player.swing(hand); worldIn.setBlock(pos, rotatedState, Block.UPDATE_CLIENTS); return InteractionResult.SUCCESS; diff --git a/src/main/java/forestry/core/items/definitions/DrinkProperties.java b/src/main/java/forestry/core/items/definitions/DrinkProperties.java index d4e5628069..ed198a3b2f 100644 --- a/src/main/java/forestry/core/items/definitions/DrinkProperties.java +++ b/src/main/java/forestry/core/items/definitions/DrinkProperties.java @@ -3,26 +3,5 @@ /** * Definition of drinking properties for the drinkable fluid containers. */ -public class DrinkProperties { - private final int healAmount; - private final int maxItemUseDuration; - private final float saturationModifier; - - public DrinkProperties(int healAmount, float saturationModifier, int maxItemUseDuration) { - this.healAmount = healAmount; - this.saturationModifier = saturationModifier; - this.maxItemUseDuration = maxItemUseDuration; - } - - public int getHealAmount() { - return this.healAmount; - } - - public float getSaturationModifier() { - return this.saturationModifier; - } - - public int getMaxItemUseDuration() { - return this.maxItemUseDuration; - } +public record DrinkProperties(int healAmount, float saturationModifier, int maxItemUseDuration) { } diff --git a/src/main/java/forestry/core/items/definitions/EnumContainerType.java b/src/main/java/forestry/core/items/definitions/EnumContainerType.java index c8ffe25f85..6a08e49278 100644 --- a/src/main/java/forestry/core/items/definitions/EnumContainerType.java +++ b/src/main/java/forestry/core/items/definitions/EnumContainerType.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items.definitions; import forestry.api.core.IItemSubtype; @@ -19,14 +9,8 @@ public enum EnumContainerType implements IItemSubtype { CAPSULE, REFRACTORY; - private final String name; - - EnumContainerType() { - this.name = name().toLowerCase(Locale.ENGLISH); - } - @Override - public String getSerializedName() { - return this.name; + public String identifier() { + return name().toLowerCase(Locale.ENGLISH); } } diff --git a/src/main/java/forestry/core/items/definitions/EnumCraftingMaterial.java b/src/main/java/forestry/core/items/definitions/EnumCraftingMaterial.java index 62312a5c53..97cf9be01b 100644 --- a/src/main/java/forestry/core/items/definitions/EnumCraftingMaterial.java +++ b/src/main/java/forestry/core/items/definitions/EnumCraftingMaterial.java @@ -15,14 +15,8 @@ public enum EnumCraftingMaterial implements IItemSubtype { IMPREGNATED_STICK, SCENTED_PANELING; - private final String name; - - EnumCraftingMaterial() { - this.name = toString().toLowerCase(Locale.ENGLISH); - } - @Override - public String getSerializedName() { - return this.name; + public String identifier() { + return name().toLowerCase(Locale.ENGLISH); } } diff --git a/src/main/java/forestry/core/items/definitions/EnumElectronTube.java b/src/main/java/forestry/core/items/definitions/EnumElectronTube.java index 8777b82473..45f3cd68cc 100644 --- a/src/main/java/forestry/core/items/definitions/EnumElectronTube.java +++ b/src/main/java/forestry/core/items/definitions/EnumElectronTube.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items.definitions; import forestry.core.items.ItemOverlay; @@ -29,7 +19,6 @@ public enum EnumElectronTube implements ItemOverlay.IOverlayInfo { LAPIS(TextColor.fromRgb(0x1c57c6)), ENDER(TextColor.fromRgb(0x33adad), TextColor.fromRgb(0x255661)); - private final String uid; private final int primaryColor; private final int secondaryColor; @@ -38,14 +27,13 @@ public enum EnumElectronTube implements ItemOverlay.IOverlayInfo { } EnumElectronTube(TextColor secondaryColor, TextColor primaryColor) { - this.uid = name().toLowerCase(Locale.ENGLISH); this.primaryColor = primaryColor.getValue(); this.secondaryColor = secondaryColor.getValue(); } @Override - public String getSerializedName() { - return this.uid; + public String identifier() { + return this.name().toLowerCase(Locale.ENGLISH); } @Override diff --git a/src/main/java/forestry/core/items/definitions/FluidHandlerItemForestry.java b/src/main/java/forestry/core/items/definitions/FluidHandlerItemForestry.java index 03ce50d018..6c3889da32 100644 --- a/src/main/java/forestry/core/items/definitions/FluidHandlerItemForestry.java +++ b/src/main/java/forestry/core/items/definitions/FluidHandlerItemForestry.java @@ -1,10 +1,11 @@ package forestry.core.items.definitions; +import forestry.core.features.CoreDataComponents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.capability.templates.FluidHandlerItemStackSimple; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.capability.templates.FluidHandlerItemStackSimple; /** * Fluid handler that consumes the container item after it was used. @@ -13,7 +14,7 @@ public class FluidHandlerItemForestry extends FluidHandlerItemStackSimple.Consum private final EnumContainerType containerType; public FluidHandlerItemForestry(ItemStack container, EnumContainerType containerType) { - super(container, FluidType.BUCKET_VOLUME); + super(CoreDataComponents.FLUID_CONTENTS, container, FluidType.BUCKET_VOLUME); this.containerType = containerType; } @@ -25,9 +26,6 @@ public FluidHandlerItemForestry(ItemStack container, EnumContainerType container */ private boolean contentsAllowed(FluidStack fluidStack) { Fluid fluid = fluidStack.getFluid(); - if (fluid == null) { - return false; - } if (this.containerType == EnumContainerType.CAPSULE) { return fluid.getFluidType().getTemperature(fluidStack) < 310.15; // melting point of wax in kelvin @@ -48,7 +46,7 @@ public boolean canDrainFluidType(FluidStack fluid) { @Override protected void setFluid(FluidStack fluid) { super.setFluid(fluid); - this.container.setDamageValue(1); // show the filled container model + this.container.setDamageValue(1); // show the filled container model } } diff --git a/src/main/java/forestry/core/items/definitions/ICraftingPlan.java b/src/main/java/forestry/core/items/definitions/ICraftingPlan.java index b394c10a07..bcaa1e8ab8 100644 --- a/src/main/java/forestry/core/items/definitions/ICraftingPlan.java +++ b/src/main/java/forestry/core/items/definitions/ICraftingPlan.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.items.definitions; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/forestry/core/items/definitions/ToolTier.java b/src/main/java/forestry/core/items/definitions/ToolTier.java index fa831b420a..9027498cde 100644 --- a/src/main/java/forestry/core/items/definitions/ToolTier.java +++ b/src/main/java/forestry/core/items/definitions/ToolTier.java @@ -1,31 +1,30 @@ package forestry.core.items.definitions; +import com.google.common.base.Suppliers; import forestry.api.ForestryTags; -import net.minecraft.util.LazyLoadedValue; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Tier; import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.block.Block; import java.util.function.Supplier; public enum ToolTier implements Tier { - SURVIVALIST(3, 200, 7.0F, 2.5F, 10, () -> { - return Ingredient.of(ForestryTags.Items.INGOTS_BRONZE); - }); + SURVIVALIST(200, 7.0F, 2.5F, 10, () -> Ingredient.of(ForestryTags.Items.INGOTS_BRONZE)); - private final int level; private final int uses; private final float speed; private final float damage; private final int enchantmentValue; - private final LazyLoadedValue repairIngredient; + private final Supplier repairIngredient; - ToolTier(int level, int uses, float speed, float damage, int enchantmentValue, Supplier repairIngredient) { - this.level = level; + ToolTier(int uses, float speed, float damage, int enchantmentValue, Supplier repairIngredient) { this.uses = uses; this.speed = speed; this.damage = damage; this.enchantmentValue = enchantmentValue; - this.repairIngredient = new LazyLoadedValue<>(repairIngredient); + this.repairIngredient = Suppliers.memoize(repairIngredient::get); } @Override @@ -44,8 +43,8 @@ public float getAttackDamageBonus() { } @Override - public int getLevel() { - return this.level; + public TagKey getIncorrectBlocksForDrops() { + return BlockTags.INCORRECT_FOR_IRON_TOOL; } @Override diff --git a/src/main/java/forestry/core/items/definitions/package-info.java b/src/main/java/forestry/core/items/definitions/package-info.java index ca0ad1a611..a2687ba4bf 100644 --- a/src/main/java/forestry/core/items/definitions/package-info.java +++ b/src/main/java/forestry/core/items/definitions/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.core.items.definitions; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/core/items/package-info.java b/src/main/java/forestry/core/items/package-info.java index dfe2e55348..f42fd4be40 100644 --- a/src/main/java/forestry/core/items/package-info.java +++ b/src/main/java/forestry/core/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.items; diff --git a/src/main/java/forestry/core/loot/ConditionLootModifier.java b/src/main/java/forestry/core/loot/ConditionLootModifier.java index c767a80002..dbf09594f0 100644 --- a/src/main/java/forestry/core/loot/ConditionLootModifier.java +++ b/src/main/java/forestry/core/loot/ConditionLootModifier.java @@ -1,27 +1,32 @@ package forestry.core.loot; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.ForestryConstants; import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraftforge.common.loot.IGlobalLootModifier; -import net.minecraftforge.common.loot.LootModifier; -import net.minecraftforge.common.loot.LootTableIdCondition; +import net.neoforged.neoforge.common.loot.IGlobalLootModifier; +import net.neoforged.neoforge.common.loot.LootModifier; +import net.neoforged.neoforge.common.loot.LootTableIdCondition; import java.util.Arrays; import java.util.List; +import java.util.Optional; import java.util.function.Consumer; /** * A global loot modifier used by forestry to inject the additional chest loot to the vanilla loot tables. */ public class ConditionLootModifier extends LootModifier { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( LOOT_CONDITIONS_CODEC.fieldOf("conditions").forGetter(lm -> lm.conditions), ResourceLocation.CODEC.fieldOf("table").forGetter(lm -> lm.tableLocation), Codec.list(Codec.STRING).fieldOf("extensions").forGetter(o -> o.extensions) @@ -31,7 +36,6 @@ public class ConditionLootModifier extends LootModifier { private final List extensions; /** - * todo is this still necessary? * Helper field to prevent an endless method loop caused by forge in {@link LootTable#getRandomItems(LootContext, Consumer)} * which calls this method again, since it keeps the {@link LootContext#getQueriedLootTableId()} value, which causes * "getRandomItems" to calling this method again, because the conditions still met even that it is an other loot @@ -65,23 +69,29 @@ protected ObjectArrayList doApply(ObjectArrayList generate return generatedLoot; } - this.operates = true; + // todo is this called by multiple threads + this.operates = true; for (String extension : this.extensions) { - ResourceLocation location = ForestryConstants.forestry(this.tableLocation.getPath() + "/" + extension); - LootTable table = context.getResolver().getLootTable(location); + ResourceKey location = ResourceKey.create(Registries.LOOT_TABLE, ForestryConstants.forestry(this.tableLocation.getPath() + "/" + extension)); + Optional> optional = context.getResolver().get(Registries.LOOT_TABLE, location); - if (table != LootTable.EMPTY) { - table.getRandomItems(context, generatedLoot::add); + if (optional.isPresent()) { + LootTable table = optional.get().value(); + + if (table != LootTable.EMPTY) { + table.getRandomItems(context, generatedLoot::add); + } } } - this.operates = false; + this.operates = false; + return generatedLoot; } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/forestry/core/loot/CoreLootFunctions.java b/src/main/java/forestry/core/loot/CoreLootFunctions.java index b7c3ae3067..689904cbf7 100644 --- a/src/main/java/forestry/core/loot/CoreLootFunctions.java +++ b/src/main/java/forestry/core/loot/CoreLootFunctions.java @@ -7,14 +7,14 @@ import forestry.modules.features.ModFeatureRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; @FeatureProvider public class CoreLootFunctions { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CORE); - private static final DeferredRegister LOOT_FUNCTIONS = REGISTRY.getRegistry(Registries.LOOT_FUNCTION_TYPE); + private static final DeferredRegister> LOOT_FUNCTIONS = REGISTRY.getRegistry(Registries.LOOT_FUNCTION_TYPE); - public static final RegistryObject ORGANISM = LOOT_FUNCTIONS.register("set_species_nbt", () -> new LootItemFunctionType(new OrganismFunction.Serializer())); - public static final RegistryObject COUNT = LOOT_FUNCTIONS.register("count_from_block", () -> new LootItemFunctionType(new CountBlockFunction.Serializer())); + public static final DeferredHolder, LootItemFunctionType> ORGANISM = LOOT_FUNCTIONS.register("set_species_nbt", () -> new LootItemFunctionType<>(OrganismFunction.CODEC)); + public static final DeferredHolder, LootItemFunctionType> COUNT = LOOT_FUNCTIONS.register("count_from_block", () -> new LootItemFunctionType<>(CountBlockFunction.CODEC)); } diff --git a/src/main/java/forestry/core/loot/OrganismFunction.java b/src/main/java/forestry/core/loot/OrganismFunction.java index ce99bb5fda..d36a11fd31 100644 --- a/src/main/java/forestry/core/loot/OrganismFunction.java +++ b/src/main/java/forestry/core/loot/OrganismFunction.java @@ -1,28 +1,36 @@ package forestry.core.loot; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.IForestryApi; import forestry.api.genetics.ILifeStage; import forestry.api.genetics.ISpecies; import forestry.api.genetics.ISpeciesType; import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.functions.LootItemConditionalFunction; import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import java.util.List; + /** * Loot function to add genetic information, an organism, to the item stack. */ public class OrganismFunction extends LootItemConditionalFunction { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> commonFields(instance) + .and(instance.group( + ResourceLocation.CODEC.fieldOf("type_id").forGetter(function -> function.typeId), + ResourceLocation.CODEC.fieldOf("species_id").forGetter(function -> function.speciesId) + )) + .apply(instance, OrganismFunction::new) + ); + private final ResourceLocation typeId; private final ResourceLocation speciesId; - private OrganismFunction(LootItemCondition[] conditions, ResourceLocation typeId, ResourceLocation speciesId) { + private OrganismFunction(List conditions, ResourceLocation typeId, ResourceLocation speciesId) { super(conditions); this.typeId = typeId; this.speciesId = speciesId; @@ -50,23 +58,7 @@ protected ItemStack run(ItemStack stack, LootContext lootContext) { } @Override - public LootItemFunctionType getType() { - return CoreLootFunctions.ORGANISM.get(); - } - - public static class Serializer extends LootItemConditionalFunction.Serializer { - @Override - public void serialize(JsonObject object, OrganismFunction function, JsonSerializationContext context) { - super.serialize(object, function, context); - object.addProperty("type_id", function.typeId.toString()); - object.addProperty("species_id", function.speciesId.toString()); - } - - @Override - public OrganismFunction deserialize(JsonObject object, JsonDeserializationContext jsonDeserializationContext, LootItemCondition[] conditions) { - String typeId = GsonHelper.getAsString(object, "type_id"); - String speciesId = GsonHelper.getAsString(object, "species_id"); - return new OrganismFunction(conditions, new ResourceLocation(typeId), new ResourceLocation(speciesId)); - } + public LootItemFunctionType getType() { + return CoreLootFunctions.ORGANISM.value(); } } diff --git a/src/main/java/forestry/core/loot/package-info.java b/src/main/java/forestry/core/loot/package-info.java index 2bdd5c50ce..657c2c4eb0 100644 --- a/src/main/java/forestry/core/loot/package-info.java +++ b/src/main/java/forestry/core/loot/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.loot; diff --git a/src/main/java/forestry/core/models/AbstractBakedModel.java b/src/main/java/forestry/core/models/AbstractBakedModel.java index e19db3b05a..731c157a1a 100644 --- a/src/main/java/forestry/core/models/AbstractBakedModel.java +++ b/src/main/java/forestry/core/models/AbstractBakedModel.java @@ -19,8 +19,8 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.Collections; diff --git a/src/main/java/forestry/core/models/ClientManager.java b/src/main/java/forestry/core/models/ClientManager.java index 63bbc2d7c3..a6942ab4a2 100644 --- a/src/main/java/forestry/core/models/ClientManager.java +++ b/src/main/java/forestry/core/models/ClientManager.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.models; import forestry.core.blocks.IColoredBlock; @@ -29,7 +19,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.event.ModelEvent; +import net.neoforged.neoforge.client.event.ModelEvent; import javax.annotation.Nullable; import java.util.ArrayList; @@ -64,20 +54,18 @@ public enum ClientManager { public ModelState getDefaultBlockState() { if (this.defaultBlockState == null) { - this.defaultBlockState = ResourceUtil.loadTransform(new ResourceLocation("block/block")); + this.defaultBlockState = ResourceUtil.loadTransform(ResourceLocation.withDefaultNamespace("block/block")); } return this.defaultBlockState; } public void registerModel(BakedModel model, Object feature) { - if (feature instanceof FeatureGroup group) { - group.getFeatures().forEach(f -> registerModel(model, f)); - } else if (feature instanceof FeatureTable group) { - group.getFeatures().forEach(f -> registerModel(model, f)); - } else if (feature instanceof FeatureBlock block) { - registerModel(model, block.block(), block.item()); - } else if (feature instanceof FeatureItem item) { - registerModel(model, item.item()); + switch (feature) { + case FeatureGroup group -> group.getFeatures().forEach(f -> registerModel(model, f)); + case FeatureTable group -> group.getFeatures().forEach(f -> registerModel(model, f)); + case FeatureBlock block -> registerModel(model, block.block(), block.item()); + case FeatureItem item -> registerModel(model, item.item()); + default -> {} } } @@ -86,16 +74,16 @@ public void registerModel(BakedModel model, Block block, @Nullable BlockItem ite } public void registerModel(BakedModel model, Block block, @Nullable BlockItem item, Collection states) { - this.customBlockModels.add(new BlockModelEntry(model, block, item, states)); + this.customBlockModels.add(new BlockModelEntry(model, block, item, states)); } public void registerModel(BakedModel model, Item item) { - this.customModels.add(new ModelEntry(new ModelResourceLocation(ModUtil.getRegistryName(item), "inventory"), model)); + this.customModels.add(new ModelEntry(new ModelResourceLocation(ModUtil.getRegistryName(item), "inventory"), model)); } public void onBakeModels(ModelEvent.ModifyBakingResult event) { //register custom models - Map registry = event.getModels(); + Map registry = event.getModels(); for (final BlockModelEntry entry : this.customBlockModels) { for (BlockState state : entry.states) { registry.put(BlockModelShaper.stateToModelLocation(state), entry.model); diff --git a/src/main/java/forestry/core/models/FluidContainerModel.java b/src/main/java/forestry/core/models/FluidContainerModel.java index 29c0fcfb30..c9dadccc51 100644 --- a/src/main/java/forestry/core/models/FluidContainerModel.java +++ b/src/main/java/forestry/core/models/FluidContainerModel.java @@ -16,13 +16,14 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.client.model.CompositeModel; -import net.minecraftforge.client.model.DynamicFluidContainerModel; -import net.minecraftforge.client.model.QuadTransformers; -import net.minecraftforge.client.model.geometry.*; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.client.ClientHooks; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.client.model.CompositeModel; +import net.neoforged.neoforge.client.model.DynamicFluidContainerModel; +import net.neoforged.neoforge.client.model.QuadTransformers; +import net.neoforged.neoforge.client.model.geometry.*; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.internal.versions.neoforge.NeoForgeVersion; import org.jetbrains.annotations.Nullable; import java.util.Collections; @@ -49,12 +50,12 @@ public FluidContainerModel withFluid(Fluid newFluid) { // Note: The fluid mask is ignored, the fluid element is always from (4, 2) to (12, 14). @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { Material baseLocation = context.hasMaterial("base") ? context.getMaterial("base") : null; Material fluidMaskLocation = context.hasMaterial("fluid") ? context.getMaterial("fluid") : null; Material coverLocation = context.hasMaterial("cover") ? context.getMaterial("cover") : null; TextureAtlasSprite baseSprite = baseLocation != null ? spriteGetter.apply(baseLocation) : null; - TextureAtlasSprite fluidSprite = this.fluid != Fluids.EMPTY ? spriteGetter.apply(ForgeHooksClient.getBlockMaterial(IClientFluidTypeExtensions.of(this.fluid).getStillTexture())) : null; + TextureAtlasSprite fluidSprite = this.fluid != Fluids.EMPTY ? spriteGetter.apply(ClientHooks.getBlockMaterial(IClientFluidTypeExtensions.of(this.fluid).getStillTexture())) : null; TextureAtlasSprite coverSprite = (coverLocation != null && (!this.coverIsMask || baseLocation != null)) ? spriteGetter.apply(coverLocation) : null; TextureAtlasSprite particleSprite = fluidSprite; @@ -64,13 +65,14 @@ public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Functio particleSprite = coverSprite; } - var itemContext = StandaloneGeometryBakingContext.builder(context).withGui3d(false).withUseBlockLight(false).build(modelLocation); + // todo is this modelLocation correct? + var itemContext = StandaloneGeometryBakingContext.builder(context).withGui3d(false).withUseBlockLight(false).build(ResourceLocation.fromNamespaceAndPath("neoforge", "dynamic_fluid_container")); var modelBuilder = CompositeModel.Baked.builder(itemContext, particleSprite, new ContainedFluidOverrideHandler(baker, itemContext, this), context.getTransforms()); var normalRenderTypes = DynamicFluidContainerModel.getLayerRenderTypes(false); if (baseLocation != null && baseSprite != null) { - var baseElement = UnbakedGeometryHelper.createUnbakedItemElements(0, baseSprite.contents()); - var quads = UnbakedGeometryHelper.bakeElements(baseElement, $ -> baseSprite, modelState, modelLocation); + var baseElement = UnbakedGeometryHelper.createUnbakedItemElements(0, baseSprite); + var quads = UnbakedGeometryHelper.bakeElements(baseElement, $ -> baseSprite, modelState); modelBuilder.addQuads(normalRenderTypes, quads); } @@ -78,7 +80,7 @@ public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Functio if (fluidMaskLocation != null && fluidSprite != null) { // no edges var fluidElement = Collections.singletonList(FilledCrateModel.make2dElement(1, 4, 2, 12, 14, -0.002f)); - var quads = UnbakedGeometryHelper.bakeElements(fluidElement, $ -> fluidSprite, modelState, modelLocation); + var quads = UnbakedGeometryHelper.bakeElements(fluidElement, $ -> fluidSprite, modelState); var emissive = this.applyFluidLuminosity && this.fluid.getFluidType().getLightLevel() > 0; var renderTypes = DynamicFluidContainerModel.getLayerRenderTypes(emissive); @@ -94,7 +96,7 @@ public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Functio if (sprite != null) { // no edges var coverElement = Collections.singletonList(FilledCrateModel.make2dElement(2, 0, 0, 16, 16, 0.002f)); // Use cover as mask - var quads = UnbakedGeometryHelper.bakeElements(coverElement, $ -> sprite, modelState, modelLocation); // Bake with selected texture + var quads = UnbakedGeometryHelper.bakeElements(coverElement, $ -> sprite, modelState); // Bake with selected texture modelBuilder.addQuads(normalRenderTypes, quads); } } @@ -138,8 +140,8 @@ public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable C if (!this.cache.containsKey(name)) { FluidContainerModel unbaked = this.parent.withFluid(fluid); - BakedModel bakedModel = unbaked.bake(this.owner, this.bakery, Material::sprite, BlockModelRotation.X0_Y0, this, new ResourceLocation("forge:bucket_override")); - this.cache.put(name, bakedModel); + BakedModel bakedModel = unbaked.bake(this.owner, this.bakery, Material::sprite, BlockModelRotation.X0_Y0, this, ResourceLocation.fromNamespaceAndPath(NeoForgeVersion.MOD_ID, "bucket_override")); + this.cache.put(name, bakedModel); return bakedModel; } diff --git a/src/main/java/forestry/core/models/ModelBlockCached.java b/src/main/java/forestry/core/models/ModelBlockCached.java index 0a9b55c173..413743ffca 100644 --- a/src/main/java/forestry/core/models/ModelBlockCached.java +++ b/src/main/java/forestry/core/models/ModelBlockCached.java @@ -7,7 +7,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; import java.util.HashSet; import java.util.Set; @@ -30,8 +30,8 @@ public static void clear() { protected ModelBlockCached(Class blockClass) { super(blockClass); - this.worldCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); - this.inventoryCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); + this.worldCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); + this.inventoryCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); CACHE_PROVIDERS.add(this); } @@ -43,7 +43,7 @@ protected BakedModel getModel(BlockState state, ModelData extraData) { BakedModel model = this.worldCache.getIfPresent(key); if (model == null) { model = super.getModel(state, extraData); - this.worldCache.put(key, model); + this.worldCache.put(key, model); } return model; } @@ -55,7 +55,7 @@ protected BakedModel getModel(ItemStack stack, Level world) { BakedModel model = this.inventoryCache.getIfPresent(key); if (model == null) { model = bakeModel(stack, world, key); - this.inventoryCache.put(key, model); + this.inventoryCache.put(key, model); } return model; } diff --git a/src/main/java/forestry/core/models/ModelBlockDefault.java b/src/main/java/forestry/core/models/ModelBlockDefault.java index 84db2990b9..317f606720 100644 --- a/src/main/java/forestry/core/models/ModelBlockDefault.java +++ b/src/main/java/forestry/core/models/ModelBlockDefault.java @@ -29,7 +29,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -55,7 +55,7 @@ protected BakedModel bakeModel(BlockState state, K key, B block, ModelData extra bakeBlock(block, extraData, key, baker, false); - this.blockModel = baker.bake(false); + this.blockModel = baker.bake(false); onCreateModel(this.blockModel); return this.blockModel; } @@ -144,7 +144,7 @@ protected ItemOverrides createOverrides() { @Override public ItemOverrides getOverrides() { if (this.overrideList == null) { - this.overrideList = createOverrides(); + this.overrideList = createOverrides(); } return this.overrideList; } diff --git a/src/main/java/forestry/core/models/TRSRBakedModel.java b/src/main/java/forestry/core/models/TRSRBakedModel.java index 52df028b2c..ecb10c538b 100644 --- a/src/main/java/forestry/core/models/TRSRBakedModel.java +++ b/src/main/java/forestry/core/models/TRSRBakedModel.java @@ -1,15 +1,3 @@ -/******************************************************************************* - * The MIT License (MIT) - * Copyright (c) 2013-2014 Slime Knights (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Any alternate licenses are noted where appropriate. - ******************************************************************************/ package forestry.core.models; import com.google.common.collect.ImmutableList; @@ -24,9 +12,9 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.BakedModelWrapper; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.common.util.TransformationHelper; +import net.neoforged.neoforge.client.model.BakedModelWrapper; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.common.util.TransformationHelper; import org.jetbrains.annotations.NotNull; import org.joml.Vector3f; @@ -45,10 +33,6 @@ public TRSRBakedModel(BakedModel original, float x, float y, float z, float scal this(original, x, y, z, 0, 0, 0, scale, scale, scale); } - public TRSRBakedModel(BakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scale) { - this(original, x, y, z, rotX, rotY, rotZ, scale, scale, scale); - } - public TRSRBakedModel(BakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ) { this(original, new Transformation(new Vector3f(x, y, z), null, @@ -91,7 +75,7 @@ public TRSRBakedModel(BakedModel original, Direction facing) { //quad.pipe(transformer); builder.add(transformer.build());*/ } - } catch (Exception e) { + } catch (Exception ignored) { } } @@ -110,7 +94,6 @@ public ItemOverrides getOverrides() { } private static class TRSROverride extends ItemOverrides { - private final TRSRBakedModel model; public TRSROverride(TRSRBakedModel model) { @@ -127,49 +110,4 @@ public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable C return new TRSRBakedModel(baked, this.model.transformation); } } -/* - private static class Transformer extends VertexTransformer { - - protected Matrix4f transformation; - protected Matrix3f normalTransformation; - - public Transformer(Transformation transformation, TextureAtlasSprite textureAtlasSprite) { - super(new BakedQuadBuilder(textureAtlasSprite)); - // position transform - this.transformation = transformation.getMatrix(); - // normal transform - this.normalTransformation = new Matrix3f(this.transformation); - this.normalTransformation.invert(); - this.normalTransformation.transpose(); - } - - @Override - public void put(int element, float... data) { - VertexFormatElement.Usage usage = DefaultVertexFormat.BLOCK.getElements().get(element).getUsage(); - - // transform normals and position - if (usage == VertexFormatElement.Usage.POSITION && data.length >= 3) { - Vector4f vec = new Vector4f(data[0], data[1], data[2], 1f); - vec.transform(this.transformation); - data = new float[4]; - data[0] = vec.x(); - data[1] = vec.y(); - data[2] = vec.z(); - data[3] = vec.w(); - } else if (usage == VertexFormatElement.Usage.NORMAL && data.length >= 3) { - Vector3f vec = new Vector3f(data); - vec.transform(this.normalTransformation); - vec.normalize(); - data = new float[4]; - data[0] = vec.x(); - data[1] = vec.y(); - data[2] = vec.z(); - } - super.put(element, data); - } - - public BakedQuad build() { - return ((BakedQuadBuilder) this.parent).build(); - } - }*/ } diff --git a/src/main/java/forestry/core/models/baker/ModelBaker.java b/src/main/java/forestry/core/models/baker/ModelBaker.java index 51db65e09e..7e5b34d9c9 100644 --- a/src/main/java/forestry/core/models/baker/ModelBaker.java +++ b/src/main/java/forestry/core/models/baker/ModelBaker.java @@ -21,8 +21,8 @@ import net.minecraft.client.resources.model.BlockModelRotation; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import org.joml.Vector3f; import java.util.ArrayList; diff --git a/src/main/java/forestry/core/models/baker/ModelBakerFace.java b/src/main/java/forestry/core/models/baker/ModelBakerFace.java index a37c15ac56..5110d911c6 100644 --- a/src/main/java/forestry/core/models/baker/ModelBakerFace.java +++ b/src/main/java/forestry/core/models/baker/ModelBakerFace.java @@ -12,8 +12,8 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; /** * A face of a {@link ModelBakerModel } diff --git a/src/main/java/forestry/core/models/baker/ModelBakerModel.java b/src/main/java/forestry/core/models/baker/ModelBakerModel.java index c7f157c7e0..9492916ed5 100755 --- a/src/main/java/forestry/core/models/baker/ModelBakerModel.java +++ b/src/main/java/forestry/core/models/baker/ModelBakerModel.java @@ -21,8 +21,8 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nullable; diff --git a/src/main/java/forestry/core/models/baker/package-info.java b/src/main/java/forestry/core/models/baker/package-info.java index 3fc540c862..ec429f5840 100644 --- a/src/main/java/forestry/core/models/baker/package-info.java +++ b/src/main/java/forestry/core/models/baker/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.models.baker; diff --git a/src/main/java/forestry/core/models/package-info.java b/src/main/java/forestry/core/models/package-info.java index 3bfef03e64..66d1188c73 100644 --- a/src/main/java/forestry/core/models/package-info.java +++ b/src/main/java/forestry/core/models/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.models; diff --git a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java index b1a5f5374c..60b7b78489 100644 --- a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java +++ b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java @@ -19,8 +19,9 @@ import forestry.core.owner.FakeOwnerHandler; import forestry.core.owner.IOwnerHandler; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.level.Level; import java.util.Collection; @@ -66,15 +67,15 @@ default void recalculateMinMaxCoords() { } @Override - default void formatDescriptionPacket(CompoundTag data) { + default void encodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries) { } @Override - default void decodeDescriptionPacket(CompoundTag data) { + default void decodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries) { } @Override - default Level getWorldObj() { + default Level getLevel() { return null; } @@ -127,11 +128,11 @@ default Collection getComponents() { } @Override - default void read(CompoundTag CompoundNBT) { + default void read(CompoundTag CompoundNBT, HolderLookup.Provider registries) { } @Override - default CompoundTag write(CompoundTag CompoundNBT) { + default CompoundTag write(CompoundTag CompoundNBT, HolderLookup.Provider registries) { return CompoundNBT; } @@ -156,10 +157,10 @@ default IErrorLogic getErrorLogic() { } @Override - default void writeGuiData(FriendlyByteBuf data) { + default void writeGuiData(RegistryFriendlyByteBuf buffer) { } @Override - default void readGuiData(FriendlyByteBuf data) { + default void readGuiData(RegistryFriendlyByteBuf buffer) { } } diff --git a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java index b1b598973c..b1db9a41e2 100644 --- a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java +++ b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.multiblock; import forestry.api.climate.IClimateProvider; @@ -19,6 +9,7 @@ import forestry.core.network.IStreamableGui; import forestry.core.owner.IOwnedTile; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.Level; @@ -101,18 +92,20 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN /** * Called when the save delegate's tile entity is being asked for its description packet * - * @param data A fresh compound tag to write your multiblock data into + * @param data A fresh compound tag to write your multiblock data into + * @param registries Registry access */ - void formatDescriptionPacket(CompoundTag data); + void encodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries); /** * Called when the save delegate's tile entity receiving a description packet * - * @param data A compound tag containing multiblock data to import + * @param data A compound tag containing multiblock data to import + * @param registries */ - void decodeDescriptionPacket(CompoundTag data); + void decodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries); - Level getWorldObj(); + Level getLevel(); /** * @return True if this controller has no associated blocks, false otherwise diff --git a/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java b/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java deleted file mode 100644 index 4f4d48ceef..0000000000 --- a/src/main/java/forestry/core/multiblock/IMultiblockSizeLimits.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.multiblock; - -public interface IMultiblockSizeLimits { - /** - * Helper method so we don't check for a whole machine until we have enough blocks - * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines - * or for machines with hollow/complex interiors. - * - * @return The minimum number of blocks connected to the machine for it to be assembled. - */ - int getMinimumNumberOfBlocksForAssembledMachine(); - - /** - * Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * - * @return The maximum X dimension size of the machine, or -1 - */ - int getMaximumXSize(); - - /** - * Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * - * @return The maximum Z dimension size of the machine, or -1 - */ - int getMaximumZSize(); - - /** - * Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable - * dimension checking in X. (This is not recommended.) - * - * @return The maximum Y dimension size of the machine, or -1 - */ - int getMaximumYSize(); - - /** - * Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense. - * - * @return The minimum X dimension size of the machine - */ - int getMinimumXSize(); - - /** - * Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense. - * - * @return The minimum Y dimension size of the machine - */ - int getMinimumYSize(); - - /** - * Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense. - * - * @return The minimum Z dimension size of the machine - */ - int getMinimumZSize(); -} diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java index d579515dec..40684eddd3 100755 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java @@ -11,8 +11,8 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.chunk.ChunkSource; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.*; @@ -107,7 +107,7 @@ public Collection getComponents() { @Override public void attachBlock(IMultiblockComponent part) { - BlockPos coord = part.getCoordinates(); + BlockPos coord = part.getBlockPos(); if (!this.connectedParts.add(part)) { Forestry.LOGGER.warn("[{}] Controller {} is double-adding part {} @ {}. This is unusual. " + @@ -118,7 +118,7 @@ public void attachBlock(IMultiblockComponent part) { MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); logic.setController(this); - this.onBlockAdded(part); + onBlockAdded(part); if (logic.hasMultiblockSaveData()) { CompoundTag savedData = logic.getMultiblockSaveData(); @@ -227,7 +227,7 @@ private void onDetachBlock(IMultiblockComponent part) { this.minimumCoord = this.maximumCoord = null; - if (this.referenceCoord != null && this.referenceCoord.equals(part.getCoordinates())) { + if (this.referenceCoord != null && this.referenceCoord.equals(part.getBlockPos())) { this.referenceCoord = null; } @@ -245,7 +245,7 @@ public void detachBlock(IMultiblockComponent part, boolean chunkUnloading) { // Strip out this part onDetachBlock(part); if (!this.connectedParts.remove(part)) { - BlockPos partCoords = part.getCoordinates(); + BlockPos partCoords = part.getBlockPos(); Forestry.LOGGER.warn("[{}] Double-removing part ({}) @ {}, {}, {}, this is unexpected and may cause problems. " + "If you encounter anomalies, please tear down the reactor and rebuild it.", this.level.isClientSide() ? "CLIENT" : "SERVER", part.hashCode(), partCoords.getX(), partCoords.getY(), partCoords.getZ()); @@ -516,7 +516,7 @@ public void recalculateMinMaxCoords() { this.maximumCoord = new BlockPos(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); for (IMultiblockComponent part : this.connectedParts) { - BlockPos partCoords = part.getCoordinates(); + BlockPos partCoords = part.getBlockPos(); int minX = this.minimumCoord.getX(); int minY = this.minimumCoord.getY(); int minZ = this.minimumCoord.getZ(); @@ -656,7 +656,7 @@ public String getPartsListString() { if (!first) { sb.append(", "); } - BlockPos partCoord = part.getCoordinates(); + BlockPos partCoord = part.getBlockPos(); sb.append(String.format("(%d: %d, %d, %d)", part.hashCode(), partCoord.getX(), partCoord.getY(), partCoord.getZ())); first = false; } @@ -668,7 +668,7 @@ public String getPartsListString() { public void auditParts() { HashSet deadParts = new HashSet<>(); for (IMultiblockComponent part : this.connectedParts) { - BlockPos partCoord = part.getCoordinates(); + BlockPos partCoord = part.getBlockPos(); if (isInvalid(part) || TileUtil.getTile(this.level, partCoord) != part) { onDetachBlock(part); deadParts.add(part); @@ -705,7 +705,7 @@ public Set checkForDisconnections() { for (IMultiblockComponent part : this.connectedParts) { // This happens during chunk unload. - BlockPos partCoord = part.getCoordinates(); + BlockPos partCoord = part.getBlockPos(); if (chunkProvider.getChunkNow(partCoord.getX() >> 4, partCoord.getZ() >> 4) == null || isInvalid(part)) { deadParts.add(part); onDetachBlock(part); @@ -723,7 +723,7 @@ public Set checkForDisconnections() { logic.setUnvisited(); logic.forfeitMultiblockSaveDelegate(); - c = part.getCoordinates(); + c = part.getBlockPos(); if (this.referenceCoord == null) { this.referenceCoord = c; referencePart = part; @@ -805,7 +805,7 @@ public Set checkForDisconnections() { public Set detachAllBlocks() { ChunkSource chunkProvider = this.level.getChunkSource(); for (IMultiblockComponent part : this.connectedParts) { - BlockPos partCoord = part.getCoordinates(); + BlockPos partCoord = part.getBlockPos(); if (chunkProvider.getChunkNow(partCoord.getX() >> 4, partCoord.getZ() >> 4) != null) { onDetachBlock(part); } @@ -831,14 +831,14 @@ private BlockPos selectNewReferenceCoord() { this.referenceCoord = null; for (IMultiblockComponent part : this.connectedParts) { - BlockPos partCoord = part.getCoordinates(); + BlockPos partCoord = part.getBlockPos(); if (isInvalid(part) || chunkProvider.getChunkNow(partCoord.getX() >> 4, partCoord.getZ() >> 4) == null) { // Chunk is unloading, skip this coord to prevent chunk thrashing continue; } if (this.referenceCoord == null || this.referenceCoord.compareTo(partCoord) > 0) { - this.referenceCoord = part.getCoordinates(); + this.referenceCoord = part.getBlockPos(); theChosenOne = part; } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java index b02cbff188..34e2df5a33 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java @@ -1,18 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.multiblock; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; -import com.mojang.authlib.GameProfile; import forestry.api.IForestryApi; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; @@ -24,10 +13,12 @@ import forestry.core.owner.IOwnerHandler; import forestry.core.owner.OwnerHandler; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; public abstract class MultiblockControllerForestry extends MultiblockControllerBase implements WorldlyContainer, IOwnedTile, IErrorLogicSource, ILocationProvider { @@ -52,7 +43,7 @@ public IErrorLogic getErrorLogic() { } @Override - public Level getWorldObj() { + public Level getLevel() { return this.level; } @@ -66,17 +57,17 @@ protected void onMachineAssembled() { // Figure out who owns the multiblock, by majority - Multiset owners = HashMultiset.create(); + Multiset owners = HashMultiset.create(); for (IMultiblockComponent part : this.connectedParts) { - GameProfile owner = part.getOwner(); + ResolvableProfile owner = part.getOwner(); if (owner != null) { owners.add(owner); } } - GameProfile owner = null; + ResolvableProfile owner = null; int max = 0; - for (Multiset.Entry entry : owners.entrySet()) { + for (Multiset.Entry entry : owners.entrySet()) { int count = entry.getCount(); if (count > max) { max = count; @@ -91,14 +82,14 @@ protected void onMachineAssembled() { /* INbtWritable */ @Override - public CompoundTag write(CompoundTag data) { - this.ownerHandler.write(data); + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { + this.ownerHandler.write(data, registries); return data; } @Override - public void read(CompoundTag data) { - this.ownerHandler.read(data); + public void read(CompoundTag data, HolderLookup.Provider registries) { + this.ownerHandler.read(data, registries); } /* INVENTORY */ diff --git a/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java b/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java deleted file mode 100755 index c9189b2562..0000000000 --- a/src/main/java/forestry/core/multiblock/MultiblockEventHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package forestry.core.multiblock; - -import forestry.api.ForestryConstants; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraftforge.event.level.ChunkEvent; -import net.minecraftforge.event.level.LevelEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; - -/** - * In your mod, subscribe this on both the client and server sides side to handle chunk - * load events for your multiblock machines. - * Chunks can load asynchronously in environments like MCPC+, so we cannot - * process any blocks that are in chunks which are still loading. - */ -@Mod.EventBusSubscriber(modid = ForestryConstants.MOD_ID) -public class MultiblockEventHandler { - @SubscribeEvent - public static void onChunkLoad(ChunkEvent.Load loadEvent) { - ChunkAccess chunk = loadEvent.getChunk(); - LevelAccessor world = loadEvent.getLevel(); - MultiblockRegistry.onChunkLoaded(world, chunk.getPos().x, chunk.getPos().z); - } - - // Cleanup, for nice memory usageness - @SubscribeEvent - public static void onWorldUnload(LevelEvent.Unload unloadEvent) { - MultiblockRegistry.onWorldUnloaded(unloadEvent.getLevel()); - } -} diff --git a/src/main/java/forestry/core/multiblock/MultiblockLogic.java b/src/main/java/forestry/core/multiblock/MultiblockLogic.java index 036cf77650..6969e1acb6 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockLogic.java +++ b/src/main/java/forestry/core/multiblock/MultiblockLogic.java @@ -1,19 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.multiblock; import forestry.Forestry; import forestry.api.multiblock.IMultiblockComponent; import forestry.api.multiblock.IMultiblockLogic; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.Level; @@ -62,22 +53,22 @@ public Class getControllerClass() { *

* TL;DR: Here there be dragons. * - * @see net.minecraft.tileentity.TileEntity#validate() + * @see net.minecraft.world.level.block.entity.BlockEntity#validate() */ @Override - public void validate(Level world, IMultiblockComponent part) { - MultiblockRegistry.onPartAdded(world, part); + public void validate(Level level, IMultiblockComponent part) { + MultiblockRegistry.onPartAdded(level, part); } /** * Called when a block is removed by game actions, such as a player breaking the block * or the block being changed into another block. * - * @see net.minecraft.tileentity.TileEntity#invalidate() + * @see net.minecraft.world.level.block.entity.BlockEntity#setRemoved() */ @Override - public final void invalidate(Level world, IMultiblockComponent part) { - detachSelf(world, part, false); + public final void setRemoved(Level level, IMultiblockComponent part) { + detachSelf(level, part, false); } /** @@ -85,11 +76,11 @@ public final void invalidate(Level world, IMultiblockComponent part) { * as the chunk in which this tile entity is contained is unloading. * Happens before the Forge TickEnd event. * - * @see net.minecraft.tileentity.TileEntity#onChunkUnload() + * @see net.minecraft.world.level.block.entity.BlockEntity#onChunkUnloaded() */ @Override - public final void onChunkUnload(Level world, IMultiblockComponent part) { - detachSelf(world, part, true); + public final void onChunkUnload(Level level, IMultiblockComponent part) { + detachSelf(level, part, true); } /* @@ -109,27 +100,27 @@ protected void detachSelf(Level world, IMultiblockComponent part, boolean chunkU } @Override - public void readFromNBT(CompoundTag data) { + public void read(CompoundTag nbt, HolderLookup.Provider registries) { // We can't directly initialize a multiblock controller yet, so we cache the data here until // we receive a validate() call, which creates the controller and hands off the cached data. - if (data.contains("multiblockData")) { - this.cachedMultiblockData = data.getCompound("multiblockData"); + if (nbt.contains("multiblockData")) { + this.cachedMultiblockData = nbt.getCompound("multiblockData"); } } @Override - public CompoundTag write(CompoundTag data) { + public CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries) { if (isMultiblockSaveDelegate() && this.controller != null) { CompoundTag multiblockData = new CompoundTag(); - this.controller.write(multiblockData); - data.put("multiblockData", multiblockData); + this.controller.write(multiblockData, registries); + nbt.put("multiblockData", multiblockData); } - return data; + return nbt; } public final void assertDetached(IMultiblockComponent part) { if (this.controller != null) { - BlockPos coords = part.getCoordinates(); + BlockPos coords = part.getBlockPos(); Forestry.LOGGER.info("[assert] Part @ ({}, {}, {}) should be detached already, but detected that it was not. This is not a fatal error, and will be repaired, but is unusual.", coords.getX(), coords.getY(), coords.getZ()); this.controller = null; } @@ -180,31 +171,33 @@ public final void onMultiblockDataAssimilated() { /** * Override this to easily modify the description packet's data without having * to worry about sending the packet itself. - * Decode this data in decodeDescriptionPacket. + * Decode this data in decodeUpdatePacket. * - * @param packetData An NBT compound tag into which you should write your custom description data. + * @param nbt An NBT compound tag into which you should write your custom description data. + * @param registries Registry access */ @Override - public void encodeDescriptionPacket(CompoundTag packetData) { + public void encodeUpdatePacket(CompoundTag nbt, HolderLookup.Provider registries) { if (this.isMultiblockSaveDelegate() && this.controller != null) { CompoundTag tag = new CompoundTag(); - this.controller.formatDescriptionPacket(tag); - packetData.put("multiblockData", tag); + this.controller.encodeUpdatePacket(tag, registries); + nbt.put("multiblockData", tag); } } /** * Override this to easily read in data from a TileEntity's description packet. - * Encoded in encodeDescriptionPacket. + * Encoded in encodeUpdatePacket. * - * @param packetData The NBT data from the tile entity's description packet. + * @param nbt The NBT data from the tile entity's description packet. + * @param registries Registry access */ @Override - public void decodeDescriptionPacket(CompoundTag packetData) { - if (packetData.contains("multiblockData")) { - CompoundTag tag = packetData.getCompound("multiblockData"); + public void decodeUpdatePacket(CompoundTag nbt, HolderLookup.Provider registries) { + if (nbt.contains("multiblockData")) { + CompoundTag tag = nbt.getCompound("multiblockData"); if (this.controller != null) { - this.controller.decodeDescriptionPacket(tag); + this.controller.decodeUpdatePacket(tag, registries); } else { // This part hasn't been added to a machine yet, so cache the data. this.cachedMultiblockData = tag; diff --git a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java index 172544ee23..84db0d6f4e 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java @@ -49,11 +49,11 @@ public static void onChunkLoaded(LevelAccessor world, int chunkX, int chunkZ) { /** * Register a new part in the system. The part has been created either through user action or via a chunk loading. * - * @param world The world into which this part is loading. + * @param level The world into which this part is loading. * @param part The part being loaded. */ - public static void onPartAdded(Level world, IMultiblockComponent part) { - MultiblockWorldRegistry registry = getOrCreateRegistry(world); + public static void onPartAdded(Level level, IMultiblockComponent part) { + MultiblockWorldRegistry registry = getOrCreateRegistry(level); registry.onPartAdded(part); } @@ -125,12 +125,12 @@ public static Set getControllersFromWorld(LevelAc } /// *** PRIVATE HELPERS *** /// - private static MultiblockWorldRegistry getOrCreateRegistry(Level world) { - if (registries.containsKey(world)) { - return registries.get(world); + private static MultiblockWorldRegistry getOrCreateRegistry(Level level) { + if (registries.containsKey(level)) { + return registries.get(level); } else { - MultiblockWorldRegistry newRegistry = new MultiblockWorldRegistry(world); - registries.put(world, newRegistry); + MultiblockWorldRegistry newRegistry = new MultiblockWorldRegistry(level); + registries.put(level, newRegistry); return newRegistry; } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockSizeLimits.java b/src/main/java/forestry/core/multiblock/MultiblockSizeLimits.java new file mode 100644 index 0000000000..4125b2182d --- /dev/null +++ b/src/main/java/forestry/core/multiblock/MultiblockSizeLimits.java @@ -0,0 +1,40 @@ +package forestry.core.multiblock; + +import com.google.common.base.Preconditions; + +/** + * @param minimumNumberOfBlocksForAssembledMachine The minimum number of blocks connected to the machine for it to be + * assembled. Helper method so we don't check for a whole machine until + * we have enough blocks to actually assemble it. This isn't as simple + * as xmax*ymax*zmax for non-cubic machines or for machines with + * hollow/complex interiors. + * @param minimumXSize The minimum X dimension size of the machine + * @param minimumYSize The minimum Y dimension size of the machine + * @param minimumZSize The minimum Z dimension size of the machine + * @param maximumXSize The maximum X dimension size of the machine, or {@link #DIMENSION_UNBOUNDED} + * @param maximumYSize The maximum Y dimension size of the machine, or {@link #DIMENSION_UNBOUNDED} + * @param maximumZSize The maximum Z dimension size of the machine, or {@link #DIMENSION_UNBOUNDED} + */ +public record MultiblockSizeLimits( + int minimumNumberOfBlocksForAssembledMachine, + int minimumXSize, + int minimumYSize, + int minimumZSize, + int maximumXSize, + int maximumYSize, + int maximumZSize +) { + /** + * Used to specify that this multiblock has no maximum size in a given dimension. + */ + public static final int DIMENSION_UNBOUNDED = -1; + + public MultiblockSizeLimits { + Preconditions.checkArgument(minimumXSize >= 1); + Preconditions.checkArgument(minimumYSize >= 1); + Preconditions.checkArgument(minimumZSize >= 1); + Preconditions.checkArgument(maximumXSize >= minimumXSize || maximumXSize == DIMENSION_UNBOUNDED); + Preconditions.checkArgument(maximumYSize >= minimumYSize || maximumYSize == DIMENSION_UNBOUNDED); + Preconditions.checkArgument(maximumZSize >= minimumZSize || maximumZSize == DIMENSION_UNBOUNDED); + } +} diff --git a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java index 7cd80b7bcf..45c5f4ec56 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.multiblock; -import com.mojang.authlib.GameProfile; import forestry.api.core.ILocationProvider; import forestry.api.core.ISpectacleBlock; import forestry.api.multiblock.IMultiblockLogic; @@ -21,23 +10,23 @@ import forestry.core.tiles.IFilterSlotDelegate; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; +import net.minecraft.nbt.NbtOps; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.MenuProvider; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkHooks; import javax.annotation.Nullable; public abstract class MultiblockTileEntityForestry extends MultiblockTileEntityBase implements WorldlyContainer, IFilterSlotDelegate, ILocationProvider, MenuProvider, ISpectacleBlock { @Nullable - private GameProfile owner; + private ResolvableProfile owner; public MultiblockTileEntityForestry(BlockEntityType tileEntityType, BlockPos pos, BlockState state, T multiblockLogic) { super(tileEntityType, pos, state, multiblockLogic); @@ -47,32 +36,32 @@ public MultiblockTileEntityForestry(BlockEntityType tileEntityType, BlockPos * Called by a structure block when it is right clicked by a player. */ public void openGui(ServerPlayer player, BlockPos pos) { - NetworkHooks.openScreen(player, this, pos); + player.openMenu(this, pos); } @Override - public void load(CompoundTag data) { - super.load(data); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - if (data.contains("owner")) { - CompoundTag ownerNbt = data.getCompound("owner"); - this.owner = NbtUtils.readGameProfile(ownerNbt); + if (nbt.contains("owner")) { + ResolvableProfile.CODEC + .parse(NbtOps.INSTANCE, nbt.get("profile")) + .result() + .ifPresent(this::setOwner); } - getInternalInventory().read(data); + getInternalInventory().read(nbt, registries); } @Override - public void saveAdditional(CompoundTag data) { - super.saveAdditional(data); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); if (this.owner != null) { - CompoundTag nbt = new CompoundTag(); - NbtUtils.writeGameProfile(nbt, this.owner); - data.put("owner", nbt); + nbt.put("owner", ResolvableProfile.CODEC.encodeStart(NbtOps.INSTANCE, this.owner).getOrThrow()); } - getInternalInventory().write(data); + getInternalInventory().write(nbt, registries); } /* INVENTORY */ @@ -168,21 +157,13 @@ public final boolean isLocked(int slotIndex) { return getInternalInventory().isLocked(slotIndex); } - /* ILocatable */ - @Override - public final @Nullable Level getWorldObj() { - return this.level; - } - - /* IMultiblockComponent */ - @Override @Nullable - public final GameProfile getOwner() { + public final @Nullable ResolvableProfile getOwner() { return this.owner; } - public final void setOwner(GameProfile owner) { + public final void setOwner(@Nullable ResolvableProfile owner) { this.owner = owner; } diff --git a/src/main/java/forestry/core/multiblock/MultiblockUtil.java b/src/main/java/forestry/core/multiblock/MultiblockUtil.java index d6034af1ab..9d5be322e4 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockUtil.java +++ b/src/main/java/forestry/core/multiblock/MultiblockUtil.java @@ -35,13 +35,11 @@ public class MultiblockUtil { * @return An array of references to neighboring IMultiblockComponent tile entities. */ public static List getNeighboringParts(Level world, IMultiblockComponent part) { - BlockPos partCoord = part.getCoordinates(); + BlockPos partCoord = part.getBlockPos(); - List neighbors = new ArrayList<>(Direction.values().length); - for (Direction facing : Direction.values()) { - BlockPos neighborCoord = new BlockPos(partCoord); - neighborCoord = neighborCoord.relative(facing); - neighbors.add(neighborCoord); + List neighbors = new ArrayList<>(Direction.VALUES.length); + for (Direction facing : Direction.VALUES) { + neighbors.add(partCoord.relative(facing)); } List neighborParts = new ArrayList<>(); diff --git a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java index 59b338e32f..4066319a41 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java @@ -22,7 +22,7 @@ * @author Erogenous Beef */ public class MultiblockWorldRegistry { - private final Level world; + private final Level level; private final Set controllers; // Active controllers private final Set dirtyControllers; // Controllers whose parts lists have changed @@ -46,8 +46,8 @@ public class MultiblockWorldRegistry { private final Object partsAwaitingChunkLoadMutex; private final Object orphanedPartsMutex; - public MultiblockWorldRegistry(Level world) { - this.world = world; + public MultiblockWorldRegistry(Level level) { + this.level = level; this.controllers = new HashSet<>(); this.deadControllers = new HashSet<>(); @@ -67,7 +67,7 @@ public MultiblockWorldRegistry(Level world) { public void tickStart() { if (!this.controllers.isEmpty()) { for (IMultiblockControllerInternal controller : this.controllers) { - if (controller.getWorldObj() == this.world && controller.getWorldObj().isClientSide == this.world.isClientSide) { + if (controller.getLevel() == this.level && controller.getLevel().isClientSide == this.level.isClientSide) { if (controller.hasNoParts()) { // This happens on the server when the user breaks the last block. It's fine. // Mark 'er dead and move on. @@ -85,7 +85,7 @@ public void tickStart() { * Called prior to processing multiblock controllers. Do bookkeeping. */ public void processMultiblockChanges() { - ChunkSource chunkProvider = this.world.getChunkSource(); + ChunkSource chunkProvider = this.level.getChunkSource(); BlockPos coord; // Merge pools - sets of adjacent machines which should be merged later on in processing @@ -110,7 +110,7 @@ public void processMultiblockChanges() { // Process orphaned blocks // These are blocks that exist in a valid chunk and require a controller for (IMultiblockComponent orphan : orphansToProcess) { - coord = orphan.getCoordinates(); + coord = orphan.getBlockPos(); if (!chunkProvider.hasChunk(coord.getX() >> 4, coord.getZ() >> 4)) { continue; } @@ -120,7 +120,7 @@ public void processMultiblockChanges() { continue; } - if (TileUtil.getTile(this.world, coord) != orphan) { + if (TileUtil.getTile(this.level, coord) != orphan) { // This block has been replaced by another. continue; } @@ -132,7 +132,7 @@ public void processMultiblockChanges() { // FOREVER ALONE! Create and register a new controller. // THIS IS THE ONLY PLACE WHERE NEW CONTROLLERS ARE CREATED. MultiblockLogic logic = (MultiblockLogic) orphan.getMultiblockLogic(); - IMultiblockControllerInternal newController = logic.createNewController(this.world); + IMultiblockControllerInternal newController = logic.createNewController(this.level); newController.attachBlock(orphan); this.controllers.add(newController); } else if (compatibleControllers.size() > 1) { @@ -156,10 +156,10 @@ public void processMultiblockChanges() { mergePools.add(compatibleControllers); } else if (candidatePools.size() == 1) { // Only one pool nearby, simply add to that one - candidatePools.get(0).addAll(compatibleControllers); + candidatePools.getFirst().addAll(compatibleControllers); } else { // Multiple pools- merge into one, then add the compatible controllers - Set masterPool = candidatePools.get(0); + Set masterPool = candidatePools.getFirst(); Set consumedPool; for (int i = 1; i < candidatePools.size(); i++) { consumedPool = candidatePools.get(i); @@ -275,7 +275,7 @@ private Set attachToNeighbors(IMultiblockComponen MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); Class controllerClass = logic.getControllerClass(); // Look for a compatible controller in our neighboring parts. - List partsToCheck = MultiblockUtil.getNeighboringParts(this.world, part); + List partsToCheck = MultiblockUtil.getNeighboringParts(this.level, part); for (IMultiblockComponent neighborPart : partsToCheck) { IMultiblockLogic neighborLogic = neighborPart.getMultiblockLogic(); if (neighborLogic.isConnected()) { @@ -310,9 +310,9 @@ private Set attachToNeighbors(IMultiblockComponen * @param part The part which is being added to this world. */ public void onPartAdded(IMultiblockComponent part) { - BlockPos worldLocation = part.getCoordinates(); + BlockPos worldLocation = part.getBlockPos(); - if (!this.world.getChunkSource().hasChunk(worldLocation.getX() >> 4, worldLocation.getZ() >> 4)) { + if (!this.level.getChunkSource().hasChunk(worldLocation.getX() >> 4, worldLocation.getZ() >> 4)) { // Part goes into the waiting-for-chunk-load list Set partSet; long chunkHash = ChunkPos.asLong(worldLocation.getX() >> 4, worldLocation.getZ() >> 4); @@ -339,7 +339,7 @@ public void onPartAdded(IMultiblockComponent part) { * @param part The part which is being removed. */ public void onPartRemovedFromWorld(IMultiblockComponent part) { - BlockPos coord = part.getCoordinates(); + BlockPos coord = part.getBlockPos(); long hash = ChunkPos.asLong(coord.getX() >> 4, coord.getZ() >> 4); if (this.partsAwaitingChunkLoad.containsKey(hash)) { diff --git a/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java index 3b1a365eb4..c03fd604b5 100644 --- a/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java @@ -8,21 +8,20 @@ import net.minecraft.world.level.block.entity.BlockEntity; public abstract class RectangularMultiblockControllerBase extends MultiblockControllerForestry { + protected final MultiblockSizeLimits sizeLimits; - private final IMultiblockSizeLimits sizeLimits; - - protected RectangularMultiblockControllerBase(Level world, IMultiblockSizeLimits sizeLimits) { + protected RectangularMultiblockControllerBase(Level world, MultiblockSizeLimits sizeLimits) { super(world); this.sizeLimits = sizeLimits; } @Override protected void isMachineWhole() throws MultiblockValidationException { - int minX = this.sizeLimits.getMinimumXSize(); - int minY = this.sizeLimits.getMinimumYSize(); - int minZ = this.sizeLimits.getMinimumZSize(); + int minX = this.sizeLimits.minimumXSize(); + int minY = this.sizeLimits.minimumYSize(); + int minZ = this.sizeLimits.minimumZSize(); - if (this.connectedParts.size() < this.sizeLimits.getMinimumNumberOfBlocksForAssembledMachine()) { + if (this.connectedParts.size() < this.sizeLimits.minimumNumberOfBlocksForAssembledMachine()) { throw new MultiblockValidationException(Component.translatable("for.multiblock.error.small", minX, minY, minZ).getString()); } @@ -34,9 +33,9 @@ protected void isMachineWhole() throws MultiblockValidationException { int deltaY = maximumCoord.getY() - minimumCoord.getY() + 1; int deltaZ = maximumCoord.getZ() - minimumCoord.getZ() + 1; - int maxX = this.sizeLimits.getMaximumXSize(); - int maxY = this.sizeLimits.getMaximumYSize(); - int maxZ = this.sizeLimits.getMaximumZSize(); + int maxX = this.sizeLimits.maximumXSize(); + int maxY = this.sizeLimits.maximumYSize(); + int maxZ = this.sizeLimits.maximumZSize(); if (maxX > 0 && deltaX > maxX) { throw new MultiblockValidationException(Component.translatable("for.multiblock.error.large.x", maxX).getString()); @@ -124,10 +123,6 @@ protected void isMachineWhole() throws MultiblockValidationException { } } - protected IMultiblockSizeLimits getSizeLimits() { - return this.sizeLimits; - } - protected abstract void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException; protected abstract void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException; diff --git a/src/main/java/forestry/core/multiblock/package-info.java b/src/main/java/forestry/core/multiblock/package-info.java index f8d0205c43..83ef1fbd83 100644 --- a/src/main/java/forestry/core/multiblock/package-info.java +++ b/src/main/java/forestry/core/multiblock/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.multiblock; diff --git a/src/main/java/forestry/core/network/IStreamable.java b/src/main/java/forestry/core/network/IStreamable.java index 9ff92d8e48..4ad92fcede 100644 --- a/src/main/java/forestry/core/network/IStreamable.java +++ b/src/main/java/forestry/core/network/IStreamable.java @@ -1,29 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; public interface IStreamable { /** * Called on the serverside to sync additional information about this block to the client. * - * @param data The stream of data about this object to send to the client. + * @param buffer The stream of data about this object to send to the client. */ - void writeData(FriendlyByteBuf data); + void writeData(RegistryFriendlyByteBuf buffer); /** * Called on the clientside to receive data from the server. * - * @param data The stream of data about this object sent by the server. + * @param buffer The stream of data about this object sent by the server. */ - void readData(FriendlyByteBuf data); + void readData(RegistryFriendlyByteBuf buffer); } diff --git a/src/main/java/forestry/core/network/IStreamableGui.java b/src/main/java/forestry/core/network/IStreamableGui.java index 39bcfe402b..3bc91b0cb6 100644 --- a/src/main/java/forestry/core/network/IStreamableGui.java +++ b/src/main/java/forestry/core/network/IStreamableGui.java @@ -1,20 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; -// IStreamable variant for screen data +/** + * IStreamable variant for synchronizing screen data from the server to the client + */ public interface IStreamableGui { - void writeGuiData(FriendlyByteBuf data); + void writeGuiData(RegistryFriendlyByteBuf buffer); - void readGuiData(FriendlyByteBuf data); + void readGuiData(RegistryFriendlyByteBuf buffer); } diff --git a/src/main/java/forestry/core/network/NetworkHandler.java b/src/main/java/forestry/core/network/NetworkHandler.java deleted file mode 100644 index 3d85b7d044..0000000000 --- a/src/main/java/forestry/core/network/NetworkHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package forestry.core.network; - -import forestry.Forestry; -import forestry.api.ForestryConstants; -import forestry.api.IForestryApi; -import forestry.api.modules.IForestryPacket; -import forestry.api.modules.IForestryPacketClient; -import forestry.api.modules.IForestryPacketServer; -import forestry.api.modules.IPacketRegistry; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Player; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.simple.SimpleChannel; - -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.function.Supplier; - -public class NetworkHandler { - public static final ResourceLocation CHANNEL_ID = ForestryConstants.forestry("channel"); - // todo correspond to mod version - public static final String VERSION = "1.0.0"; - public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(CHANNEL_ID, () -> VERSION, VERSION::equals, VERSION::equals); - - public static void register() { - IPacketRegistry registry = new NetworkHandler.PacketRegistry(CHANNEL); - - // packets must be registered in the same order across runs (until 1.20.4) - IForestryApi.INSTANCE.getModuleManager().getLoadedModules().forEach(module -> module.registerPackets(registry)); - } - - private static final class PacketRegistry implements IPacketRegistry { - private final SimpleChannel channel; - private int packetId; - - private PacketRegistry(SimpleChannel channel) { - this.channel = channel; - } - - @Override - public

void serverbound(ResourceLocation id, Class

packetClass, Function decoder, BiConsumer packetHandler) { - this.channel.registerMessage(this.packetId++, packetClass, IForestryPacket::write, decoder, (msg, ctxSupplier) -> handleServerbound(msg, ctxSupplier, packetHandler)); - } - - @Override - public

void clientbound(ResourceLocation id, Class

packetClass, Function decoder, BiConsumer packetHandler) { - this.channel.registerMessage(this.packetId++, packetClass, IForestryPacket::write, decoder, (msg, ctxSupplier) -> handleClientbound(msg, ctxSupplier, packetHandler)); - } - } - - private static void handleServerbound(T message, Supplier ctxSupplier, BiConsumer handler) { - var ctx = ctxSupplier.get(); - - if (ctx.getSender() == null) { - Forestry.LOGGER.warn("the player was null, message: {}", message); - } else { - ctx.enqueueWork(() -> handler.accept(message, ctx.getSender())); - } - - ctx.setPacketHandled(true); - } - - private static void handleClientbound(T message, Supplier ctxSupplier, BiConsumer handler) { - var ctx = ctxSupplier.get(); - ctx.enqueueWork(() -> handler.accept(message, Minecraft.getInstance().player)); - ctx.setPacketHandled(true); - } -} diff --git a/src/main/java/forestry/core/network/PacketIdClient.java b/src/main/java/forestry/core/network/PacketIdClient.java index 759849a554..40a16fbedd 100644 --- a/src/main/java/forestry/core/network/PacketIdClient.java +++ b/src/main/java/forestry/core/network/PacketIdClient.java @@ -1,54 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network; -import forestry.api.ForestryConstants; -import net.minecraft.resources.ResourceLocation; +import forestry.apiculture.network.packets.PacketAlvearyControllerChange; +import forestry.apiculture.network.packets.PacketBeeLogicActive; +import forestry.arboriculture.network.PacketRipeningUpdate; +import forestry.core.network.packets.*; +import forestry.mail.network.packets.PacketLetterInfoResponsePlayer; +import forestry.mail.network.packets.PacketLetterInfoResponseTrader; +import forestry.mail.network.packets.PacketPOBoxInfoResponse; +import forestry.mail.network.packets.PacketTraderAddressResponse; +import forestry.worktable.network.packets.PacketWorktableMemoryUpdate; +import forestry.worktable.network.packets.PacketWorktableRecipeUpdate; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +import static forestry.core.network.PacketIdServer.type; /** * Packets sent to the client from the server */ public class PacketIdClient { // Core - public static final ResourceLocation RECIPE_CACHE = ForestryConstants.forestry("recipe_cache"); + public static final CustomPacketPayload.Type RECIPE_CACHE = type("recipe_cache"); // Core Gui - public static final ResourceLocation ERROR_UPDATE = ForestryConstants.forestry("error_update"); - public static final ResourceLocation GUI_UPDATE = ForestryConstants.forestry("gui_update"); - public static final ResourceLocation GUI_LAYOUT_SELECT = ForestryConstants.forestry("gui_layout_select"); - public static final ResourceLocation GUI_ENERGY = ForestryConstants.forestry("gui_energy"); - public static final ResourceLocation SOCKET_UPDATE = ForestryConstants.forestry("socket_update"); + public static final CustomPacketPayload.Type ERROR_UPDATE = type("error_update"); + public static final CustomPacketPayload.Type GUI_STREAM = type("gui_stream"); + public static final CustomPacketPayload.Type GUI_LAYOUT_SELECT = type("gui_layout_select"); + public static final CustomPacketPayload.Type GUI_ENERGY = type("gui_energy"); + public static final CustomPacketPayload.Type SOCKET_UPDATE = type("socket_update"); // Core Tile Entities - public static final ResourceLocation TILE_FORESTRY_UPDATE = ForestryConstants.forestry("tile_forestry_update"); - public static final ResourceLocation ITEMSTACK_DISPLAY = ForestryConstants.forestry("itemstack_display"); - public static final ResourceLocation TANK_LEVEL_UPDATE = ForestryConstants.forestry("tank_level_update"); - public static final ResourceLocation REFRACTORY_WAX_ON = ForestryConstants.forestry("refractory_wax_on"); + public static final CustomPacketPayload.Type TILE_STREAM = type("tile_stream"); + public static final CustomPacketPayload.Type ITEMSTACK_DISPLAY = type("itemstack_display"); + public static final CustomPacketPayload.Type TANK_LEVEL_UPDATE = type("tank_level_update"); + public static final CustomPacketPayload.Type REFRACTORY_WAX_ON = type("refractory_wax_on"); // Core Genome - public static final ResourceLocation GENOME_TRACKER_UPDATE = ForestryConstants.forestry("genome_tracker_update"); + public static final CustomPacketPayload.Type GENOME_TRACKER_UPDATE = type("genome_tracker_update"); // Factory - public static final ResourceLocation WORKTABLE_MEMORY_UPDATE = ForestryConstants.forestry("worktable_memory_update"); - public static final ResourceLocation WORKTABLE_CRAFTING_UPDATE = ForestryConstants.forestry("worktable_crafting_update"); + public static final CustomPacketPayload.Type WORKTABLE_MEMORY_UPDATE = type("worktable_memory_update"); + public static final CustomPacketPayload.Type WORKTABLE_CRAFTING_UPDATE = type("worktable_crafting_update"); // Apiculture - public static final ResourceLocation TILE_FORESTRY_ACTIVE = ForestryConstants.forestry("tile_forestry_active"); - public static final ResourceLocation BEE_LOGIC_ACTIVE = ForestryConstants.forestry("bee_logic_active"); - public static final ResourceLocation HABITAT_BIOME_POINTER = ForestryConstants.forestry("habitat_biome_pointer"); - public static final ResourceLocation ALVERAY_CONTROLLER_CHANGE = ForestryConstants.forestry("alveray_controller_change"); + public static final CustomPacketPayload.Type ACTIVE_UPDATE = type("active_update"); + public static final CustomPacketPayload.Type BEE_LOGIC_ACTIVE = type("bee_logic_active"); + public static final CustomPacketPayload.Type ALVEARY_CONTROLLER_CHANGE = type("alveary_controller_change"); // Arboriculture - public static final ResourceLocation RIPENING_UPDATE = ForestryConstants.forestry("ripening_update"); + public static final CustomPacketPayload.Type RIPENING_UPDATE = type("ripening_update"); // Mail - public static final ResourceLocation TRADING_ADDRESS_RESPONSE = ForestryConstants.forestry("trading_address_response"); - public static final ResourceLocation LETTER_INFO_RESPONSE_PLAYER = ForestryConstants.forestry("letter_info_response_player"); - public static final ResourceLocation LETTER_INFO_RESPONSE_TRADER = ForestryConstants.forestry("letter_info_response_trader"); - public static final ResourceLocation POBOX_INFO_RESPONSE = ForestryConstants.forestry("pobox_info_response"); + public static final CustomPacketPayload.Type TRADING_ADDRESS_RESPONSE = type("trading_address_response"); + public static final CustomPacketPayload.Type LETTER_INFO_RESPONSE_PLAYER = type("letter_info_response_player"); + public static final CustomPacketPayload.Type LETTER_INFO_RESPONSE_TRADER = type("letter_info_response_trader"); + public static final CustomPacketPayload.Type POBOX_INFO_RESPONSE = type("pobox_info_response"); // Sorting - public static final ResourceLocation GUI_UPDATE_FILTER = ForestryConstants.forestry("gui_update_filter"); + public static final CustomPacketPayload.Type GUI_UPDATE_FILTER = type("gui_update_filter"); // JEI - public static final ResourceLocation RECIPE_TRANSFER_UPDATE = ForestryConstants.forestry("recipe_transfer_update"); + public static final CustomPacketPayload.Type RECIPE_TRANSFER_UPDATE = type("recipe_transfer_update"); } diff --git a/src/main/java/forestry/core/network/PacketIdServer.java b/src/main/java/forestry/core/network/PacketIdServer.java index b8d681230e..3a4c7c1880 100644 --- a/src/main/java/forestry/core/network/PacketIdServer.java +++ b/src/main/java/forestry/core/network/PacketIdServer.java @@ -1,41 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network; import forestry.api.ForestryConstants; -import net.minecraft.resources.ResourceLocation; +import forestry.core.network.packets.PacketChipsetClick; +import forestry.core.network.packets.PacketGuiSelectRequest; +import forestry.core.network.packets.PacketPipetteClick; +import forestry.core.network.packets.PacketSolderingIronClick; +import forestry.factory.network.packets.PacketRecipeTransferRequest; +import forestry.mail.network.packets.PacketLetterInfoRequest; +import forestry.mail.network.packets.PacketLetterTextSet; +import forestry.mail.network.packets.PacketTraderAddressRequest; +import forestry.sorting.network.packets.PacketFilterChangeGenome; +import forestry.sorting.network.packets.PacketFilterChangeRule; +import forestry.worktable.network.packets.PacketWorktableRecipeRequest; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; /** * Packets sent to the server from the client */ public class PacketIdServer { // Core Gui - public static final ResourceLocation GUI_SELECTION_REQUEST = ForestryConstants.forestry("gui_selection_request"); - public static final ResourceLocation PIPETTE_CLICK = ForestryConstants.forestry("pipette_click"); - public static final ResourceLocation CHIPSET_CLICK = ForestryConstants.forestry("chipset_click"); - public static final ResourceLocation SOLDERING_IRON_CLICK = ForestryConstants.forestry("soldering_iron_click"); - // Climate - public static final ResourceLocation SELECT_CLIMATE_TARGETED = ForestryConstants.forestry("select_climate_targeted"); - public static final ResourceLocation CLIMATE_LISTENER_UPDATE_REQUEST = ForestryConstants.forestry("climate_listener_update_request"); - // Database - public static final ResourceLocation INSERT_ITEM = ForestryConstants.forestry("insert_item"); - public static final ResourceLocation EXTRACT_ITEM = ForestryConstants.forestry("extract_item"); + public static final CustomPacketPayload.Type GUI_SELECTION_REQUEST = type("gui_selection_request"); + public static final CustomPacketPayload.Type PIPETTE_CLICK = type("pipette_click"); + public static final CustomPacketPayload.Type CHIPSET_CLICK = type("chipset_click"); + public static final CustomPacketPayload.Type SOLDERING_IRON_CLICK = type("soldering_iron_click"); // Sorting - public static final ResourceLocation FILTER_CHANGE_RULE = ForestryConstants.forestry("filter_change_rule"); - public static final ResourceLocation FILTER_CHANGE_GENOME = ForestryConstants.forestry("filter_change_genome"); + public static final CustomPacketPayload.Type FILTER_CHANGE_RULE = type("filter_change_rule"); + public static final CustomPacketPayload.Type FILTER_CHANGE_GENOME = type("filter_change_genome"); // JEI - public static final ResourceLocation WORKTABLE_RECIPE_REQUEST = ForestryConstants.forestry("worktable_recipe_request"); - public static final ResourceLocation RECIPE_TRANSFER_REQUEST = ForestryConstants.forestry("recipe_transfer_request"); + public static final CustomPacketPayload.Type WORKTABLE_RECIPE_REQUEST = type("worktable_recipe_request"); + public static final CustomPacketPayload.Type RECIPE_TRANSFER_REQUEST = type("recipe_transfer_request"); // Mail - public static final ResourceLocation LETTER_INFO_REQUEST = ForestryConstants.forestry("letter_info_request"); - public static final ResourceLocation TRADING_ADDRESS_REQUEST = ForestryConstants.forestry("trading_address_request"); - public static final ResourceLocation LETTER_TEXT_SET = ForestryConstants.forestry("letter_text_set"); + public static final CustomPacketPayload.Type LETTER_INFO_REQUEST = type("letter_info_request"); + public static final CustomPacketPayload.Type TRADING_ADDRESS_REQUEST = type("trading_address_request"); + public static final CustomPacketPayload.Type LETTER_TEXT_SET = type("letter_text_set"); + + static

CustomPacketPayload.Type

type(String path) { + return new CustomPacketPayload.Type<>(ForestryConstants.forestry(path)); + } } diff --git a/src/main/java/forestry/core/network/package-info.java b/src/main/java/forestry/core/network/package-info.java index bb9cb316bb..3fcad3f647 100644 --- a/src/main/java/forestry/core/network/package-info.java +++ b/src/main/java/forestry/core/network/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.network; diff --git a/src/main/java/forestry/core/network/packets/PacketActiveUpdate.java b/src/main/java/forestry/core/network/packets/PacketActiveUpdate.java index 9849f6e215..35ebf78444 100644 --- a/src/main/java/forestry/core/network/packets/PacketActiveUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketActiveUpdate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketClient; @@ -16,33 +6,30 @@ import forestry.core.tiles.IActivatable; import forestry.core.tiles.TileUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketActiveUpdate(BlockPos pos, boolean active) implements IForestryPacketClient { public PacketActiveUpdate(IActivatable tile) { - this(tile.getCoordinates(), tile.isActive()); + this(tile.getBlockPos(), tile.isActive()); } - @Override - public ResourceLocation id() { - return PacketIdClient.TILE_FORESTRY_ACTIVE; + public Type type() { + return PacketIdClient.ACTIVE_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeBoolean(this.active); + public static void encode(RegistryFriendlyByteBuf buffer, PacketActiveUpdate msg) { + buffer.writeBlockPos(msg.pos); + buffer.writeBoolean(msg.active); } - public static PacketActiveUpdate decode(FriendlyByteBuf buffer) { + public static PacketActiveUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketActiveUpdate(buffer.readBlockPos(), buffer.readBoolean()); } - public static void handle(PacketActiveUpdate msg, Player player) { - BlockEntity tile = TileUtil.getTile(player.level(), msg.pos); + public static void handle(PacketActiveUpdate msg, IPayloadContext ctx) { + BlockEntity tile = TileUtil.getTile(ctx.player().level(), msg.pos); if (tile instanceof IActivatable activatable) { activatable.setActive(msg.active); diff --git a/src/main/java/forestry/core/network/packets/PacketChipsetClick.java b/src/main/java/forestry/core/network/packets/PacketChipsetClick.java index 6511188450..153b6baf06 100644 --- a/src/main/java/forestry/core/network/packets/PacketChipsetClick.java +++ b/src/main/java/forestry/core/network/packets/PacketChipsetClick.java @@ -1,46 +1,36 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketServer; import forestry.core.circuits.ItemCircuitBoard; import forestry.core.gui.IContainerSocketed; import forestry.core.network.PacketIdServer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketChipsetClick(int slot) implements IForestryPacketServer { - public static void handle(PacketChipsetClick msg, ServerPlayer player) { + public static void handle(PacketChipsetClick msg, IPayloadContext ctx) { + Player player = ctx.player(); if (player.containerMenu instanceof IContainerSocketed socketMenu) { ItemStack itemstack = player.containerMenu.getCarried(); - // todo replace check with tag if (itemstack.getItem() instanceof ItemCircuitBoard) { - socketMenu.handleChipsetClickServer(msg.slot(), player, itemstack); + socketMenu.handleChipsetClickServer(msg.slot(), (ServerPlayer) player, itemstack); } } } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(this.slot); + public static void encode(RegistryFriendlyByteBuf buffer, PacketChipsetClick msg) { + buffer.writeVarInt(msg.slot); } @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.CHIPSET_CLICK; } - public static PacketChipsetClick decode(FriendlyByteBuf buffer) { + public static PacketChipsetClick decode(RegistryFriendlyByteBuf buffer) { return new PacketChipsetClick(buffer.readVarInt()); } } diff --git a/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java b/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java index 8171853e32..6188bead51 100644 --- a/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.core.IErrorLogicSource; @@ -16,34 +6,31 @@ import forestry.core.tiles.TileUtil; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketErrorUpdate(BlockPos pos, short[] errorStates) implements IForestryPacketClient { public PacketErrorUpdate(BlockEntity tile, IErrorLogicSource errorLogicSource) { this(tile.getBlockPos(), errorLogicSource.getErrorLogic().toArray()); } - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.ERROR_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writeShortArray(buffer, this.errorStates); + public static void encode(RegistryFriendlyByteBuf buffer, PacketErrorUpdate msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writeShortArray(buffer, msg.errorStates); } - public static PacketErrorUpdate decode(FriendlyByteBuf buffer) { + public static PacketErrorUpdate decode(RegistryFriendlyByteBuf buffer) { BlockPos pos = buffer.readBlockPos(); short[] errorStats = NetworkUtil.readShortArray(buffer); return new PacketErrorUpdate(pos, errorStats); } - public static void handle(PacketErrorUpdate msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, IErrorLogicSource.class, errorSourceTile -> errorSourceTile.getErrorLogic().fromArray(msg.errorStates)); + public static void handle(PacketErrorUpdate msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, IErrorLogicSource.class, errorSourceTile -> errorSourceTile.getErrorLogic().fromArray(msg.errorStates)); } } diff --git a/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java b/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java index af6faa385c..134c084eb8 100644 --- a/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java +++ b/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java @@ -1,54 +1,44 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.IForestryApi; -import forestry.api.core.ForestryEvent; +import forestry.api.event.BreedingTrackerEvent; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesType; import forestry.api.modules.IForestryPacketClient; import forestry.core.genetics.BreedingTracker; import forestry.core.network.PacketIdClient; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.MinecraftForge; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.network.handling.IPayloadContext; import javax.annotation.Nullable; public record PacketGenomeTrackerSync(@Nullable CompoundTag nbt) implements IForestryPacketClient { @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.GENOME_TRACKER_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeNbt(this.nbt); + public static void encode(RegistryFriendlyByteBuf buffer, PacketGenomeTrackerSync msg) { + buffer.writeNbt(msg.nbt); } - public static PacketGenomeTrackerSync decode(FriendlyByteBuf buffer) { + public static PacketGenomeTrackerSync decode(RegistryFriendlyByteBuf buffer) { return new PacketGenomeTrackerSync(buffer.readNbt()); } - public static void handle(PacketGenomeTrackerSync msg, Player player) { + public static void handle(PacketGenomeTrackerSync msg, IPayloadContext ctx) { if (msg.nbt != null) { - String type = msg.nbt.getString(BreedingTracker.TYPE_KEY); - ISpeciesType root = IForestryApi.INSTANCE.getGeneticManager().getSpeciesTypeSafe(new ResourceLocation(type)); + ISpeciesType type = IForestryApi.INSTANCE.getGeneticManager().getSpeciesTypeSafe(ResourceLocation.parse(msg.nbt.getString(BreedingTracker.TYPE_KEY))); - if (root != null) { - IBreedingTracker tracker = root.getBreedingTracker(player.getCommandSenderWorld(), player.getGameProfile()); - tracker.readFromNbt(msg.nbt); - MinecraftForge.EVENT_BUS.post(new ForestryEvent.SyncedBreedingTracker(tracker, player)); + if (type != null) { + Player player = ctx.player(); + IBreedingTracker tracker = type.getBreedingTracker(player.getCommandSenderWorld(), player.getGameProfile()); + tracker.readFromNbt(msg.nbt, player.registryAccess()); + NeoForge.EVENT_BUS.post(new BreedingTrackerEvent.Synced(type, tracker, player)); } } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java b/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java index 8f47302b3f..5a7f2e7ba2 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java @@ -1,40 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketClient; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.network.PacketIdClient; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketGuiEnergy(int windowId, int value) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.GUI_ENERGY; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(this.windowId); - buffer.writeVarInt(this.value); + public static void encode(RegistryFriendlyByteBuf buffer, PacketGuiEnergy msg) { + buffer.writeVarInt(msg.windowId); + buffer.writeVarInt(msg.value); } - public static PacketGuiEnergy decode(FriendlyByteBuf buffer) { + public static PacketGuiEnergy decode(RegistryFriendlyByteBuf buffer) { return new PacketGuiEnergy(buffer.readVarInt(), buffer.readVarInt()); } - public static void handle(PacketGuiEnergy msg, Player player) { - if (player.containerMenu.containerId == msg.windowId && player.containerMenu instanceof ContainerTile menu) { + public static void handle(PacketGuiEnergy msg, IPayloadContext ctx) { + if (ctx.player().containerMenu.containerId == msg.windowId && ctx.player().containerMenu instanceof TileMenu menu) { menu.onGuiEnergy(msg.value); } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java b/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java index 0f37d86a2b..296a9c8216 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java @@ -1,42 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.IForestryApi; -import forestry.api.circuits.ICircuitLayout; +import forestry.api.circuits.CircuitLayout; import forestry.api.modules.IForestryPacketClient; -import forestry.core.circuits.ContainerSolderingIron; +import forestry.core.circuits.SolderingIronMenu; import forestry.core.network.PacketIdClient; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketGuiLayoutSelect(String layoutUid) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.GUI_LAYOUT_SELECT; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeUtf(this.layoutUid); + public static void encode(RegistryFriendlyByteBuf buffer, PacketGuiLayoutSelect msg) { + buffer.writeUtf(msg.layoutUid); } - public static PacketGuiLayoutSelect decode(FriendlyByteBuf buffer) { + public static PacketGuiLayoutSelect decode(RegistryFriendlyByteBuf buffer) { return new PacketGuiLayoutSelect(buffer.readUtf()); } - public static void handle(PacketGuiLayoutSelect msg, Player player) { - if (player.containerMenu instanceof ContainerSolderingIron solderingIron) { - ICircuitLayout layout = IForestryApi.INSTANCE.getCircuitManager().getLayout(msg.layoutUid); + public static void handle(PacketGuiLayoutSelect msg, IPayloadContext ctx) { + if (ctx.player().containerMenu instanceof SolderingIronMenu solderingIron) { + CircuitLayout layout = IForestryApi.INSTANCE.getCircuitManager().getLayout(msg.layoutUid); if (layout != null) { solderingIron.setLayout(layout); diff --git a/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java b/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java index 9dea5ac3ff..7d28e8e778 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java @@ -1,44 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketServer; import forestry.core.gui.IGuiSelectable; import forestry.core.network.PacketIdServer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketGuiSelectRequest(int primaryIndex, int secondaryIndex) implements IForestryPacketServer { - public static void handle(PacketGuiSelectRequest msg, ServerPlayer player) { - AbstractContainerMenu container = player.containerMenu; + public static void handle(PacketGuiSelectRequest msg, IPayloadContext ctx) { + AbstractContainerMenu container = ctx.player().containerMenu; if (container instanceof IGuiSelectable guiSelectable) { - guiSelectable.handleSelectionRequest(player, msg.primaryIndex(), msg.secondaryIndex()); + guiSelectable.handleSelectionRequest((ServerPlayer) ctx.player(), msg.primaryIndex(), msg.secondaryIndex()); } } @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.GUI_SELECTION_REQUEST; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(this.primaryIndex); - buffer.writeVarInt(this.secondaryIndex); + public static void encode(RegistryFriendlyByteBuf buffer, PacketGuiSelectRequest msg) { + buffer.writeVarInt(msg.primaryIndex); + buffer.writeVarInt(msg.secondaryIndex); } - public static PacketGuiSelectRequest decode(FriendlyByteBuf buffer) { + public static PacketGuiSelectRequest decode(RegistryFriendlyByteBuf buffer) { return new PacketGuiSelectRequest(buffer.readVarInt(), buffer.readVarInt()); } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiStream.java b/src/main/java/forestry/core/network/packets/PacketGuiStream.java index d6bc2a859a..4f35446345 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiStream.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiStream.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.core.ILocationProvider; @@ -17,9 +7,8 @@ import forestry.core.tiles.TileUtil; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; // Streamable is used on the server side to serialize the packet data (payload is null) // Payload is used on the client side to sync the packet data (streamable is null) @@ -28,29 +17,28 @@ public record PacketGuiStream( // null on client side IStreamableGui guiStreamable, // null on server side - FriendlyByteBuf payload + RegistryFriendlyByteBuf payload ) implements IForestryPacketClient { public PacketGuiStream(T guiStreamable) { - this(guiStreamable.getCoordinates(), guiStreamable, null); + this(guiStreamable.getBlockPos(), guiStreamable, null); } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writePayloadBuffer(buffer, this.guiStreamable::writeGuiData); + public static void encode(RegistryFriendlyByteBuf buffer, PacketGuiStream msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writePayloadBuffer(buffer, msg.guiStreamable::writeGuiData); } - public static PacketGuiStream decode(FriendlyByteBuf data) { - return new PacketGuiStream(data.readBlockPos(), null, NetworkUtil.readPayloadBuffer(data)); + public static PacketGuiStream decode(RegistryFriendlyByteBuf buffer) { + return new PacketGuiStream(buffer.readBlockPos(), null, NetworkUtil.readPayloadBuffer(buffer)); } @Override - public ResourceLocation id() { - return PacketIdClient.GUI_UPDATE; + public Type type() { + return PacketIdClient.GUI_STREAM; } - public static void handle(PacketGuiStream msg, Player player) { - IStreamableGui tile = TileUtil.getTile(player.level(), msg.pos, IStreamableGui.class); + public static void handle(PacketGuiStream msg, IPayloadContext ctx) { + IStreamableGui tile = TileUtil.getTile(ctx.player().level(), msg.pos, IStreamableGui.class); if (tile != null) { tile.readGuiData(msg.payload); } diff --git a/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java b/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java index f189fe314d..c95f2ffaab 100644 --- a/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java +++ b/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketClient; @@ -16,32 +6,30 @@ import forestry.core.tiles.TileForestry; import forestry.core.tiles.TileUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public record PacketItemStackDisplay(BlockPos pos, ItemStack itemStack) implements IForestryPacketClient { +public record PacketItemStackDisplay(BlockPos pos, ItemStack stack) implements IForestryPacketClient { public PacketItemStackDisplay(T tile, ItemStack itemStack) { this(tile.getBlockPos(), itemStack); } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeItem(this.itemStack); + public static void encode(RegistryFriendlyByteBuf buffer, PacketItemStackDisplay msg) { + buffer.writeBlockPos(msg.pos); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buffer, msg.stack); } @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.ITEMSTACK_DISPLAY; } - public static PacketItemStackDisplay decode(FriendlyByteBuf buffer) { - return new PacketItemStackDisplay(buffer.readBlockPos(), buffer.readItem()); + public static PacketItemStackDisplay decode(RegistryFriendlyByteBuf buffer) { + return new PacketItemStackDisplay(buffer.readBlockPos(), ItemStack.OPTIONAL_STREAM_CODEC.decode(buffer)); } - public static void handle(PacketItemStackDisplay msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, IItemStackDisplay.class, tile -> tile.handleItemStackForDisplay(msg.itemStack)); + public static void handle(PacketItemStackDisplay msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, IItemStackDisplay.class, tile -> tile.handleItemStackForDisplay(msg.stack)); } } diff --git a/src/main/java/forestry/core/network/packets/PacketPipetteClick.java b/src/main/java/forestry/core/network/packets/PacketPipetteClick.java index 5c0c63af01..d5ee9e9305 100644 --- a/src/main/java/forestry/core/network/packets/PacketPipetteClick.java +++ b/src/main/java/forestry/core/network/packets/PacketPipetteClick.java @@ -1,40 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketServer; import forestry.core.gui.IContainerLiquidTanks; import forestry.core.network.PacketIdServer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketPipetteClick(int slot) implements IForestryPacketServer { - public static void handle(PacketPipetteClick msg, ServerPlayer player) { - if (player.containerMenu instanceof IContainerLiquidTanks tanksMenu) { - tanksMenu.handlePipetteClick(msg.slot(), player); + public static void handle(PacketPipetteClick msg, IPayloadContext ctx) { + if (ctx.player().containerMenu instanceof IContainerLiquidTanks tanksMenu) { + tanksMenu.handlePipetteClick(msg.slot(), (ServerPlayer) ctx.player()); } } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(this.slot); + public static void encode(RegistryFriendlyByteBuf buffer, PacketPipetteClick msg) { + buffer.writeVarInt(msg.slot); } @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.PIPETTE_CLICK; } - public static PacketPipetteClick decode(FriendlyByteBuf buffer) { + public static PacketPipetteClick decode(RegistryFriendlyByteBuf buffer) { return new PacketPipetteClick(buffer.readVarInt()); } } diff --git a/src/main/java/forestry/core/network/packets/PacketRefractoryWax.java b/src/main/java/forestry/core/network/packets/PacketRefractoryWax.java index 9e644175a5..5a1e3c0f26 100644 --- a/src/main/java/forestry/core/network/packets/PacketRefractoryWax.java +++ b/src/main/java/forestry/core/network/packets/PacketRefractoryWax.java @@ -2,34 +2,31 @@ import forestry.api.modules.IForestryPacketClient; import forestry.core.network.PacketIdClient; -import forestry.core.particles.CoreParticles; +import forestry.core.features.CoreParticles; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.ParticleUtils; import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketRefractoryWax(BlockPos pos) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.REFRACTORY_WAX_ON; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); + public static void encode(RegistryFriendlyByteBuf buffer, PacketRefractoryWax msg) { + buffer.writeBlockPos(msg.pos); } - public static PacketRefractoryWax decode(FriendlyByteBuf buffer) { + public static PacketRefractoryWax decode(RegistryFriendlyByteBuf buffer) { return new PacketRefractoryWax(buffer.readBlockPos()); } - public static void handle(PacketRefractoryWax msg, Player player) { - Level level = player.level(); + public static void handle(PacketRefractoryWax msg, IPayloadContext ctx) { + Level level = ctx.player().level(); BlockPos pos = msg.pos; ParticleUtils.spawnParticlesOnBlockFaces(level, pos, CoreParticles.REFRACTORY_WAX.get(), UniformInt.of(3, 5)); diff --git a/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java b/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java index 3c61c9aad8..88411f3899 100644 --- a/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java @@ -1,33 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketClient; import forestry.core.circuits.ISocketable; import forestry.core.network.PacketIdClient; -import forestry.core.tiles.TileUtil; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; -import net.minecraft.core.NonNullList; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public record PacketSocketUpdate(BlockPos pos, NonNullList itemStacks) implements IForestryPacketClient { +import java.util.ArrayList; +import java.util.List; + +public record PacketSocketUpdate(BlockPos pos, List itemStacks) implements IForestryPacketClient { public static PacketSocketUpdate create(T tile) { BlockPos pos = tile.getBlockPos(); - NonNullList itemStacks = NonNullList.withSize(tile.getSocketCount(), ItemStack.EMPTY); + ArrayList itemStacks = new ArrayList<>(tile.getSocketCount()); for (int i = 0; i < tile.getSocketCount(); i++) { itemStacks.set(i, tile.getSocket(i)); } @@ -35,26 +25,24 @@ public static PacketSocketUpdate create(T return new PacketSocketUpdate(pos, itemStacks); } - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.SOCKET_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writeItemStacks(buffer, this.itemStacks); + public static void encode(RegistryFriendlyByteBuf buffer, PacketSocketUpdate msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writeItemStacks(buffer, msg.itemStacks); } - public static PacketSocketUpdate decode(FriendlyByteBuf buffer) { + public static PacketSocketUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketSocketUpdate(buffer.readBlockPos(), NetworkUtil.readItemStacks(buffer)); } - public static void handle(PacketSocketUpdate msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, ISocketable.class, socketable -> { + public static void handle(PacketSocketUpdate msg, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(msg.pos) instanceof ISocketable socketable) { for (int i = 0; i < msg.itemStacks.size(); i++) { socketable.setSocket(i, msg.itemStacks.get(i)); } - }); + } } } diff --git a/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java b/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java index 3c314c5c20..e7140a66b1 100644 --- a/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java +++ b/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java @@ -1,43 +1,35 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketServer; import forestry.core.gui.IContainerSocketed; import forestry.core.network.PacketIdServer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketSolderingIronClick(int slot) implements IForestryPacketServer { @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.SOLDERING_IRON_CLICK; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(this.slot); + public static void encode(RegistryFriendlyByteBuf buffer, PacketSolderingIronClick msg) { + buffer.writeVarInt(msg.slot); } - public static PacketSolderingIronClick decode(FriendlyByteBuf buffer) { + public static PacketSolderingIronClick decode(RegistryFriendlyByteBuf buffer) { return new PacketSolderingIronClick(buffer.readVarInt()); } - public static void handle(PacketSolderingIronClick msg, ServerPlayer player) { + public static void handle(PacketSolderingIronClick msg, IPayloadContext ctx) { + Player player = ctx.player(); + if (player.containerMenu instanceof IContainerSocketed socketMenu) { ItemStack itemstack = player.containerMenu.getCarried(); - socketMenu.handleSolderingIronClickServer(msg.slot(), player, itemstack); + socketMenu.handleSolderingIronClickServer(msg.slot(), (ServerPlayer) player, itemstack); } } } diff --git a/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java b/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java index 6f570f675f..e539f59d66 100644 --- a/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketClient; @@ -16,34 +6,28 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TileUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; -import net.minecraftforge.fluids.FluidStack; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketTankLevelUpdate(BlockPos pos, int tankIndex, FluidStack contents) implements IForestryPacketClient { - public PacketTankLevelUpdate(ILiquidTankTile tileEntity, int tankIndex, FluidStack contents) { - this(tileEntity.getCoordinates(), tankIndex, contents); - } - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.TANK_LEVEL_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeVarInt(this.tankIndex); - buffer.writeFluidStack(this.contents); + public static void encode(RegistryFriendlyByteBuf buffer, PacketTankLevelUpdate msg) { + buffer.writeBlockPos(msg.pos); + buffer.writeVarInt(msg.tankIndex); + FluidStack.STREAM_CODEC.encode(buffer, msg.contents); } - public static PacketTankLevelUpdate decode(FriendlyByteBuf buffer) { - return new PacketTankLevelUpdate(buffer.readBlockPos(), buffer.readVarInt(), buffer.readFluidStack()); + public static PacketTankLevelUpdate decode(RegistryFriendlyByteBuf buffer) { + return new PacketTankLevelUpdate(buffer.readBlockPos(), buffer.readVarInt(), FluidStack.STREAM_CODEC.decode(buffer)); } - public static void handle(PacketTankLevelUpdate msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, ILiquidTankTile.class, tile -> { + public static void handle(PacketTankLevelUpdate msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, ILiquidTankTile.class, tile -> { ITankManager tankManager = tile.getTankManager(); tankManager.processTankUpdate(msg.tankIndex, msg.contents); }); diff --git a/src/main/java/forestry/core/network/packets/PacketTileStream.java b/src/main/java/forestry/core/network/packets/PacketTileStream.java index 98abb1f81b..a623e69085 100644 --- a/src/main/java/forestry/core/network/packets/PacketTileStream.java +++ b/src/main/java/forestry/core/network/packets/PacketTileStream.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.network.packets; import forestry.api.modules.IForestryPacketClient; @@ -16,10 +6,9 @@ import forestry.core.tiles.TileUtil; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.handling.IPayloadContext; import javax.annotation.Nullable; @@ -28,7 +17,7 @@ public class PacketTileStream implements IForestryPacketClient { @Nullable protected final IStreamable streamable; @Nullable - protected final FriendlyByteBuf payload; + protected final RegistryFriendlyByteBuf payload; public PacketTileStream(T streamable) { this.pos = streamable.getBlockPos(); @@ -36,29 +25,28 @@ public PacketTileStream(T streamable) { this.payload = null; } - private PacketTileStream(BlockPos pos, FriendlyByteBuf payload) { + private PacketTileStream(BlockPos pos, RegistryFriendlyByteBuf payload) { this.pos = pos; this.streamable = null; this.payload = payload; } @Override - public ResourceLocation id() { - return PacketIdClient.TILE_FORESTRY_UPDATE; + public Type type() { + return PacketIdClient.TILE_STREAM; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writePayloadBuffer(buffer, this.streamable::writeData); + public static void encode(RegistryFriendlyByteBuf buffer, PacketTileStream msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writePayloadBuffer(buffer, msg.streamable::writeData); } - public static PacketTileStream decode(FriendlyByteBuf data) { - return new PacketTileStream(data.readBlockPos(), NetworkUtil.readPayloadBuffer(data)); + public static PacketTileStream decode(RegistryFriendlyByteBuf buffer) { + return new PacketTileStream(buffer.readBlockPos(), NetworkUtil.readPayloadBuffer(buffer)); } - public static void handle(PacketTileStream msg, Player player) { - IStreamable tile = TileUtil.getTile(player.level(), msg.pos, IStreamable.class); + public static void handle(PacketTileStream msg, IPayloadContext ctx) { + IStreamable tile = TileUtil.getTile(ctx.player().level(), msg.pos, IStreamable.class); if (tile != null) { tile.readData(msg.payload); diff --git a/src/main/java/forestry/core/network/packets/RecipeCachePacket.java b/src/main/java/forestry/core/network/packets/RecipeCachePacket.java index c971afd2d1..1776d10e9e 100644 --- a/src/main/java/forestry/core/network/packets/RecipeCachePacket.java +++ b/src/main/java/forestry/core/network/packets/RecipeCachePacket.java @@ -3,25 +3,15 @@ import forestry.api.modules.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.core.recipes.RecipeManagers; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.neoforged.neoforge.network.handling.IPayloadContext; public class RecipeCachePacket implements IForestryPacketClient { @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.RECIPE_CACHE; } - @Override - public void write(FriendlyByteBuf buffer) { - } - - public static RecipeCachePacket decode(FriendlyByteBuf buffer) { - return new RecipeCachePacket(); - } - - public static void handle(RecipeCachePacket msg, Player player) { + public static void handle(RecipeCachePacket msg, IPayloadContext ctx) { RecipeManagers.invalidateCaches(); } } diff --git a/src/main/java/forestry/core/network/packets/package-info.java b/src/main/java/forestry/core/network/packets/package-info.java index 828c392fd3..436ae96598 100644 --- a/src/main/java/forestry/core/network/packets/package-info.java +++ b/src/main/java/forestry/core/network/packets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.network.packets; diff --git a/src/main/java/forestry/core/owner/FakeOwnerHandler.java b/src/main/java/forestry/core/owner/FakeOwnerHandler.java index 3a8f68f982..a86a58fd88 100644 --- a/src/main/java/forestry/core/owner/FakeOwnerHandler.java +++ b/src/main/java/forestry/core/owner/FakeOwnerHandler.java @@ -1,16 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.owner; import com.mojang.authlib.GameProfile; +import net.minecraft.world.item.component.ResolvableProfile; public enum FakeOwnerHandler implements IOwnerHandler { INSTANCE; @@ -21,6 +12,6 @@ public GameProfile getOwner() { } @Override - public void setOwner(GameProfile owner) { + public void setOwner(ResolvableProfile owner) { } } diff --git a/src/main/java/forestry/core/owner/GameProfileDataSerializer.java b/src/main/java/forestry/core/owner/GameProfileDataSerializer.java deleted file mode 100755 index e331642deb..0000000000 --- a/src/main/java/forestry/core/owner/GameProfileDataSerializer.java +++ /dev/null @@ -1,47 +0,0 @@ -package forestry.core.owner; - -import com.mojang.authlib.GameProfile; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.syncher.EntityDataAccessor; -import net.minecraft.network.syncher.EntityDataSerializer; - -import java.util.Optional; -import java.util.UUID; - -public enum GameProfileDataSerializer implements EntityDataSerializer> { - INSTANCE; - - @Override - public void write(FriendlyByteBuf buf, Optional value) { - if (!value.isPresent()) { - buf.writeBoolean(false); - } else { - buf.writeBoolean(true); - GameProfile gameProfile = value.get(); - buf.writeUUID(gameProfile.getId()); - buf.writeUtf(gameProfile.getName()); - } - } - - @Override - public Optional read(FriendlyByteBuf buf) { - if (buf.readBoolean()) { - UUID uuid = buf.readUUID(); - String name = buf.readUtf(1024); - GameProfile gameProfile = new GameProfile(uuid, name); - return Optional.of(gameProfile); - } else { - return Optional.empty(); - } - } - - @Override - public EntityDataAccessor> createAccessor(int id) { - return new EntityDataAccessor<>(id, this); - } - - @Override - public Optional copy(Optional value) { - return value; - } -} diff --git a/src/main/java/forestry/core/owner/IOwnerHandler.java b/src/main/java/forestry/core/owner/IOwnerHandler.java index 34bcf10a3d..7cd904fd4f 100644 --- a/src/main/java/forestry/core/owner/IOwnerHandler.java +++ b/src/main/java/forestry/core/owner/IOwnerHandler.java @@ -1,22 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.owner; -import com.mojang.authlib.GameProfile; +import net.minecraft.world.item.component.ResolvableProfile; import javax.annotation.Nullable; public interface IOwnerHandler { @Nullable - GameProfile getOwner(); + ResolvableProfile getOwner(); - void setOwner(GameProfile owner); + void setOwner(ResolvableProfile owner); } diff --git a/src/main/java/forestry/core/owner/OwnerHandler.java b/src/main/java/forestry/core/owner/OwnerHandler.java index be9dce0c55..05385b1a2b 100644 --- a/src/main/java/forestry/core/owner/OwnerHandler.java +++ b/src/main/java/forestry/core/owner/OwnerHandler.java @@ -1,77 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.owner; -import com.mojang.authlib.GameProfile; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.core.network.IStreamable; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.nbt.NbtOps; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.world.item.component.ResolvableProfile; import javax.annotation.Nullable; -import java.util.UUID; public class OwnerHandler implements IOwnerHandler, IStreamable, INbtWritable, INbtReadable { @Nullable - private GameProfile owner = null; + private ResolvableProfile owner = null; @Override @Nullable - public GameProfile getOwner() { + public ResolvableProfile getOwner() { return this.owner; } @Override - public void setOwner(GameProfile owner) { + public void setOwner(ResolvableProfile owner) { this.owner = owner; } @Override - public void writeData(FriendlyByteBuf data) { - if (this.owner == null) { - data.writeBoolean(false); + public void writeData(RegistryFriendlyByteBuf buffer) { + if (this.owner == null || this.owner.id().isEmpty()) { + buffer.writeBoolean(false); } else { - data.writeBoolean(true); - data.writeLong(this.owner.getId().getMostSignificantBits()); - data.writeLong(this.owner.getId().getLeastSignificantBits()); - data.writeUtf(this.owner.getName()); + buffer.writeBoolean(true); + ResolvableProfile.STREAM_CODEC.encode(buffer, this.owner); } } @Override - public void readData(FriendlyByteBuf data) { - if (data.readBoolean()) { - GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUtf()); + public void readData(RegistryFriendlyByteBuf buffer) { + if (buffer.readBoolean()) { + ResolvableProfile owner = ResolvableProfile.STREAM_CODEC.decode(buffer); setOwner(owner); } } @Override - public void read(CompoundTag data) { + public void read(CompoundTag data, HolderLookup.Provider registries) { if (data.contains("owner")) { - GameProfile owner = NbtUtils.readGameProfile(data.getCompound("owner")); - if (owner != null) { - setOwner(owner); - } + ResolvableProfile.CODEC + .parse(NbtOps.INSTANCE, data.get("profile")) + .result() + .ifPresent(this::setOwner); } } @Override - public CompoundTag write(CompoundTag data) { + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { if (this.owner != null) { - CompoundTag nbt = new CompoundTag(); - NbtUtils.writeGameProfile(nbt, this.owner); - data.put("owner", nbt); + data.put("owner", ResolvableProfile.CODEC.encodeStart(NbtOps.INSTANCE, this.owner).getOrThrow()); } return data; } diff --git a/src/main/java/forestry/core/owner/package-info.java b/src/main/java/forestry/core/owner/package-info.java index f307c43f90..5e48c64d5a 100644 --- a/src/main/java/forestry/core/owner/package-info.java +++ b/src/main/java/forestry/core/owner/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.owner; diff --git a/src/main/java/forestry/core/package-info.java b/src/main/java/forestry/core/package-info.java index 6e8a71a4b0..f3733d4b20 100644 --- a/src/main/java/forestry/core/package-info.java +++ b/src/main/java/forestry/core/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core; diff --git a/src/main/java/forestry/core/recipes/jei/ChanceTooltipCallback.java b/src/main/java/forestry/core/recipes/jei/ChanceTooltipCallback.java index a37db00ad5..b3b0ff0c91 100644 --- a/src/main/java/forestry/core/recipes/jei/ChanceTooltipCallback.java +++ b/src/main/java/forestry/core/recipes/jei/ChanceTooltipCallback.java @@ -1,6 +1,6 @@ package forestry.core.recipes.jei; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import mezz.jei.api.gui.ingredient.IRecipeSlotTooltipCallback; import mezz.jei.api.gui.ingredient.IRecipeSlotView; import net.minecraft.network.chat.Component; diff --git a/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java b/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java index e71b74959e..6a8c9378e8 100644 --- a/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java +++ b/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java @@ -17,12 +17,12 @@ public ForestryRecipeCategory(IDrawable background, String unlocalizedName) { @Override public Component getTitle() { - return Component.translatable(localizedName); + return Component.translatable(this.localizedName); } @Override public IDrawable getBackground() { - return background; + return this.background; } @Override diff --git a/src/main/java/forestry/core/recipes/jei/ForestryRecipeType.java b/src/main/java/forestry/core/recipes/jei/ForestryRecipeType.java index c86e3ef462..596730e3eb 100644 --- a/src/main/java/forestry/core/recipes/jei/ForestryRecipeType.java +++ b/src/main/java/forestry/core/recipes/jei/ForestryRecipeType.java @@ -1,7 +1,7 @@ package forestry.core.recipes.jei; import forestry.api.ForestryConstants; -import forestry.api.fuels.RainSubstrate; +import forestry.api.fuels.RainmakerFuel; import forestry.api.recipes.*; import mezz.jei.api.recipe.RecipeType; @@ -11,7 +11,7 @@ public class ForestryRecipeType { public static final RecipeType FABRICATOR = create("fabricator", IFabricatorRecipe.class); public static final RecipeType FERMENTER = create("fermenter", IFermenterRecipe.class); public static final RecipeType MOISTENER = create("moistener", IMoistenerRecipe.class); - public static final RecipeType RAINMAKER = create("rainmaker", RainSubstrate.class); + public static final RecipeType RAINMAKER = create("rainmaker", RainmakerFuel.class); public static final RecipeType SQUEEZER = create("squeezer", ISqueezerRecipe.class); public static final RecipeType STILL = create("still", IStillRecipe.class); diff --git a/src/main/java/forestry/core/recipes/jei/package-info.java b/src/main/java/forestry/core/recipes/jei/package-info.java index 5d08602975..2d9c83976a 100644 --- a/src/main/java/forestry/core/recipes/jei/package-info.java +++ b/src/main/java/forestry/core/recipes/jei/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.recipes.jei; diff --git a/src/main/java/forestry/core/recipes/package-info.java b/src/main/java/forestry/core/recipes/package-info.java index eb33d87a60..0e7e98f7da 100644 --- a/src/main/java/forestry/core/recipes/package-info.java +++ b/src/main/java/forestry/core/recipes/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.recipes; diff --git a/src/main/java/forestry/core/registration/VillagerTrade.java b/src/main/java/forestry/core/registration/VillagerTrade.java index bc7866f272..0e1d98ed78 100644 --- a/src/main/java/forestry/core/registration/VillagerTrade.java +++ b/src/main/java/forestry/core/registration/VillagerTrade.java @@ -6,15 +6,17 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.trading.ItemCost; import net.minecraft.world.item.trading.MerchantOffer; -import net.minecraftforge.items.ItemHandlerHelper; + +import java.util.Optional; public class VillagerTrade { public record GiveItemForEmeralds(Item sellingItem, PriceInterval sellingAmounts, PriceInterval emeraldAmounts, int maxUses, int xp) implements VillagerTrades.ItemListing { @Override public MerchantOffer getOffer(Entity trader, RandomSource rand) { - return new MerchantOffer(new ItemStack(Items.EMERALD, this.emeraldAmounts.getPrice(rand)), new ItemStack(this.sellingItem, this.sellingAmounts.getPrice(rand)), this.maxUses, this.xp, 0.05f); + return new MerchantOffer(new ItemCost(Items.EMERALD, this.emeraldAmounts.getPrice(rand)), new ItemStack(this.sellingItem, this.sellingAmounts.getPrice(rand)), this.maxUses, this.xp, 0.05f); } } @@ -22,7 +24,7 @@ public record GiveEmeraldForItem(Item buyingItem, PriceInterval buyingAmounts, P int maxUses, int xp) implements VillagerTrades.ItemListing { @Override public MerchantOffer getOffer(Entity trader, RandomSource rand) { - return new MerchantOffer(new ItemStack(this.buyingItem, this.buyingAmounts.getPrice(rand)), new ItemStack(Items.EMERALD, this.emeraldAmounts.getPrice(rand)), this.maxUses, this.xp, 0.05f); + return new MerchantOffer(new ItemCost(this.buyingItem, this.buyingAmounts.getPrice(rand)), new ItemStack(Items.EMERALD, this.emeraldAmounts.getPrice(rand)), this.maxUses, this.xp, 0.05f); } } @@ -31,10 +33,10 @@ public record GiveItemForItemAndEmerald(Item buyingItem, PriceInterval buyAmount int xp) implements VillagerTrades.ItemListing { @Override public MerchantOffer getOffer(Entity trader, RandomSource rand) { - ItemStack buy1 = new ItemStack(this.buyingItem, this.buyAmounts.getPrice(rand)); - ItemStack buy2 = new ItemStack(Items.EMERALD, this.emeralsAmounts.getPrice(rand)); - ItemStack sell = ItemHandlerHelper.copyStackWithSize(this.sellingItem, this.sellingAmounts.getPrice(rand)); - return new MerchantOffer(buy1, buy2, sell, this.maxUses, this.xp, 0.05f); + ItemCost buy1 = new ItemCost(this.buyingItem, this.buyAmounts.getPrice(rand)); + ItemCost buy2 = new ItemCost(Items.EMERALD, this.emeralsAmounts.getPrice(rand)); + ItemStack sell = this.sellingItem.copyWithCount(this.sellingAmounts.getPrice(rand)); + return new MerchantOffer(buy1, Optional.of(buy2), sell, this.maxUses, this.xp, 0.05f); } } @@ -52,11 +54,10 @@ public MerchantOffer getOffer(Entity trader, RandomSource rand) { Items.OAK_LOG, Items.SPRUCE_LOG, Items.MANGROVE_LOG, - // todo 1.20 - //Items.CHERRY_LOG, + Items.CHERRY_LOG, }; - return new MerchantOffer(new ItemStack(logsBlock[rand.nextInt(logsBlock.length)], this.buyAmounts.getPrice(rand)), new ItemStack(Items.EMERALD, this.emeraldAmounts.getPrice(rand)), new ItemStack(this.sellingItem, this.sellingAmounts.getPrice(rand)), this.maxUses, this.xp, 0.05f); + return new MerchantOffer(new ItemCost(logsBlock[rand.nextInt(logsBlock.length)], this.buyAmounts.getPrice(rand)), Optional.of(new ItemCost(Items.EMERALD, this.emeraldAmounts.getPrice(rand))), new ItemStack(this.sellingItem, this.sellingAmounts.getPrice(rand)), this.maxUses, this.xp, 0.05f); } } @@ -65,10 +66,10 @@ public record GiveItemForTwoItems(Item buyingItem, PriceInterval buyAmounts, Ite int maxUses, int xp) implements VillagerTrades.ItemListing { @Override public MerchantOffer getOffer(Entity trader, RandomSource rand) { - ItemStack buy1 = new ItemStack(this.buyingItem, this.buyAmounts.getPrice(rand)); - ItemStack buy2 = new ItemStack(this.buyingItem2, this.buyAmounts2.getPrice(rand)); - ItemStack sell = ItemHandlerHelper.copyStackWithSize(this.sellingItem, this.sellingAmounts.getPrice(rand)); - return new MerchantOffer(buy1, buy2, sell, this.maxUses, this.xp, 0.05f); + ItemCost buy1 = new ItemCost(this.buyingItem, this.buyAmounts.getPrice(rand)); + ItemCost buy2 = new ItemCost(this.buyingItem2, this.buyAmounts2.getPrice(rand)); + ItemStack sell = this.sellingItem.copyWithCount(this.sellingAmounts.getPrice(rand)); + return new MerchantOffer(buy1, Optional.of(buy2), sell, this.maxUses, this.xp, 0.05f); } } diff --git a/src/main/java/forestry/core/registration/package-info.java b/src/main/java/forestry/core/registration/package-info.java index ccc41e5590..779fb8fdb0 100644 --- a/src/main/java/forestry/core/registration/package-info.java +++ b/src/main/java/forestry/core/registration/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.core.registration; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/core/render/ColourProperties.java b/src/main/java/forestry/core/render/ColourProperties.java index 45cc6a3a98..26d5e6cf03 100644 --- a/src/main/java/forestry/core/render/ColourProperties.java +++ b/src/main/java/forestry/core/render/ColourProperties.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; import forestry.Forestry; diff --git a/src/main/java/forestry/core/render/EnumTankLevel.java b/src/main/java/forestry/core/render/EnumTankLevel.java index cda1691c3e..dafcb39c50 100644 --- a/src/main/java/forestry/core/render/EnumTankLevel.java +++ b/src/main/java/forestry/core/render/EnumTankLevel.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.IFluidTank; public enum EnumTankLevel { EMPTY(0), diff --git a/src/main/java/forestry/core/render/ForestryBewlr.java b/src/main/java/forestry/core/render/ForestryBewlr.java index dec1a3776d..349ee616b0 100644 --- a/src/main/java/forestry/core/render/ForestryBewlr.java +++ b/src/main/java/forestry/core/render/ForestryBewlr.java @@ -2,7 +2,6 @@ import com.mojang.blaze3d.vertex.PoseStack; import forestry.apiculture.blocks.NaturalistChestBlockType; -import forestry.core.blocks.BlockBase; import forestry.core.blocks.BlockTypeCoreTesr; import forestry.core.features.CoreBlocks; import forestry.core.tiles.*; @@ -23,6 +22,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; @@ -65,8 +65,8 @@ public ForestryBewlr(BlockEntityRenderDispatcher dispatcher) { private static void addTile(IdentityHashMap map, FeatureBlock block, BiFunction factory) { BlockState state = block.defaultState(); - if (state.hasProperty(BlockBase.FACING)) { - state = state.setValue(BlockBase.FACING, Direction.SOUTH); + if (state.hasProperty(HorizontalDirectionalBlock.FACING)) { + state = state.setValue(HorizontalDirectionalBlock.FACING, Direction.SOUTH); } map.put(block.item(), factory.apply(BlockPos.ZERO, state)); } diff --git a/src/main/java/forestry/core/render/ForestryTextureManager.java b/src/main/java/forestry/core/render/ForestryTextureManager.java index cf6c1ee6f6..60bbfe9a7b 100644 --- a/src/main/java/forestry/core/render/ForestryTextureManager.java +++ b/src/main/java/forestry/core/render/ForestryTextureManager.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; import forestry.api.client.ITextureManager; @@ -16,7 +6,7 @@ import net.minecraft.resources.ResourceLocation; public class ForestryTextureManager implements ITextureManager { - private final ForestrySpriteUploader uploader = new ForestrySpriteUploader(Minecraft.getInstance().textureManager); + private final ForestrySpriteUploader uploader = new ForestrySpriteUploader(Minecraft.getInstance().getTextureManager()); public ForestrySpriteUploader getSpriteUploader() { return this.uploader; diff --git a/src/main/java/forestry/core/render/ParticleRender.java b/src/main/java/forestry/core/render/ParticleRender.java index 9bbff2232d..0d6df03ff0 100755 --- a/src/main/java/forestry/core/render/ParticleRender.java +++ b/src/main/java/forestry/core/render/ParticleRender.java @@ -1,7 +1,6 @@ package forestry.core.render; import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.hives.IHiveTile; import forestry.api.genetics.IGenome; import forestry.api.genetics.alleles.BeeChromosomes; import forestry.apiculture.genetics.Bee; @@ -10,6 +9,7 @@ import forestry.apiculture.particles.BeeParticleData; import forestry.apiculture.particles.BeeTargetParticleData; import forestry.apiculture.particles.ParticleSnow; +import forestry.apiculture.tiles.TileHive; import forestry.core.config.ForestryConfig; import forestry.core.entities.ParticleIgnition; import forestry.core.entities.ParticleSmoke; @@ -27,8 +27,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import org.joml.Vector3f; import java.util.List; @@ -55,7 +55,7 @@ public static boolean shouldSpawnParticle(Level world) { } public static void addBeeHiveFX(IBeeHousing housing, IGenome genome, List flowerPositions) { - LevelAccessor world1 = housing.getWorldObj(); + LevelAccessor world1 = housing.getLevel(); ClientLevel world = (ClientLevel) world1; if (!shouldSpawnParticle(world)) { return; @@ -66,8 +66,7 @@ public static void addBeeHiveFX(IBeeHousing housing, IGenome genome, List= 85) { + if (housing instanceof TileHive hive) { + if (hive.isAngry() || randomInt >= 85) { List entitiesInRange = ThrottledBeeEffect.getEntitiesInRange(genome, housing, LivingEntity.class); if (!entitiesInRange.isEmpty()) { LivingEntity entity = entitiesInRange.get(world.random.nextInt(entitiesInRange.size())); - //Particle particle = new ParticleBeeTargetEntity(world, particleStart, entity, color); - //effectRenderer.add(particle); - world.addParticle(new BeeTargetParticleData(entity, color), particleStart.x, particleStart.y, particleStart.z, 0, 0, 0); + world.addParticle(new BeeTargetParticleData(entity.getId(), color), particleStart.x, particleStart.y, particleStart.z, 0, 0, 0); return; } } @@ -91,16 +88,12 @@ public static void addBeeHiveFX(IBeeHousing housing, IGenome genome, List { @@ -79,7 +69,7 @@ public static LayerDefinition createBodyLayer() { @Override public void render(TileAnalyzer analyzer, float partialTick, PoseStack stack, MultiBufferSource buffers, int light, int overlay) { stack.pushPose(); - Direction facing = analyzer.getBlockState().getValue(BlockBase.FACING); + Direction facing = analyzer.getBlockState().getValue(HorizontalDirectionalBlock.FACING); RenderUtil.rotateByHorizontalDirection(stack, facing); VertexConsumer buffer0 = buffers.getBuffer(RenderType.entityCutout(TEXTURE0)); diff --git a/src/main/java/forestry/core/render/RenderEscritoire.java b/src/main/java/forestry/core/render/RenderEscritoire.java index 56f8dda62f..180ab27d69 100755 --- a/src/main/java/forestry/core/render/RenderEscritoire.java +++ b/src/main/java/forestry/core/render/RenderEscritoire.java @@ -1,19 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import forestry.api.ForestryConstants; -import forestry.core.blocks.BlockBase; import forestry.core.config.Constants; import forestry.core.tiles.TileEscritoire; import forestry.core.utils.RenderUtil; @@ -31,6 +20,7 @@ import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; public class RenderEscritoire implements BlockEntityRenderer { private static final ResourceLocation TEXTURE = ForestryConstants.forestry(Constants.TEXTURE_PATH_BLOCK + "/escritoire.png"); @@ -74,7 +64,7 @@ public static LayerDefinition createBodyLayer() { @Override public void render(TileEscritoire escritoire, float partialTick, PoseStack stack, MultiBufferSource buffers, int light, int overlay) { stack.pushPose(); - Direction facing = escritoire.getBlockState().getValue(BlockBase.FACING); + Direction facing = escritoire.getBlockState().getValue(HorizontalDirectionalBlock.FACING); RenderUtil.rotateByHorizontalDirection(stack, facing); VertexConsumer buffer = buffers.getBuffer(RenderType.entityCutout(TEXTURE)); diff --git a/src/main/java/forestry/core/render/RenderMachine.java b/src/main/java/forestry/core/render/RenderMachine.java index 87cfbc65ad..cc94bf8d58 100755 --- a/src/main/java/forestry/core/render/RenderMachine.java +++ b/src/main/java/forestry/core/render/RenderMachine.java @@ -1,20 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.math.Axis; import forestry.api.ForestryConstants; -import forestry.core.blocks.BlockBase; import forestry.core.tiles.IRenderableTile; import forestry.core.tiles.TileBase; import forestry.core.utils.RenderUtil; @@ -31,6 +20,7 @@ import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import java.util.EnumMap; import java.util.Locale; @@ -92,24 +82,21 @@ public static LayerDefinition createBodyLayer() { private void renderTank(PoseStack stack, ModelPart tankModel, MultiBufferSource buffers, ResourceLocation textureBase, TankRenderInfo renderInfo, int light, int overlay) { tankModel.render(stack, buffers.getBuffer(RenderType.entityCutout(textureBase)), light, overlay); - ResourceLocation textureResourceTankLevel = this.texturesTankLevels.get(renderInfo.getLevel()); + ResourceLocation textureResourceTankLevel = this.texturesTankLevels.get(renderInfo.level()); if (textureResourceTankLevel == null) { return; } - int color = RenderUtil.getFluidColor(renderInfo.getFluidStack().getFluid()); - float r = (color >> 16 & 255) / 255f; - float g = (color >> 8 & 255) / 255f; - float b = (color & 255) / 255f; + int color = RenderUtil.getFluidColor(renderInfo.fluidStack().getFluid()); - tankModel.render(stack, buffers.getBuffer(RenderType.entityCutout(textureResourceTankLevel)), light, overlay, r, g, b, 1.0f); + tankModel.render(stack, buffers.getBuffer(RenderType.entityCutout(textureResourceTankLevel)), light, overlay, color); } @Override public void render(TileBase machine, float partialTick, PoseStack stack, MultiBufferSource buffers, int light, int overlay) { stack.pushPose(); // apply direction rotation - Direction orientation = machine.getBlockState().getValue(BlockBase.FACING); + Direction orientation = machine.getBlockState().getValue(HorizontalDirectionalBlock.FACING); RenderUtil.rotateByHorizontalDirection(stack, orientation); // flip the machine on its side stack.translate(0.5, 0.5, 0.5); diff --git a/src/main/java/forestry/core/render/RenderMill.java b/src/main/java/forestry/core/render/RenderMill.java index 4d7128c78c..75d24247fc 100755 --- a/src/main/java/forestry/core/render/RenderMill.java +++ b/src/main/java/forestry/core/render/RenderMill.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; import com.mojang.blaze3d.vertex.PoseStack; diff --git a/src/main/java/forestry/core/render/RenderNaturalistChest.java b/src/main/java/forestry/core/render/RenderNaturalistChest.java index 2868a94ad4..24b288812e 100755 --- a/src/main/java/forestry/core/render/RenderNaturalistChest.java +++ b/src/main/java/forestry/core/render/RenderNaturalistChest.java @@ -1,19 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import forestry.api.ForestryConstants; -import forestry.core.blocks.BlockBase; import forestry.core.config.Constants; import forestry.core.tiles.TileNaturalistChest; import forestry.core.utils.RenderUtil; @@ -29,6 +18,7 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; public class RenderNaturalistChest implements BlockEntityRenderer { private static final String LID = "lid"; @@ -67,7 +57,7 @@ public static LayerDefinition createBodyLayer() { public void render(TileNaturalistChest chest, float partialTick, PoseStack stack, MultiBufferSource buffers, int light, int overlay) { stack.pushPose(); - RenderUtil.rotateByHorizontalDirection(stack, chest.getBlockState().getValue(BlockBase.FACING)); + RenderUtil.rotateByHorizontalDirection(stack, chest.getBlockState().getValue(HorizontalDirectionalBlock.FACING)); // calculate lid angle float prevLidAngle = chest.prevLidAngle; diff --git a/src/main/java/forestry/core/render/TankRenderInfo.java b/src/main/java/forestry/core/render/TankRenderInfo.java index a9878795e5..85d1116013 100644 --- a/src/main/java/forestry/core/render/TankRenderInfo.java +++ b/src/main/java/forestry/core/render/TankRenderInfo.java @@ -1,38 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.render; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; -public class TankRenderInfo { +public record TankRenderInfo(FluidStack fluidStack, EnumTankLevel level) { public static final TankRenderInfo EMPTY = new TankRenderInfo(FluidStack.EMPTY, EnumTankLevel.EMPTY); - private final FluidStack fluidStack; - private final EnumTankLevel level; - public TankRenderInfo(IFluidTank fluidTank) { this(fluidTank.getFluid(), EnumTankLevel.rateTankLevel(fluidTank)); } - - public TankRenderInfo(FluidStack fluidStack, EnumTankLevel level) { - this.fluidStack = fluidStack; - this.level = level; - } - - public FluidStack getFluidStack() { - return this.fluidStack; - } - - public EnumTankLevel getLevel() { - return this.level; - } } diff --git a/src/main/java/forestry/core/render/package-info.java b/src/main/java/forestry/core/render/package-info.java index 2bf91edbb6..746c69487c 100644 --- a/src/main/java/forestry/core/render/package-info.java +++ b/src/main/java/forestry/core/render/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.render; diff --git a/src/main/java/forestry/core/tiles/AdjacentTileCache.java b/src/main/java/forestry/core/tiles/AdjacentTileCache.java index 025072ff19..03405f3611 100644 --- a/src/main/java/forestry/core/tiles/AdjacentTileCache.java +++ b/src/main/java/forestry/core/tiles/AdjacentTileCache.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import net.minecraft.core.BlockPos; @@ -20,14 +10,10 @@ import java.util.LinkedHashSet; import java.util.Set; -// todo does this actually improve performance? - /** * A helper class that caches adjacent tiles for a given tile entity. *

* Listeners can be added to listen for adjacent tile changes. - * - * @author CovertJaguar */ public final class AdjacentTileCache { private static final int DELAY_MIN = 20; @@ -69,16 +55,16 @@ public void addListener(ICacheListener listener) { @Nullable private BlockEntity searchSide(Direction side) { - Level world = this.source.getLevel(); + Level level = this.source.getLevel(); BlockPos pos = this.source.getBlockPos().relative(side); - if (world.hasChunkAt(pos) && !world.isEmptyBlock(pos)) { - return TileUtil.getTile(world, pos); + if (level.hasChunkAt(pos) && !level.isEmptyBlock(pos)) { + return TileUtil.getTile(level, pos); } return null; } public void refresh() { - for (Direction side : Direction.values()) { + for (Direction side : Direction.VALUES) { getTileOnSide(side); } } @@ -151,7 +137,6 @@ public BlockEntity getSource() { } private static class Timer { - private long startTime = Long.MIN_VALUE; public boolean hasTriggered(Level world, int ticks) { @@ -166,6 +151,5 @@ public boolean hasTriggered(Level world, int ticks) { public void reset() { this.startTime = Long.MIN_VALUE; } - } } diff --git a/src/main/java/forestry/core/tiles/EscritoireGame.java b/src/main/java/forestry/core/tiles/EscritoireGame.java index b2c0d21064..9843b6db9c 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGame.java +++ b/src/main/java/forestry/core/tiles/EscritoireGame.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.core.INbtReadable; @@ -17,8 +7,9 @@ import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.core.network.IStreamable; import forestry.core.utils.NetworkUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.util.RandomSource; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -58,17 +49,17 @@ public long getLastUpdate() { } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { compoundNBT.putInt("bountyLevel", this.bountyLevel); compoundNBT.putLong("lastUpdate", this.lastUpdate); - this.gameBoard.write(compoundNBT); + this.gameBoard.write(compoundNBT, registries); compoundNBT.putInt("Status", this.status.ordinal()); return compoundNBT; } @Override - public void read(CompoundTag nbt) { + public void read(CompoundTag nbt, HolderLookup.Provider registries) { this.bountyLevel = nbt.getInt("bountyLevel"); this.lastUpdate = nbt.getLong("lastUpdate"); this.gameBoard = new EscritoireGameBoard(nbt); @@ -83,17 +74,17 @@ public void read(CompoundTag nbt) { /* NETWORK */ @Override - public void writeData(FriendlyByteBuf data) { - data.writeInt(this.bountyLevel); - this.gameBoard.writeData(data); - NetworkUtil.writeEnum(data, this.status); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeInt(this.bountyLevel); + this.gameBoard.writeData(buffer); + NetworkUtil.writeEnum(buffer, this.status); } @Override - public void readData(FriendlyByteBuf data) { - this.bountyLevel = data.readInt(); - this.gameBoard.readData(data); - this.status = NetworkUtil.readEnum(data, Status.VALUES); + public void readData(RegistryFriendlyByteBuf buffer) { + this.bountyLevel = buffer.readInt(); + this.gameBoard.readData(buffer); + this.status = NetworkUtil.readEnum(buffer, Status.VALUES); } /* INTERACTION */ diff --git a/src/main/java/forestry/core/tiles/EscritoireGameBoard.java b/src/main/java/forestry/core/tiles/EscritoireGameBoard.java index b5693e2492..16c455b125 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGameBoard.java +++ b/src/main/java/forestry/core/tiles/EscritoireGameBoard.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.core.INbtWritable; @@ -17,10 +7,11 @@ import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.core.network.IStreamable; import forestry.core.utils.NetworkUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; @@ -189,7 +180,7 @@ private static int getTokenCount(IIndividual individual) { } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { if (this.tokenCount > 0) { compoundNBT.putInt("TokenCount", this.tokenCount); ListTag nbttaglist = new ListTag(); @@ -202,7 +193,7 @@ public CompoundTag write(CompoundTag compoundNBT) { CompoundTag compoundNBT2 = new CompoundTag(); compoundNBT2.putByte("Slot", (byte) i); - token.write(compoundNBT2); + token.write(compoundNBT2, registries); nbttaglist.add(compoundNBT2); } @@ -214,14 +205,14 @@ public CompoundTag write(CompoundTag compoundNBT) { } @Override - public void writeData(FriendlyByteBuf data) { - data.writeVarInt(this.tokenCount); - NetworkUtil.writeStreamables(data, this.gameTokens); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeVarInt(this.tokenCount); + NetworkUtil.writeStreamables(buffer, this.gameTokens); } @Override - public void readData(FriendlyByteBuf data) { - this.tokenCount = data.readVarInt(); - NetworkUtil.readStreamables(data, this.gameTokens, EscritoireGameToken::new); + public void readData(RegistryFriendlyByteBuf buffer) { + this.tokenCount = buffer.readVarInt(); + NetworkUtil.readStreamables(buffer, this.gameTokens, EscritoireGameToken::new); } } diff --git a/src/main/java/forestry/core/tiles/EscritoireGameToken.java b/src/main/java/forestry/core/tiles/EscritoireGameToken.java index cc527b4c18..49489d9ced 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGameToken.java +++ b/src/main/java/forestry/core/tiles/EscritoireGameToken.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.IForestryApi; @@ -19,8 +9,9 @@ import forestry.core.network.IStreamable; import forestry.core.utils.ColourUtil; import forestry.core.utils.NetworkUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; @@ -45,7 +36,7 @@ private enum State { private State state = State.UNREVEALED; - public EscritoireGameToken(FriendlyByteBuf data) { + public EscritoireGameToken(RegistryFriendlyByteBuf data) { readData(data); } @@ -145,7 +136,7 @@ public boolean matches(EscritoireGameToken other) { } @Override - public CompoundTag write(CompoundTag nbt) { + public CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries) { nbt.putInt("state", this.state.ordinal()); if (this.tokenIndividual != null) { @@ -164,28 +155,33 @@ private void read(CompoundTag nbt) { String tokenType = nbt.getString("tokenSpeciesType"); if (!tokenSpecies.isEmpty() && !tokenType.isEmpty()) { - setTokenSpecies(new ResourceLocation(tokenType), new ResourceLocation(tokenSpecies)); + ResourceLocation typeId = ResourceLocation.tryParse(tokenType); + ResourceLocation speciesId = ResourceLocation.tryParse(tokenSpecies); + + if (speciesId != null && typeId != null) { + setTokenSpecies(typeId, speciesId); + } } } @Override - public void writeData(FriendlyByteBuf data) { - NetworkUtil.writeEnum(data, this.state); + public void writeData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.writeEnum(buffer, this.state); if (this.tokenIndividual != null && this.tokenType != null) { - data.writeBoolean(true); - data.writeResourceLocation(this.tokenIndividual.getSpecies().id()); - data.writeResourceLocation(this.tokenType.id()); + buffer.writeBoolean(true); + buffer.writeResourceLocation(this.tokenIndividual.getSpecies().id()); + buffer.writeResourceLocation(this.tokenType.id()); } else { - data.writeBoolean(false); + buffer.writeBoolean(false); } } @Override - public void readData(FriendlyByteBuf data) { - this.state = NetworkUtil.readEnum(data, State.VALUES); - if (data.readBoolean()) { - ResourceLocation speciesId = data.readResourceLocation(); - ResourceLocation typeId = data.readResourceLocation(); + public void readData(RegistryFriendlyByteBuf buffer) { + this.state = NetworkUtil.readEnum(buffer, State.VALUES); + if (buffer.readBoolean()) { + ResourceLocation speciesId = buffer.readResourceLocation(); + ResourceLocation typeId = buffer.readResourceLocation(); setTokenSpecies(typeId, speciesId); } } diff --git a/src/main/java/forestry/core/tiles/EscritoireTextSource.java b/src/main/java/forestry/core/tiles/EscritoireTextSource.java index 6f6e8adc62..b1386af44c 100644 --- a/src/main/java/forestry/core/tiles/EscritoireTextSource.java +++ b/src/main/java/forestry/core/tiles/EscritoireTextSource.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import com.google.common.collect.ArrayListMultimap; diff --git a/src/main/java/forestry/core/tiles/IActivatable.java b/src/main/java/forestry/core/tiles/IActivatable.java index 55e86fe73c..7a5cbcffcf 100644 --- a/src/main/java/forestry/core/tiles/IActivatable.java +++ b/src/main/java/forestry/core/tiles/IActivatable.java @@ -21,7 +21,7 @@ public interface IActivatable { * * @return The position of the tile entity */ - BlockPos getCoordinates(); + BlockPos getBlockPos(); /** * Retrieves the current state of the tile entity. diff --git a/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java b/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java index d63d8ad2e1..af82eb9033 100644 --- a/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java +++ b/src/main/java/forestry/core/tiles/IFilterSlotDelegate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/forestry/core/tiles/IItemStackDisplay.java b/src/main/java/forestry/core/tiles/IItemStackDisplay.java index 0af454273e..dd7f64ebf4 100644 --- a/src/main/java/forestry/core/tiles/IItemStackDisplay.java +++ b/src/main/java/forestry/core/tiles/IItemStackDisplay.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; public interface IItemStackDisplay { - @OnlyIn(Dist.CLIENT) - void handleItemStackForDisplay(ItemStack itemStack); + /** + * Called on the client to sync the displayed item from the server. + */ + void handleItemStackForDisplay(ItemStack stack); } diff --git a/src/main/java/forestry/core/tiles/ILiquidTankTile.java b/src/main/java/forestry/core/tiles/ILiquidTankTile.java index 8f6e5feb97..6980ccae76 100644 --- a/src/main/java/forestry/core/tiles/ILiquidTankTile.java +++ b/src/main/java/forestry/core/tiles/ILiquidTankTile.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.core.ILocationProvider; diff --git a/src/main/java/forestry/core/tiles/IRenderableTile.java b/src/main/java/forestry/core/tiles/IRenderableTile.java index 8e365b6b7f..79842a2464 100644 --- a/src/main/java/forestry/core/tiles/IRenderableTile.java +++ b/src/main/java/forestry/core/tiles/IRenderableTile.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.core.render.TankRenderInfo; diff --git a/src/main/java/forestry/core/tiles/TileAnalyzer.java b/src/main/java/forestry/core/tiles/TileAnalyzer.java index 9babbf96db..f4475fc273 100644 --- a/src/main/java/forestry/core/tiles/TileAnalyzer.java +++ b/src/main/java/forestry/core/tiles/TileAnalyzer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.core.ForestryError; @@ -19,7 +9,7 @@ import forestry.core.fluids.FluidHelper; import forestry.core.fluids.FluidTagFilter; import forestry.core.fluids.TankManager; -import forestry.core.gui.ContainerAnalyzer; +import forestry.core.gui.AnalyzerMenu; import forestry.core.inventory.InventoryAnalyzer; import forestry.core.inventory.wrappers.InventoryMapper; import forestry.core.network.packets.PacketItemStackDisplay; @@ -29,9 +19,10 @@ import forestry.core.utils.SpeciesUtil; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; @@ -40,13 +31,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; @@ -69,28 +57,28 @@ public class TileAnalyzer extends TilePowered implements WorldlyContainer, ILiqu public TileAnalyzer(BlockPos pos, BlockState state) { super(CoreTiles.ANALYZER.tileType(), pos, state, 800, Constants.MACHINE_MAX_ENERGY); setInternalInventory(new InventoryAnalyzer(this)); - this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilter(FluidTagFilter.HONEY); - this.tankManager = new TankManager(this, this.resourceTank); - this.invInput = new InventoryMapper(getInternalInventory(), InventoryAnalyzer.SLOT_INPUT_1, InventoryAnalyzer.SLOT_INPUT_COUNT); - this.invOutput = new InventoryMapper(getInternalInventory(), InventoryAnalyzer.SLOT_OUTPUT_1, InventoryAnalyzer.SLOT_OUTPUT_COUNT); + this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilter(FluidTagFilter.HONEY); + this.tankManager = new TankManager(this, this.resourceTank); + this.invInput = new InventoryMapper(getInternalInventory(), InventoryAnalyzer.SLOT_INPUT_1, InventoryAnalyzer.SLOT_INPUT_COUNT); + this.invOutput = new InventoryMapper(getInternalInventory(), InventoryAnalyzer.SLOT_OUTPUT_1, InventoryAnalyzer.SLOT_OUTPUT_COUNT); } /* SAVING & LOADING */ @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.tankManager.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.tankManager.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.tankManager.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); ItemStack stackToAnalyze = getItem(InventoryAnalyzer.SLOT_ANALYZE); if (!stackToAnalyze.isEmpty()) { - this.specimenToAnalyze = IIndividualHandlerItem.getIndividual(stackToAnalyze); + this.specimenToAnalyze = IIndividualHandlerItem.getIndividual(stackToAnalyze); } } @@ -117,11 +105,11 @@ public boolean workCycle() { if (drained.isEmpty() || drained.getAmount() != HONEY_REQUIRED) { return false; } - this.resourceTank.drain(HONEY_REQUIRED, IFluidHandler.FluidAction.EXECUTE); + this.resourceTank.drain(HONEY_REQUIRED, IFluidHandler.FluidAction.EXECUTE); - this.specimenToAnalyze.analyze(); + this.specimenToAnalyze.analyze(); - this.specimenToAnalyze.saveToStack(stackToAnalyze); + this.specimenToAnalyze.saveToStack(stackToAnalyze); } boolean added = InventoryUtil.tryAddStack(this.invOutput, stackToAnalyze, true); @@ -131,7 +119,7 @@ public boolean workCycle() { setItem(InventoryAnalyzer.SLOT_ANALYZE, ItemStack.EMPTY); PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - NetworkUtil.sendNetworkPacket(packet, this.worldPosition, this.level); + NetworkUtil.sendToPlayersTrackingPos(packet, this.worldPosition, (ServerLevel) this.level); return true; } @@ -149,29 +137,24 @@ private Integer getInputSlotIndex() { /* Network */ @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); ItemStack displayStack = getIndividualOnDisplay(); - data.writeItem(displayStack); - this.tankManager.writeData(data); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buffer, displayStack); + this.tankManager.writeData(buffer); } @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.individualOnDisplayClient = data.readItem(); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.individualOnDisplayClient = ItemStack.OPTIONAL_STREAM_CODEC.decode(buffer); + this.tankManager.readData(buffer); } @Override - public void handleItemStackForDisplay(ItemStack itemStack) { - if (!ItemStack.matches(itemStack, this.individualOnDisplayClient)) { - this.individualOnDisplayClient = itemStack; - //TODO - BlockPos pos = getBlockPos(); - Minecraft.getInstance().levelRenderer.setSectionDirty(pos.getX(), pos.getY(), pos.getZ()); - // world.markForRerender(getPos()); + public void handleItemStackForDisplay(ItemStack stack) { + if (!ItemStack.matches(stack, this.individualOnDisplayClient)) { + this.individualOnDisplayClient = stack; } } @@ -221,24 +204,24 @@ private void moveSpecimenToAnalyzeSlot() { inputStack = GeneticsUtil.convertToGeneticEquivalent(inputStack); } - this.specimenToAnalyze = IIndividualHandlerItem.getIndividual(inputStack); + this.specimenToAnalyze = IIndividualHandlerItem.getIndividual(inputStack); if (this.specimenToAnalyze == null) { return; } setItem(InventoryAnalyzer.SLOT_ANALYZE, inputStack); - this.invInput.setItem(slotIndex, ItemStack.EMPTY); + this.invInput.setItem(slotIndex, ItemStack.EMPTY); if (this.specimenToAnalyze.isAnalyzed()) { - setTicksPerWorkCycle(1); + setStepsPerWorkCycle(1); setEnergyPerWorkCycle(0); } else { - setTicksPerWorkCycle(TIME_TO_ANALYZE); + setStepsPerWorkCycle(TIME_TO_ANALYZE); setEnergyPerWorkCycle(analyzerEnergyPerWork); } PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - NetworkUtil.sendNetworkPacket(packet, this.worldPosition, this.level); + NetworkUtil.sendToPlayersTrackingPos(packet, this.worldPosition, ((ServerLevel) this.level)); } public ItemStack getIndividualOnDisplay() { @@ -249,24 +232,13 @@ public ItemStack getIndividualOnDisplay() { return getItem(InventoryAnalyzer.SLOT_ANALYZE); } - /* ILiquidTankTile */ - @Override public TankManager getTankManager() { return this.tankManager; } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerAnalyzer(windowId, player.getInventory(), this); + return new AnalyzerMenu(windowId, player.getInventory(), this); } } diff --git a/src/main/java/forestry/core/tiles/TileBase.java b/src/main/java/forestry/core/tiles/TileBase.java index 78caa58e73..9be01619b1 100644 --- a/src/main/java/forestry/core/tiles/TileBase.java +++ b/src/main/java/forestry/core/tiles/TileBase.java @@ -1,38 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; -import forestry.core.blocks.BlockBase; -import forestry.core.blocks.IBlockType; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; +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.Block; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkHooks; + +import forestry.core.blocks.BlockBase; +import forestry.core.blocks.IBlockType; public abstract class TileBase extends TileForestry { public TileBase(BlockEntityType tileEntityTypeIn, BlockPos pos, BlockState state) { super(tileEntityTypeIn, pos, state); } - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { - if (!hasGui()) { - return; - } - NetworkHooks.openScreen(player, this, pos); + public boolean interactWithItem(Level level, BlockPos pos, Player player, InteractionHand hand, ItemStack stack) { + return false; } - protected boolean hasGui() { + public boolean interactNoItem(Level level, Player player, BlockPos pos) { + player.openMenu(this, pos); return true; } diff --git a/src/main/java/forestry/core/tiles/TileEscritoire.java b/src/main/java/forestry/core/tiles/TileEscritoire.java index 24b97f0d97..67b225efeb 100644 --- a/src/main/java/forestry/core/tiles/TileEscritoire.java +++ b/src/main/java/forestry/core/tiles/TileEscritoire.java @@ -1,22 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; -import com.mojang.authlib.GameProfile; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpecies; import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.core.features.CoreTiles; -import forestry.core.gui.ContainerEscritoire; +import forestry.core.gui.EscritoireMenu; import forestry.core.inventory.InventoryAnalyzer; import forestry.core.inventory.InventoryEscritoire; import forestry.core.inventory.watchers.ISlotPickupWatcher; @@ -25,16 +14,17 @@ import forestry.core.utils.InventoryUtil; import forestry.core.utils.NetworkUtil; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; public class TileEscritoire extends TileBase implements WorldlyContainer, ISlotPickupWatcher, IStreamableGui, IItemStackDisplay { private final EscritoireGame game = new EscritoireGame(); @@ -47,16 +37,16 @@ public TileEscritoire(BlockPos pos, BlockState state) { /* SAVING & LOADING */ @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.game.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.game.read(nbt, registries); } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.game.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.game.write(nbt, registries); } /* GAME */ @@ -64,12 +54,12 @@ public EscritoireGame getGame() { return this.game; } - public void choose(GameProfile gameProfile, int index) { + public void choose(ResolvableProfile gameProfile, int index) { this.game.choose(index); processTurnResult(gameProfile); } - private void processTurnResult(GameProfile gameProfile) { + private void processTurnResult(ResolvableProfile gameProfile) { if (getGame().getStatus() != EscritoireGame.Status.SUCCESS) { return; } @@ -112,36 +102,35 @@ public void probe() { /* NETWORK */ @Override - public void writeGuiData(FriendlyByteBuf data) { - this.game.writeData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + this.game.writeData(buffer); } @Override - public void readGuiData(FriendlyByteBuf data) { - this.game.readData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.game.readData(buffer); } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - ItemStack displayStack = getIndividualOnDisplay(); - data.writeItem(displayStack); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + ItemStack.STREAM_CODEC.encode(buffer, getIndividualOnDisplay()); } @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.individualOnDisplayClient = data.readItem(); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.individualOnDisplayClient = ItemStack.STREAM_CODEC.decode(buffer); } - /* ISlotPickupWatcher */ @Override public void onTake(int slotIndex, Player player) { if (slotIndex == InventoryEscritoire.SLOT_ANALYZE) { this.game.reset(); - PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - NetworkUtil.sendNetworkPacket(packet, this.worldPosition, this.level); + if (this.level instanceof ServerLevel serverLevel) { + PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); + NetworkUtil.sendToPlayersTrackingPos(packet, this.worldPosition, serverLevel); + } } } @@ -149,22 +138,22 @@ public void onTake(int slotIndex, Player player) { public void setItem(int slotIndex, ItemStack itemstack) { super.setItem(slotIndex, itemstack); if (slotIndex == InventoryEscritoire.SLOT_ANALYZE) { - if (this.level != null && !this.level.isClientSide) { + if (this.level != null && this.level instanceof ServerLevel serverLevel) { PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - NetworkUtil.sendNetworkPacket(packet, this.worldPosition, this.level); + NetworkUtil.sendToPlayersTrackingPos(packet, this.worldPosition, serverLevel); } } } @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerEscritoire(windowId, player.getInventory(), this); + return new EscritoireMenu(windowId, player.getInventory(), this); } @Override - public void handleItemStackForDisplay(ItemStack itemStack) { - if (!ItemStack.matches(itemStack, this.individualOnDisplayClient)) { - this.individualOnDisplayClient = itemStack; + public void handleItemStackForDisplay(ItemStack stack) { + if (!ItemStack.matches(stack, this.individualOnDisplayClient)) { + this.individualOnDisplayClient = stack; } } diff --git a/src/main/java/forestry/core/tiles/TileForestry.java b/src/main/java/forestry/core/tiles/TileForestry.java index 0f609ef210..1b019bb55f 100644 --- a/src/main/java/forestry/core/tiles/TileForestry.java +++ b/src/main/java/forestry/core/tiles/TileForestry.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; -import com.google.common.base.Preconditions; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; import forestry.api.core.ILocationProvider; @@ -23,8 +12,9 @@ import forestry.core.utils.NBTUtilForestry; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.server.level.ServerLevel; @@ -36,11 +26,9 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.wrapper.InvWrapper; -import net.minecraftforge.items.wrapper.SidedInvWrapper; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.wrapper.InvWrapper; +import net.neoforged.neoforge.items.wrapper.SidedInvWrapper; import javax.annotation.Nullable; @@ -53,8 +41,8 @@ public abstract class TileForestry extends BlockEntity implements IStreamable, I // package private for ForestryTicker final TickHelper tickHelper; - public TileForestry(BlockEntityType tileEntityTypeIn, BlockPos pos, BlockState state) { - super(tileEntityTypeIn, pos, state); + public TileForestry(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); this.tickHelper = new TickHelper(pos.hashCode()); } @@ -63,19 +51,19 @@ protected AdjacentTileCache getTileCache() { return this.tileCache; } - public void onNeighborTileChange(Level world, BlockPos pos, BlockPos neighbor) { - this.tileCache.onNeighborChange(); + public void onNeighborTileChange(Level level, BlockPos pos, BlockPos neighbor) { + this.tileCache.onNeighborChange(); } @Override public void setRemoved() { - this.tileCache.purge(); + this.tileCache.purge(); super.setRemoved(); } @Override public void clearRemoved() { - this.tileCache.purge(); + this.tileCache.purge(); super.clearRemoved(); } @@ -92,15 +80,15 @@ protected final boolean updateOnInterval(int tickInterval) { // / SAVING & LOADING @Override - public void load(CompoundTag data) { - super.load(data); - this.inventory.read(data); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.inventory.read(nbt, registries); } @Override - public void saveAdditional(CompoundTag data) { - super.saveAdditional(data); - this.inventory.write(data); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.inventory.write(nbt, registries); } @Nullable @@ -110,15 +98,15 @@ public ClientboundBlockEntityDataPacket getUpdatePacket() { } @Override - public CompoundTag getUpdateTag() { - CompoundTag tag = super.getUpdateTag(); - return NBTUtilForestry.writeStreamableToNbt(this, tag); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag nbt = super.getUpdateTag(registries); + return NBTUtilForestry.writeStreamableToNbt(this, nbt); } @Override - public void handleUpdateTag(CompoundTag tag) { - super.handleUpdateTag(tag); - NBTUtilForestry.readStreamableFromNbt(this, tag); + public void handleUpdateTag(CompoundTag nbt, HolderLookup.Provider registries) { + super.handleUpdateTag(nbt, registries); + NBTUtilForestry.readStreamableFromNbt(this, nbt); } /* INetworkedEntity */ @@ -128,23 +116,17 @@ protected final void sendNetworkUpdate() { /* IStreamable */ @Override - public void writeData(FriendlyByteBuf data) { + public void writeData(RegistryFriendlyByteBuf buffer) { } @Override - public void readData(FriendlyByteBuf data) { + public void readData(RegistryFriendlyByteBuf buffer) { } // serverside only, called when the block is destroyed and its inventory is spilled into the world public void onDropContents(ServerLevel level) { } - @Nullable - @Override - public Level getWorldObj() { - return this.level; - } - // / REDSTONE INFO protected boolean isRedstoneActivated() { return this.level.getBestNeighborSignal(getBlockPos()) > 0; @@ -171,7 +153,6 @@ public IInventoryAdapter getInternalInventory() { } protected final void setInternalInventory(IInventoryAdapter inv) { - Preconditions.checkNotNull(inv); this.inventory = inv; } @@ -257,25 +238,12 @@ public final boolean canTakeItemThroughFace(int slotIndex, ItemStack itemStack, return getInternalInventory().canTakeItemThroughFace(slotIndex, itemStack, side); } - @Override - public final BlockPos getCoordinates() { - return getBlockPos(); - } - @Override public void clearContent() { } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.ITEM_HANDLER) { - if (facing != null) { - return LazyOptional.of(() -> new SidedInvWrapper(getInternalInventory(), facing)).cast(); - } else { - return LazyOptional.of(() -> new InvWrapper(getInternalInventory())).cast(); - } - } - return super.getCapability(capability, facing); + public IItemHandler getInventory(@Nullable Direction facing) { + return facing == null ? new InvWrapper(getInternalInventory()) : new SidedInvWrapper(getInternalInventory(), facing); } @Override diff --git a/src/main/java/forestry/core/tiles/TileMill.java b/src/main/java/forestry/core/tiles/TileMill.java index 3965c3e202..2421a1362a 100644 --- a/src/main/java/forestry/core/tiles/TileMill.java +++ b/src/main/java/forestry/core/tiles/TileMill.java @@ -1,17 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -38,19 +28,19 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - data.writeInt(this.charge); - data.writeFloat(this.speed); - data.writeInt(this.stage); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + buffer.writeInt(this.charge); + buffer.writeFloat(this.speed); + buffer.writeInt(this.stage); } @Override - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.charge = data.readInt(); - this.speed = data.readFloat(); - this.stage = data.readInt(); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.charge = buffer.readInt(); + this.speed = buffer.readFloat(); + this.stage = buffer.readInt(); } private void update(Level level, BlockPos pos, boolean isSimulating) { diff --git a/src/main/java/forestry/core/tiles/TileNaturalistChest.java b/src/main/java/forestry/core/tiles/TileNaturalistChest.java index adf24b4f15..38d9291f1b 100644 --- a/src/main/java/forestry/core/tiles/TileNaturalistChest.java +++ b/src/main/java/forestry/core/tiles/TileNaturalistChest.java @@ -1,27 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.genetics.ISpeciesType; -import forestry.core.gui.ContainerNaturalistInventory; +import forestry.core.gui.NaturalistInventoryMenu; import forestry.core.gui.IPagedInventory; import forestry.core.inventory.InventoryNaturalistChest; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; -import net.minecraft.world.InteractionHand; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -31,7 +20,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.network.NetworkHooks; public abstract class TileNaturalistChest extends TileBase implements IPagedInventory { private static final float lidAngleVariationPerTick = 0.1F; @@ -89,34 +77,35 @@ private void playLidSound(Level level, SoundEvent sound) { @Override public void flipPage(ServerPlayer player, short page) { - NetworkHooks.openScreen(player, new PagedMenuProvider(page), p -> { + player.openMenu(new PagedMenuProvider(page), p -> { p.writeBlockPos(this.worldPosition); p.writeVarInt(page); }); } @Override - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { - NetworkHooks.openScreen(player, new PagedMenuProvider(0), p -> { + public boolean interactNoItem(Level level, Player player, BlockPos pos) { + player.openMenu(new PagedMenuProvider(0), p -> { p.writeBlockPos(this.worldPosition); p.writeVarInt(0); }); + return false; } /* IStreamable */ @Override - public void writeData(FriendlyByteBuf data) { - data.writeInt(this.numPlayersUsing); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeInt(this.numPlayersUsing); } @Override - public void readData(FriendlyByteBuf data) { - this.numPlayersUsing = data.readInt(); + public void readData(RegistryFriendlyByteBuf buffer) { + this.numPlayersUsing = buffer.readInt(); } @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerNaturalistInventory(windowId, inv, this, 5); + return new NaturalistInventoryMenu(windowId, inv, this, 5); } public ISpeciesType getSpeciesType() { @@ -138,7 +127,7 @@ public Component getDisplayName() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory playerInv, Player player) { - return new ContainerNaturalistInventory(windowId, playerInv, TileNaturalistChest.this, this.page); + return new NaturalistInventoryMenu(windowId, playerInv, TileNaturalistChest.this, this.page); } } } diff --git a/src/main/java/forestry/core/tiles/TilePowered.java b/src/main/java/forestry/core/tiles/TilePowered.java index abfb6519c7..9710312e59 100644 --- a/src/main/java/forestry/core/tiles/TilePowered.java +++ b/src/main/java/forestry/core/tiles/TilePowered.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import forestry.api.core.ForestryError; @@ -19,31 +9,22 @@ import forestry.energy.EnergyTransferMode; import forestry.energy.ForestryEnergyStorage; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import javax.annotation.Nullable; - -// todo rename "ticks" to "steps" in 1.21 to clarify they're different than actual ticks public abstract class TilePowered extends TileBase implements IRenderableTile, ISpeedUpgradable, IStreamableGui, IPowerHandler { - private static final int WORK_TICK_INTERVAL = 5; // one Forestry work tick happens every WORK_TICK_INTERVAL game ticks + private static final int STEP_INTERVAL = 5; private final ForestryEnergyStorage energyStorage; - private final LazyOptional energyCap; // The amount of "ticks" into the current work cycle. Between 0 and ticksPerWorkCycle - private int workCounter; + private int stepCounter; // The number of "ticks" a work cycle takes to complete. In reality, a "tick" here is 5 real ticks - private int ticksPerWorkCycle; + private int stepsPerWorkCycle; // The amount of energy consumed over the course of an entire work cycle private int energyPerWorkCycle; @@ -57,58 +38,53 @@ protected TilePowered(BlockEntityType type, BlockPos pos, BlockState state, i super(type, pos, state); this.energyStorage = new ForestryEnergyStorage(maxTransfer, capacity, EnergyTransferMode.RECEIVE); - this.energyCap = LazyOptional.of(() -> this.energyStorage); - this.ticksPerWorkCycle = 4; + this.stepsPerWorkCycle = 4; } public ForestryEnergyStorage getEnergyManager() { return this.energyStorage; } - public int getWorkCounter() { - return this.workCounter; + public int getStepCounter() { + return this.stepCounter; } - // A "tick" is actually 5 ticks. Yay! - public void setTicksPerWorkCycle(int ticksPerWorkCycle) { - this.ticksPerWorkCycle = ticksPerWorkCycle; - this.workCounter = 0; + // A step is actually 5 ticks. Yay! + public void setStepsPerWorkCycle(int stepsPerWorkCycle) { + this.stepsPerWorkCycle = stepsPerWorkCycle; + this.stepCounter = 0; } - public int getTicksPerWorkCycle() { + public int getStepsPerWorkCycle() { if (this.level.isClientSide) { - return this.ticksPerWorkCycle; + return this.stepsPerWorkCycle; } - return Math.round(this.ticksPerWorkCycle / this.speedMultiplier); + return Math.round(this.stepsPerWorkCycle / this.speedMultiplier); } // RF/t is energyPerWorkCycle / ticksPerWorkCycle public void setEnergyPerWorkCycle(int energyPerWorkCycle) { - this.energyPerWorkCycle = EnergyHelper.scaleForDifficulty(energyPerWorkCycle); + this.energyPerWorkCycle = energyPerWorkCycle; } public int getEnergyPerWorkCycle() { return Math.round(this.energyPerWorkCycle * this.powerMultiplier); } - /* STATE INFORMATION */ - public boolean hasResourcesMin(float percentage) { - return false; - } - - public boolean hasFuelMin(float percentage) { - return false; - } - - // Called every tick to determine whether the tile can start working or continue working + /** + * Called every step to determine whether the tile can start working or continue working + * + * @return Whether this tile can start working or continue working + */ public abstract boolean hasWork(); @Override public void serverTick(Level level, BlockPos pos, BlockState state) { super.serverTick(level, pos, state); - if (!updateOnInterval(WORK_TICK_INTERVAL)) { + // A step is 5 ticks + if (!updateOnInterval(STEP_INTERVAL)) { return; } @@ -124,76 +100,84 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { return; } - int ticksPerWorkCycle = getTicksPerWorkCycle(); + int stepsPerWorkCycle = getStepsPerWorkCycle(); - if (this.workCounter < ticksPerWorkCycle) { + if (this.stepCounter < stepsPerWorkCycle) { int energyPerWorkCycle = getEnergyPerWorkCycle(); - boolean consumedEnergy = EnergyHelper.consumeEnergyToDoWork(this.energyStorage, ticksPerWorkCycle, energyPerWorkCycle); + boolean consumedEnergy = EnergyHelper.consumeEnergyToDoWork(this.energyStorage, stepsPerWorkCycle, energyPerWorkCycle); if (consumedEnergy) { errorLogic.setCondition(false, ForestryError.NO_POWER); - this.workCounter++; - this.noPowerTime = 0; + this.stepCounter++; + this.noPowerTime = 0; } else { - this.noPowerTime++; + this.noPowerTime++; if (this.noPowerTime > 4) { errorLogic.setCondition(true, ForestryError.NO_POWER); } } } - if (this.workCounter >= ticksPerWorkCycle) { + if (this.stepCounter >= stepsPerWorkCycle) { if (workCycle()) { - this.workCounter = 0; + this.stepCounter = 0; } } } - // Called when the tile reaches the end of a work cycle. Consume inputs and produce outputs here. + /** + * Called on the server when the tile reaches the end of a work cycle. Consume inputs and produce outputs here. + * + * @return Whether the work cycle completed successfully. If {@code false}, the machine will call this again every step until it returns {@code true}. + */ protected abstract boolean workCycle(); - // Returns the width for a progress bar. pixels is the full width of the progress bar. + /** + * Returns the width for a progress bar. + * + * @param pixels the full width of the progress bar. + * @return The number of pixels of the progress bar to draw. + */ public int getProgressScaled(int pixels) { - int ticksPerWorkCycle = getTicksPerWorkCycle(); + int ticksPerWorkCycle = getStepsPerWorkCycle(); if (ticksPerWorkCycle == 0) { return 0; } - return this.workCounter * pixels / ticksPerWorkCycle; + return this.stepCounter * pixels / ticksPerWorkCycle; } @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); - this.energyStorage.write(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.energyStorage.write(nbt, registries); } @Override - public void load(CompoundTag nbt) { - super.load(nbt); - this.energyStorage.read(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.energyStorage.read(nbt, registries); } @Override - public void writeGuiData(FriendlyByteBuf data) { - this.energyStorage.writeData(data); - data.writeVarInt(this.workCounter); - data.writeVarInt(getTicksPerWorkCycle()); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + this.energyStorage.writeData(buffer); + buffer.writeVarInt(this.stepCounter); + buffer.writeVarInt(getStepsPerWorkCycle()); } @Override - @OnlyIn(Dist.CLIENT) - public void readGuiData(FriendlyByteBuf data) { - this.energyStorage.readData(data); - this.workCounter = data.readVarInt(); - this.ticksPerWorkCycle = data.readVarInt(); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.energyStorage.readData(buffer); + this.stepCounter = buffer.readVarInt(); + this.stepsPerWorkCycle = buffer.readVarInt(); } /* ISpeedUpgradable */ @Override - public void applySpeedUpgrade(double speedChange, double powerChange) { - this.speedMultiplier += speedChange; - this.powerMultiplier += powerChange; - this.workCounter = 0; + public void applySpeedUpgrade(float speedChange, float powerChange) { + this.speedMultiplier += speedChange; + this.powerMultiplier += powerChange; + this.stepCounter = 0; } /* IRenderableTile */ @@ -206,12 +190,4 @@ public TankRenderInfo getResourceTankInfo() { public TankRenderInfo getProductTankInfo() { return TankRenderInfo.EMPTY; } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (!this.remove && capability == ForgeCapabilities.ENERGY) { - return this.energyCap.cast(); - } - return super.getCapability(capability, facing); - } } diff --git a/src/main/java/forestry/core/tiles/TileUtil.java b/src/main/java/forestry/core/tiles/TileUtil.java index b4bb64fb71..0467ab3a8b 100644 --- a/src/main/java/forestry/core/tiles/TileUtil.java +++ b/src/main/java/forestry/core/tiles/TileUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.tiles; import net.minecraft.core.BlockPos; @@ -19,12 +9,10 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.InvWrapper; -import net.minecraftforge.items.wrapper.SidedInvWrapper; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.wrapper.InvWrapper; +import net.neoforged.neoforge.items.wrapper.SidedInvWrapper; import javax.annotation.Nullable; import java.util.function.Consumer; @@ -32,10 +20,10 @@ public abstract class TileUtil { public static boolean isUsableByPlayer(Player player, BlockEntity tile) { BlockPos pos = tile.getBlockPos(); - Level world = tile.getLevel(); + Level level = tile.getLevel(); return !tile.isRemoved() && - getTile(world, pos) == tile && + getTile(level, pos) == tile && player.distanceToSqr(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D) <= 64.0D; } @@ -45,7 +33,7 @@ public static boolean isUsableByPlayer(Player player, BlockEntity tile) { */ @Nullable public static BlockEntity getTile(BlockGetter level, BlockPos pos) { - return level.getExistingBlockEntity(pos); + return level.getBlockEntity(pos); } /** @@ -53,8 +41,8 @@ public static BlockEntity getTile(BlockGetter level, BlockPos pos) { * Avoids creating new tile entities when using a ChunkCache (off the main thread). */ @Nullable - public static T getTile(BlockGetter world, BlockPos pos, Class tileClass) { - BlockEntity tileEntity = getTile(world, pos); + public static T getTile(BlockGetter level, BlockPos pos, Class tileClass) { + BlockEntity tileEntity = getTile(level, pos); if (tileClass.isInstance(tileEntity)) { return tileClass.cast(tileEntity); } else { @@ -63,16 +51,16 @@ public static T getTile(BlockGetter world, BlockPos pos, Class tileClass) } @Nullable - public static T getTile(BlockEntity tileEntity, Class tileClass) { - if (tileClass.isInstance(tileEntity)) { - return tileClass.cast(tileEntity); + public static T getTile(BlockEntity tile, Class tileClass) { + if (tileClass.isInstance(tile)) { + return tileClass.cast(tile); } else { return null; } } - public static void actOnTile(LevelReader world, BlockPos pos, Class tileClass, Consumer tileAction) { - T tile = getTile(world, pos, tileClass); + public static void actOnTile(LevelReader level, BlockPos pos, Class tileClass, Consumer tileAction) { + T tile = getTile(level, pos, tileClass); if (tile != null) { tileAction.accept(tile); } @@ -84,9 +72,9 @@ public static IItemHandler getInventoryFromTile(@Nullable BlockEntity tile, @Nul return null; } - LazyOptional itemCap = tile.getCapability(ForgeCapabilities.ITEM_HANDLER, side); - if (itemCap.isPresent()) { - return itemCap.orElse(null); + IItemHandler itemCap = tile.getLevel().getCapability(Capabilities.ItemHandler.BLOCK, tile.getBlockPos(), side); + if (itemCap != null) { + return itemCap; } if (tile instanceof WorldlyContainer worldly) { @@ -99,12 +87,4 @@ public static IItemHandler getInventoryFromTile(@Nullable BlockEntity tile, @Nul return null; } - - public static LazyOptional getInterface(Level world, BlockPos pos, Capability capability, @Nullable Direction facing) { - BlockEntity tileEntity = world.getBlockEntity(pos); - if (tileEntity == null) { - return LazyOptional.empty(); - } - return tileEntity.getCapability(capability, facing); - } } diff --git a/src/main/java/forestry/core/tiles/package-info.java b/src/main/java/forestry/core/tiles/package-info.java index d2eaae727a..8e3a65b8d4 100644 --- a/src/main/java/forestry/core/tiles/package-info.java +++ b/src/main/java/forestry/core/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.tiles; diff --git a/src/main/java/forestry/core/utils/BlockUtil.java b/src/main/java/forestry/core/utils/BlockUtil.java index c6ebd80e2a..b1f3600e8c 100755 --- a/src/main/java/forestry/core/utils/BlockUtil.java +++ b/src/main/java/forestry/core/utils/BlockUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import forestry.core.tiles.TileUtil; @@ -16,15 +6,11 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundSource; import net.minecraft.tags.BlockTags; -import net.minecraft.tags.TagKey; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.LevelEvent; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; @@ -43,96 +29,61 @@ public abstract class BlockUtil { public static final BlockBehaviour.StateArgumentPredicate> IS_PARROT_OR_OCELOT = (a, b, c, entityType) -> entityType == EntityType.OCELOT || entityType == EntityType.PARROT; public static List getBlockDrops(LevelAccessor level, BlockPos pos) { - //TODO - this call needs sorting return Block.getDrops(level.getBlockState(pos), (ServerLevel) level, pos, TileUtil.getTile(level, pos)); - - } - - public static boolean tryPlantCocoaPod(LevelAccessor world, BlockPos pos) { - Direction facing = getValidPodFacing(world, pos, BlockTags.JUNGLE_LOGS); - if (facing == null) { - return false; - } - - BlockState state = Blocks.COCOA.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, facing); - world.setBlock(pos, state, 18); - return true; - } - - @Nullable - public static Direction getValidPodFacing(LevelAccessor world, BlockPos pos, TagKey logTag) { - for (Direction facing : Direction.Plane.HORIZONTAL) { - if (isValidPodLocation(world, pos, facing, logTag)) { - return facing; - } - } - return null; } - public static boolean isValidPodLocation(LevelReader world, BlockPos pos, Direction direction, TagKey logTag) { - pos = pos.relative(direction); - if (!world.hasChunkAt(pos)) { - return false; - } - BlockState state = world.getBlockState(pos); - return state.is(logTag); + public static boolean isBreakableBlock(Level level, BlockPos pos) { + BlockState blockState = level.getBlockState(pos); + return isBreakableBlock(blockState, level, pos); } - public static boolean isBreakableBlock(Level world, BlockPos pos) { - BlockState blockState = world.getBlockState(pos); - return isBreakableBlock(blockState, world, pos); + public static boolean isBreakableBlock(BlockState state, Level level, BlockPos pos) { + return state.getDestroySpeed(level, pos) >= 0.0F; } - public static boolean isBreakableBlock(BlockState blockState, Level world, BlockPos pos) { - return blockState.getDestroySpeed(world, pos) >= 0.0F; + public static boolean isReplaceableBlock(Level level, BlockPos pos) { + return level.getBlockState(pos).canBeReplaced(); } - public static boolean isReplaceableBlock(BlockState blockState, Level world, BlockPos pos) { - Block block = blockState.getBlock(); - return world.getBlockState(pos).canBeReplaced();//!(block instanceof BlockStaticLiquid); - } - - /* CHUNKS */ - - public static boolean canReplace(BlockState blockState, LevelAccessor world, BlockPos pos) { - return world.getBlockState(pos).canBeReplaced() && !blockState.liquid(); + public static boolean canReplace(BlockState state, LevelAccessor level, BlockPos pos) { + return level.getBlockState(pos).canBeReplaced() && !state.liquid(); } - public static boolean canPlaceTree(BlockState state, LevelAccessor world, BlockPos pos) { + public static boolean canPlaceTree(BlockState state, LevelAccessor level, BlockPos pos) { BlockPos downPos = pos.below(); - BlockState belowState = world.getBlockState(downPos); - return !(world.getBlockState(pos).canBeReplaced() && state.liquid()) && + BlockState belowState = level.getBlockState(downPos); + return !(level.getBlockState(pos).canBeReplaced() && state.liquid()) && !belowState.is(BlockTags.LEAVES) && !belowState.is(BlockTags.LOGS); } - public static BlockPos getNextReplaceableUpPos(Level world, BlockPos pos) { - BlockPos topPos = world.getHeightmapPos(Heightmap.Types.WORLD_SURFACE_WG, pos); + public static BlockPos getNextReplaceableUpPos(Level level, BlockPos pos) { + BlockPos topPos = level.getHeightmapPos(Heightmap.Types.WORLD_SURFACE_WG, pos); final BlockPos.MutableBlockPos newPos = new BlockPos.MutableBlockPos(); - BlockState blockState = world.getBlockState(newPos.set(pos)); + BlockState blockState = level.getBlockState(newPos.set(pos)); - while (!BlockUtil.canReplace(blockState, world, newPos)) { + while (!BlockUtil.canReplace(blockState, level, newPos)) { newPos.move(Direction.UP); if (newPos.getY() > topPos.getY()) { return null; } - blockState = world.getBlockState(newPos); + blockState = level.getBlockState(newPos); } return newPos.below(); } @Nullable - public static BlockPos getNextSolidDownPos(Level world, BlockPos pos) { + public static BlockPos getNextSolidDownPos(Level level, BlockPos pos) { final BlockPos.MutableBlockPos newPos = new BlockPos.MutableBlockPos(); - BlockState blockState = world.getBlockState(newPos.set(pos)); - while (canReplace(blockState, world, newPos)) { + BlockState blockState = level.getBlockState(newPos.set(pos)); + while (canReplace(blockState, level, newPos)) { newPos.move(Direction.DOWN); if (newPos.getY() <= 0) { return null; } - blockState = world.getBlockState(newPos); + blockState = level.getBlockState(newPos); } return newPos.above(); } diff --git a/src/main/java/forestry/core/utils/CodecUtil.java b/src/main/java/forestry/core/utils/CodecUtil.java new file mode 100644 index 0000000000..143c2d55ba --- /dev/null +++ b/src/main/java/forestry/core/utils/CodecUtil.java @@ -0,0 +1,66 @@ +package forestry.core.utils; + +import com.mojang.serialization.*; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeSerializer; + +import java.util.stream.Stream; + +public class CodecUtil { + public static final Codec CRAFTING_RECIPE_CODEC = new CraftingRecipeCodec().codec(); + public static final StreamCodec CRAFTING_RECIPE_STREAM_CODEC = StreamCodec.of(CodecUtil::encodeCraftingRecipe, CodecUtil::decodeCraftingRecipe); + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void encodeCraftingRecipe(RegistryFriendlyByteBuf buffer, CraftingRecipe recipe) { + RecipeSerializer serializer = recipe.getSerializer(); + buffer.writeBoolean(serializer == RecipeSerializer.SHAPELESS_RECIPE); + serializer.streamCodec().encode(buffer, recipe); + } + + private static CraftingRecipe decodeCraftingRecipe(RegistryFriendlyByteBuf buffer) { + return (buffer.readBoolean() ? RecipeSerializer.SHAPELESS_RECIPE : RecipeSerializer.SHAPED_RECIPE).streamCodec().decode(buffer); + } + + // why did i write this + private static class CraftingRecipeCodec extends MapCodec { + // using static references is safe maybe probably + private static final MapCodec SHAPED = RecipeSerializer.SHAPED_RECIPE.codec(); + private static final MapCodec SHAPELESS = RecipeSerializer.SHAPELESS_RECIPE.codec(); + + @Override + public Stream keys(DynamicOps ops) { + return Stream.of(ops.createString("shapeless")); + } + + @SuppressWarnings("unchecked") + @Override + public DataResult decode(DynamicOps ops, MapLike input) { + T isShapelessPart = input.get("shapeless"); + + if (isShapelessPart == null) { + // default to shaped recipe + return (DataResult) SHAPED.decode(ops, input); + } + + return (DataResult) Codec.BOOL + .decode(ops, isShapelessPart) + .flatMap(isShapeless -> (isShapeless.getFirst() ? SHAPELESS : SHAPED).decode(ops, input)); + } + + @SuppressWarnings("unchecked") + @Override + public RecordBuilder encode(CraftingRecipe input, DynamicOps ops, RecordBuilder prefix) { + if (input.getSerializer() == RecipeSerializer.SHAPELESS_RECIPE) { + return ((MapCodec) SHAPELESS).encode(input, ops, prefix) + .add("shapeless", Codec.BOOL.encodeStart(ops, true)); + } else if (input.getSerializer() == RecipeSerializer.SHAPED_RECIPE) { + // no need to serialize the default value of "shapeless": "false" + return ((MapCodec) SHAPED).encode(input, ops, prefix); + } + // not gonna bother with other types of recipes for now. if someone wants it, open an issue. + return prefix.withErrorsFrom(DataResult.error(() -> "Error: Recipe was not of serializer minecraft:crafting_shaped or minecraft:crafting_shapeless:" + input)); + } + } +} diff --git a/src/main/java/forestry/core/utils/ColourUtil.java b/src/main/java/forestry/core/utils/ColourUtil.java index 7fc902fc63..6f1226782e 100644 --- a/src/main/java/forestry/core/utils/ColourUtil.java +++ b/src/main/java/forestry/core/utils/ColourUtil.java @@ -1,20 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; public class ColourUtil { - - private ColourUtil() { - } - public static int addRGBComponents(int colour, int r, int g, int b) { r = getRed(colour) + r; g = getGreen(colour) + g; diff --git a/src/main/java/forestry/core/utils/DayMonth.java b/src/main/java/forestry/core/utils/DayMonth.java index 7c0f06b571..7e1ad0e214 100644 --- a/src/main/java/forestry/core/utils/DayMonth.java +++ b/src/main/java/forestry/core/utils/DayMonth.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import net.minecraft.network.chat.Component; diff --git a/src/main/java/forestry/core/utils/EntityUtil.java b/src/main/java/forestry/core/utils/EntityUtil.java index 8072712211..eddfbb255e 100644 --- a/src/main/java/forestry/core/utils/EntityUtil.java +++ b/src/main/java/forestry/core/utils/EntityUtil.java @@ -1,45 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.Mth; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.level.Level; +import net.neoforged.neoforge.event.EventHooks; import javax.annotation.Nullable; public abstract class EntityUtil { @Nullable - public static T spawnEntity(Level world, EntityType type, double x, double y, double z) { - T entityLiving = type.create(world); + public static T spawnEntity(Level level, EntityType type, double x, double y, double z) { + T entityLiving = type.create(level); if (entityLiving == null) { return null; } - return spawnEntity(world, entityLiving, x, y, z); + return spawnEntity(level, entityLiving, x, y, z); } - public static T spawnEntity(Level world, T living, double x, double y, double z) { - living.moveTo(x, y, z, Mth.wrapDegrees(world.random.nextFloat() * 360.0f), 0.0f); + public static T spawnEntity(Level level, T living, double x, double y, double z) { + living.moveTo(x, y, z, level.random.nextFloat() * 360.0f, 0.0f); living.yHeadRot = living.getYRot(); living.yBodyRot = living.getYRot(); - DifficultyInstance diff = world.getCurrentDifficultyAt(BlockPos.containing(x, y, z)); - //TODO - check SpawnReason - living.finalizeSpawn((ServerLevel) world, diff, MobSpawnType.MOB_SUMMONED, null, null); - world.addFreshEntity(living); - //TODO - right sound? + DifficultyInstance diff = level.getCurrentDifficultyAt(BlockPos.containing(x, y, z)); + EventHooks.finalizeMobSpawn(living, (ServerLevel) level, diff, MobSpawnType.MOB_SUMMONED, null); + level.addFreshEntity(living); living.playAmbientSound(); return living; } diff --git a/src/main/java/forestry/core/utils/GeneticsUtil.java b/src/main/java/forestry/core/utils/GeneticsUtil.java index 0b5bd14217..bc9e8bfe23 100644 --- a/src/main/java/forestry/core/utils/GeneticsUtil.java +++ b/src/main/java/forestry/core/utils/GeneticsUtil.java @@ -1,74 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import forestry.api.ForestryCapabilities; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.arboriculture.ITreeSpecies; -import forestry.api.core.IArmorNaturalist; +import forestry.api.core.ISpectacleVision; import forestry.api.genetics.*; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.lepidopterology.IButterflyNursery; import forestry.api.lepidopterology.genetics.IButterfly; -import forestry.api.lepidopterology.genetics.IButterflySpecies; -import forestry.arboriculture.capabilities.ArmorNaturalist; import forestry.compat.curios.CuriosCompat; import forestry.core.genetics.ItemGE; import forestry.core.tiles.TileUtil; import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.common.util.LazyOptional; import java.util.*; public class GeneticsUtil { - private static String getKeyPrefix(ISpecies allele) { - if (allele instanceof IBeeSpecies) { - return "for.bees"; - } else if (allele instanceof ITreeSpecies) { - return "for.trees"; - } else if (allele instanceof IButterflySpecies) { - return "for.butterflies"; - } - throw new IllegalStateException(); - } - - public static Component getAlyzerName(ILifeStage type, ISpecies allele) { - String customKey = getKeyPrefix(allele) + - ".custom.alyzer." + - type.getSerializedName() + - '.' + - allele.getTranslationKey(); - return Translator.tryTranslate(customKey, allele::getDisplayName); - } - - public static Component getItemName(ILifeStage type, ISpecies species) { - String prefix = getKeyPrefix(species); - String customKey = prefix + - ".custom." + - type.getSerializedName() + - '.' + - species.getTranslationKey(); - return Translator.tryTranslate(customKey, () -> { - Component speciesName = species.getDisplayName(); - Component typeName = Component.translatable(prefix + ".grammar." + type.getSerializedName() + ".type"); - return Component.translatable(prefix + ".grammar." + type.getSerializedName(), speciesName, typeName); - }); - } - public static boolean hasNaturalistEye(Player player) { ItemStack armorItemStack = player.getItemBySlot(EquipmentSlot.HEAD); if (armorItemStack.isEmpty()) { @@ -83,15 +33,9 @@ public static boolean hasNaturalistEye(Player player) { } public static boolean hasNaturalistEye(Player player, ItemStack armorItemStack) { - final IArmorNaturalist armorNaturalist; - LazyOptional armorCap = armorItemStack.getCapability(ForestryCapabilities.ARMOR_NATURALIST); - if (armorCap.isPresent()) { - armorNaturalist = armorCap.orElse(ArmorNaturalist.INSTANCE); - } else { - return false; - } + final ISpectacleVision armorNaturalist = armorItemStack.getCapability(ForestryCapabilities.SPECTACLE_VISION); - return armorNaturalist.canSeePollination(player, armorItemStack, true); + return armorNaturalist != null && armorNaturalist.canSeePollination(player, armorItemStack, true); } public static boolean canNurse(IButterfly butterfly, Level world, final BlockPos pos) { diff --git a/src/main/java/forestry/core/utils/InventoryUtil.java b/src/main/java/forestry/core/utils/InventoryUtil.java index 7b7956e3e0..fbdcbaaf94 100644 --- a/src/main/java/forestry/core/utils/InventoryUtil.java +++ b/src/main/java/forestry/core/utils/InventoryUtil.java @@ -1,18 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import forestry.core.circuits.ISocketable; import forestry.core.inventory.ItemHandlerInventoryManipulator; -import forestry.core.inventory.StandardStackFilters; import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; @@ -23,8 +12,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.common.CommonHooks; +import net.neoforged.neoforge.items.IItemHandler; import javax.annotation.Nullable; import java.util.List; @@ -39,7 +28,7 @@ public abstract class InventoryUtil { */ public static boolean moveItemStack(IItemHandler source, IItemHandler dest) { ItemHandlerInventoryManipulator manipulator = new ItemHandlerInventoryManipulator(source); - return manipulator.transferOneStack(dest, StandardStackFilters.ALL); + return manipulator.transferOneStack(dest, stack -> true); } /** @@ -299,7 +288,7 @@ public static int addStack(Container inventory, ItemStack stack, int startSlot, if (!inventoryStack.isStackable()) { continue; } - if (!ItemStack.isSameItemSameTags(inventoryStack, stack)) { + if (!ItemStack.isSameItemSameComponents(inventoryStack, stack)) { continue; } @@ -367,7 +356,7 @@ public static boolean stowInInventory(ItemStack stack, Container inventory, bool } // Not same type - if (!ItemStack.isSameItemSameTags(inventoryStack, stack)) { + if (!ItemStack.isSameItemSameComponents(inventoryStack, stack)) { continue; } @@ -399,7 +388,7 @@ public static void stowContainerItem(ItemStack itemstack, Container stowing, int return; } - ItemStack container = ForgeHooks.getCraftingRemainingItem(itemstack); + ItemStack container = CommonHooks.getCraftingRemainingItem(itemstack); if (!container.isEmpty()) { if (!tryAddStack(stowing, container, slotIndex, 1, true)) { if (!tryAddStack(stowing, container, true) && player != null) { @@ -450,7 +439,7 @@ public static void readFromNBT(Container inventory, String name, CompoundTag com for (int j = 0; j < nbttaglist.size(); ++j) { CompoundTag compoundNBT2 = nbttaglist.getCompound(j); int index = compoundNBT2.getInt("Slot"); - inventory.setItem(index, ItemStack.of(compoundNBT2)); + inventory.setItem(index, ItemStack.parseOptional(registries, compoundNBT2)); } } diff --git a/src/main/java/forestry/core/utils/ItemStackUtil.java b/src/main/java/forestry/core/utils/ItemStackUtil.java index 471398f58e..f494326d0f 100755 --- a/src/main/java/forestry/core/utils/ItemStackUtil.java +++ b/src/main/java/forestry/core/utils/ItemStackUtil.java @@ -28,10 +28,7 @@ public int hashCode(ItemStack o) { int result = 1; result = 31 * result + o.getCount(); result = 31 * result + o.getItem().hashCode(); - if (o.hasTag()) { - result = 31 * result + o.getTag().hashCode(); - } - + result = 31 * result + o.getComponents().hashCode(); return result; } diff --git a/src/main/java/forestry/core/utils/ItemTooltipUtil.java b/src/main/java/forestry/core/utils/ItemTooltipUtil.java index df366062c7..222919aae6 100755 --- a/src/main/java/forestry/core/utils/ItemTooltipUtil.java +++ b/src/main/java/forestry/core/utils/ItemTooltipUtil.java @@ -2,58 +2,37 @@ import forestry.api.core.tooltips.ToolTip; import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.List; public class ItemTooltipUtil { - @OnlyIn(Dist.CLIENT) - public static void addInformation(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag flag) { - String unlocalizedName = stack.getDescriptionId(); - String tooltipKey = unlocalizedName + ".tooltip"; + // todo this should probably be removed + public static void addInformation(ItemStack stack, List tooltip) { + String translationKey = stack.getDescriptionId(); + String tooltipKey = translationKey + ".tooltip"; if (Translator.canTranslateToLocal(tooltipKey)) { tooltip.add(Component.translatable(tooltipKey).withStyle(ChatFormatting.GRAY)); - /*Minecraft minecraft = Minecraft.getInstance(); - List tooltipInfoWrapped = minecraft.fontRenderer.split(tooltipInfo, 150); - tooltipInfoWrapped.forEach(s -> { - if(s instanceof IFormattableTextComponent) { - s = ((IFormattableTextComponent) s).mergeStyle(TextFormatting.GRAY); - } - tooltip.add((ITextComponent) s); - CharacterManager - });*/ } } - public static void addShiftInformation(ItemStack stack, @Nullable BlockGetter world, List tooltip, TooltipFlag flag) { + public static void addShiftInformation(List tooltip) { tooltip.add(Component.translatable("for.gui.tooltip.tmi", "< %s >").withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY)); } @Nullable - @OnlyIn(Dist.CLIENT) - public static ToolTip getInformation(ItemStack stack) { - Minecraft minecraft = Minecraft.getInstance(); - boolean advancedTooltips = minecraft.options.advancedItemTooltips; - return getInformation(stack, minecraft.player, advancedTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL); - } - - @Nullable - @OnlyIn(Dist.CLIENT) - public static ToolTip getInformation(ItemStack stack, Player player, TooltipFlag flag) { + public static ToolTip getInformation(ItemStack stack, @Nullable Player player, TooltipFlag flag) { if (stack.isEmpty()) { return null; } ToolTip toolTip = new ToolTip(); - toolTip.addAll(stack.getTooltipLines(player, flag)); + Item.TooltipContext context = Item.TooltipContext.EMPTY; + toolTip.addAll(stack.getTooltipLines(context, player, flag)); return toolTip; } } diff --git a/src/main/java/forestry/core/utils/NBTUtilForestry.java b/src/main/java/forestry/core/utils/NBTUtilForestry.java index 402ea15be0..221a0dbed9 100644 --- a/src/main/java/forestry/core/utils/NBTUtilForestry.java +++ b/src/main/java/forestry/core/utils/NBTUtilForestry.java @@ -1,27 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import forestry.core.network.IStreamable; import io.netty.buffer.Unpooled; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; -/** - * @author CovertJaguar - */ +// todo wtf remove ts public abstract class NBTUtilForestry { public static CompoundTag writeStreamableToNbt(IStreamable streamable, CompoundTag nbt) { - FriendlyByteBuf data = new FriendlyByteBuf(Unpooled.buffer()); + FriendlyByteBuf data = new RegistryFriendlyByteBuf(Unpooled.buffer()); streamable.writeData(data); byte[] bytes = new byte[data.readableBytes()]; diff --git a/src/main/java/forestry/core/utils/NetworkUtil.java b/src/main/java/forestry/core/utils/NetworkUtil.java index a9f02bcca8..8b5cac32a6 100644 --- a/src/main/java/forestry/core/utils/NetworkUtil.java +++ b/src/main/java/forestry/core/utils/NetworkUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import com.google.common.base.Preconditions; @@ -19,43 +9,33 @@ import forestry.api.modules.IForestryPacketClient; import forestry.api.modules.IForestryPacketServer; import forestry.core.network.IStreamable; -import forestry.core.network.NetworkHandler; +import forestry.core.network.packets.PacketGuiSelectRequest; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.core.NonNullList; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; +import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.PacketDistributor; -import net.minecraftforge.server.ServerLifecycleHooks; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.connection.ConnectionType; import javax.annotation.Nullable; +import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; public class NetworkUtil { - public static void sendNetworkPacket(IForestryPacketClient packet, BlockPos pos, Level level) { - NetworkHandler.CHANNEL.send(PacketDistributor.TRACKING_CHUNK.with(() -> level.getChunkAt(pos)), packet); - } - - public static void sendToPlayer(IForestryPacketClient packet, ServerPlayer player) { - NetworkHandler.CHANNEL.sendTo(packet, player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); - } - - public static void sendToAllPlayers(IForestryPacketClient packet) { - if (ServerLifecycleHooks.getCurrentServer() != null) { - NetworkHandler.CHANNEL.send(PacketDistributor.ALL.noArg(), packet); - } + public static void sendToPlayersTrackingPos(IForestryPacketClient packet, BlockPos pos, ServerLevel level) { + PacketDistributor.sendToPlayersTrackingChunk(level, new ChunkPos(pos), packet); } // Used for Streamable to prepare FriendlyByteBuf for sending over the network - public static void writePayloadBuffer(FriendlyByteBuf buffer, Consumer dataWriter) { + public static void writePayloadBuffer(RegistryFriendlyByteBuf buffer, Consumer dataWriter) { // write a placeholder value for the number of bytes, keeping its index for replacing later int dataBytesIndex = buffer.writerIndex(); buffer.writeInt(0); @@ -67,45 +47,41 @@ public static void writePayloadBuffer(FriendlyByteBuf buffer, Consumer itemStacks) { + public static void writeItemStacks(RegistryFriendlyByteBuf buffer, List itemStacks) { buffer.writeVarInt(itemStacks.size()); for (ItemStack stack : itemStacks) { - buffer.writeItem(stack); + ItemStack.STREAM_CODEC.encode(buffer, stack); } } - public static NonNullList readItemStacks(FriendlyByteBuf buffer) { + public static List readItemStacks(RegistryFriendlyByteBuf buffer) { int stackCount = buffer.readVarInt(); - NonNullList itemStacks = NonNullList.create(); + ArrayList itemStacks = new ArrayList<>(stackCount); for (int i = 0; i < stackCount; i++) { - itemStacks.add(buffer.readItem()); + itemStacks.add(ItemStack.STREAM_CODEC.decode(buffer)); } return itemStacks; } - public static void writeInventory(FriendlyByteBuf buffer, Container inventory) { + public static void writeInventory(RegistryFriendlyByteBuf buffer, Container inventory) { int size = inventory.getContainerSize(); buffer.writeVarInt(size); for (int i = 0; i < size; i++) { ItemStack stack = inventory.getItem(i); - buffer.writeItem(stack); + ItemStack.STREAM_CODEC.encode(buffer, stack); } } - public static void readInventory(FriendlyByteBuf buffer, Container inventory) { + public static void readInventory(RegistryFriendlyByteBuf buffer, Container inventory) { int size = buffer.readVarInt(); for (int i = 0; i < size; i++) { - ItemStack stack = buffer.readItem(); + ItemStack stack = ItemStack.STREAM_CODEC.decode(buffer); inventory.setItem(i, stack); } } @@ -120,7 +96,7 @@ public static > T readEnum(FriendlyByteBuf buffer, T[] enumVal return enumValues[buffer.readByte()]; } - public static void writeStreamable(FriendlyByteBuf buffer, @Nullable IStreamable streamable) { + public static void writeStreamable(RegistryFriendlyByteBuf buffer, @Nullable IStreamable streamable) { if (streamable != null) { buffer.writeBoolean(true); streamable.writeData(buffer); @@ -130,14 +106,14 @@ public static void writeStreamable(FriendlyByteBuf buffer, @Nullable IStreamable } @Nullable - public static T readStreamable(FriendlyByteBuf buffer, Function factory) { + public static T readStreamable(RegistryFriendlyByteBuf buffer, Function factory) { if (buffer.readBoolean()) { return factory.apply(buffer); } return null; } - public static void writeStreamables(FriendlyByteBuf buffer, @Nullable List streamables) { + public static void writeStreamables(RegistryFriendlyByteBuf buffer, @Nullable List streamables) { if (streamables == null) { buffer.writeVarInt(0); } else { @@ -148,7 +124,7 @@ public static void writeStreamables(FriendlyByteBuf buff } } - public static void readStreamables(FriendlyByteBuf buffer, List outputList, Function factory) { + public static void readStreamables(RegistryFriendlyByteBuf buffer, List outputList, Function factory) { outputList.clear(); int length = buffer.readVarInt(); if (length > 0) { @@ -159,7 +135,7 @@ public static void readStreamables(FriendlyByteBuf buffe } } - public static void writeClimateState(FriendlyByteBuf buffer, @Nullable IClimateProvider climateState) { + public static void writeClimateState(RegistryFriendlyByteBuf buffer, @Nullable IClimateProvider climateState) { if (climateState != null) { buffer.writeBoolean(true); buffer.writeByte(climateState.temperature().ordinal()); @@ -169,13 +145,13 @@ public static void writeClimateState(FriendlyByteBuf buffer, @Nullable IClimateP } } - public static void writeClimateState(FriendlyByteBuf buffer, TemperatureType temperature, HumidityType humidity) { + public static void writeClimateState(RegistryFriendlyByteBuf buffer, TemperatureType temperature, HumidityType humidity) { buffer.writeBoolean(true); buffer.writeByte(temperature.ordinal()); buffer.writeByte(humidity.ordinal()); } - public static IClimateProvider readClimateState(FriendlyByteBuf buffer) { + public static IClimateProvider readClimateState(RegistryFriendlyByteBuf buffer) { if (buffer.readBoolean()) { return new ClimateState(TemperatureType.VALUES.get(buffer.readByte()), HumidityType.VALUES.get(buffer.readByte())); } else { @@ -183,19 +159,19 @@ public static IClimateProvider readClimateState(FriendlyByteBuf buffer) { } } - public static void writeBlockState(FriendlyByteBuf buffer, BlockState state) { - buffer.writeId(Block.BLOCK_STATE_REGISTRY, state); + public static void writeBlockState(RegistryFriendlyByteBuf buffer, BlockState state) { + buffer.writeById(Block.BLOCK_STATE_REGISTRY::getId, state); } - public static BlockState readBlockState(FriendlyByteBuf buffer) { - return buffer.readById(Block.BLOCK_STATE_REGISTRY); + public static BlockState readBlockState(RegistryFriendlyByteBuf buffer) { + return buffer.readById(Block.BLOCK_STATE_REGISTRY::byId); } - public static void writeDirection(FriendlyByteBuf buffer, Direction direction) { + public static void writeDirection(RegistryFriendlyByteBuf buffer, Direction direction) { buffer.writeByte(direction.ordinal()); } - public static Direction readDirection(FriendlyByteBuf buffer) { + public static Direction readDirection(RegistryFriendlyByteBuf buffer) { byte ordinal = buffer.readByte(); if (ordinal > 5 || ordinal < 0) { throw new IllegalArgumentException("Tried to deserialize Direction enum from network, but got invalid ordinal: " + ordinal); @@ -203,7 +179,7 @@ public static Direction readDirection(FriendlyByteBuf buffer) { return Direction.VALUES[ordinal]; } - public static void writeShortArray(FriendlyByteBuf buffer, short[] array) { + public static void writeShortArray(RegistryFriendlyByteBuf buffer, short[] array) { buffer.writeVarInt(array.length); for (short value : array) { buffer.writeShort(value); @@ -217,4 +193,9 @@ public static short[] readShortArray(FriendlyByteBuf buffer) { } return array; } + + public static void sendRecipeClick(int mouseButton, int recipeIndex) { + IForestryPacketServer packet = new PacketGuiSelectRequest(mouseButton, recipeIndex); + PacketDistributor.sendToServer(packet); + } } diff --git a/src/main/java/forestry/core/utils/PlayerUtil.java b/src/main/java/forestry/core/utils/PlayerUtil.java index de74a9e0c5..d13d9452b0 100644 --- a/src/main/java/forestry/core/utils/PlayerUtil.java +++ b/src/main/java/forestry/core/utils/PlayerUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import com.mojang.authlib.GameProfile; @@ -21,9 +11,6 @@ import java.util.UUID; public abstract class PlayerUtil { - //TODO: use null everywhere instead of an emptyUUID - private static final UUID emptyUUID = new UUID(0, 0); - public static boolean isSameGameProfile(GameProfile player1, GameProfile player2) { UUID id1 = player1.getId(); UUID id2 = player2.getId(); diff --git a/src/main/java/forestry/core/utils/RecipeUtils.java b/src/main/java/forestry/core/utils/RecipeUtil.java similarity index 60% rename from src/main/java/forestry/core/utils/RecipeUtils.java rename to src/main/java/forestry/core/utils/RecipeUtil.java index d82df1b3f3..73b923d286 100644 --- a/src/main/java/forestry/core/utils/RecipeUtils.java +++ b/src/main/java/forestry/core/utils/RecipeUtil.java @@ -4,6 +4,7 @@ import forestry.core.ClientsideCode; import forestry.core.fluids.FluidHelper; import forestry.factory.features.FactoryRecipeTypes; +import forestry.factory.recipes.FabricatorSmeltingRecipe; import forestry.modules.features.FeatureRecipeType; import forestry.worktable.inventory.WorktableCraftingContainer; import net.minecraft.core.NonNullList; @@ -13,26 +14,24 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.world.Container; -import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.*; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.server.ServerLifecycleHooks; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.FluidIngredient; +import net.neoforged.neoforge.server.ServerLifecycleHooks; import javax.annotation.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; -public class RecipeUtils { +public class RecipeUtil { /** * @return The global registry manager. {@code null} on server when there is no server, or when there is no world (on client). */ @@ -53,15 +52,19 @@ public static Registry getFluidRegistry() { } @Nullable - public static > Recipe getRecipe(RecipeType recipeType, ResourceLocation name) { + public static > RecipeHolder getRecipe(@Nullable ResourceLocation name) { + if (name == null) { + return null; + } RecipeManager manager = getRecipeManager(); if (manager == null) { return null; } - return manager.byType(recipeType).get(name); + Optional> holder = manager.byKey(name); + return (RecipeHolder) holder.orElse(null); } - public static > List getRecipes(RecipeType recipeType, C inventory, @Nullable Level world) { + public static > List> getRecipes(RecipeType recipeType, I inventory, @Nullable Level world) { RecipeManager manager = getRecipeManager(); if (manager == null || world == null) { return Collections.emptyList(); @@ -69,18 +72,20 @@ public static > List getRecipes(Reci return manager.getRecipesFor(recipeType, inventory, world); } - public static List findMatchingRecipes(CraftingContainer inventory, Level level) { + public static List> findMatchingRecipes(CraftingInput inventory, Level level) { return level.getRecipeManager().getRecipesFor(RecipeType.CRAFTING, inventory, level); } // Returns a crafting matrix for a certain recipe using available items @Nullable public static WorktableCraftingContainer getUsedMatrix(WorktableCraftingContainer originalMatrix, NonNullList availableItems, Level level, CraftingRecipe recipe) { - if (!recipe.matches(originalMatrix, level)) { + CraftingInput input = originalMatrix.asCraftInput(); + + if (!recipe.matches(input, level)) { return null; } - ItemStack expectedOutput = recipe.assemble(originalMatrix, level.registryAccess()); + ItemStack expectedOutput = recipe.assemble(input, level.registryAccess()); if (expectedOutput.isEmpty()) { return null; } @@ -101,8 +106,10 @@ public static WorktableCraftingContainer getUsedMatrix(WorktableCraftingContaine } } - if (recipe.matches(usedMatrix, level)) { - ItemStack output = recipe.assemble(usedMatrix, level.registryAccess()); + CraftingInput usedInput = usedMatrix.asCraftInput(); + + if (recipe.matches(usedInput, level)) { + ItemStack output = recipe.assemble(usedInput, level.registryAccess()); if (ItemStack.matches(output, expectedOutput)) { return usedMatrix; } @@ -113,14 +120,16 @@ public static WorktableCraftingContainer getUsedMatrix(WorktableCraftingContaine private static ItemStack getCraftingEquivalent(List stockCopy, WorktableCraftingContainer originalMatrix, int slot, Level level, CraftingRecipe recipe, ItemStack expectedOutput) { ItemStack originalStack = originalMatrix.getItem(slot); + CraftingInput input = originalMatrix.asCraftInput(); + for (ItemStack stockStack : stockCopy) { if (!stockStack.isEmpty()) { ItemStack singleStockStack = stockStack.copy(); singleStockStack.setCount(1); originalMatrix.setItem(slot, singleStockStack); - if (recipe.matches(originalMatrix, level)) { - ItemStack output = recipe.assemble(originalMatrix, level.registryAccess()); + if (recipe.matches(input, level)) { + ItemStack output = recipe.assemble(input, level.registryAccess()); if (ItemStack.matches(output, expectedOutput)) { originalMatrix.setItem(slot, originalStack); return stockStack.split(1); @@ -133,22 +142,22 @@ private static ItemStack getCraftingEquivalent(List stockCopy, Workta } @Nullable - public static IHygroregulatorRecipe getHygroRegulatorRecipe(RecipeManager manager, FluidStack input) { - return getMatchingRecipe(manager, FactoryRecipeTypes.HYGROREGULATOR, recipe -> recipe.getInputFluid().isFluidEqual(input)); + public static RecipeHolder getHygroRegulatorRecipe(RecipeManager manager, FluidStack input) { + return getMatchingRecipe(manager, FactoryRecipeTypes.HYGROREGULATOR, recipe -> recipe.getInputFluid().test(input)); } @Nullable - public static IFermenterRecipe getFermenterRecipe(RecipeManager manager, ItemStack inputItem, FluidStack inputFluid) { + public static RecipeHolder getFermenterRecipe(RecipeManager manager, ItemStack inputItem, FluidStack inputFluid) { return getMatchingRecipe(manager, FactoryRecipeTypes.FERMENTER, recipe -> recipe.matches(inputItem, inputFluid)); } public static boolean isFermenterInput(RecipeManager manager, ItemStack stack) { return getRecipes(manager, FactoryRecipeTypes.FERMENTER) - .anyMatch(recipe -> recipe.getInputItem().test(stack)); + .anyMatch(recipe -> recipe.value().getInputItem().test(stack)); } @Nullable - public static ICarpenterRecipe getCarpenterRecipe(RecipeManager manager, FluidStack fluid, ItemStack boxStack, Container craftingInventory, Level level) { + public static RecipeHolder getCarpenterRecipe(RecipeManager manager, FluidStack fluid, ItemStack boxStack, Container craftingInventory, Level level) { return getMatchingRecipe(manager, FactoryRecipeTypes.CARPENTER, recipe -> recipe.matches(fluid, boxStack, craftingInventory, level)); } @@ -159,7 +168,7 @@ public static boolean isCarpenterBox(RecipeManager manager, ItemStack stack) { // Returns true if the item is part of any squeezer recipe. public static boolean isSqueezerIngredient(RecipeManager manager, ItemStack stack) { return getRecipes(manager, FactoryRecipeTypes.SQUEEZER).anyMatch(recipe -> { - for (Ingredient ingredient : recipe.getInputs()) { + for (Ingredient ingredient : recipe.value().getInputs()) { if (ingredient.test(stack)) { return true; } @@ -169,7 +178,7 @@ public static boolean isSqueezerIngredient(RecipeManager manager, ItemStack stac } @Nullable - public static ISqueezerContainerRecipe getSqueezerContainerRecipe(RecipeManager manager, ItemStack stack) { + public static RecipeHolder getSqueezerContainerRecipe(RecipeManager manager, ItemStack stack) { if (!FluidHelper.isDrainableFilledContainer(stack)) { return null; } @@ -177,17 +186,17 @@ public static ISqueezerContainerRecipe getSqueezerContainerRecipe(RecipeManager } @Nullable - public static ICentrifugeRecipe getCentrifugeRecipe(RecipeManager manager, ItemStack stack) { + public static RecipeHolder getCentrifugeRecipe(RecipeManager manager, ItemStack stack) { return getMatchingRecipe(manager, FactoryRecipeTypes.CENTRIFUGE, recipe -> recipe.getInput().test(stack)); } @Nullable - public static IFabricatorSmeltingRecipe getFabricatorMeltingRecipe(RecipeManager manager, ItemStack stack) { - return getMatchingRecipe(manager, FactoryRecipeTypes.FABRICATOR_SMELTING, recipe -> recipe.getInput().test(stack)); + public static RecipeHolder getFabricatorMeltingRecipe(RecipeManager manager, ItemStack stack) { + return getMatchingRecipe(manager, FactoryRecipeTypes.FABRICATOR_SMELTING, recipe -> recipe.input().test(stack)); } @Nullable - public static IFabricatorRecipe getFabricatorRecipe(RecipeManager manager, Level level, FluidStack liquid, ItemStack stack, Container inventory) { + public static RecipeHolder getFabricatorRecipe(RecipeManager manager, Level level, FluidStack liquid, ItemStack stack, Container inventory) { return getMatchingRecipe(manager, FactoryRecipeTypes.FABRICATOR, recipe -> recipe.matches(level, liquid, stack, inventory)); } @@ -196,46 +205,51 @@ public static boolean isFabricatorPlan(RecipeManager manager, ItemStack stack) { } @Nullable - public static IMoistenerRecipe getMoistenerRecipe(RecipeManager manager, ItemStack stack) { + public static RecipeHolder getMoistenerRecipe(RecipeManager manager, ItemStack stack) { return getMatchingRecipe(manager, FactoryRecipeTypes.MOISTENER, recipe -> recipe.getInput().test(stack)); } @Nullable - public static ISqueezerRecipe getSqueezerRecipe(RecipeManager manager, List inputs) { + public static RecipeHolder getSqueezerRecipe(RecipeManager manager, List inputs) { return getMatchingRecipe(manager, FactoryRecipeTypes.SQUEEZER, recipe -> ItemStackUtil.createConsume(recipe.getInputs(), inputs.size(), inputs::get, false).length > 0); } @Nullable - public static IStillRecipe getStillRecipe(RecipeManager manager, FluidStack input) { + public static RecipeHolder getStillRecipe(RecipeManager manager, FluidStack input) { return getMatchingRecipe(manager, FactoryRecipeTypes.STILL, recipe -> recipe.matches(input)); } @Nullable - private static , C extends Container> R getMatchingRecipe(RecipeManager manager, FeatureRecipeType type, Predicate matcher) { + private static , I extends RecipeInput> RecipeHolder getMatchingRecipe(RecipeManager manager, FeatureRecipeType type, Predicate matcher) { return getRecipes(manager, type) - .filter(matcher) + .filter(holder -> matcher.test(holder.value())) .findFirst() .orElse(null); } - public static , C extends Container> Stream getRecipes(RecipeManager manager, FeatureRecipeType type) { - return manager.byType(type.type()).values().stream(); + public static , I extends RecipeInput> Stream> getRecipes(RecipeManager manager, FeatureRecipeType type) { + return manager.byType(type.type()).stream(); } - public static , C extends Container> Set getTargetFluidsFromStacks(RecipeManager manager, RecipeType type, Function targetFluid) { - return getTargetFluids(manager, type, recipe -> targetFluid.apply(recipe).getFluid()); + public static , C extends RecipeInput> Set getTargetFluidsFromIngredients(RecipeManager manager, RecipeType type, Function targetFluid) { + return getTargetFluids(manager, type, recipe -> Arrays.stream(targetFluid.apply(recipe).getStacks()).map(FluidStack::getFluid)); } - public static , C extends Container> Set getTargetFluids(RecipeManager manager, RecipeType type, Function targetFluid) { - return manager.byType(type).values().stream() - .map(value -> ModUtil.getRegistryName(targetFluid.apply(value))) + public static , I extends RecipeInput> Set getTargetFluids(RecipeManager manager, RecipeType type, Function> targetFluid) { + return manager.byType(type).stream() + .flatMap(holder -> targetFluid.apply(holder.value()).map(ModUtil::getRegistryName)) .collect(Collectors.toSet()); } - public static , C extends Container> R getRecipeByOutput(FeatureRecipeType recipeType, RegistryAccess registryAccess, ItemStack output) { + public static , I extends RecipeInput> RecipeHolder getRecipeByOutput(FeatureRecipeType recipeType, RegistryAccess registryAccess, ItemStack output) { return getRecipes(getRecipeManager(), recipeType) - .filter(recipe -> ItemStack.isSameItem(recipe.getResultItem(registryAccess), output)) + .filter(recipe -> ItemStack.isSameItem(recipe.value().getResultItem(registryAccess), output)) .findFirst() .orElseThrow(() -> new IllegalStateException("Couldn't find a recipe with output: " + output)); } + + @Nullable + public static > T unwrap(@Nullable RecipeHolder holder) { + return holder == null ? null : holder.value(); + } } diff --git a/src/main/java/forestry/core/utils/RenderUtil.java b/src/main/java/forestry/core/utils/RenderUtil.java index fa0c73aeb5..700e07fb40 100644 --- a/src/main/java/forestry/core/utils/RenderUtil.java +++ b/src/main/java/forestry/core/utils/RenderUtil.java @@ -14,8 +14,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidType; import java.awt.*; @@ -59,10 +59,6 @@ public static int getFluidColor(Fluid fluid) { return color; } - public static Color getRainbowColor(long time, float partialTicks) { - return Color.getHSBColor((180 * Mth.sin((time + partialTicks) / 30.0f) - 180) / 360.0f, 0.5f, 0.8f); - } - // VANILLA COPY public static int getYImage(Button button) { int i = 1; @@ -74,4 +70,8 @@ public static int getYImage(Button button) { return i; } + + public static Color getRainbowColor(long time, float partialTicks) { + return Color.getHSBColor((180 * Mth.sin((time + partialTicks) / 30.0f) - 180) / 360.0f, 0.5f, 0.8f); + } } diff --git a/src/main/java/forestry/core/utils/ResourceUtil.java b/src/main/java/forestry/core/utils/ResourceUtil.java index 8e9f18ce83..34e122d7ae 100644 --- a/src/main/java/forestry/core/utils/ResourceUtil.java +++ b/src/main/java/forestry/core/utils/ResourceUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import com.mojang.math.Transformation; @@ -16,17 +6,15 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.InventoryMenu; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.SimpleModelState; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.model.SimpleModelState; /** * Util methods used at the installation of the game or at the reloading or baking of resources like models or * textures. */ -@OnlyIn(Dist.CLIENT) public class ResourceUtil { - public static TextureAtlasSprite getMissingTexture() { return getSprite(InventoryMenu.BLOCK_ATLAS, MissingTextureAtlasSprite.getLocation()); } @@ -40,7 +28,7 @@ public static TextureAtlasSprite getBlockSprite(ResourceLocation location) { } public static TextureAtlasSprite getBlockSprite(String location) { - return getBlockSprite(new ResourceLocation(location)); + return getBlockSprite(ResourceLocation.parse(location)); } public static SimpleModelState loadTransform(ResourceLocation location) { diff --git a/src/main/java/forestry/core/utils/SlotUtil.java b/src/main/java/forestry/core/utils/SlotUtil.java index 8c8f7719ca..532050fca3 100644 --- a/src/main/java/forestry/core/utils/SlotUtil.java +++ b/src/main/java/forestry/core/utils/SlotUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import forestry.core.gui.slots.SlotForestry; diff --git a/src/main/java/forestry/core/utils/SoundUtil.java b/src/main/java/forestry/core/utils/SoundUtil.java index f21f74bc4a..fa68e26216 100644 --- a/src/main/java/forestry/core/utils/SoundUtil.java +++ b/src/main/java/forestry/core/utils/SoundUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import net.minecraft.client.Minecraft; diff --git a/src/main/java/forestry/core/utils/SpeciesUtil.java b/src/main/java/forestry/core/utils/SpeciesUtil.java index 2b133cfea4..56b9644ad7 100644 --- a/src/main/java/forestry/core/utils/SpeciesUtil.java +++ b/src/main/java/forestry/core/utils/SpeciesUtil.java @@ -1,13 +1,12 @@ package forestry.core.utils; import com.google.common.collect.ImmutableList; -import com.mojang.authlib.GameProfile; import com.mojang.serialization.Codec; import forestry.Forestry; import forestry.api.IForestryApi; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import forestry.api.climate.IClimateProvider; import forestry.api.genetics.*; @@ -22,8 +21,9 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; -import net.minecraftforge.common.util.Lazy; +import net.neoforged.neoforge.common.util.Lazy; import javax.annotation.Nullable; import java.util.List; @@ -95,7 +95,7 @@ public static I deserializeIndividual(ISpeciesType } @Nullable - public static > ImmutableList> mutateSpecies(Level level, BlockPos pos, @Nullable GameProfile profile, IGenome parent1, IGenome parent2, IRegistryChromosome speciesChromosome, IMutationChanceGetter chanceGetter) { + public static > ImmutableList> mutateSpecies(Level level, BlockPos pos, @Nullable ResolvableProfile profile, IGenome parent1, IGenome parent2, IRegistryChromosome speciesChromosome, IMutationChanceGetter chanceGetter) { IGenome firstGenome; IGenome secondGenome; diff --git a/src/main/java/forestry/core/utils/StringUtil.java b/src/main/java/forestry/core/utils/StringUtil.java index 9ef95194cb..ea65e36e8a 100755 --- a/src/main/java/forestry/core/utils/StringUtil.java +++ b/src/main/java/forestry/core/utils/StringUtil.java @@ -1,39 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.FormattedText; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -import java.util.Locale; -import java.util.regex.Pattern; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class StringUtil { - - private static final Pattern camelCaseToUnderscores = Pattern.compile("(.)([A-Z])"); - - public static String camelCaseToUnderscores(String uid) { - return camelCaseToUnderscores.matcher(uid).replaceAll("$1_$2").toLowerCase(Locale.ENGLISH); - } - public static String append(String delim, String source, String appendix) { - if (source.length() <= 0) { + if (source.isEmpty()) { return appendix; } - if (appendix.length() <= 0) { + if (appendix.isEmpty()) { return source; } @@ -45,12 +25,7 @@ public static String floatAsPercent(float val) { } public static Component line(int length) { - StringBuilder line = new StringBuilder(); - for (int i = 0; i < length; i++) { - line.append('-'); - } - - return Component.literal(line.toString()); + return Component.literal("-".repeat(Math.max(0, length))); } @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/forestry/core/utils/TreeUtil.java b/src/main/java/forestry/core/utils/TreeUtil.java index aa16f0681c..4a1f67378d 100644 --- a/src/main/java/forestry/core/utils/TreeUtil.java +++ b/src/main/java/forestry/core/utils/TreeUtil.java @@ -1,10 +1,10 @@ package forestry.core.utils; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.ITree; import forestry.api.lepidopterology.IButterflyNursery; -import forestry.apiculture.ModuleApiculture; import forestry.arboriculture.tiles.TileLeaves; +import forestry.core.config.ForestryConfig; import net.minecraft.core.BlockPos; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.state.BlockState; @@ -87,6 +87,6 @@ public static boolean tryMate(TileLeaves leaves, ITree pollen) { } public static boolean canMate(@Nullable ITree leaves, ITree pollen) { - return leaves != null && leaves.getMate() == null && (ModuleApiculture.doSelfPollination || !leaves.getGenome().isSameAlleles(pollen.getGenome())); + return leaves != null && leaves.getMate() == null && (ForestryConfig.SERVER.treesSelfPollination.get() || !leaves.getGenome().isSameAlleles(pollen.getGenome())); } } diff --git a/src/main/java/forestry/core/utils/VecUtil.java b/src/main/java/forestry/core/utils/VecUtil.java index aed704931f..53ca95487a 100644 --- a/src/main/java/forestry/core/utils/VecUtil.java +++ b/src/main/java/forestry/core/utils/VecUtil.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.core.utils; import com.google.common.collect.AbstractIterator; @@ -22,7 +12,7 @@ import java.util.Comparator; import java.util.Iterator; -public final class VecUtil { +public class VecUtil { /** * Sorts positions by height in descending order */ diff --git a/src/main/java/forestry/core/utils/datastructures/FluidMap.java b/src/main/java/forestry/core/utils/datastructures/FluidMap.java deleted file mode 100644 index 693832b01f..0000000000 --- a/src/main/java/forestry/core/utils/datastructures/FluidMap.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.datastructures; - - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; - -import java.io.Serial; - -public class FluidMap extends StackMap { - @Serial - private static final long serialVersionUID = 15891293315299994L; - - @Override - protected boolean areEqual(Fluid a, Fluid b) { - return a.equals(b); - } - - @Override - protected boolean isValidKey(Object key) { - return key instanceof FluidStack || key instanceof Fluid || key instanceof String || key instanceof ResourceLocation; - } - - @Override - protected Fluid getStack(Object key) { - if (key instanceof FluidStack) { - return ((FluidStack) key).getFluid(); - } - if (key instanceof Fluid) { - return (Fluid) key; - } - if (key instanceof String) { - return ForgeRegistries.FLUIDS.getValue(new ResourceLocation((String) key)); - } - if (key instanceof ResourceLocation) { - return ForgeRegistries.FLUIDS.getValue((ResourceLocation) key); - } - return null; - } -} diff --git a/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java b/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java deleted file mode 100644 index 8bf1590130..0000000000 --- a/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.datastructures; - -import forestry.core.utils.ItemStackUtil; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import java.io.Serial; - -// todo remove -public class ItemStackMap extends StackMap { - @Serial - private static final long serialVersionUID = -8511966739130702305L; - - @Override - protected boolean areEqual(ItemStack a, ItemStack b) { - return ItemStackUtil.isCraftingEquivalent(b, a); - } - - @Override - protected boolean isValidKey(Object key) { - return key instanceof ItemStack || key instanceof Item || key instanceof String || key instanceof ResourceLocation; - } - - @Override - protected ItemStack getStack(Object key) { - if (key instanceof ItemStack) { - return (ItemStack) key; - } - return ItemStack.EMPTY; - } - -} diff --git a/src/main/java/forestry/core/utils/datastructures/StackMap.java b/src/main/java/forestry/core/utils/datastructures/StackMap.java deleted file mode 100644 index 8d4914f27c..0000000000 --- a/src/main/java/forestry/core/utils/datastructures/StackMap.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.utils.datastructures; - -import com.google.common.base.Preconditions; - -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; - -/** - * Map for fluids and items. - * - * @param The thing this map maps onto - * @param

The stack class (i.e. ItemStack, FluidStack) used for lookups - * @author Alex Binnie - */ -public abstract class StackMap extends HashMap { - - @Override - public final T put(P key, T value) { - Preconditions.checkArgument(isValidKey(key), "Key is invalid"); - Preconditions.checkNotNull(value); - return super.put(key, value); - } - - private static final long serialVersionUID = 5383477742290646466L; - - @Override - public final boolean containsKey(Object key) { - P stack = getStack(key); - if (stack == null) { - return false; - } - for (Map.Entry entry : this.entrySet()) { - if (areEqual(stack, entry.getKey())) { - return true; - } - } - return super.containsKey(key); - } - - @Override - @Nullable - public final T get(Object key) { - P stack = getStack(key); - if (stack == null) { - return null; - } - for (Map.Entry entry : this.entrySet()) { - if (areEqual(stack, entry.getKey())) { - return entry.getValue(); - } - } - return super.get(key); - } - - /** - * Is a, the key used to lookup, equivelant to the key b - * - * @param a - * @param b - * @return - */ - protected abstract boolean areEqual(P a, P b); - - /** - * Can this key be added to the map - * - * @param key - * @return - */ - protected abstract boolean isValidKey(Object key); - - /** - * Converts a key used to lookup something into P (ItemStack or FluidStack) - * - * @param key - * @return - */ - @Nullable - protected abstract P getStack(Object key); - -} diff --git a/src/main/java/forestry/core/utils/datastructures/TriFunction.java b/src/main/java/forestry/core/utils/datastructures/TriFunction.java deleted file mode 100644 index dd8fac23de..0000000000 --- a/src/main/java/forestry/core/utils/datastructures/TriFunction.java +++ /dev/null @@ -1,15 +0,0 @@ -package forestry.core.utils.datastructures; - -import java.util.Objects; -import java.util.function.Function; - -@FunctionalInterface -public interface TriFunction { - - R apply(A a, B b, C c); - - default TriFunction andThen(Function after) { - Objects.requireNonNull(after); - return (A a, B b, C c) -> after.apply(apply(a, b, c)); - } -} diff --git a/src/main/java/forestry/core/utils/datastructures/package-info.java b/src/main/java/forestry/core/utils/datastructures/package-info.java deleted file mode 100644 index af820b58cd..0000000000 --- a/src/main/java/forestry/core/utils/datastructures/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault -@net.minecraft.MethodsReturnNonnullByDefault -package forestry.core.utils.datastructures; diff --git a/src/main/java/forestry/core/utils/package-info.java b/src/main/java/forestry/core/utils/package-info.java index 58f7caadd5..12a7691d1a 100644 --- a/src/main/java/forestry/core/utils/package-info.java +++ b/src/main/java/forestry/core/utils/package-info.java @@ -1,8 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.core.utils; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/core/worldgen/ApiaristPoolElement.java b/src/main/java/forestry/core/worldgen/ApiaristPoolElement.java index 517be8a6cb..e3ea761842 100644 --- a/src/main/java/forestry/core/worldgen/ApiaristPoolElement.java +++ b/src/main/java/forestry/core/worldgen/ApiaristPoolElement.java @@ -3,13 +3,13 @@ import com.google.common.collect.ImmutableList; import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.IForestryApi; -import forestry.api.apiculture.genetics.BeeLifeStage; -import forestry.api.apiculture.genetics.IBee; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.BeeLifeStage; +import forestry.api.apiculture.bee.IBee; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.api.apiculture.hives.IHiveManager; import forestry.api.climate.ClimateState; import forestry.api.genetics.ClimateHelper; @@ -40,22 +40,21 @@ import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement; import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElementType; import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; -import net.minecraft.world.level.levelgen.structure.templatesystem.BlockIgnoreProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.world.level.levelgen.structure.templatesystem.*; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; public class ApiaristPoolElement extends SinglePoolElement { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> { - return instance.group(templateCodec(), processorsCodec()).apply(instance, ApiaristPoolElement::new); - }); + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + templateCodec(), + processorsCodec() + ).apply(inst, ApiaristPoolElement::new)); public ApiaristPoolElement(Either template, Holder processors) { - super(template, processors, StructureTemplatePool.Projection.RIGID); + super(template, processors, StructureTemplatePool.Projection.RIGID, Optional.empty()); } @Override @@ -73,9 +72,9 @@ public void handleDataMarker(LevelAccessor level, StructureTemplate.StructureBlo } @Override - protected StructurePlaceSettings getSettings(Rotation rotation, BoundingBox bounds, boolean keepJigsaws) { + protected StructurePlaceSettings getSettings(Rotation rotation, BoundingBox bounds, LiquidSettings settings, boolean offset) { // data markers get wiped (ignored) if we don't remove the structure block processor - return super.getSettings(rotation, bounds, keepJigsaws) + return super.getSettings(rotation, bounds, settings, offset) .popProcessor(BlockIgnoreProcessor.STRUCTURE_BLOCK); } diff --git a/src/main/java/forestry/core/worldgen/FeatureHelper.java b/src/main/java/forestry/core/worldgen/FeatureHelper.java index f428576ece..3aacb28e93 100644 --- a/src/main/java/forestry/core/worldgen/FeatureHelper.java +++ b/src/main/java/forestry/core/worldgen/FeatureHelper.java @@ -1,6 +1,6 @@ package forestry.core.worldgen; -import forestry.api.arboriculture.ITreeGenData; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.arboriculture.worldgen.ITreeBlockType; import forestry.arboriculture.worldgen.TreeBlockType; import forestry.arboriculture.worldgen.TreeContour; @@ -23,18 +23,18 @@ import java.util.Set; public class FeatureHelper { - public static boolean addBlock(LevelAccessor world, BlockPos pos, ITreeBlockType type, EnumReplaceMode replaceMode) { - return addBlock(world, pos, type, replaceMode, TreeContour.EMPTY); + public static boolean addBlock(LevelAccessor level, BlockPos pos, ITreeBlockType type, EnumReplaceMode replaceMode) { + return addBlock(level, pos, type, replaceMode, TreeContour.EMPTY); } - public static boolean addBlock(LevelAccessor world, BlockPos pos, ITreeBlockType type, EnumReplaceMode replaceMode, TreeContour contour) { - if (!world.hasChunkAt(pos)) { + public static boolean addBlock(LevelAccessor level, BlockPos pos, ITreeBlockType type, EnumReplaceMode replaceMode, TreeContour contour) { + if (!level.hasChunkAt(pos)) { return false; } - BlockState blockState = world.getBlockState(pos); - if (replaceMode.canReplace(blockState, world, pos)) { - type.setBlock(world, pos); + BlockState blockState = level.getBlockState(pos); + if (replaceMode.canReplace(blockState, level, pos)) { + type.setBlock(level, pos); contour.addLeaf(pos); return true; } @@ -44,14 +44,14 @@ public static boolean addBlock(LevelAccessor world, BlockPos pos, ITreeBlockType /** * Uses centerPos and girth of a tree to calculate the center */ - public static void generateCylinderFromTreeStartPos(LevelAccessor world, ITreeBlockType block, BlockPos startPos, int girth, float radius, int height, EnumReplaceMode replace, TreeContour contour) { - generateCylinderFromPos(world, block, startPos.offset(girth / 2, 0, girth / 2), radius, height, replace, contour); + public static void generateCylinderFromTreeStartPos(LevelAccessor level, ITreeBlockType block, BlockPos startPos, int girth, float radius, int height, EnumReplaceMode replace, TreeContour contour) { + generateCylinderFromPos(level, block, startPos.offset(girth / 2, 0, girth / 2), radius, height, replace, contour); } /** * Center is the bottom middle of the cylinder */ - public static void generateCylinderFromPos(LevelAccessor world, ITreeBlockType block, BlockPos center, float radius, int height, EnumReplaceMode replace, TreeContour contour) { + public static void generateCylinderFromPos(LevelAccessor level, ITreeBlockType block, BlockPos center, float radius, int height, EnumReplaceMode replace, TreeContour contour) { BlockPos start = BlockPos.containing(center.getX() - radius, center.getY(), center.getZ() - radius); for (int x = 0; x < radius * 2 + 1; x++) { for (int y = height - 1; y >= 0; y--) { // generating top-down is faster for lighting calculations @@ -61,7 +61,7 @@ public static void generateCylinderFromPos(LevelAccessor world, ITreeBlockType b if (position.distSqr(treeCenter) <= radius * radius + 0.01) { Direction direction = VecUtil.direction(position, treeCenter); block.setDirection(direction); - if (addBlock(world, position, block, replace)) { + if (addBlock(level, position, block, replace)) { contour.addLeaf(position); } } @@ -70,11 +70,11 @@ public static void generateCylinderFromPos(LevelAccessor world, ITreeBlockType b } } - public static void generateCircleFromTreeStartPos(LevelAccessor world, RandomSource rand, BlockPos startPos, int girth, float radius, int width, int height, ITreeBlockType block, float chance, EnumReplaceMode replace, TreeContour contour) { - generateCircle(world, rand, startPos.offset(girth / 2, 0, girth / 2), radius, width, height, block, chance, replace, contour); + public static void generateCircleFromTreeStartPos(LevelAccessor level, RandomSource rand, BlockPos startPos, int girth, float radius, int width, int height, ITreeBlockType block, float chance, EnumReplaceMode replace, TreeContour contour) { + generateCircle(level, rand, startPos.offset(girth / 2, 0, girth / 2), radius, width, height, block, chance, replace, contour); } - public static void generateCircle(LevelAccessor world, RandomSource rand, BlockPos center, float radius, int width, int height, ITreeBlockType block, float chance, EnumReplaceMode replace, TreeContour contour) { + public static void generateCircle(LevelAccessor level, RandomSource rand, BlockPos center, float radius, int width, int height, ITreeBlockType block, float chance, EnumReplaceMode replace, TreeContour contour) { BlockPos start = BlockPos.containing(center.getX() - radius, center.getY(), center.getZ() - radius); BlockPos area = BlockPos.containing(radius * 2 + 1, height, radius * 2 + 1); @@ -89,7 +89,7 @@ public static void generateCircle(LevelAccessor world, RandomSource rand, BlockP double distance = mutablePos.set(x, y, z).distToLowCornerSqr(center.getX(), y, center.getZ()); if ((radius - width - 0.01) * (radius - width - 0.01) < distance && distance <= (radius + 0.01) * (radius + 0.01)) { - if (addBlock(world, mutablePos, block, replace)) { + if (addBlock(level, mutablePos, block, replace)) { contour.addLeaf(mutablePos); } } @@ -98,11 +98,11 @@ public static void generateCircle(LevelAccessor world, RandomSource rand, BlockP } } - public static void generateSphereFromTreeStartPos(LevelAccessor world, BlockPos startPos, int girth, int radius, ITreeBlockType block, EnumReplaceMode replace, TreeContour contour) { - generateSphere(world, startPos.offset(girth / 2, 0, girth / 2), radius, block, replace, contour); + public static void generateSphereFromTreeStartPos(LevelAccessor level, BlockPos startPos, int girth, int radius, ITreeBlockType block, EnumReplaceMode replace, TreeContour contour) { + generateSphere(level, startPos.offset(girth / 2, 0, girth / 2), radius, block, replace, contour); } - public static void generateSphere(LevelAccessor world, BlockPos center, int radius, ITreeBlockType block, EnumReplaceMode replace, TreeContour contour) { + public static void generateSphere(LevelAccessor level, BlockPos center, int radius, ITreeBlockType block, EnumReplaceMode replace, TreeContour contour) { Vec3i start = new Vec3i(center.getX() - radius, center.getY() - radius, center.getZ() - radius); Vec3i area = new Vec3i(radius * 2 + 1, radius * 2 + 1, radius * 2 + 1); BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos(); @@ -111,7 +111,7 @@ public static void generateSphere(LevelAccessor world, BlockPos center, int radi for (int y = start.getY() + area.getY() - 1; y >= start.getY(); y--) { // generating top-down is faster for lighting calculations for (int z = start.getZ(); z < start.getZ() + area.getZ(); z++) { if (center.closerThan(mutablePos.set(x, y, z), radius + 0.01)) { - if (addBlock(world, mutablePos, block, replace)) { + if (addBlock(level, mutablePos, block, replace)) { contour.addLeaf(mutablePos); } } @@ -187,56 +187,55 @@ public static Set generateTreeTrunk( return treeTops; } - protected static void addVines(LevelAccessor world, RandomSource rand, BlockPos pos, float chance) { + protected static void addVines(LevelAccessor level, RandomSource rand, BlockPos pos, float chance) { if (chance <= 0) { return; } if (rand.nextFloat() < chance) { BlockState blockState = Blocks.VINE.defaultBlockState().setValue(VineBlock.EAST, true); - addBlock(world, pos.west(), new TreeBlockType(blockState), EnumReplaceMode.AIR); + addBlock(level, pos.west(), new TreeBlockType(blockState), EnumReplaceMode.AIR); } if (rand.nextFloat() < chance) { BlockState blockState = Blocks.VINE.defaultBlockState().setValue(VineBlock.WEST, true); - addBlock(world, pos.east(), new TreeBlockType(blockState), EnumReplaceMode.AIR); + addBlock(level, pos.east(), new TreeBlockType(blockState), EnumReplaceMode.AIR); } if (rand.nextFloat() < chance) { BlockState blockState = Blocks.VINE.defaultBlockState().setValue(VineBlock.SOUTH, true); - addBlock(world, pos.north(), new TreeBlockType(blockState), EnumReplaceMode.AIR); + addBlock(level, pos.north(), new TreeBlockType(blockState), EnumReplaceMode.AIR); } if (rand.nextFloat() < chance) { BlockState blockState = Blocks.VINE.defaultBlockState().setValue(VineBlock.NORTH, true); - addBlock(world, pos.south(), new TreeBlockType(blockState), EnumReplaceMode.AIR); + addBlock(level, pos.south(), new TreeBlockType(blockState), EnumReplaceMode.AIR); } } - public static void generatePods(ITreeGenData tree, LevelAccessor world, RandomSource rand, BlockPos startPos, int height, int minHeight, int girth, EnumReplaceMode replaceMode) { + public static void generatePods(ITreeSpecies species, LevelAccessor level, RandomSource rand, BlockPos startPos, int height, int minHeight, int girth, EnumReplaceMode replaceMode) { + // todo mutable block pos for (int y = height - 1; y >= minHeight; y--) { // generating top-down is faster for lighting calculations for (int x = 0; x < girth; x++) { for (int z = 0; z < girth; z++) { - if (x > 0 && z > 0) { continue; } - trySpawnFruitBlock(tree, world, rand, startPos.offset(x + 1, y, z), replaceMode); - trySpawnFruitBlock(tree, world, rand, startPos.offset(x - 1, y, z), replaceMode); - trySpawnFruitBlock(tree, world, rand, startPos.offset(x, y, z + 1), replaceMode); - trySpawnFruitBlock(tree, world, rand, startPos.offset(x, y, z - 1), replaceMode); + trySpawnPod(species, level, rand, startPos.offset(x + 1, y, z), replaceMode); + trySpawnPod(species, level, rand, startPos.offset(x - 1, y, z), replaceMode); + trySpawnPod(species, level, rand, startPos.offset(x, y, z + 1), replaceMode); + trySpawnPod(species, level, rand, startPos.offset(x, y, z - 1), replaceMode); } } } } - private static void trySpawnFruitBlock(ITreeGenData tree, LevelAccessor world, RandomSource rand, BlockPos pos, EnumReplaceMode replaceMode) { - BlockState blockState = world.getBlockState(pos); - if (replaceMode.canReplace(blockState, world, pos)) { - tree.trySpawnFruitBlock(world, rand, pos); + private static void trySpawnPod(ITreeSpecies species, LevelAccessor level, RandomSource rand, BlockPos pos, EnumReplaceMode replaceMode) { + BlockState blockState = level.getBlockState(pos); + if (replaceMode.canReplace(blockState, level, pos)) { + species.trySpawnFruitPod(level, rand, pos); } } - public static void generateSupportStems(ITreeBlockType wood, LevelAccessor world, RandomSource rand, BlockPos startPos, int height, int girth, float chance, float maxHeight) { - + public static void generateSupportStems(ITreeBlockType wood, LevelAccessor level, RandomSource rand, BlockPos startPos, int height, int girth, float chance, float maxHeight) { final int min = -1; for (int x = min; x <= girth; x++) { @@ -250,14 +249,14 @@ public static void generateSupportStems(ITreeBlockType wood, LevelAccessor world int stemHeight = rand.nextInt(Math.round(height * maxHeight)); if (rand.nextFloat() < chance) { for (int y = 0; y < stemHeight; y++) { - addBlock(world, startPos.offset(x, y, z), wood, EnumReplaceMode.SOFT); + addBlock(level, startPos.offset(x, y, z), wood, EnumReplaceMode.SOFT); } } } } } - public static Set generateBranches(final LevelAccessor world, final RandomSource rand, final ITreeBlockType wood, final BlockPos startPos, final int girth, final float spreadY, final float spreadXZ, int radius, final int count, final float chance) { + public static Set generateBranches(final LevelAccessor level, final RandomSource rand, final ITreeBlockType wood, final BlockPos startPos, final int girth, final float spreadY, final float spreadXZ, int radius, final int count, final float chance) { Set branchEnds = new HashSet<>(); if (radius < 1) { radius = 1; @@ -316,7 +315,7 @@ public static Set generateBranches(final LevelAccessor world, final Ra } BlockPos pos = branchStart.offset(x, y, z); - if (addBlock(world, pos, wood, EnumReplaceMode.SOFT)) { + if (addBlock(level, pos, wood, EnumReplaceMode.SOFT)) { branchEnd = pos; } else { break; diff --git a/src/main/java/forestry/core/worldgen/ForestryBiomeModifier.java b/src/main/java/forestry/core/worldgen/ForestryBiomeModifier.java index a69e693a8e..3a6fdab2c4 100644 --- a/src/main/java/forestry/core/worldgen/ForestryBiomeModifier.java +++ b/src/main/java/forestry/core/worldgen/ForestryBiomeModifier.java @@ -1,6 +1,6 @@ package forestry.core.worldgen; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.IForestryApi; import forestry.api.apiculture.hives.IHive; @@ -13,14 +13,14 @@ import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraftforge.common.world.BiomeModifier; -import net.minecraftforge.common.world.ModifiableBiomeInfo; +import net.neoforged.neoforge.common.world.BiomeModifier; +import net.neoforged.neoforge.common.world.ModifiableBiomeInfo; // Pass in the feature holders from the codec public record ForestryBiomeModifier(Holder hive, Holder tree, Holder apatiteOre, Holder tinOre) implements BiomeModifier { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( PlacedFeature.CODEC.fieldOf("hive").forGetter(ForestryBiomeModifier::hive), PlacedFeature.CODEC.fieldOf("tree").forGetter(ForestryBiomeModifier::tree), PlacedFeature.CODEC.fieldOf("apatite_ore").forGetter(ForestryBiomeModifier::apatiteOre), @@ -56,7 +56,7 @@ public void modify(Holder biome, Phase phase, ModifiableBiomeInfo.BiomeIn } @Override - public Codec codec() { + public MapCodec codec() { return CODEC; } } diff --git a/src/main/java/forestry/core/worldgen/package-info.java b/src/main/java/forestry/core/worldgen/package-info.java index 01f18d0a34..5a8fd2cc80 100644 --- a/src/main/java/forestry/core/worldgen/package-info.java +++ b/src/main/java/forestry/core/worldgen/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.core.worldgen; diff --git a/src/main/java/forestry/cultivation/blocks/BlockTypePlanter.java b/src/main/java/forestry/cultivation/blocks/BlockTypePlanter.java index e0590d5053..2a18a74b7c 100644 --- a/src/main/java/forestry/cultivation/blocks/BlockTypePlanter.java +++ b/src/main/java/forestry/cultivation/blocks/BlockTypePlanter.java @@ -7,8 +7,6 @@ import forestry.cultivation.tiles.TilePlanter; import forestry.modules.features.FeatureTileType; -import java.util.List; - public enum BlockTypePlanter implements IBlockType { ARBORETUM(CultivationTiles.ARBORETUM, "arboretum"), FARM_CROPS(CultivationTiles.CROPS, "farm_crops"), @@ -18,8 +16,6 @@ public enum BlockTypePlanter implements IBlockType { FARM_ENDER(CultivationTiles.ENDER, "farm_ender"), PEAT_POG(CultivationTiles.BOG, "peat_bog"); - public static final List VALUES = List.of(values()); - private final IMachineProperties machineProperties; BlockTypePlanter(FeatureTileType teClass, String name) { @@ -34,7 +30,7 @@ public IMachineProperties getMachineProperties() { } @Override - public String getSerializedName() { - return getMachineProperties().getSerializedName(); + public String identifier() { + return getMachineProperties().identifier(); } } diff --git a/src/main/java/forestry/cultivation/blocks/package-info.java b/src/main/java/forestry/cultivation/blocks/package-info.java index a48cbbbd69..d43d3e3a68 100644 --- a/src/main/java/forestry/cultivation/blocks/package-info.java +++ b/src/main/java/forestry/cultivation/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.blocks; diff --git a/src/main/java/forestry/cultivation/features/CultivationBlocks.java b/src/main/java/forestry/cultivation/features/CultivationBlocks.java index e2b2b1fcf9..4745773a42 100644 --- a/src/main/java/forestry/cultivation/features/CultivationBlocks.java +++ b/src/main/java/forestry/cultivation/features/CultivationBlocks.java @@ -10,6 +10,6 @@ public class CultivationBlocks { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CULTIVATION); - public static final FeatureBlockGroup MANAGED_PLANTER = REGISTRY.blockGroup(type -> new BlockPlanter(type, false), BlockTypePlanter.VALUES).item(ItemBlockPlanter::new).identifier("managed", FeatureGroup.IdentifierType.SUFFIX).create(); - public static final FeatureBlockGroup MANUAL_PLANTER = REGISTRY.blockGroup(type -> new BlockPlanter(type, true), BlockTypePlanter.VALUES).item(ItemBlockPlanter::new).identifier("manual", FeatureGroup.IdentifierType.SUFFIX).create(); + public static final FeatureBlockGroup MANAGED_PLANTER = REGISTRY.blockGroup(type -> new BlockPlanter(type, false), BlockTypePlanter.values()).item(ItemBlockPlanter::new).identifier("managed", FeatureGroup.IdentifierType.SUFFIX).create(); + public static final FeatureBlockGroup MANUAL_PLANTER = REGISTRY.blockGroup(type -> new BlockPlanter(type, true), BlockTypePlanter.values()).item(ItemBlockPlanter::new).identifier("manual", FeatureGroup.IdentifierType.SUFFIX).create(); } diff --git a/src/main/java/forestry/cultivation/features/CultivationMenuTypes.java b/src/main/java/forestry/cultivation/features/CultivationMenuTypes.java index 435b5674a7..f1d58d22a4 100644 --- a/src/main/java/forestry/cultivation/features/CultivationMenuTypes.java +++ b/src/main/java/forestry/cultivation/features/CultivationMenuTypes.java @@ -1,7 +1,7 @@ package forestry.cultivation.features; import forestry.api.modules.ForestryModuleIds; -import forestry.cultivation.gui.ContainerPlanter; +import forestry.cultivation.gui.PlanterMenu; import forestry.modules.features.FeatureMenuType; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; @@ -11,5 +11,5 @@ public class CultivationMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.CULTIVATION); - public static final FeatureMenuType PLANTER = REGISTRY.menuType(ContainerPlanter::fromNetwork, "planter"); + public static final FeatureMenuType PLANTER = REGISTRY.menuType(PlanterMenu::fromNetwork, "planter"); } diff --git a/src/main/java/forestry/cultivation/features/package-info.java b/src/main/java/forestry/cultivation/features/package-info.java index 60baf6f81f..4b46b7db08 100644 --- a/src/main/java/forestry/cultivation/features/package-info.java +++ b/src/main/java/forestry/cultivation/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.features; diff --git a/src/main/java/forestry/cultivation/gui/GuiPlanter.java b/src/main/java/forestry/cultivation/gui/GuiPlanter.java index 0c4326089e..c152d8f8c4 100644 --- a/src/main/java/forestry/cultivation/gui/GuiPlanter.java +++ b/src/main/java/forestry/cultivation/gui/GuiPlanter.java @@ -5,7 +5,7 @@ import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.cultivation.gui.widgets.GhostItemStackWidget; -import forestry.cultivation.inventory.InventoryPlanter; +import forestry.cultivation.inventory.LegacyFarmInventory; import forestry.cultivation.tiles.TilePlanter; import forestry.farming.gui.FarmLedger; import net.minecraft.client.gui.GuiGraphics; @@ -15,10 +15,10 @@ import java.util.List; -public class GuiPlanter extends GuiForestryTitled { +public class GuiPlanter extends GuiForestryTitled { private final TilePlanter tile; - public GuiPlanter(ContainerPlanter container, Inventory playerInventory, Component title) { + public GuiPlanter(PlanterMenu container, Inventory playerInventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/planter.png", container, playerInventory, title); this.tile = container.getTile(); this.imageWidth = 202; @@ -35,7 +35,7 @@ public GuiPlanter(ContainerPlanter container, Inventory playerInventory, Compone for (int j = 0; j < 2; j++) { int index = j + i * 2; if (resourceStacks.size() == 4) { - this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 11 + j * 18, 65 + i * 18, resourceStacks.get(index), this.getMenu().getSlot(36 + InventoryPlanter.CONFIG.resourcesStart + index))); + this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 11 + j * 18, 65 + i * 18, resourceStacks.get(index), this.getMenu().getSlot(36 + LegacyFarmInventory.CONFIG.resourcesStart + index))); } } } @@ -45,7 +45,7 @@ public GuiPlanter(ContainerPlanter container, Inventory playerInventory, Compone for (int j = 0; j < 2; j++) { int index = j + i * 2; if (germlingStacks.size() == 4) { - this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 71 + j * 18, 65 + i * 18, germlingStacks.get(index), this.getMenu().getSlot(36 + InventoryPlanter.CONFIG.germlingsStart + index))); + this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 71 + j * 18, 65 + i * 18, germlingStacks.get(index), this.getMenu().getSlot(36 + LegacyFarmInventory.CONFIG.germlingsStart + index))); } } } @@ -55,12 +55,12 @@ public GuiPlanter(ContainerPlanter container, Inventory playerInventory, Compone for (int j = 0; j < 2; j++) { int index = j + i * 2; if (productionStacks.size() == 4) { - this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 131 + j * 18, 65 + i * 18, productionStacks.get(index), getMenu().getSlot(36 + InventoryPlanter.CONFIG.productionStart + j + i * 2))); + this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 131 + j * 18, 65 + i * 18, productionStacks.get(index), getMenu().getSlot(36 + LegacyFarmInventory.CONFIG.productionStart + j + i * 2))); } } } - this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 83, 22, CoreItems.FERTILIZER_COMPOUND.stack(), getMenu().getSlot(36 + InventoryPlanter.CONFIG.fertilizerStart))); + this.widgetManager.add(new GhostItemStackWidget(this.widgetManager, 83, 22, CoreItems.FERTILIZER_COMPOUND.stack(), getMenu().getSlot(36 + LegacyFarmInventory.CONFIG.fertilizerStart))); } @Override @@ -73,8 +73,8 @@ protected void addLedgers() { } @Override - protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseY, int mouseX) { - super.renderBg(graphics, partialTicks, mouseY, mouseX); + protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseX, int mouseY) { + super.renderBg(graphics, partialTicks, mouseX, mouseY); // Fuel remaining int fertilizerRemain = this.tile.getStoredFertilizerScaled(16); diff --git a/src/main/java/forestry/cultivation/gui/ContainerPlanter.java b/src/main/java/forestry/cultivation/gui/PlanterMenu.java similarity index 51% rename from src/main/java/forestry/cultivation/gui/ContainerPlanter.java rename to src/main/java/forestry/cultivation/gui/PlanterMenu.java index a279277ae8..448ca8a064 100644 --- a/src/main/java/forestry/cultivation/gui/ContainerPlanter.java +++ b/src/main/java/forestry/cultivation/gui/PlanterMenu.java @@ -1,51 +1,51 @@ package forestry.cultivation.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotLiquidIn; import forestry.core.gui.slots.SlotOutput; import forestry.core.network.packets.PacketGuiStream; import forestry.core.tiles.TileUtil; import forestry.cultivation.features.CultivationMenuTypes; -import forestry.cultivation.inventory.InventoryPlanter; +import forestry.cultivation.inventory.LegacyFarmInventory; import forestry.cultivation.tiles.TilePlanter; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerPlanter extends ContainerLiquidTanks { - public static ContainerPlanter fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { +public class PlanterMenu extends LiquidTanksMenu { + public static PlanterMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { TilePlanter planter = TileUtil.getTile(playerInv.player.level(), extraData.readBlockPos(), TilePlanter.class); - return new ContainerPlanter(windowId, playerInv, planter); + return new PlanterMenu(windowId, playerInv, planter); } - public ContainerPlanter(int windowId, Inventory playerInventory, TilePlanter tileForestry) { + public PlanterMenu(int windowId, Inventory playerInventory, TilePlanter tileForestry) { super(windowId, CultivationMenuTypes.PLANTER.menuType(), playerInventory, tileForestry, 21, 110); // Resources for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { - addSlot(new SlotFiltered(this.tile.getInternalInventory(), InventoryPlanter.CONFIG.resourcesStart + j + i * 2, 11 + j * 18, 65 + i * 18)); + addSlot(new SlotFiltered(this.tile.getInternalInventory(), LegacyFarmInventory.CONFIG.resourcesStart + j + i * 2, 11 + j * 18, 65 + i * 18)); } } // Germlings for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { - addSlot(new SlotFiltered(this.tile.getInternalInventory(), InventoryPlanter.CONFIG.germlingsStart + j + i * 2, 71 + j * 18, 65 + i * 18)); + addSlot(new SlotFiltered(this.tile.getInternalInventory(), LegacyFarmInventory.CONFIG.germlingsStart + j + i * 2, 71 + j * 18, 65 + i * 18)); } } // Production for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { - addSlot(new SlotOutput(this.tile.getInternalInventory(), InventoryPlanter.CONFIG.productionStart + j + i * 2, 131 + j * 18, 65 + i * 18)); + addSlot(new SlotOutput(this.tile.getInternalInventory(), LegacyFarmInventory.CONFIG.productionStart + j + i * 2, 131 + j * 18, 65 + i * 18)); } } // Fertilizer - addSlot(new SlotFiltered(this.tile.getInternalInventory(), InventoryPlanter.CONFIG.fertilizerStart, 83, 22)); + addSlot(new SlotFiltered(this.tile.getInternalInventory(), LegacyFarmInventory.CONFIG.fertilizerStart, 83, 22)); // Can Slot - addSlot(new SlotLiquidIn(this.tile.getInternalInventory(), InventoryPlanter.CONFIG.canStart, 178, 18)); + addSlot(new SlotLiquidIn(this.tile.getInternalInventory(), LegacyFarmInventory.CONFIG.canStart, 178, 18)); } @Override diff --git a/src/main/java/forestry/cultivation/gui/package-info.java b/src/main/java/forestry/cultivation/gui/package-info.java index 608779ca69..000b955575 100644 --- a/src/main/java/forestry/cultivation/gui/package-info.java +++ b/src/main/java/forestry/cultivation/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.gui; diff --git a/src/main/java/forestry/cultivation/gui/widgets/GhostItemStackWidget.java b/src/main/java/forestry/cultivation/gui/widgets/GhostItemStackWidget.java index 694addbbbe..7bf611505b 100644 --- a/src/main/java/forestry/cultivation/gui/widgets/GhostItemStackWidget.java +++ b/src/main/java/forestry/cultivation/gui/widgets/GhostItemStackWidget.java @@ -6,7 +6,7 @@ import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.WidgetManager; import forestry.core.render.ColourProperties; -import forestry.cultivation.inventory.InventoryPlanter; +import forestry.cultivation.inventory.LegacyFarmInventory; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.core.Direction; @@ -50,8 +50,8 @@ public void draw(GuiGraphics graphics, int startX, int startY) { @Nullable private Component getDirectionString() { - if (this.slot.getSlotIndex() >= InventoryPlanter.CONFIG.productionStart - || this.slot.getSlotIndex() < InventoryPlanter.CONFIG.productionStart + InventoryPlanter.CONFIG.productionCount) { + if (this.slot.getSlotIndex() >= LegacyFarmInventory.CONFIG.productionStart + || this.slot.getSlotIndex() < LegacyFarmInventory.CONFIG.productionStart + LegacyFarmInventory.CONFIG.productionCount) { return null; } int index = this.slot.getSlotIndex() % 4; diff --git a/src/main/java/forestry/cultivation/gui/widgets/package-info.java b/src/main/java/forestry/cultivation/gui/widgets/package-info.java index 540e6f0cce..7bf7f71770 100644 --- a/src/main/java/forestry/cultivation/gui/widgets/package-info.java +++ b/src/main/java/forestry/cultivation/gui/widgets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.gui.widgets; diff --git a/src/main/java/forestry/cultivation/inventory/InventoryPlanter.java b/src/main/java/forestry/cultivation/inventory/LegacyFarmInventory.java similarity index 84% rename from src/main/java/forestry/cultivation/inventory/InventoryPlanter.java rename to src/main/java/forestry/cultivation/inventory/LegacyFarmInventory.java index 94da044db0..fca87c3674 100644 --- a/src/main/java/forestry/cultivation/inventory/InventoryPlanter.java +++ b/src/main/java/forestry/cultivation/inventory/LegacyFarmInventory.java @@ -2,6 +2,7 @@ import forestry.api.farming.HorizontalDirection; import forestry.api.farming.IFarmable; +import forestry.core.config.ForestryConfig; import forestry.cultivation.tiles.TilePlanter; import forestry.farming.multiblock.IFarmInventoryInternal; import forestry.farming.multiblock.InventoryPlantation; @@ -10,7 +11,7 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -public class InventoryPlanter extends InventoryPlantation implements IFarmInventoryInternal { +public class LegacyFarmInventory extends InventoryPlantation implements IFarmInventoryInternal { public static InventoryPlantation.InventoryConfig CONFIG = new InventoryPlantation.InventoryConfig( 0, 4, 4, 4, @@ -19,8 +20,8 @@ public class InventoryPlanter extends InventoryPlantation implement 13, 1 ); - public InventoryPlanter(TilePlanter housing) { - super(housing, CONFIG); + public LegacyFarmInventory(TilePlanter housing) { + super(housing, CONFIG, ForestryConfig.SERVER.legacyFarmFertilizerModifier); } @Override diff --git a/src/main/java/forestry/cultivation/inventory/package-info.java b/src/main/java/forestry/cultivation/inventory/package-info.java index b51a916483..5bee18e939 100644 --- a/src/main/java/forestry/cultivation/inventory/package-info.java +++ b/src/main/java/forestry/cultivation/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.inventory; diff --git a/src/main/java/forestry/cultivation/items/ItemBlockPlanter.java b/src/main/java/forestry/cultivation/items/ItemBlockPlanter.java index 4e248d9e8c..017c4431df 100644 --- a/src/main/java/forestry/cultivation/items/ItemBlockPlanter.java +++ b/src/main/java/forestry/cultivation/items/ItemBlockPlanter.java @@ -12,7 +12,7 @@ public ItemBlockPlanter(BlockPlanter block) { @Override public Component getName(ItemStack stack) { - String name = getBlock().blockType.getSerializedName(); + String name = getBlock().blockType.identifier(); return Component.translatable("block.forestry.planter." + (getBlock().isManual() ? "manual" : "managed"), Component.translatable("block.forestry." + name)); } } diff --git a/src/main/java/forestry/cultivation/items/package-info.java b/src/main/java/forestry/cultivation/items/package-info.java index 49cea623d8..4c9f2103db 100644 --- a/src/main/java/forestry/cultivation/items/package-info.java +++ b/src/main/java/forestry/cultivation/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.items; diff --git a/src/main/java/forestry/cultivation/package-info.java b/src/main/java/forestry/cultivation/package-info.java index e8839c6927..517668aa81 100644 --- a/src/main/java/forestry/cultivation/package-info.java +++ b/src/main/java/forestry/cultivation/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation; diff --git a/src/main/java/forestry/cultivation/proxy/CultivationClientHandler.java b/src/main/java/forestry/cultivation/proxy/CultivationClientHandler.java index 1ff72d7ee9..6a3e8c30ea 100644 --- a/src/main/java/forestry/cultivation/proxy/CultivationClientHandler.java +++ b/src/main/java/forestry/cultivation/proxy/CultivationClientHandler.java @@ -1,36 +1,31 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.cultivation.proxy; import forestry.api.client.IClientModuleHandler; import forestry.cultivation.features.CultivationBlocks; import forestry.cultivation.features.CultivationMenuTypes; import forestry.cultivation.gui.GuiPlanter; -import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; public class CultivationClientHandler implements IClientModuleHandler { @Override public void registerEvents(IEventBus modBus) { modBus.addListener(CultivationClientHandler::onClientSetup); + modBus.addListener(CultivationClientHandler::registerMenuScreens); } public static void onClientSetup(FMLClientSetupEvent event) { event.enqueueWork(() -> { + // todo move to model JSON CultivationBlocks.MANAGED_PLANTER.getBlocks().forEach(block -> ItemBlockRenderTypes.setRenderLayer(block, RenderType.cutoutMipped())); CultivationBlocks.MANUAL_PLANTER.getBlocks().forEach(block -> ItemBlockRenderTypes.setRenderLayer(block, RenderType.cutoutMipped())); - MenuScreens.register(CultivationMenuTypes.PLANTER.menuType(), GuiPlanter::new); }); } + + private static void registerMenuScreens(RegisterMenuScreensEvent event) { + event.register(CultivationMenuTypes.PLANTER.menuType(), GuiPlanter::new); + } } diff --git a/src/main/java/forestry/cultivation/proxy/package-info.java b/src/main/java/forestry/cultivation/proxy/package-info.java index 3a76adff0e..e87318ed3c 100644 --- a/src/main/java/forestry/cultivation/proxy/package-info.java +++ b/src/main/java/forestry/cultivation/proxy/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.proxy; diff --git a/src/main/java/forestry/cultivation/tiles/TilePlanter.java b/src/main/java/forestry/cultivation/tiles/TilePlanter.java index bd7416eb1c..cbe584a305 100644 --- a/src/main/java/forestry/cultivation/tiles/TilePlanter.java +++ b/src/main/java/forestry/cultivation/tiles/TilePlanter.java @@ -19,8 +19,8 @@ import forestry.core.utils.PlayerUtil; import forestry.cultivation.IFarmHousingInternal; import forestry.cultivation.blocks.BlockTypePlanter; -import forestry.cultivation.gui.ContainerPlanter; -import forestry.cultivation.inventory.InventoryPlanter; +import forestry.cultivation.gui.PlanterMenu; +import forestry.cultivation.inventory.LegacyFarmInventory; import forestry.farming.FarmHelper; import forestry.farming.FarmManager; import forestry.farming.FarmTarget; @@ -28,9 +28,10 @@ import forestry.farming.multiblock.IFarmInventoryInternal; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; @@ -40,11 +41,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.Collection; @@ -53,7 +51,7 @@ import java.util.Map; public abstract class TilePlanter extends TilePowered implements IFarmHousingInternal, IClimateProvider, ILiquidTankTile, IOwnedTile, IStreamableGui { - private final InventoryPlanter inventory; + private final LegacyFarmInventory inventory; private final OwnerHandler ownerHandler = new OwnerHandler(); private final FarmManager manager; @@ -71,11 +69,11 @@ protected TilePlanter(BlockEntityType type, BlockPos pos, BlockState state, Reso this.properties = Preconditions.checkNotNull(IForestryApi.INSTANCE.getFarmingManager().getFarmType(farmTypeId)); this.manual = false; - this.inventory = new InventoryPlanter(this); + this.inventory = new LegacyFarmInventory(this); setInternalInventory(this.inventory); this.manager = new FarmManager(this); setEnergyPerWorkCycle(10); - setTicksPerWorkCycle(2); + setStepsPerWorkCycle(2); } public void setManual(boolean manual) { @@ -85,7 +83,7 @@ public void setManual(boolean manual) { @Override public Component getDisplayName() { - String name = getBlockType(BlockTypePlanter.ARBORETUM).getSerializedName(); + String name = getBlockType(BlockTypePlanter.ARBORETUM).identifier(); return Component.translatable("block.forestry.planter." + (this.manual ? "manual" : "managed"), Component.translatable("block.forestry." + name)); } @@ -97,45 +95,45 @@ public boolean hasWork() { @Override public void serverTick(Level level, BlockPos pos, BlockState state) { super.serverTick(level, pos, state); - this.manager.getHydrationManager().updateServer(); + this.manager.getHydrationManager().updateServer(); if (updateOnInterval(20)) { - this.inventory.drainCan(this.manager.getTankManager()); + this.inventory.drainCan(this.manager.getTankManager()); } } @Override protected boolean workCycle() { - this.manager.doWork(); + this.manager.doWork(); return false; } @Override - public void saveAdditional(CompoundTag data) { - super.saveAdditional(data); - this.manager.write(data); - this.ownerHandler.write(data); + public void saveAdditional(CompoundTag data, HolderLookup.Provider registries) { + super.saveAdditional(data, registries); + this.manager.write(data, registries); + this.ownerHandler.write(data, registries); data.putBoolean("manual", this.manual); } @Override - public void load(CompoundTag data) { - super.load(data); - this.manager.read(data); - this.ownerHandler.read(data); + public void loadAdditional(CompoundTag data, HolderLookup.Provider registries) { + super.loadAdditional(data, registries); + this.manager.read(data, registries); + this.ownerHandler.read(data, registries); setManual(data.getBoolean("manual")); } @Override - public void writeGuiData(FriendlyByteBuf data) { - super.writeGuiData(data); - this.manager.writeData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + super.writeGuiData(buffer); + this.manager.writeData(buffer); } @Override - public void readGuiData(FriendlyByteBuf data) { - super.readGuiData(data); - this.manager.readData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + super.readGuiData(buffer); + this.manager.readData(buffer); } @@ -176,7 +174,7 @@ public Vec3i getArea() { if (ForestryConfig.SERVER.legacyFarmsUseRings.get()) { basisArea = basisArea + 1 + ForestryConfig.SERVER.legacyFarmsRingSize.get() * 2; } - this.area = new Vec3i(basisArea + ForestryConfig.SERVER.legacyFarmsPlanterRings.get(), 13, basisArea + ForestryConfig.SERVER.legacyFarmsPlanterRings.get()); + this.area = new Vec3i(basisArea + ForestryConfig.SERVER.legacyFarmsPlanterRings.get(), 13, basisArea + ForestryConfig.SERVER.legacyFarmsPlanterRings.get()); } return this.area; } @@ -185,7 +183,7 @@ public Vec3i getArea() { public Vec3i getOffset() { if (this.offset == null) { Vec3i area = getArea(); - this.offset = new Vec3i(-area.getX() / 2, -2, -area.getZ() / 2); + this.offset = new Vec3i(-area.getX() / 2, -2, -area.getZ() / 2); } return this.offset; } @@ -198,12 +196,12 @@ public boolean doWork() { @Override public boolean hasLiquid(FluidStack liquid) { FluidStack drained = this.manager.getResourceTank().drainInternal(liquid, IFluidHandler.FluidAction.SIMULATE); - return liquid.isFluidStackIdentical(drained); + return FluidStack.matches(liquid, drained); } @Override public void removeLiquid(FluidStack liquid) { - this.manager.getResourceTank().drain(liquid.getAmount(), IFluidHandler.FluidAction.EXECUTE); + this.manager.getResourceTank().drain(liquid.getAmount(), IFluidHandler.FluidAction.EXECUTE); } @Override @@ -239,7 +237,7 @@ public IFarmInventoryInternal getFarmInventory() { @Override public void addPendingProduct(ItemStack stack) { - this.manager.addPendingProduct(stack); + this.manager.addPendingProduct(stack); } @Override @@ -272,19 +270,19 @@ public int getStoredFertilizerScaled(int scale) { @Override public void setRemoved() { super.setRemoved(); - this.manager.clearTargets(); + this.manager.clearTargets(); } @Override - public CompoundTag getUpdateTag() { - CompoundTag data = super.getUpdateTag(); - this.manager.write(data); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag data = super.getUpdateTag(registries); + this.manager.write(data, registries); return data; } @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerPlanter(windowId, inv, this); + return new PlanterMenu(windowId, inv, this); } public IFarmLedgerDelegate getFarmLedgerDelegate() { @@ -306,14 +304,6 @@ public ITankManager getTankManager() { return this.manager.getTankManager(); } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(this::getTankManager).cast(); - } - return super.getCapability(capability, facing); - } - public abstract List createGermlingStacks(); public abstract List createResourceStacks(); @@ -332,11 +322,11 @@ public int getExtents(Direction direction, BlockPos pos) { @Override public void setExtents(Direction direction, BlockPos pos, int extend) { - this.manager.setExtents(direction, pos, extend); + this.manager.setExtents(direction, pos, extend); } @Override public void cleanExtents(Direction direction) { - this.manager.cleanExtents(direction); + this.manager.cleanExtents(direction); } } diff --git a/src/main/java/forestry/cultivation/tiles/package-info.java b/src/main/java/forestry/cultivation/tiles/package-info.java index c156bd93ba..4e9bd78ed2 100644 --- a/src/main/java/forestry/cultivation/tiles/package-info.java +++ b/src/main/java/forestry/cultivation/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.cultivation.tiles; diff --git a/src/main/java/forestry/energy/EnergyHelper.java b/src/main/java/forestry/energy/EnergyHelper.java index 0616fa6e2d..78b5d77956 100644 --- a/src/main/java/forestry/energy/EnergyHelper.java +++ b/src/main/java/forestry/energy/EnergyHelper.java @@ -1,19 +1,14 @@ package forestry.energy; -import forestry.core.config.Preference; import forestry.energy.tiles.EngineBlockEntity; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.energy.IEnergyStorage; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.energy.IEnergyStorage; import javax.annotation.Nullable; public class EnergyHelper { - public static int scaleForDifficulty(int energyValue) { - return Math.round(energyValue * Preference.ENERGY_DEMAND_MODIFIER); - } /** * Consumes one work cycle's worth of energy. @@ -58,9 +53,9 @@ private static int sendEnergyToTile(@Nullable BlockEntity tile, Direction side, return receptor.getEnergyManager().forceReceiveEnergy(extractable, simulate); } - return tile.getCapability(ForgeCapabilities.ENERGY, side).map(storage -> { - return storage.receiveEnergy(extractable, simulate); - }).orElse(0); + IEnergyStorage energyStorage = tile.getLevel().getCapability(Capabilities.EnergyStorage.BLOCK, tile.getBlockPos(), side); + + return energyStorage != null ? energyStorage.receiveEnergy(extractable, simulate) : 0; } public static boolean canSendEnergy(ForestryEnergyStorage energyStorage, Direction orientation, BlockEntity tile) { @@ -75,12 +70,8 @@ public static boolean isEnergyReceiverOrEngine(Direction side, @Nullable BlockEn return true; } - LazyOptional energyStorage = tile.getCapability(ForgeCapabilities.ENERGY, side); - if (energyStorage.isPresent()) { - return energyStorage.orElse(null).canReceive(); - } + IEnergyStorage energyStorage = tile.getLevel().getCapability(Capabilities.EnergyStorage.BLOCK, tile.getBlockPos(), side); - return false; + return energyStorage != null && energyStorage.canReceive(); } - } diff --git a/src/main/java/forestry/energy/ForestryEnergyStorage.java b/src/main/java/forestry/energy/ForestryEnergyStorage.java index 74334fac00..08c437cd37 100644 --- a/src/main/java/forestry/energy/ForestryEnergyStorage.java +++ b/src/main/java/forestry/energy/ForestryEnergyStorage.java @@ -3,10 +3,11 @@ import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.core.network.IStreamable; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.util.Mth; -import net.minecraftforge.energy.EnergyStorage; +import net.neoforged.neoforge.energy.EnergyStorage; public class ForestryEnergyStorage extends EnergyStorage implements IStreamable, INbtReadable, INbtWritable { public ForestryEnergyStorage(int maxTransfer, int capacity) { @@ -15,31 +16,31 @@ public ForestryEnergyStorage(int maxTransfer, int capacity) { public ForestryEnergyStorage(int maxTransfer, int capacity, EnergyTransferMode mode) { super( - EnergyHelper.scaleForDifficulty(capacity), - mode.canReceive() ? EnergyHelper.scaleForDifficulty(maxTransfer) : 0, - mode.canExtract() ? EnergyHelper.scaleForDifficulty(maxTransfer) : 0 + capacity, + mode.canReceive() ? maxTransfer : 0, + mode.canExtract() ? maxTransfer : 0 ); } @Override - public void read(CompoundTag nbt) { + public void read(CompoundTag nbt, HolderLookup.Provider registries) { setEnergyStored(nbt.getInt("Energy")); } @Override - public CompoundTag write(CompoundTag nbt) { + public CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries) { nbt.putInt("Energy", this.energy); return nbt; } @Override - public void writeData(FriendlyByteBuf data) { - data.writeVarInt(this.energy); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeVarInt(this.energy); } @Override - public void readData(FriendlyByteBuf data) { - int energyStored = data.readVarInt(); + public void readData(RegistryFriendlyByteBuf buffer) { + int energyStored = buffer.readVarInt(); setEnergyStored(energyStored); } @@ -62,7 +63,7 @@ public void generateEnergy(int amount) { public int forceReceiveEnergy(int maxReceive, boolean simulate) { int energyReceived = Math.min(this.capacity - this.energy, maxReceive); if (!simulate) { - this.energy += energyReceived; + this.energy += energyReceived; } return energyReceived; } diff --git a/src/main/java/forestry/energy/ModuleEnergy.java b/src/main/java/forestry/energy/ModuleEnergy.java index 1d732c01d6..addc96d1a9 100644 --- a/src/main/java/forestry/energy/ModuleEnergy.java +++ b/src/main/java/forestry/energy/ModuleEnergy.java @@ -1,23 +1,17 @@ package forestry.energy; import forestry.api.client.IClientModuleHandler; -import forestry.api.fuels.EngineBronzeFuel; -import forestry.api.fuels.EngineCopperFuel; -import forestry.api.fuels.FuelManager; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.core.config.Constants; -import forestry.core.features.CoreItems; -import forestry.core.fluids.ForestryFluids; -import forestry.core.utils.datastructures.FluidMap; -import forestry.core.utils.datastructures.ItemStackMap; import forestry.energy.client.EnergyClientHandler; +import forestry.energy.features.EnergyTiles; +import forestry.energy.tiles.BiogasEngineBlockEntity; +import forestry.energy.tiles.PeatEngineBlockEntity; import forestry.modules.BlankForestryModule; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.common.ForgeMod; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; import java.util.function.Consumer; @@ -29,40 +23,19 @@ public ResourceLocation getId() { } @Override - public void setupApi() { - FuelManager.biogasEngineFuel = new FluidMap<>(); - FuelManager.peatEngineFuel = new ItemStackMap<>(); - - // Biogas Engine - Fluid biomass = ForestryFluids.BIOMASS.getFluid(); - FuelManager.biogasEngineFuel.put(biomass, new EngineBronzeFuel(biomass, - Constants.ENGINE_FUEL_VALUE_BIOMASS, Constants.ENGINE_CYCLE_DURATION_BIOMASS, 1)); - - FuelManager.biogasEngineFuel.put(Fluids.WATER, new EngineBronzeFuel(Fluids.WATER, - Constants.ENGINE_FUEL_VALUE_WATER, Constants.ENGINE_CYCLE_DURATION_WATER, 3)); - - Fluid milk = ForgeMod.MILK.get(); - FuelManager.biogasEngineFuel.put(milk, new EngineBronzeFuel(milk, - Constants.ENGINE_FUEL_VALUE_MILK, Constants.ENGINE_CYCLE_DURATION_MILK, 3)); - - Fluid seedOil = ForestryFluids.SEED_OIL.getFluid(); - FuelManager.biogasEngineFuel.put(seedOil, new EngineBronzeFuel(seedOil, - Constants.ENGINE_FUEL_VALUE_SEED_OIL, Constants.ENGINE_CYCLE_DURATION_SEED_OIL, 1)); - - Fluid honey = ForestryFluids.HONEY.getFluid(); - FuelManager.biogasEngineFuel.put(honey, new EngineBronzeFuel(honey, - Constants.ENGINE_FUEL_VALUE_HONEY, Constants.ENGINE_CYCLE_DURATION_HONEY, 1)); + public void registerEvents(IEventBus modBus) { + modBus.addListener(ModuleEnergy::registerCapabilities); + } - Fluid juice = ForestryFluids.JUICE.getFluid(); - FuelManager.biogasEngineFuel.put(juice, new EngineBronzeFuel(juice, - Constants.ENGINE_FUEL_VALUE_JUICE, Constants.ENGINE_CYCLE_DURATION_JUICE, 1)); + private static void registerCapabilities(RegisterCapabilitiesEvent event) { + event.registerBlockEntity(Capabilities.EnergyStorage.BLOCK, EnergyTiles.BIOGAS_ENGINE.tileType(), (tile, facing) -> tile.getEnergyManager()); + event.registerBlockEntity(Capabilities.FluidHandler.BLOCK, EnergyTiles.BIOGAS_ENGINE.tileType(), (tile, facing) -> tile.getTankManager()); + event.registerBlockEntity(Capabilities.ItemHandler.BLOCK, EnergyTiles.BIOGAS_ENGINE.tileType(), BiogasEngineBlockEntity::getInventory); - // Peat Engine - ItemStack peat = CoreItems.PEAT.stack(); - FuelManager.peatEngineFuel.put(peat, new EngineCopperFuel(peat, Constants.ENGINE_COPPER_FUEL_VALUE_PEAT, Constants.ENGINE_COPPER_CYCLE_DURATION_PEAT)); + event.registerBlockEntity(Capabilities.EnergyStorage.BLOCK, EnergyTiles.CLOCKWORK_ENGINE.tileType(), (tile, facing) -> tile.getEnergyManager()); - ItemStack bituminousPeat = CoreItems.BITUMINOUS_PEAT.stack(); - FuelManager.peatEngineFuel.put(bituminousPeat, new EngineCopperFuel(bituminousPeat, Constants.ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT, Constants.ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT)); + event.registerBlockEntity(Capabilities.EnergyStorage.BLOCK, EnergyTiles.PEAT_ENGINE.tileType(), (tile, facing) -> tile.getEnergyManager()); + event.registerBlockEntity(Capabilities.ItemHandler.BLOCK, EnergyTiles.PEAT_ENGINE.tileType(), PeatEngineBlockEntity::getInventory); } @Override diff --git a/src/main/java/forestry/energy/blocks/EngineBlockType.java b/src/main/java/forestry/energy/blocks/EngineBlockType.java index 3fcb27c338..845aacdceb 100644 --- a/src/main/java/forestry/energy/blocks/EngineBlockType.java +++ b/src/main/java/forestry/energy/blocks/EngineBlockType.java @@ -12,8 +12,6 @@ public enum EngineBlockType implements IBlockType { BIOGAS(createEngineProperties(EnergyTiles.BIOGAS_ENGINE, "biogas")), CLOCKWORK(createEngineProperties(EnergyTiles.CLOCKWORK_ENGINE, "clockwork")); - public static final EngineBlockType[] VALUES = values(); - private final IMachineProperties machineProperties; EngineBlockType(IMachineProperties machineProperties) { @@ -33,7 +31,7 @@ public IMachineProperties getMachineProperties() { } @Override - public String getSerializedName() { - return getMachineProperties().getSerializedName(); + public String identifier() { + return getMachineProperties().identifier(); } } diff --git a/src/main/java/forestry/energy/blocks/package-info.java b/src/main/java/forestry/energy/blocks/package-info.java index ca09cc5ff8..7d077fa287 100644 --- a/src/main/java/forestry/energy/blocks/package-info.java +++ b/src/main/java/forestry/energy/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy.blocks; diff --git a/src/main/java/forestry/energy/client/EnergyClientHandler.java b/src/main/java/forestry/energy/client/EnergyClientHandler.java index c72470f5ef..fdf40fd853 100644 --- a/src/main/java/forestry/energy/client/EnergyClientHandler.java +++ b/src/main/java/forestry/energy/client/EnergyClientHandler.java @@ -3,20 +3,17 @@ import forestry.energy.features.EnergyMenus; import forestry.energy.screen.BiogasEngineScreen; import forestry.energy.screen.PeatEngineScreen; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; public class EnergyClientHandler implements forestry.api.client.IClientModuleHandler { @Override public void registerEvents(IEventBus modBus) { - modBus.addListener(EnergyClientHandler::setupClient); + modBus.addListener(EnergyClientHandler::registerMenuScreens); } - private static void setupClient(FMLClientSetupEvent event) { - event.enqueueWork(() -> { - MenuScreens.register(EnergyMenus.ENGINE_BIOGAS.menuType(), BiogasEngineScreen::new); - MenuScreens.register(EnergyMenus.ENGINE_PEAT.menuType(), PeatEngineScreen::new); - }); + private static void registerMenuScreens(RegisterMenuScreensEvent event) { + event.register(EnergyMenus.ENGINE_BIOGAS.menuType(), BiogasEngineScreen::new); + event.register(EnergyMenus.ENGINE_PEAT.menuType(), PeatEngineScreen::new); } } diff --git a/src/main/java/forestry/energy/client/package-info.java b/src/main/java/forestry/energy/client/package-info.java index 71b447bdc0..1471a2e3e7 100644 --- a/src/main/java/forestry/energy/client/package-info.java +++ b/src/main/java/forestry/energy/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy.client; diff --git a/src/main/java/forestry/energy/features/EnergyBlocks.java b/src/main/java/forestry/energy/features/EnergyBlocks.java index e66c87cb43..6fc96e87ff 100644 --- a/src/main/java/forestry/energy/features/EnergyBlocks.java +++ b/src/main/java/forestry/energy/features/EnergyBlocks.java @@ -13,5 +13,5 @@ public class EnergyBlocks { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.ENERGY); - public static final FeatureBlockGroup ENGINES = REGISTRY.blockGroup(EngineBlock::new, EngineBlockType.VALUES).item(ItemBlockTesr::new).identifier("engine").create(); + public static final FeatureBlockGroup ENGINES = REGISTRY.blockGroup(EngineBlock::new, EngineBlockType.values()).item(ItemBlockTesr::new).identifier("engine").create(); } diff --git a/src/main/java/forestry/energy/features/package-info.java b/src/main/java/forestry/energy/features/package-info.java index c79afabff8..ecc37f309c 100644 --- a/src/main/java/forestry/energy/features/package-info.java +++ b/src/main/java/forestry/energy/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy.features; diff --git a/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java b/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java index 1f8517d759..87b35abe33 100644 --- a/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java +++ b/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java @@ -1,21 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.energy.inventory; import forestry.core.inventory.InventoryAdapterTile; import forestry.energy.tiles.BiogasEngineBlockEntity; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.Optional; diff --git a/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java b/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java index b70bcbee35..cc0ff36e2d 100644 --- a/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java +++ b/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java @@ -1,20 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.energy.inventory; -import forestry.api.fuels.FuelManager; +import forestry.api.ForestryDataMaps; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.utils.SlotUtil; import forestry.energy.tiles.PeatEngineBlockEntity; import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.item.ItemStack; public class InventoryEnginePeat extends InventoryAdapterTile { @@ -28,7 +19,7 @@ public InventoryEnginePeat(PeatEngineBlockEntity engineCopper) { @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { - return slotIndex == SLOT_FUEL && FuelManager.peatEngineFuel.containsKey(stack); + return slotIndex == SLOT_FUEL && BuiltInRegistries.ITEM.getData(ForestryDataMaps.PEAT_FUELS, stack.getItemHolder().getKey()) != null; } @Override diff --git a/src/main/java/forestry/energy/inventory/package-info.java b/src/main/java/forestry/energy/inventory/package-info.java index c486486a63..18d45a0d9e 100644 --- a/src/main/java/forestry/energy/inventory/package-info.java +++ b/src/main/java/forestry/energy/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy.inventory; diff --git a/src/main/java/forestry/energy/menu/BiogasEngineMenu.java b/src/main/java/forestry/energy/menu/BiogasEngineMenu.java index 5ec295b8a2..1fa0ec33e4 100644 --- a/src/main/java/forestry/energy/menu/BiogasEngineMenu.java +++ b/src/main/java/forestry/energy/menu/BiogasEngineMenu.java @@ -1,6 +1,6 @@ package forestry.energy.menu; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotLiquidIn; import forestry.core.network.packets.PacketGuiStream; import forestry.core.tiles.TileUtil; @@ -10,7 +10,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class BiogasEngineMenu extends ContainerLiquidTanks { +public class BiogasEngineMenu extends LiquidTanksMenu { public static BiogasEngineMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf extraData) { BiogasEngineBlockEntity tile = TileUtil.getTile(inv.player.level(), extraData.readBlockPos(), BiogasEngineBlockEntity.class); return new BiogasEngineMenu(windowId, inv, tile); diff --git a/src/main/java/forestry/energy/menu/PeatEngineMenu.java b/src/main/java/forestry/energy/menu/PeatEngineMenu.java index f345300f89..572c5e6a18 100644 --- a/src/main/java/forestry/energy/menu/PeatEngineMenu.java +++ b/src/main/java/forestry/energy/menu/PeatEngineMenu.java @@ -1,6 +1,6 @@ package forestry.energy.menu; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.network.packets.PacketGuiStream; @@ -10,7 +10,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class PeatEngineMenu extends ContainerTile { +public class PeatEngineMenu extends TileMenu { public static PeatEngineMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf extraData) { PeatEngineBlockEntity tile = TileUtil.getTile(inv.player.level(), extraData.readBlockPos(), PeatEngineBlockEntity.class); return new PeatEngineMenu(windowId, inv, tile); diff --git a/src/main/java/forestry/apiculture/render/package-info.java b/src/main/java/forestry/energy/menu/package-info.java similarity index 52% rename from src/main/java/forestry/apiculture/render/package-info.java rename to src/main/java/forestry/energy/menu/package-info.java index b721960f31..d57fa19cb2 100644 --- a/src/main/java/forestry/apiculture/render/package-info.java +++ b/src/main/java/forestry/energy/menu/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault -package forestry.apiculture.render; +package forestry.energy.menu; diff --git a/src/main/java/forestry/energy/package-info.java b/src/main/java/forestry/energy/package-info.java index 22152b94b7..e283394fa6 100644 --- a/src/main/java/forestry/energy/package-info.java +++ b/src/main/java/forestry/energy/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy; diff --git a/src/main/java/forestry/energy/screen/BiogasSlot.java b/src/main/java/forestry/energy/screen/BiogasSlot.java index d34845150d..a0b763cb93 100644 --- a/src/main/java/forestry/energy/screen/BiogasSlot.java +++ b/src/main/java/forestry/energy/screen/BiogasSlot.java @@ -15,8 +15,8 @@ import forestry.core.gui.widgets.ReservoirWidget; import forestry.core.gui.widgets.WidgetManager; import net.minecraft.network.chat.Component; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; public class BiogasSlot extends ReservoirWidget { public BiogasSlot(WidgetManager manager, int xPos, int yPos, int slot) { diff --git a/src/main/java/forestry/energy/screen/package-info.java b/src/main/java/forestry/energy/screen/package-info.java index a75ec644ad..4b43ed2e2e 100644 --- a/src/main/java/forestry/energy/screen/package-info.java +++ b/src/main/java/forestry/energy/screen/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy.screen; diff --git a/src/main/java/forestry/energy/tiles/BiogasEngineBlockEntity.java b/src/main/java/forestry/energy/tiles/BiogasEngineBlockEntity.java index 3f39c09ac1..365a25355c 100644 --- a/src/main/java/forestry/energy/tiles/BiogasEngineBlockEntity.java +++ b/src/main/java/forestry/energy/tiles/BiogasEngineBlockEntity.java @@ -1,20 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.energy.tiles; +import forestry.api.ForestryDataMaps; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; -import forestry.api.fuels.EngineBronzeFuel; -import forestry.api.fuels.FuelManager; -import forestry.core.config.Constants; +import forestry.api.fuels.BiogasEngineFuel; import forestry.core.fluids.*; import forestry.core.tiles.ILiquidTankTile; import forestry.energy.features.EnergyTiles; @@ -22,8 +11,9 @@ import forestry.energy.menu.BiogasEngineMenu; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -32,21 +22,21 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; -import static net.minecraftforge.fluids.FluidType.BUCKET_VOLUME; +import static net.neoforged.neoforge.fluids.FluidType.BUCKET_VOLUME; public class BiogasEngineBlockEntity extends EngineBlockEntity implements WorldlyContainer, ILiquidTankTile { public static final int ENGINE_BRONZE_HEAT_MAX = 10000; public static final int ENGINE_BRONZE_HEAT_GENERATION_ENERGY = 1; + public static final int ENGINE_HEAT_VALUE_LAVA = 20; + // Energy + public static final int ENGINE_TANK_CAPACITY = 10 * BUCKET_VOLUME; private final FilteredTank fuelTank; private final FilteredTank heatingTank; private final StandardTank burnTank; @@ -54,19 +44,16 @@ public class BiogasEngineBlockEntity extends EngineBlockEntity implements Worldl private boolean shutdown; // true if the engine is too cold and needs to warm itself up. - private final LazyOptional fluidCap; - public BiogasEngineBlockEntity(BlockPos pos, BlockState state) { super(EnergyTiles.BIOGAS_ENGINE.tileType(), pos, state, "engine.bronze", ENGINE_BRONZE_HEAT_MAX, 300000); setInternalInventory(new InventoryEngineBiogas(this)); - this.fuelTank = new FilteredTank(Constants.ENGINE_TANK_CAPACITY).setFilters(FuelManager.biogasEngineFuel.keySet()); - this.heatingTank = new FilteredTank(Constants.ENGINE_TANK_CAPACITY, true, false).setFilter(FluidTagFilter.LAVA); + this.fuelTank = new FilteredTank(ENGINE_TANK_CAPACITY).setFilters(FuelManager.biogasEngineFuel.keySet()); + this.heatingTank = new FilteredTank(ENGINE_TANK_CAPACITY, true, false).setFilter(FluidTagFilter.LAVA); this.burnTank = new StandardTank(BUCKET_VOLUME, false, false); this.tankManager = new TankManager(this, this.fuelTank, this.heatingTank, this.burnTank); - this.fluidCap = LazyOptional.of(() -> this.tankManager); } @Override @@ -103,8 +90,7 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { */ @Override public void burn() { - - this.currentOutput = 0; + this.currentOutput = 0; if (isRedstoneActivated() && (this.fuelTank.getFluidAmount() >= BUCKET_VOLUME || this.burnTank.getFluidAmount() > 0)) { @@ -115,8 +101,8 @@ public void burn() { shutdown(false); } else if (this.shutdown) { if (this.heatingTank.getFluidAmount() > 0 && this.heatingTank.getFluidType() == Fluids.LAVA) { - addHeat(Constants.ENGINE_HEAT_VALUE_LAVA); - this.heatingTank.drainInternal(1, IFluidHandler.FluidAction.EXECUTE); + addHeat(ENGINE_HEAT_VALUE_LAVA); + this.heatingTank.drainInternal(1, IFluidHandler.FluidAction.EXECUTE); } } @@ -124,17 +110,17 @@ public void burn() { if (heatStage > 0.2) { if (this.burnTank.getFluidAmount() > 0) { FluidStack drained = this.burnTank.drainInternal(1, IFluidHandler.FluidAction.EXECUTE); - this.currentOutput = determineFuelValue(drained); - this.energyStorage.generateEnergy(this.currentOutput); - this.level.updateNeighbourForOutputSignal(this.worldPosition, getBlockState().getBlock()); + this.currentOutput = determineFuelValue(drained); + this.energyStorage.generateEnergy(this.currentOutput); + this.level.updateNeighbourForOutputSignal(this.worldPosition, getBlockState().getBlock()); } else { FluidStack fuel = this.fuelTank.drainInternal(BUCKET_VOLUME, IFluidHandler.FluidAction.EXECUTE); int burnTime = determineBurnTime(fuel); if (!fuel.isEmpty()) { fuel.setAmount(burnTime); } - this.burnTank.setCapacity(burnTime); - this.burnTank.setFluid(fuel); + this.burnTank.setCapacity(burnTime); + this.burnTank.setFluid(fuel); } } else { shutdown(true); @@ -143,7 +129,7 @@ public void burn() { } private void shutdown(boolean val) { - this.shutdown = val; + this.shutdown = val; } @Override @@ -167,14 +153,14 @@ public void dissipateHeat() { if (this.fuelTank.getFluidAmount() > 0) { FluidStack fuelFluidStack = this.fuelTank.getFluid(); if (!fuelFluidStack.isEmpty()) { - EngineBronzeFuel fuel = FuelManager.biogasEngineFuel.get(fuelFluidStack.getFluid()); + BiogasEngineFuel fuel = fuelFluidStack.getFluidHolder().getData(ForestryDataMaps.BIOGAS_FUELS); if (fuel != null) { loss = loss * fuel.dissipationMultiplier(); } } } - this.heat -= loss; + this.heat -= loss; } @Override @@ -193,19 +179,17 @@ public void generateHeat() { } } - this.heat += generate; + this.heat += generate; } /** * Returns the fuel value (power per cycle) an item of the passed fluid */ - private static int determineFuelValue(@Nullable FluidStack fluidStack) { - if (fluidStack != null) { - Fluid fluid = fluidStack.getFluid(); - if (FuelManager.biogasEngineFuel.containsKey(fluid)) { - return FuelManager.biogasEngineFuel.get(fluid).powerPerCycle(); - } + private static int determineFuelValue(FluidStack fluidStack) { + BiogasEngineFuel fluid = fluidStack.getFluidHolder().getData(ForestryDataMaps.BIOGAS_FUELS); + if (fluid != null) { + return fluid.powerPerCycle(); } return 0; } @@ -213,17 +197,14 @@ private static int determineFuelValue(@Nullable FluidStack fluidStack) { /** * @return Duration of burn cycle of one bucket */ - private static int determineBurnTime(@Nullable FluidStack fluidStack) { - if (fluidStack != null) { - Fluid fluid = fluidStack.getFluid(); - if (FuelManager.biogasEngineFuel.containsKey(fluid)) { - return FuelManager.biogasEngineFuel.get(fluid).burnDuration(); - } + private static int determineBurnTime(FluidStack fluidStack) { + BiogasEngineFuel fluid = fluidStack.getFluidHolder().getData(ForestryDataMaps.BIOGAS_FUELS); + if (fluid != null) { + return fluid.burnDuration(); } return 0; } - // / STATE INFORMATION @Override protected boolean isBurning() { return mayBurn() && this.burnTank.getFluidAmount() > 0; @@ -243,53 +224,37 @@ public int getOperatingTemperatureScaled(int i) { } @Override - public void load(CompoundTag nbt) { - super.load(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); if (nbt.contains("shutdown")) { - this.shutdown = nbt.getBoolean("shutdown"); + this.shutdown = nbt.getBoolean("shutdown"); } - this.tankManager.read(nbt); + this.tankManager.read(nbt, registries); } @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); nbt.putBoolean("shutdown", this.shutdown); - this.tankManager.write(nbt); + this.tankManager.write(nbt, registries); } - /* NETWORK */ @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - data.writeBoolean(this.shutdown); - this.tankManager.writeData(data); - this.burnTank.writeData(data); - } - - @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.shutdown = data.readBoolean(); - this.tankManager.readData(data); - this.burnTank.readData(data); - } - - @Override - public LazyOptional getCapability(Capability cap, @Nullable Direction facing) { - if (!this.remove && cap == ForgeCapabilities.FLUID_HANDLER) { - return this.fluidCap.cast(); - } - return super.getCapability(cap, facing); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + buffer.writeBoolean(this.shutdown); + this.tankManager.writeData(buffer); + this.burnTank.writeData(buffer); } @Override - public void invalidateCaps() { - super.invalidateCaps(); - this.fluidCap.invalidate(); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.shutdown = buffer.readBoolean(); + this.tankManager.readData(buffer); + this.burnTank.readData(buffer); } @Override diff --git a/src/main/java/forestry/energy/tiles/ClockworkEngineBlockEntity.java b/src/main/java/forestry/energy/tiles/ClockworkEngineBlockEntity.java index 72bb20207c..b76573c1ad 100644 --- a/src/main/java/forestry/energy/tiles/ClockworkEngineBlockEntity.java +++ b/src/main/java/forestry/energy/tiles/ClockworkEngineBlockEntity.java @@ -1,32 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.energy.tiles; -import forestry.core.config.Constants; -import forestry.core.damage.CoreDamageTypes; +import forestry.core.features.CoreDamageTypes; import forestry.core.tiles.TemperatureState; import forestry.energy.features.EnergyTiles; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.util.FakePlayer; import org.jetbrains.annotations.Nullable; public class ClockworkEngineBlockEntity extends EngineBlockEntity { - private final static float WIND_EXHAUSTION = 0.05f; private final static float WIND_TENSION_BASE = 0.5f; private final static int WIND_DELAY = 10; @@ -43,9 +30,9 @@ public ClockworkEngineBlockEntity(BlockPos pos, BlockState state) { } @Override - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { - if (player instanceof FakePlayer) { - return; + public boolean interactNoItem(Level level, Player player, BlockPos pos) { + if (player.isFakePlayer()) { + return false; } if (this.tension <= 0) { @@ -53,7 +40,7 @@ public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { } else if (this.tension < ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) { this.tension += (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE - this.tension) / (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) * WIND_TENSION_BASE; } else { - return; + return false; } player.causeFoodExhaustion(WIND_EXHAUSTION); @@ -63,20 +50,19 @@ public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { this.tension = Math.min(this.tension, ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE); this.delay = WIND_DELAY; sendNetworkUpdate(); + return true; } - /* LOADING & SAVING */ @Override - public void load(CompoundTag nbt) { - super.load(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); this.tension = nbt.getFloat("tension"); } - @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); nbt.putFloat("tension", this.tension); } @@ -128,7 +114,7 @@ protected boolean isBurning() { @Override public TemperatureState getTemperatureState() { - TemperatureState state = TemperatureState.getState(this.heat / 10000, ENGINE_CLOCKWORK_WIND_MAX); + TemperatureState state = TemperatureState.getState(this.heat / 10000.0, ENGINE_CLOCKWORK_WIND_MAX); if (state == TemperatureState.MELTING) { state = TemperatureState.OVERHEATING; } @@ -141,7 +127,7 @@ public float getPistonSpeed() { return 0; } - float fromClockwork = this.tension / ENGINE_CLOCKWORK_WIND_MAX * Constants.ENGINE_PISTON_SPEED_MAX; + float fromClockwork = this.tension / ENGINE_CLOCKWORK_WIND_MAX * EngineBlockEntity.ENGINE_PISTON_SPEED_MAX; fromClockwork = Math.round(fromClockwork * 100f) / 100f; diff --git a/src/main/java/forestry/energy/tiles/EngineBlockEntity.java b/src/main/java/forestry/energy/tiles/EngineBlockEntity.java index bd652f8d45..94802bdf82 100644 --- a/src/main/java/forestry/energy/tiles/EngineBlockEntity.java +++ b/src/main/java/forestry/energy/tiles/EngineBlockEntity.java @@ -1,18 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.energy.tiles; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; -import forestry.core.config.Constants; import forestry.core.network.IStreamableGui; import forestry.core.network.packets.PacketActiveUpdate; import forestry.core.tiles.IActivatable; @@ -25,22 +14,17 @@ import forestry.energy.blocks.EngineBlock; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.energy.IEnergyStorage; - -import javax.annotation.Nullable; public abstract class EngineBlockEntity extends TileBase implements IActivatable, IStreamableGui { + public static final float ENGINE_PISTON_SPEED_MAX = 0.08f; private static final int CANT_SEND_ENERGY_TIME = 20; private boolean active = false; // Used for smp. @@ -61,7 +45,6 @@ public abstract class EngineBlockEntity extends TileBase implements IActivatable protected boolean forceCooldown = false; public float progress; protected final ForestryEnergyStorage energyStorage; - private final LazyOptional energyCap; private final String hintKey; protected EngineBlockEntity(BlockEntityType type, BlockPos pos, BlockState state, String hintKey, int maxHeat, int maxEnergy) { @@ -69,7 +52,6 @@ protected EngineBlockEntity(BlockEntityType type, BlockPos pos, BlockState st this.hintKey = hintKey; this.maxHeat = maxHeat; this.energyStorage = new ForestryEnergyStorage(2000, maxEnergy, EnergyTransferMode.EXTRACT); - this.energyCap = LazyOptional.of(() -> this.energyStorage); } public String getHintKey() { @@ -77,10 +59,10 @@ public String getHintKey() { } protected void addHeat(int i) { - this.heat += i; + this.heat += i; if (this.heat > this.maxHeat) { - this.heat = this.maxHeat; + this.heat = this.maxHeat; } } @@ -98,14 +80,14 @@ protected boolean mayBurn() { @Override public void clientTick(Level level, BlockPos pos, BlockState state) { if (this.stagePiston != 0) { - this.progress += this.pistonSpeedServer; + this.progress += this.pistonSpeedServer; if (this.progress > 1) { - this.stagePiston = 0; - this.progress = 0; + this.stagePiston = 0; + this.progress = 0; } } else if (this.active) { - this.stagePiston = 1; + this.stagePiston = 1; } } @@ -113,9 +95,9 @@ public void clientTick(Level level, BlockPos pos, BlockState state) { public void serverTick(Level level, BlockPos pos, BlockState state) { TemperatureState energyState = getTemperatureState(); if (energyState == TemperatureState.MELTING && this.heat > 0) { - this.forceCooldown = true; + this.forceCooldown = true; } else if (this.forceCooldown && this.heat <= 0) { - this.forceCooldown = false; + this.forceCooldown = false; } IErrorLogic errorLogic = getErrorLogic(); @@ -131,29 +113,29 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { float newPistonSpeed = getPistonSpeed(); if (newPistonSpeed != this.pistonSpeedServer) { - this.pistonSpeedServer = newPistonSpeed; + this.pistonSpeedServer = newPistonSpeed; sendNetworkUpdate(); } if (this.stagePiston != 0) { - this.progress += this.pistonSpeedServer; + this.progress += this.pistonSpeedServer; EnergyHelper.sendEnergy(this.energyStorage, facing, tile); if (this.progress > 0.25 && this.stagePiston == 1) { - this.stagePiston = 2; + this.stagePiston = 2; } else if (this.progress >= 0.5) { - this.progress = 0; - this.stagePiston = 0; + this.progress = 0; + this.stagePiston = 0; } } else if (enabledRedstone && EnergyHelper.isEnergyReceiverOrEngine(facing.getOpposite(), tile)) { if (EnergyHelper.canSendEnergy(this.energyStorage, facing, tile)) { - this.stagePiston = 1; // If we can transfer energy, start running + this.stagePiston = 1; // If we can transfer energy, start running setActive(true); - this.cantSendEnergyCountdown = CANT_SEND_ENERGY_TIME; + this.cantSendEnergyCountdown = CANT_SEND_ENERGY_TIME; } else { if (isActive()) { - this.cantSendEnergyCountdown--; + this.cantSendEnergyCountdown--; if (this.cantSendEnergyCountdown <= 0) { setActive(false); } @@ -169,7 +151,7 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { if (mayBurn()) { burn(); } else { - this.energyStorage.drainEnergy(20); + this.energyStorage.drainEnergy(20); } } @@ -186,7 +168,7 @@ public void setActive(boolean active) { this.active = active; if (!this.level.isClientSide) { - NetworkUtil.sendNetworkPacket(new PacketActiveUpdate(this), this.worldPosition, this.level); + NetworkUtil.sendToPlayersTrackingPos(new PacketActiveUpdate(this), this.worldPosition, (ServerLevel) this.level); } } @@ -217,9 +199,6 @@ public int getHeat() { return this.heat; } - /** - * Returns the current energy state of the engine - */ public TemperatureState getTemperatureState() { return TemperatureState.getState(this.heat, this.maxHeat); } @@ -231,79 +210,66 @@ protected float getPistonSpeed() { case OPERATING_TEMPERATURE -> 0.05f; case RUNNING_HOT -> 0.06f; case OVERHEATING -> 0.07f; - case MELTING -> Constants.ENGINE_PISTON_SPEED_MAX; + case MELTING -> ENGINE_PISTON_SPEED_MAX; default -> 0; }; } - /* SAVING & LOADING */ - @Override - public void load(CompoundTag nbt) { - super.load(nbt); - this.energyStorage.read(nbt); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.energyStorage.read(nbt, registries); - this.heat = nbt.getInt("EngineHeat"); + this.heat = nbt.getInt("EngineHeat"); - this.progress = nbt.getFloat("EngineProgress"); - this.forceCooldown = nbt.getBoolean("ForceCooldown"); + this.progress = nbt.getFloat("EngineProgress"); + this.forceCooldown = nbt.getBoolean("ForceCooldown"); } - @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); - this.energyStorage.write(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.energyStorage.write(nbt, registries); nbt.putInt("EngineHeat", this.heat); nbt.putFloat("EngineProgress", this.progress); nbt.putBoolean("ForceCooldown", this.forceCooldown); } - /* NETWORK */ @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - data.writeBoolean(this.active); - data.writeInt(this.heat); - data.writeFloat(this.pistonSpeedServer); - this.energyStorage.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + buffer.writeBoolean(this.active); + buffer.writeInt(this.heat); + buffer.writeFloat(this.pistonSpeedServer); + this.energyStorage.writeData(buffer); } @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.active = data.readBoolean(); - this.heat = data.readInt(); - this.pistonSpeedServer = data.readFloat(); - this.energyStorage.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.active = buffer.readBoolean(); + this.heat = buffer.readInt(); + this.pistonSpeedServer = buffer.readFloat(); + this.energyStorage.readData(buffer); } @Override - public void writeGuiData(FriendlyByteBuf data) { - data.writeInt(this.currentOutput); - data.writeInt(this.heat); - data.writeBoolean(this.forceCooldown); - this.energyStorage.writeData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + buffer.writeInt(this.currentOutput); + buffer.writeInt(this.heat); + buffer.writeBoolean(this.forceCooldown); + this.energyStorage.writeData(buffer); } @Override - public void readGuiData(FriendlyByteBuf data) { - this.currentOutput = data.readInt(); - this.heat = data.readInt(); - this.forceCooldown = data.readBoolean(); - this.energyStorage.readData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.currentOutput = buffer.readInt(); + this.heat = buffer.readInt(); + this.forceCooldown = buffer.readBoolean(); + this.energyStorage.readData(buffer); } public ForestryEnergyStorage getEnergyManager() { return this.energyStorage; } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction side) { - if (!this.remove && capability == ForgeCapabilities.ENERGY && side == getBlockState().getValue(EngineBlock.VERTICAL_FACING)) { - return this.energyCap.cast(); - } - return super.getCapability(capability, side); - } } diff --git a/src/main/java/forestry/energy/tiles/PeatEngineBlockEntity.java b/src/main/java/forestry/energy/tiles/PeatEngineBlockEntity.java index 3e064004fa..1412312462 100644 --- a/src/main/java/forestry/energy/tiles/PeatEngineBlockEntity.java +++ b/src/main/java/forestry/energy/tiles/PeatEngineBlockEntity.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.energy.tiles; +import forestry.api.ForestryDataMaps; import forestry.api.core.ForestryError; -import forestry.api.fuels.FuelManager; -import forestry.core.config.Constants; +import forestry.api.fuels.PeatEngineFuel; import forestry.core.features.CoreItems; import forestry.core.inventory.IInventoryAdapter; import forestry.core.tiles.TemperatureState; @@ -20,8 +10,9 @@ import forestry.energy.inventory.InventoryEnginePeat; import forestry.energy.menu.PeatEngineMenu; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -33,6 +24,8 @@ import javax.annotation.Nullable; public class PeatEngineBlockEntity extends EngineBlockEntity implements WorldlyContainer { + public static final int ENGINE_COPPER_HEAT_MAX = 10000; + public static final int ENGINE_COPPER_ASH_FOR_ITEM = 7500; private ItemStack fuel = ItemStack.EMPTY; private int burnTime; private int totalBurnTime; @@ -40,9 +33,9 @@ public class PeatEngineBlockEntity extends EngineBlockEntity implements WorldlyC private final int ashForItem; public PeatEngineBlockEntity(BlockPos pos, BlockState state) { - super(EnergyTiles.PEAT_ENGINE.tileType(), pos, state, "engine.copper", Constants.ENGINE_COPPER_HEAT_MAX, 200000); + super(EnergyTiles.PEAT_ENGINE.tileType(), pos, state, "engine.copper", ENGINE_COPPER_HEAT_MAX, 200000); - this.ashForItem = Constants.ENGINE_COPPER_ASH_FOR_ITEM; + this.ashForItem = ENGINE_COPPER_ASH_FOR_ITEM; setInternalInventory(new InventoryEnginePeat(this)); } @@ -92,7 +85,6 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { @Override public void burn() { - this.currentOutput = 0; if (this.burnTime > 0) { @@ -142,7 +134,6 @@ public void dissipateHeat() { @Override public void generateHeat() { - int heatToAdd = 0; if (isBurning()) { @@ -156,7 +147,6 @@ public void generateHeat() { } private void addAsh(int amount) { - this.ashProduction += amount; if (this.ashProduction < this.ashForItem) { return; @@ -180,23 +170,17 @@ private void addAsh(int amount) { /** * Returns the fuel value (power per cycle) an item of the passed ItemStack provides */ - private static int determineFuelValue(ItemStack fuel) { - if (FuelManager.peatEngineFuel.containsKey(fuel)) { - return FuelManager.peatEngineFuel.get(fuel).powerPerCycle(); - } else { - return 0; - } + private static int determineFuelValue(ItemStack stack) { + PeatEngineFuel fuel = stack.getItemHolder().getData(ForestryDataMaps.PEAT_FUELS); + return fuel != null ? fuel.powerPerCycle() : 0; } /** * Returns the fuel value (power per cycle) an item of the passed ItemStack provides */ - private static int determineBurnDuration(ItemStack fuel) { - if (FuelManager.peatEngineFuel.containsKey(fuel)) { - return FuelManager.peatEngineFuel.get(fuel).burnDuration(); - } else { - return 0; - } + private static int determineBurnDuration(ItemStack stack) { + PeatEngineFuel fuel = stack.getItemHolder().getData(ForestryDataMaps.PEAT_FUELS); + return fuel != null ? fuel.burnDuration() : 0; } // / STATE INFORMATION @@ -227,28 +211,27 @@ public boolean hasFuelMin(float percentage) { // / LOADING AND SAVING @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - if (compoundNBT.contains("EngineFuelItemStack")) { - CompoundTag fuelItemNbt = compoundNBT.getCompound("EngineFuelItemStack"); - this.fuel = ItemStack.of(fuelItemNbt); + if (nbt.contains("EngineFuelItemStack")) { + this.fuel = ItemStack.parseOptional(registries, nbt.getCompound("EngineFuelItemStack")); } - this.burnTime = compoundNBT.getInt("EngineBurnTime"); - this.totalBurnTime = compoundNBT.getInt("EngineTotalTime"); - if (compoundNBT.contains("AshProduction")) { - this.ashProduction = compoundNBT.getInt("AshProduction"); + this.burnTime = nbt.getInt("EngineBurnTime"); + this.totalBurnTime = nbt.getInt("EngineTotalTime"); + if (nbt.contains("AshProduction")) { + this.ashProduction = nbt.getInt("AshProduction"); } } @Override - public void saveAdditional(CompoundTag nbt) { - super.saveAdditional(nbt); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); if (!this.fuel.isEmpty()) { - nbt.put("EngineFuelItemStack", this.fuel.serializeNBT()); + nbt.put("EngineFuelItemStack", this.fuel.save(registries)); } nbt.putInt("EngineBurnTime", this.burnTime); @@ -257,17 +240,17 @@ public void saveAdditional(CompoundTag nbt) { } @Override - public void writeGuiData(FriendlyByteBuf data) { - super.writeGuiData(data); - data.writeInt(this.burnTime); - data.writeInt(this.totalBurnTime); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + super.writeGuiData(buffer); + buffer.writeInt(this.burnTime); + buffer.writeInt(this.totalBurnTime); } @Override - public void readGuiData(FriendlyByteBuf data) { - super.readGuiData(data); - this.burnTime = data.readInt(); - this.totalBurnTime = data.readInt(); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + super.readGuiData(buffer); + this.burnTime = buffer.readInt(); + this.totalBurnTime = buffer.readInt(); } @Nullable diff --git a/src/main/java/forestry/energy/tiles/package-info.java b/src/main/java/forestry/energy/tiles/package-info.java index 756988da46..bd457e93bc 100644 --- a/src/main/java/forestry/energy/tiles/package-info.java +++ b/src/main/java/forestry/energy/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.energy.tiles; diff --git a/src/main/java/forestry/factory/ModuleFactory.java b/src/main/java/forestry/factory/ModuleFactory.java index d7f1096c72..b92c14a01b 100644 --- a/src/main/java/forestry/factory/ModuleFactory.java +++ b/src/main/java/forestry/factory/ModuleFactory.java @@ -14,23 +14,20 @@ import forestry.api.fuels.FermenterFuel; import forestry.api.fuels.FuelManager; import forestry.api.fuels.MoistenerFuel; -import forestry.api.fuels.RainSubstrate; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.api.modules.IPacketRegistry; -import forestry.core.config.Preference; import forestry.core.features.CoreItems; import forestry.core.network.PacketIdClient; import forestry.core.network.PacketIdServer; -import forestry.core.utils.datastructures.ItemStackMap; import forestry.factory.client.FactoryClientHandler; import forestry.factory.network.packets.PacketRecipeTransferRequest; import forestry.factory.network.packets.PacketRecipeTransferUpdate; import forestry.modules.BlankForestryModule; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.function.Consumer; @@ -41,10 +38,6 @@ public ResourceLocation getId() { return ForestryModuleIds.FACTORY; } - @Override - public void registerEvents(IEventBus modBus) { - } - @Override public void registerClientHandler(Consumer registrar) { registrar.accept(new FactoryClientHandler()); @@ -52,17 +45,13 @@ public void registerClientHandler(Consumer registrar) { @Override public void setupApi() { - FuelManager.fermenterFuel = new ItemStackMap<>(); - FuelManager.moistenerResource = new ItemStackMap<>(); - FuelManager.rainSubstrate = new ItemStackMap<>(); - // Set fuels and resources for the fermenter ItemStack fertilizerCompound = CoreItems.FERTILIZER_COMPOUND.stack(); FuelManager.fermenterFuel.put(fertilizerCompound, new FermenterFuel(fertilizerCompound, - Preference.FERMENTED_CYCLE_FERTILIZER, Preference.FERMENTATION_DURATION_FERTILIZER)); + 56, 200)); - int cyclesCompost = Preference.FERMENTATION_DURATION_COMPOST; - int valueCompost = Preference.FERMENTED_CYCLE_COMPOST; + int cyclesCompost = 250; + int valueCompost = 48; ItemStack fertilizerBio = CoreItems.COMPOST.stack(); ItemStack mulch = CoreItems.MULCH.stack(); FuelManager.fermenterFuel.put(fertilizerBio, new FermenterFuel(fertilizerBio, valueCompost, cyclesCompost)); @@ -75,17 +64,11 @@ public void setupApi() { FuelManager.moistenerResource.put(wheat, new MoistenerFuel(wheat, mouldyWheat, 0, 300)); FuelManager.moistenerResource.put(mouldyWheat, new MoistenerFuel(mouldyWheat, decayingWheat, 1, 600)); FuelManager.moistenerResource.put(decayingWheat, new MoistenerFuel(decayingWheat, mulch, 2, 900)); - - // Set rain substrates - ItemStack iodineCharge = CoreItems.IODINE_CHARGE.stack(); - ItemStack dissipationCharge = CoreItems.DISSIPATION_CHARGE.stack(); - FuelManager.rainSubstrate.put(iodineCharge, new RainSubstrate(iodineCharge, 10000, 0.01f)); - FuelManager.rainSubstrate.put(dissipationCharge, new RainSubstrate(dissipationCharge, 0.075f)); } @Override - public void registerPackets(IPacketRegistry registry) { - registry.serverbound(PacketIdServer.RECIPE_TRANSFER_REQUEST, PacketRecipeTransferRequest.class, PacketRecipeTransferRequest::decode, PacketRecipeTransferRequest::handle); - registry.clientbound(PacketIdClient.RECIPE_TRANSFER_UPDATE, PacketRecipeTransferUpdate.class, PacketRecipeTransferUpdate::decode, PacketRecipeTransferUpdate::handle); + public void registerPackets(PayloadRegistrar registrar) { + registrar.playToServer(PacketIdServer.RECIPE_TRANSFER_REQUEST, StreamCodec.of(PacketRecipeTransferRequest::encode, PacketRecipeTransferRequest::decode), PacketRecipeTransferRequest::handle); + registrar.playToClient(PacketIdClient.RECIPE_TRANSFER_UPDATE, StreamCodec.of(PacketRecipeTransferUpdate::encode, PacketRecipeTransferUpdate::decode), PacketRecipeTransferUpdate::handle); } } diff --git a/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java b/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java index 3c38ccfe72..3c6f7322f4 100644 --- a/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java +++ b/src/main/java/forestry/factory/blocks/BlockFactoryPlain.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.blocks; import forestry.core.blocks.BlockBase; diff --git a/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java b/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java index cdf9126062..fab4435ea9 100644 --- a/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java +++ b/src/main/java/forestry/factory/blocks/BlockFactoryTESR.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.blocks; import forestry.core.blocks.BlockBase; diff --git a/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java b/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java index b81ad911d1..f887299ad2 100644 --- a/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java +++ b/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java @@ -1,20 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.blocks; -import forestry.core.blocks.BlockBase; import forestry.core.blocks.IBlockType; import forestry.core.blocks.IMachineProperties; import forestry.core.blocks.MachineProperties; -import forestry.core.config.Constants; import forestry.core.tiles.IForestryTicker; import forestry.core.tiles.TileBase; import forestry.core.tiles.TileMill; @@ -23,6 +11,7 @@ import forestry.modules.features.FeatureTileType; import net.minecraft.core.Direction; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; @@ -36,7 +25,7 @@ public enum BlockTypeFactoryTesr implements IBlockType { MOISTENER(FactoryTiles.MOISTENER, "moistener", TileMoistener::serverTick), SQUEEZER(FactoryTiles.SQUEEZER, "squeezer", TileSqueezer::serverTick), STILL(FactoryTiles.STILL, "still", TileStill::serverTick), - RAINMAKER(FactoryTiles.RAINMAKER, "rainmaker", Constants.TEXTURE_PATH_BLOCK + "/rainmaker_"); + RAINMAKER(FactoryTiles.RAINMAKER, "rainmaker"); private final IMachineProperties machineProperties; @@ -53,13 +42,13 @@ BlockTypeFactoryTesr(FeatureTileType teClass, String nam this.machineProperties = new MachineProperties.Builder<>(teClass, name) .setServerTicker(serverTicker) .setShape((state, reader, pos, context) -> { - Direction direction = state.getValue(BlockBase.FACING); + Direction direction = state.getValue(HorizontalDirectionalBlock.FACING); return (direction == Direction.NORTH || direction == Direction.SOUTH) ? ns : ew; }) .create(); } - BlockTypeFactoryTesr(FeatureTileType teClass, String name, String renderMillTexture) { + BlockTypeFactoryTesr(FeatureTileType teClass, String name) { final VoxelShape pedestal = Block.box(0D, 0D, 0D, 16, 1, 16); final VoxelShape column = Block.box(5D, 1D, 4D, 11, 16, 12); final VoxelShape extension = Block.box(1D, 8D, 7D, 15, 10, 9); @@ -77,7 +66,7 @@ public IMachineProperties getMachineProperties() { } @Override - public String getSerializedName() { - return getMachineProperties().getSerializedName(); + public String identifier() { + return getMachineProperties().identifier(); } } diff --git a/src/main/java/forestry/factory/blocks/package-info.java b/src/main/java/forestry/factory/blocks/package-info.java index b3a0e4c4cb..7441b2b7b5 100644 --- a/src/main/java/forestry/factory/blocks/package-info.java +++ b/src/main/java/forestry/factory/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.blocks; diff --git a/src/main/java/forestry/factory/circuits/package-info.java b/src/main/java/forestry/factory/circuits/package-info.java index 41c8fd769e..d879b5a173 100644 --- a/src/main/java/forestry/factory/circuits/package-info.java +++ b/src/main/java/forestry/factory/circuits/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.circuits; diff --git a/src/main/java/forestry/factory/client/package-info.java b/src/main/java/forestry/factory/client/package-info.java index 25829bc425..a64e30c889 100644 --- a/src/main/java/forestry/factory/client/package-info.java +++ b/src/main/java/forestry/factory/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.client; diff --git a/src/main/java/forestry/factory/features/FactoryMenuTypes.java b/src/main/java/forestry/factory/features/FactoryMenuTypes.java index 6a0f9da0fb..90803dd81d 100644 --- a/src/main/java/forestry/factory/features/FactoryMenuTypes.java +++ b/src/main/java/forestry/factory/features/FactoryMenuTypes.java @@ -11,13 +11,13 @@ public class FactoryMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.FACTORY); - public static final FeatureMenuType BOTTLER = REGISTRY.menuType(ContainerBottler::fromNetwork, "bottler"); - public static final FeatureMenuType CARPENTER = REGISTRY.menuType(ContainerCarpenter::fromNetwork, "carpenter"); - public static final FeatureMenuType CENTRIFUGE = REGISTRY.menuType(ContainerCentrifuge::fromNetwork, "centrifuge"); - public static final FeatureMenuType FABRICATOR = REGISTRY.menuType(ContainerFabricator::fromNetwork, "fabricator"); - public static final FeatureMenuType FERMENTER = REGISTRY.menuType(ContainerFermenter::fromNetwork, "fermenter"); - public static final FeatureMenuType MOISTENER = REGISTRY.menuType(ContainerMoistener::fromNetwork, "moistener"); - public static final FeatureMenuType RAINTANK = REGISTRY.menuType(ContainerRaintank::fromNetwork, "raintank"); - public static final FeatureMenuType SQUEEZER = REGISTRY.menuType(ContainerSqueezer::fromNetwork, "squeezer"); - public static final FeatureMenuType STILL = REGISTRY.menuType(ContainerStill::fromNetwork, "still"); + public static final FeatureMenuType BOTTLER = REGISTRY.menuType(BottlerMenu::fromNetwork, "bottler"); + public static final FeatureMenuType CARPENTER = REGISTRY.menuType(CarpenterMenu::fromNetwork, "carpenter"); + public static final FeatureMenuType CENTRIFUGE = REGISTRY.menuType(CentrifugeMenu::fromNetwork, "centrifuge"); + public static final FeatureMenuType FABRICATOR = REGISTRY.menuType(FabricatorMenu::fromNetwork, "fabricator"); + public static final FeatureMenuType FERMENTER = REGISTRY.menuType(FermenterMenu::fromNetwork, "fermenter"); + public static final FeatureMenuType MOISTENER = REGISTRY.menuType(MoistenerMenu::fromNetwork, "moistener"); + public static final FeatureMenuType RAINTANK = REGISTRY.menuType(RaintankMenu::fromNetwork, "raintank"); + public static final FeatureMenuType SQUEEZER = REGISTRY.menuType(SqueezerMenu::fromNetwork, "squeezer"); + public static final FeatureMenuType STILL = REGISTRY.menuType(StillMenu::fromNetwork, "still"); } diff --git a/src/main/java/forestry/factory/features/FactoryRecipeTypes.java b/src/main/java/forestry/factory/features/FactoryRecipeTypes.java index fed2b5c52d..fad7dfe98c 100644 --- a/src/main/java/forestry/factory/features/FactoryRecipeTypes.java +++ b/src/main/java/forestry/factory/features/FactoryRecipeTypes.java @@ -16,7 +16,7 @@ public class FactoryRecipeTypes { public static final FeatureRecipeType CARPENTER = REGISTRY.recipeType("carpenter", CarpenterRecipe.Serializer::new); public static final FeatureRecipeType CENTRIFUGE = REGISTRY.recipeType("centrifuge", CentrifugeRecipe.Serializer::new); public static final FeatureRecipeType FABRICATOR = REGISTRY.recipeType("fabricator", FabricatorRecipe.Serializer::new); - public static final FeatureRecipeType FABRICATOR_SMELTING = REGISTRY.recipeType("fabricator_smelting", FabricatorSmeltingRecipe.Serializer::new); + public static final FeatureRecipeType FABRICATOR_SMELTING = REGISTRY.recipeType("fabricator_smelting", FabricatorSmeltingRecipe.Serializer::new); public static final FeatureRecipeType FERMENTER = REGISTRY.recipeType("fermenter", FermenterRecipe.Serializer::new); public static final FeatureRecipeType HYGROREGULATOR = REGISTRY.recipeType("hygroregulator", HygroregulatorRecipe.Serializer::new); public static final FeatureRecipeType MOISTENER = REGISTRY.recipeType("moistener", MoistenerRecipe.Serializer::new); diff --git a/src/main/java/forestry/factory/features/package-info.java b/src/main/java/forestry/factory/features/package-info.java index 76852afc58..39e0965907 100644 --- a/src/main/java/forestry/factory/features/package-info.java +++ b/src/main/java/forestry/factory/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.features; diff --git a/src/main/java/forestry/factory/gui/ContainerBottler.java b/src/main/java/forestry/factory/gui/BottlerMenu.java old mode 100755 new mode 100644 similarity index 84% rename from src/main/java/forestry/factory/gui/ContainerBottler.java rename to src/main/java/forestry/factory/gui/BottlerMenu.java index 2889dc2ffd..a6684b253e --- a/src/main/java/forestry/factory/gui/ContainerBottler.java +++ b/src/main/java/forestry/factory/gui/BottlerMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotEmptyLiquidContainerIn; import forestry.core.gui.slots.SlotLiquidIn; import forestry.core.gui.slots.SlotOutput; @@ -21,13 +21,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerBottler extends ContainerLiquidTanks { - public static ContainerBottler fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class BottlerMenu extends LiquidTanksMenu { + public static BottlerMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileBottler tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileBottler.class); - return new ContainerBottler(windowId, inv, tile); + return new BottlerMenu(windowId, inv, tile); } - public ContainerBottler(int windowId, Inventory player, TileBottler tile) { + public BottlerMenu(int windowId, Inventory player, TileBottler tile) { super(windowId, FactoryMenuTypes.BOTTLER.menuType(), player, tile, 8, 84); this.addSlot(new SlotLiquidIn(tile, InventoryBottler.SLOT_INPUT_FULL_CONTAINER, 18, 7)); diff --git a/src/main/java/forestry/factory/gui/ContainerCarpenter.java b/src/main/java/forestry/factory/gui/CarpenterMenu.java old mode 100755 new mode 100644 similarity index 87% rename from src/main/java/forestry/factory/gui/ContainerCarpenter.java rename to src/main/java/forestry/factory/gui/CarpenterMenu.java index f38e0e028f..a03768658f --- a/src/main/java/forestry/factory/gui/ContainerCarpenter.java +++ b/src/main/java/forestry/factory/gui/CarpenterMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.IContainerCrafting; import forestry.core.gui.slots.*; import forestry.core.network.packets.PacketItemStackDisplay; @@ -24,15 +24,15 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -public class ContainerCarpenter extends ContainerLiquidTanks implements IContainerCrafting { +public class CarpenterMenu extends LiquidTanksMenu implements IContainerCrafting { private ItemStack oldCraftPreview = ItemStack.EMPTY; - public static ContainerCarpenter fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + public static CarpenterMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileCarpenter tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileCarpenter.class); - return new ContainerCarpenter(windowId, inv, tile); + return new CarpenterMenu(windowId, inv, tile); } - public ContainerCarpenter(int windowId, Inventory inventoryplayer, TileCarpenter tile) { + public CarpenterMenu(int windowId, Inventory inventoryplayer, TileCarpenter tile) { super(windowId, FactoryMenuTypes.CARPENTER.menuType(), inventoryplayer, tile, 8, 136); // Internal inventory diff --git a/src/main/java/forestry/factory/gui/ContainerCentrifuge.java b/src/main/java/forestry/factory/gui/CentrifugeMenu.java old mode 100755 new mode 100644 similarity index 85% rename from src/main/java/forestry/factory/gui/ContainerCentrifuge.java rename to src/main/java/forestry/factory/gui/CentrifugeMenu.java index ae5c733d8b..b503fab13d --- a/src/main/java/forestry/factory/gui/ContainerCentrifuge.java +++ b/src/main/java/forestry/factory/gui/CentrifugeMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerSocketed; +import forestry.core.gui.SocketedMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotLocked; import forestry.core.gui.slots.SlotOutput; @@ -23,15 +23,15 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; -public class ContainerCentrifuge extends ContainerSocketed { +public class CentrifugeMenu extends SocketedMenu { private ItemStack oldCraftPreview = ItemStack.EMPTY; - public static ContainerCentrifuge fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + public static CentrifugeMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileCentrifuge tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileCentrifuge.class); - return new ContainerCentrifuge(windowId, inv, tile); + return new CentrifugeMenu(windowId, inv, tile); } - public ContainerCentrifuge(int windowId, Inventory player, TileCentrifuge tile) { + public CentrifugeMenu(int windowId, Inventory player, TileCentrifuge tile) { super(windowId, FactoryMenuTypes.CENTRIFUGE.menuType(), player, tile, 8, 84); // Resource diff --git a/src/main/java/forestry/factory/gui/ContainerFabricator.java b/src/main/java/forestry/factory/gui/FabricatorMenu.java old mode 100755 new mode 100644 similarity index 87% rename from src/main/java/forestry/factory/gui/ContainerFabricator.java rename to src/main/java/forestry/factory/gui/FabricatorMenu.java index 1f6ea44fb4..c6139ab27e --- a/src/main/java/forestry/factory/gui/ContainerFabricator.java +++ b/src/main/java/forestry/factory/gui/FabricatorMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.IContainerCrafting; import forestry.core.gui.slots.SlotCraftMatrix; import forestry.core.gui.slots.SlotFiltered; @@ -27,13 +27,13 @@ import net.minecraft.world.inventory.SimpleContainerData; import net.minecraft.world.inventory.Slot; -public class ContainerFabricator extends ContainerLiquidTanks implements IContainerCrafting { - public static ContainerFabricator fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class FabricatorMenu extends LiquidTanksMenu implements IContainerCrafting { + public static FabricatorMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileFabricator tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileFabricator.class); - return new ContainerFabricator(windowId, inv, tile); + return new FabricatorMenu(windowId, inv, tile); } - public ContainerFabricator(int windowId, Inventory playerInventory, TileFabricator tile) { + public FabricatorMenu(int windowId, Inventory playerInventory, TileFabricator tile) { super(windowId, FactoryMenuTypes.FABRICATOR.menuType(), playerInventory, tile, 8, 129); addDataSlots(new SimpleContainerData(4)); diff --git a/src/main/java/forestry/factory/gui/ContainerFermenter.java b/src/main/java/forestry/factory/gui/FermenterMenu.java old mode 100755 new mode 100644 similarity index 52% rename from src/main/java/forestry/factory/gui/ContainerFermenter.java rename to src/main/java/forestry/factory/gui/FermenterMenu.java index 210e039674..3696554420 --- a/src/main/java/forestry/factory/gui/ContainerFermenter.java +++ b/src/main/java/forestry/factory/gui/FermenterMenu.java @@ -1,16 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotEmptyLiquidContainerIn; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotLiquidIn; @@ -21,18 +11,15 @@ import forestry.factory.tiles.TileFermenter; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.ContainerListener; import net.minecraft.world.inventory.SimpleContainerData; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -public class ContainerFermenter extends ContainerLiquidTanks { - public static ContainerFermenter fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class FermenterMenu extends LiquidTanksMenu { + public static FermenterMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileFermenter tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileFermenter.class); - return new ContainerFermenter(windowId, inv, tile); + return new FermenterMenu(windowId, inv, tile); } - public ContainerFermenter(int windowId, Inventory player, TileFermenter tile) { + public FermenterMenu(int windowId, Inventory player, TileFermenter tile) { super(windowId, FactoryMenuTypes.FERMENTER.menuType(), player, tile, 8, 84); addDataSlots(new SimpleContainerData(4)); @@ -44,19 +31,19 @@ public ContainerFermenter(int windowId, Inventory player, TileFermenter tile) { } @Override - @OnlyIn(Dist.CLIENT) public void setData(int messageId, int data) { super.setData(messageId, data); - this.tile.getGUINetworkData(messageId, data); + this.tile.getGUINetworkData(messageId, data); } @Override public void broadcastChanges() { super.broadcastChanges(); - for (ContainerListener crafter : this.containerListeners) { - this.tile.sendGUINetworkData(this, crafter); - } + // todo is this used? + //for (ContainerListener crafter : this.containerListeners) { + // this.tile.sendGUINetworkData(this, crafter); + //} } } diff --git a/src/main/java/forestry/factory/gui/GuiBottler.java b/src/main/java/forestry/factory/gui/GuiBottler.java index e6986d6155..037372daf8 100755 --- a/src/main/java/forestry/factory/gui/GuiBottler.java +++ b/src/main/java/forestry/factory/gui/GuiBottler.java @@ -20,10 +20,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiBottler extends GuiForestryTitled { +public class GuiBottler extends GuiForestryTitled { private final TileBottler tile; - public GuiBottler(ContainerBottler container, Inventory inventory, Component title) { + public GuiBottler(BottlerMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/bottler.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new TankWidget(this.widgetManager, 80, 14, 0)); diff --git a/src/main/java/forestry/factory/gui/GuiCarpenter.java b/src/main/java/forestry/factory/gui/GuiCarpenter.java index e393ff5a24..070dba4b43 100755 --- a/src/main/java/forestry/factory/gui/GuiCarpenter.java +++ b/src/main/java/forestry/factory/gui/GuiCarpenter.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiCarpenter extends GuiForestryTitled { +public class GuiCarpenter extends GuiForestryTitled { private final TileCarpenter tile; - public GuiCarpenter(ContainerCarpenter container, Inventory inventory, Component title) { + public GuiCarpenter(CarpenterMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/carpenter.png", container, inventory, title); this.tile = container.getTile(); diff --git a/src/main/java/forestry/factory/gui/GuiCentrifuge.java b/src/main/java/forestry/factory/gui/GuiCentrifuge.java index 3e109d59f1..05865fe24a 100755 --- a/src/main/java/forestry/factory/gui/GuiCentrifuge.java +++ b/src/main/java/forestry/factory/gui/GuiCentrifuge.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiCentrifuge extends GuiForestryTitled { +public class GuiCentrifuge extends GuiForestryTitled { private final TileCentrifuge tile; - public GuiCentrifuge(ContainerCentrifuge container, Inventory inventory, Component title) { + public GuiCentrifuge(CentrifugeMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/centrifugesocket2.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new SocketWidget(this.widgetManager, 79, 37, this.tile, 0)); diff --git a/src/main/java/forestry/factory/gui/GuiFabricator.java b/src/main/java/forestry/factory/gui/GuiFabricator.java index af961370bc..d1d39dda55 100755 --- a/src/main/java/forestry/factory/gui/GuiFabricator.java +++ b/src/main/java/forestry/factory/gui/GuiFabricator.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiFabricator extends GuiForestryTitled { +public class GuiFabricator extends GuiForestryTitled { private final TileFabricator tile; - public GuiFabricator(ContainerFabricator container, Inventory player, Component title) { + public GuiFabricator(FabricatorMenu container, Inventory player, Component title) { super(Constants.TEXTURE_PATH_GUI + "/fabricator.png", container, player, title); this.tile = container.getTile(); diff --git a/src/main/java/forestry/factory/gui/GuiFermenter.java b/src/main/java/forestry/factory/gui/GuiFermenter.java index 90694c4a9f..c9e52d47f5 100755 --- a/src/main/java/forestry/factory/gui/GuiFermenter.java +++ b/src/main/java/forestry/factory/gui/GuiFermenter.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiFermenter extends GuiForestryTitled { +public class GuiFermenter extends GuiForestryTitled { private final TileFermenter tile; - public GuiFermenter(ContainerFermenter container, Inventory inventory, Component title) { + public GuiFermenter(FermenterMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/fermenter.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new TankWidget(this.widgetManager, 35, 19, 0)); diff --git a/src/main/java/forestry/factory/gui/GuiMoistener.java b/src/main/java/forestry/factory/gui/GuiMoistener.java index c86fb53987..765b9e3c01 100755 --- a/src/main/java/forestry/factory/gui/GuiMoistener.java +++ b/src/main/java/forestry/factory/gui/GuiMoistener.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiMoistener extends GuiForestryTitled { +public class GuiMoistener extends GuiForestryTitled { private final TileMoistener tile; - public GuiMoistener(ContainerMoistener container, Inventory inventory, Component title) { + public GuiMoistener(MoistenerMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/moistener.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new TankWidget(this.widgetManager, 16, 16, 0)); diff --git a/src/main/java/forestry/factory/gui/GuiRaintank.java b/src/main/java/forestry/factory/gui/GuiRaintank.java index e648ba94a6..b96901a181 100755 --- a/src/main/java/forestry/factory/gui/GuiRaintank.java +++ b/src/main/java/forestry/factory/gui/GuiRaintank.java @@ -18,11 +18,11 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiRaintank extends GuiForestryTitled { +public class GuiRaintank extends GuiForestryTitled { private final TileRaintank tile; //TODO these all store a tile. Make a superclass to automatically do it. - public GuiRaintank(ContainerRaintank container, Inventory inventory, Component title) { + public GuiRaintank(RaintankMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/raintank.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new TankWidget(this.widgetManager, 53, 17, 0)); diff --git a/src/main/java/forestry/factory/gui/GuiSqueezer.java b/src/main/java/forestry/factory/gui/GuiSqueezer.java index bc869b88aa..5515bea251 100755 --- a/src/main/java/forestry/factory/gui/GuiSqueezer.java +++ b/src/main/java/forestry/factory/gui/GuiSqueezer.java @@ -19,10 +19,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiSqueezer extends GuiForestryTitled { +public class GuiSqueezer extends GuiForestryTitled { private final TileSqueezer tile; - public GuiSqueezer(ContainerSqueezer container, Inventory inventory, Component title) { + public GuiSqueezer(SqueezerMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/squeezersocket.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new TankWidget(this.widgetManager, 122, 18, 0)); diff --git a/src/main/java/forestry/factory/gui/GuiStill.java b/src/main/java/forestry/factory/gui/GuiStill.java index aede7d0615..6e2b62e05c 100755 --- a/src/main/java/forestry/factory/gui/GuiStill.java +++ b/src/main/java/forestry/factory/gui/GuiStill.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiStill extends GuiForestryTitled { +public class GuiStill extends GuiForestryTitled { private final TileStill tile; - public GuiStill(ContainerStill container, Inventory inventory, Component title) { + public GuiStill(StillMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/still.png", container, inventory, title); this.tile = container.getTile(); this.widgetManager.add(new TankWidget(this.widgetManager, 35, 15, 0)); @@ -34,7 +34,7 @@ protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseY, in graphics.blit(this.textureFile, this.leftPos + 81, this.topPos + 57, 176, 60, 14, 14); - if (this.tile.getWorkCounter() > 0) { + if (this.tile.getStepCounter() > 0) { int massRemaining = this.tile.getProgressScaled(16); graphics.blit(this.textureFile, this.leftPos + 84, this.topPos + 17 + massRemaining, 176, 74 + massRemaining, 4, 17 - massRemaining); } diff --git a/src/main/java/forestry/factory/gui/ContainerMoistener.java b/src/main/java/forestry/factory/gui/MoistenerMenu.java old mode 100755 new mode 100644 similarity index 83% rename from src/main/java/forestry/factory/gui/ContainerMoistener.java rename to src/main/java/forestry/factory/gui/MoistenerMenu.java index 98f81436c8..0360d85a3f --- a/src/main/java/forestry/factory/gui/ContainerMoistener.java +++ b/src/main/java/forestry/factory/gui/MoistenerMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotWatched; import forestry.core.gui.slots.SlotWorking; @@ -23,16 +23,16 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.ContainerListener; import net.minecraft.world.inventory.SimpleContainerData; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; -public class ContainerMoistener extends ContainerLiquidTanks implements ISlotChangeWatcher { - public static ContainerMoistener fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class MoistenerMenu extends LiquidTanksMenu implements ISlotChangeWatcher { + public static MoistenerMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileMoistener tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileMoistener.class); - return new ContainerMoistener(windowId, inv, tile); + return new MoistenerMenu(windowId, inv, tile); } - public ContainerMoistener(int windowId, Inventory player, TileMoistener tile) { + public MoistenerMenu(int windowId, Inventory player, TileMoistener tile) { super(windowId, FactoryMenuTypes.MOISTENER.menuType(), player, tile, 8, 84); addDataSlots(new SimpleContainerData(4)); diff --git a/src/main/java/forestry/factory/gui/ContainerRaintank.java b/src/main/java/forestry/factory/gui/RaintankMenu.java old mode 100755 new mode 100644 similarity index 84% rename from src/main/java/forestry/factory/gui/ContainerRaintank.java rename to src/main/java/forestry/factory/gui/RaintankMenu.java index bf3e3c580e..6d411795d7 --- a/src/main/java/forestry/factory/gui/ContainerRaintank.java +++ b/src/main/java/forestry/factory/gui/RaintankMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotEmptyLiquidContainerIn; import forestry.core.gui.slots.SlotOutput; import forestry.core.tiles.TileUtil; @@ -22,13 +22,13 @@ import net.minecraft.world.inventory.ContainerListener; import net.minecraft.world.inventory.SimpleContainerData; -public class ContainerRaintank extends ContainerLiquidTanks { - public static ContainerRaintank fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class RaintankMenu extends LiquidTanksMenu { + public static RaintankMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileRaintank tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileRaintank.class); - return new ContainerRaintank(windowId, inv, tile); + return new RaintankMenu(windowId, inv, tile); } - public ContainerRaintank(int windowId, Inventory player, TileRaintank tile) { + public RaintankMenu(int windowId, Inventory player, TileRaintank tile) { super(windowId, FactoryMenuTypes.RAINTANK.menuType(), player, tile, 8, 84); addDataSlots(new SimpleContainerData(1)); diff --git a/src/main/java/forestry/factory/gui/ContainerSqueezer.java b/src/main/java/forestry/factory/gui/SqueezerMenu.java old mode 100755 new mode 100644 similarity index 82% rename from src/main/java/forestry/factory/gui/ContainerSqueezer.java rename to src/main/java/forestry/factory/gui/SqueezerMenu.java index 423accd9fc..fff6bd59bb --- a/src/main/java/forestry/factory/gui/ContainerSqueezer.java +++ b/src/main/java/forestry/factory/gui/SqueezerMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanksSocketed; +import forestry.core.gui.LiquidTanksSocketedMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotLiquidIn; import forestry.core.gui.slots.SlotOutput; @@ -21,13 +21,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerSqueezer extends ContainerLiquidTanksSocketed { - public static ContainerSqueezer fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class SqueezerMenu extends LiquidTanksSocketedMenu { + public static SqueezerMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileSqueezer tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileSqueezer.class); - return new ContainerSqueezer(windowId, inv, tile); + return new SqueezerMenu(windowId, inv, tile); } - public ContainerSqueezer(int windowId, Inventory player, TileSqueezer tile) { + public SqueezerMenu(int windowId, Inventory player, TileSqueezer tile) { super(windowId, FactoryMenuTypes.SQUEEZER.menuType(), player, tile, 8, 84); // Resource inventory diff --git a/src/main/java/forestry/factory/gui/ContainerStill.java b/src/main/java/forestry/factory/gui/StillMenu.java old mode 100755 new mode 100644 similarity index 81% rename from src/main/java/forestry/factory/gui/ContainerStill.java rename to src/main/java/forestry/factory/gui/StillMenu.java index 476127253e..29b56f37c2 --- a/src/main/java/forestry/factory/gui/ContainerStill.java +++ b/src/main/java/forestry/factory/gui/StillMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.factory.gui; -import forestry.core.gui.ContainerLiquidTanks; +import forestry.core.gui.LiquidTanksMenu; import forestry.core.gui.slots.SlotEmptyLiquidContainerIn; import forestry.core.gui.slots.SlotLiquidIn; import forestry.core.gui.slots.SlotOutput; @@ -21,13 +21,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerStill extends ContainerLiquidTanks { - public static ContainerStill fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class StillMenu extends LiquidTanksMenu { + public static StillMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileStill tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileStill.class); - return new ContainerStill(windowId, inv, tile); + return new StillMenu(windowId, inv, tile); } - public ContainerStill(int windowId, Inventory player, TileStill tile) { + public StillMenu(int windowId, Inventory player, TileStill tile) { super(windowId, FactoryMenuTypes.STILL.menuType(), player, tile, 8, 84); this.addSlot(new SlotOutput(tile, InventoryStill.SLOT_PRODUCT, 150, 54)); diff --git a/src/main/java/forestry/factory/gui/package-info.java b/src/main/java/forestry/factory/gui/package-info.java index 3cf51a52ae..ce09072dcb 100644 --- a/src/main/java/forestry/factory/gui/package-info.java +++ b/src/main/java/forestry/factory/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.gui; diff --git a/src/main/java/forestry/factory/inventory/InventoryBottler.java b/src/main/java/forestry/factory/inventory/InventoryBottler.java index daaefbce7b..1fa5fdf3e5 100644 --- a/src/main/java/forestry/factory/inventory/InventoryBottler.java +++ b/src/main/java/forestry/factory/inventory/InventoryBottler.java @@ -15,8 +15,8 @@ import forestry.factory.tiles.TileBottler; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import net.minecraftforge.registries.ForgeRegistries; import java.util.Optional; diff --git a/src/main/java/forestry/factory/inventory/InventoryCarpenter.java b/src/main/java/forestry/factory/inventory/InventoryCarpenter.java index 21fa56e581..6721acb08f 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCarpenter.java +++ b/src/main/java/forestry/factory/inventory/InventoryCarpenter.java @@ -12,12 +12,12 @@ import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.core.utils.SlotUtil; import forestry.factory.tiles.TileCarpenter; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidUtil; public class InventoryCarpenter extends InventoryAdapterTile { public final static int SLOT_BOX = 9; @@ -36,7 +36,7 @@ public boolean canSlotAccept(int slotIndex, ItemStack stack) { if (slotIndex == SLOT_CAN_INPUT) { return FluidUtil.getFluidContained(stack).filter(f -> this.tile.getTankManager().canFillFluidType(f)).isPresent(); } else if (slotIndex == SLOT_BOX) { - return RecipeUtils.isCarpenterBox(this.tile.getLevel().getRecipeManager(), stack); + return RecipeUtil.isCarpenterBox(this.tile.getLevel().getRecipeManager(), stack); } else if (canSlotAccept(SLOT_CAN_INPUT, stack) || canSlotAccept(SLOT_BOX, stack)) { return false; } diff --git a/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java b/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java index 1a1f2cb3d6..da9dcecf4b 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java +++ b/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java @@ -11,7 +11,7 @@ package forestry.factory.inventory; import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.core.utils.SlotUtil; import forestry.factory.tiles.TileCentrifuge; import net.minecraft.core.Direction; @@ -28,7 +28,7 @@ public InventoryCentrifuge(TileCentrifuge centrifuge) { @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { - return slotIndex == SLOT_RESOURCE && RecipeUtils.getCentrifugeRecipe(this.tile.getLevel().getRecipeManager(), stack) != null; + return slotIndex == SLOT_RESOURCE && RecipeUtil.getCentrifugeRecipe(this.tile.getLevel().getRecipeManager(), stack) != null; } @Override diff --git a/src/main/java/forestry/factory/inventory/InventoryFabricator.java b/src/main/java/forestry/factory/inventory/InventoryFabricator.java index 0e5ee201f7..2696c84755 100644 --- a/src/main/java/forestry/factory/inventory/InventoryFabricator.java +++ b/src/main/java/forestry/factory/inventory/InventoryFabricator.java @@ -11,7 +11,7 @@ package forestry.factory.inventory; import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.core.utils.SlotUtil; import forestry.factory.tiles.TileFabricator; import net.minecraft.core.Direction; @@ -35,13 +35,13 @@ public boolean canSlotAccept(int slotIndex, ItemStack stack) { RecipeManager recipeManager = this.tile.getLevel().getRecipeManager(); if (slotIndex == SLOT_METAL) { - return RecipeUtils.getFabricatorMeltingRecipe(recipeManager, stack) != null; + return RecipeUtil.getFabricatorMeltingRecipe(recipeManager, stack) != null; } else if (slotIndex == SLOT_PLAN) { - return RecipeUtils.isFabricatorPlan(recipeManager, stack); + return RecipeUtil.isFabricatorPlan(recipeManager, stack); } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_INVENTORY_1, SLOT_INVENTORY_COUNT)) { - if (RecipeUtils.isFabricatorPlan(recipeManager, stack)) { + if (RecipeUtil.isFabricatorPlan(recipeManager, stack)) { return false; - } else if (RecipeUtils.getFabricatorMeltingRecipe(recipeManager, stack) != null) { + } else if (RecipeUtil.getFabricatorMeltingRecipe(recipeManager, stack) != null) { return false; } } diff --git a/src/main/java/forestry/factory/inventory/InventoryFermenter.java b/src/main/java/forestry/factory/inventory/InventoryFermenter.java index b07cf04d25..d17727ba4b 100644 --- a/src/main/java/forestry/factory/inventory/InventoryFermenter.java +++ b/src/main/java/forestry/factory/inventory/InventoryFermenter.java @@ -13,12 +13,12 @@ import forestry.api.fuels.FuelManager; import forestry.core.fluids.FluidHelper; import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.tiles.TileFermenter; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.Optional; @@ -36,7 +36,7 @@ public InventoryFermenter(TileFermenter fermenter) { @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { if (slotIndex == SLOT_RESOURCE) { - return RecipeUtils.isFermenterInput(this.tile.getLevel().getRecipeManager(), stack); + return RecipeUtil.isFermenterInput(this.tile.getLevel().getRecipeManager(), stack); } else if (slotIndex == SLOT_INPUT) { Optional fluid = FluidUtil.getFluidContained(stack); return fluid.map(f -> this.tile.getTankManager().canFillFluidType(f)).orElse(false); diff --git a/src/main/java/forestry/factory/inventory/InventoryMoistener.java b/src/main/java/forestry/factory/inventory/InventoryMoistener.java index 64d1f23d1a..61dade18d7 100644 --- a/src/main/java/forestry/factory/inventory/InventoryMoistener.java +++ b/src/main/java/forestry/factory/inventory/InventoryMoistener.java @@ -12,13 +12,13 @@ import forestry.api.fuels.FuelManager; import forestry.core.inventory.InventoryAdapterTile; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.core.utils.SlotUtil; import forestry.factory.tiles.TileMoistener; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.Optional; @@ -38,7 +38,7 @@ public InventoryMoistener(TileMoistener moistener) { @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { if (slotIndex == SLOT_RESOURCE) { - return RecipeUtils.getMoistenerRecipe(this.tile.getLevel().getRecipeManager(), stack) != null; + return RecipeUtil.getMoistenerRecipe(this.tile.getLevel().getRecipeManager(), stack) != null; } if (SlotUtil.isSlotInRange(slotIndex, SLOT_STASH_1, SLOT_STASH_COUNT)) { diff --git a/src/main/java/forestry/factory/inventory/InventoryRainmaker.java b/src/main/java/forestry/factory/inventory/InventoryRainmaker.java index a4ce231b1b..31ae284110 100644 --- a/src/main/java/forestry/factory/inventory/InventoryRainmaker.java +++ b/src/main/java/forestry/factory/inventory/InventoryRainmaker.java @@ -11,7 +11,7 @@ package forestry.factory.inventory; import forestry.api.fuels.FuelManager; -import forestry.api.fuels.RainSubstrate; +import forestry.api.fuels.RainmakerFuel; import forestry.core.inventory.InventoryAdapterTile; import forestry.factory.tiles.TileMillRainmaker; import net.minecraft.world.item.ItemStack; @@ -27,7 +27,7 @@ public InventoryRainmaker(TileMillRainmaker tile) { public boolean canSlotAccept(int slotIndex, ItemStack stack) { if (slotIndex == SLOT_SUBSTRATE) { if (FuelManager.rainSubstrate.containsKey(stack) && this.tile.charge == 0 && this.tile.progress == 0) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(stack); + RainmakerFuel substrate = FuelManager.rainSubstrate.get(stack); if (this.tile.getLevel().isRaining() && substrate.reverse()) { return true; } else { @@ -42,7 +42,7 @@ public boolean canSlotAccept(int slotIndex, ItemStack stack) { @Override public void setItem(int slotIndex, ItemStack itemStack) { if (slotIndex == SLOT_SUBSTRATE) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(itemStack); + RainmakerFuel substrate = FuelManager.rainSubstrate.get(itemStack); if (substrate != null && ItemStack.isSameItem(substrate.item(), itemStack)) { this.tile.addCharge(substrate); } diff --git a/src/main/java/forestry/factory/inventory/InventoryRaintank.java b/src/main/java/forestry/factory/inventory/InventoryRaintank.java index 69107814cf..bd1e665170 100644 --- a/src/main/java/forestry/factory/inventory/InventoryRaintank.java +++ b/src/main/java/forestry/factory/inventory/InventoryRaintank.java @@ -16,10 +16,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluids; import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; public class InventoryRaintank extends InventoryAdapterTile { public static final short SLOT_RESOURCE = 0; diff --git a/src/main/java/forestry/factory/inventory/InventorySqueezer.java b/src/main/java/forestry/factory/inventory/InventorySqueezer.java index 923e0434e2..befaad1e0f 100644 --- a/src/main/java/forestry/factory/inventory/InventorySqueezer.java +++ b/src/main/java/forestry/factory/inventory/InventorySqueezer.java @@ -15,14 +15,14 @@ import forestry.core.inventory.InventoryAdapterTile; import forestry.core.inventory.wrappers.InventoryMapper; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.tiles.TileSqueezer; import net.minecraft.core.Direction; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import java.util.List; @@ -50,7 +50,7 @@ public boolean canSlotAccept(int slotIndex, ItemStack stack) { } RecipeManager recipeManager = this.tile.getLevel().getRecipeManager(); - return RecipeUtils.isSqueezerIngredient(recipeManager, stack) || RecipeUtils.getSqueezerContainerRecipe(recipeManager, stack) != null; + return RecipeUtil.isSqueezerIngredient(recipeManager, stack) || RecipeUtil.getSqueezerContainerRecipe(recipeManager, stack) != null; } return false; diff --git a/src/main/java/forestry/factory/inventory/InventoryStill.java b/src/main/java/forestry/factory/inventory/InventoryStill.java index 775cbf9f19..3eccebe143 100644 --- a/src/main/java/forestry/factory/inventory/InventoryStill.java +++ b/src/main/java/forestry/factory/inventory/InventoryStill.java @@ -15,8 +15,8 @@ import forestry.factory.tiles.TileStill; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.Optional; diff --git a/src/main/java/forestry/factory/inventory/package-info.java b/src/main/java/forestry/factory/inventory/package-info.java index 0763700a14..ba56375d9b 100644 --- a/src/main/java/forestry/factory/inventory/package-info.java +++ b/src/main/java/forestry/factory/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.inventory; diff --git a/src/main/java/forestry/factory/network/package-info.java b/src/main/java/forestry/factory/network/package-info.java index 834768c927..b9d81d4c89 100644 --- a/src/main/java/forestry/factory/network/package-info.java +++ b/src/main/java/forestry/factory/network/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.network; diff --git a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java index 3785b2190c..cc7bf4c10d 100644 --- a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java +++ b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java @@ -18,14 +18,12 @@ import forestry.factory.tiles.TileFabricator; import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -public record PacketRecipeTransferRequest(BlockPos pos, - NonNullList craftingInventory) implements IForestryPacketServer { +public record PacketRecipeTransferRequest(BlockPos pos, NonNullList craftingInventory) implements IForestryPacketServer { public static void handle(PacketRecipeTransferRequest msg, ServerPlayer player) { BlockPos pos = msg.pos(); NonNullList craftingInventory = msg.craftingInventory(); @@ -38,7 +36,7 @@ public static void handle(PacketRecipeTransferRequest msg, ServerPlayer player) index++; } - NetworkUtil.sendNetworkPacket(new PacketRecipeTransferUpdate(carpenter.getBlockPos(), craftingInventory), pos, player.level()); + NetworkUtil.sendToPlayersTrackingPos(new PacketRecipeTransferUpdate(carpenter.getBlockPos(), craftingInventory), pos, player.level()); } else if (tile instanceof TileFabricator fabricator) { int index = 0; for (ItemStack stack : craftingInventory) { @@ -46,22 +44,21 @@ public static void handle(PacketRecipeTransferRequest msg, ServerPlayer player) index++; } - NetworkUtil.sendNetworkPacket(new PacketRecipeTransferUpdate(fabricator.getBlockPos(), craftingInventory), pos, player.level()); + NetworkUtil.sendToPlayersTrackingPos(new PacketRecipeTransferUpdate(fabricator.getBlockPos(), craftingInventory), pos, player.level()); } } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writeItemStacks(buffer, this.craftingInventory); + public static void encode(RegistryFriendlyByteBuf buffer, PacketRecipeTransferRequest msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writeItemStacks(buffer, msg.craftingInventory); } @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.RECIPE_TRANSFER_REQUEST; } - public static PacketRecipeTransferRequest decode(FriendlyByteBuf buffer) { + public static PacketRecipeTransferRequest decode(RegistryFriendlyByteBuf buffer) { return new PacketRecipeTransferRequest(buffer.readBlockPos(), NetworkUtil.readItemStacks(buffer)); } } diff --git a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java index 95ef105a8c..7804cf1f06 100644 --- a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java +++ b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java @@ -19,29 +19,29 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketRecipeTransferUpdate(BlockPos pos, NonNullList craftingInventory) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.RECIPE_TRANSFER_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { + public void write(RegistryFriendlyByteBuf buffer) { buffer.writeBlockPos(this.pos); NetworkUtil.writeItemStacks(buffer, this.craftingInventory); } - public static PacketRecipeTransferUpdate decode(FriendlyByteBuf buffer) { + public static PacketRecipeTransferUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketRecipeTransferUpdate(buffer.readBlockPos(), NetworkUtil.readItemStacks(buffer)); } - public static void handle(PacketRecipeTransferUpdate msg, Player player) { + public static void handle(PacketRecipeTransferUpdate msg, IPayloadContext ctx) { BlockEntity tile = TileUtil.getTile(player.level(), msg.pos); if (tile instanceof TileCarpenter carpenter) { int index = 0; diff --git a/src/main/java/forestry/factory/network/packets/package-info.java b/src/main/java/forestry/factory/network/packets/package-info.java index 012b7fb275..3fe83d1778 100644 --- a/src/main/java/forestry/factory/network/packets/package-info.java +++ b/src/main/java/forestry/factory/network/packets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.network.packets; diff --git a/src/main/java/forestry/factory/package-info.java b/src/main/java/forestry/factory/package-info.java index 1c370638e0..5379394488 100644 --- a/src/main/java/forestry/factory/package-info.java +++ b/src/main/java/forestry/factory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory; diff --git a/src/main/java/forestry/factory/recipes/BottlerRecipe.java b/src/main/java/forestry/factory/recipes/BottlerRecipe.java index d48e23d488..45e5976f53 100644 --- a/src/main/java/forestry/factory/recipes/BottlerRecipe.java +++ b/src/main/java/forestry/factory/recipes/BottlerRecipe.java @@ -1,38 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; import javax.annotation.Nullable; -public class BottlerRecipe { +public record BottlerRecipe(ItemStack input, FluidStack fluid, ItemStack output, boolean isFillRecipe) { @Nullable public static BottlerRecipe createEmptyingRecipe(ItemStack filled) { ItemStack empty = filled.copy(); empty.setCount(1); - LazyOptional fluidHandlerCap = FluidUtil.getFluidHandler(empty); - if (!fluidHandlerCap.isPresent()) { + IFluidHandlerItem fluidHandler = empty.getCapability(Capabilities.FluidHandler.ITEM); + if (fluidHandler == null) { return null; } - IFluidHandlerItem fluidHandler = fluidHandlerCap.orElse(null); - FluidStack drained = fluidHandler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.EXECUTE); if (!drained.isEmpty() && drained.getAmount() > 0) { return new BottlerRecipe(fluidHandler.getContainer(), drained, filled, false); @@ -46,13 +33,11 @@ public static BottlerRecipe createFillingRecipe(Fluid res, ItemStack empty) { ItemStack filled = empty.copy(); filled.setCount(1); - LazyOptional fluidHandlerCap = FluidUtil.getFluidHandler(filled); - if (!fluidHandlerCap.isPresent()) { + IFluidHandlerItem fluidHandler = empty.getCapability(Capabilities.FluidHandler.ITEM); + if (fluidHandler == null) { return null; } - IFluidHandlerItem fluidHandler = fluidHandlerCap.orElse(null); - int fillAmount = fluidHandler.fill(new FluidStack(res, Integer.MAX_VALUE), IFluidHandler.FluidAction.EXECUTE); if (fillAmount > 0) { return new BottlerRecipe(empty, new FluidStack(res, fillAmount), fluidHandler.getContainer(), true); @@ -61,23 +46,11 @@ public static BottlerRecipe createFillingRecipe(Fluid res, ItemStack empty) { return null; } - public final FluidStack fluid; - public final ItemStack inputStack; - public final ItemStack outputStack; - public final boolean fillRecipe; - - public BottlerRecipe(ItemStack inputStack, FluidStack fluid, ItemStack outputStack, boolean fillRecipe) { - this.fluid = fluid; - this.inputStack = inputStack; - this.outputStack = outputStack; - this.fillRecipe = fillRecipe; - } - public boolean matchEmpty(ItemStack emptyCan, FluidStack resource) { - return !emptyCan.isEmpty() && ItemStack.isSameItem(emptyCan, this.inputStack) && resource.isFluidEqual(this.fluid) && this.fillRecipe; + return !emptyCan.isEmpty() && ItemStack.isSameItem(emptyCan, this.input) && FluidStack.isSameFluidSameComponents(resource, this.fluid) && this.isFillRecipe; } public boolean matchFilled(ItemStack filledCan) { - return !this.outputStack.isEmpty() && !this.fillRecipe && ItemStack.isSameItem(this.outputStack, filledCan); + return !this.output.isEmpty() && !this.isFillRecipe && ItemStack.isSameItem(this.output, filledCan); } } diff --git a/src/main/java/forestry/factory/recipes/CarpenterRecipe.java b/src/main/java/forestry/factory/recipes/CarpenterRecipe.java index 66f868231f..33461fd733 100644 --- a/src/main/java/forestry/factory/recipes/CarpenterRecipe.java +++ b/src/main/java/forestry/factory/recipes/CarpenterRecipe.java @@ -1,52 +1,56 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.ICarpenterRecipe; +import forestry.core.utils.CodecUtil; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.game.ClientboundUpdateRecipesPacket; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.*; +import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; -import javax.annotation.Nullable; +import java.util.Optional; public class CarpenterRecipe implements ICarpenterRecipe { - private final ResourceLocation id; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Codec.INT.fieldOf("time").forGetter(CarpenterRecipe::getPackagingTime), + SizedFluidIngredient.FLAT_CODEC.optionalFieldOf("liquid").forGetter(CarpenterRecipe::getInputFluid), + Ingredient.CODEC.optionalFieldOf("box", Ingredient.EMPTY).forGetter(CarpenterRecipe::getBox), + CodecUtil.CRAFTING_RECIPE_CODEC.fieldOf("recipe").forGetter(CarpenterRecipe::getCraftingGridRecipe) + ).apply(inst, CarpenterRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, + CarpenterRecipe::getPackagingTime, + SizedFluidIngredient.STREAM_CODEC.apply(ByteBufCodecs::optional), + CarpenterRecipe::getInputFluid, + Ingredient.CONTENTS_STREAM_CODEC, + CarpenterRecipe::getBox, + CodecUtil.CRAFTING_RECIPE_STREAM_CODEC, + CarpenterRecipe::getCraftingGridRecipe, + CarpenterRecipe::new + ); + private final int packagingTime; - private final FluidStack liquid; + private final Optional liquid; private final Ingredient box; private final CraftingRecipe recipe; - @Nullable - private final ItemStack result; - - public CarpenterRecipe(ResourceLocation id, int packagingTime, FluidStack liquid, Ingredient box, CraftingRecipe recipe, @Nullable ItemStack result) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(box); - Preconditions.checkNotNull(recipe); - this.id = id; + public CarpenterRecipe(int packagingTime, Optional liquid, Ingredient box, CraftingRecipe recipe) { this.packagingTime = packagingTime; this.liquid = liquid; this.box = box; this.recipe = recipe; - this.result = result; } @Override @@ -60,7 +64,7 @@ public Ingredient getBox() { } @Override - public FluidStack getInputFluid() { + public Optional getInputFluid() { return this.liquid; } @@ -70,15 +74,14 @@ public CraftingRecipe getCraftingGridRecipe() { } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { - return this.result != null ? this.result : this.recipe.getResultItem(registryAccess); + public ItemStack getResultItem(HolderLookup.Provider registries) { + return this.recipe.getResultItem(registries); } @Override public boolean matches(FluidStack fluid, ItemStack boxStack, Container craftingInventory, Level level) { - FluidStack liquid = this.liquid; - if (!liquid.isEmpty()) { - if (fluid.isEmpty() || !fluid.containsFluid(liquid)) { + if (this.liquid.isPresent()) { + if (fluid.isEmpty() || !this.liquid.get().test(fluid)) { return false; } } @@ -91,11 +94,6 @@ public boolean matches(FluidStack fluid, ItemStack boxStack, Container craftingI return this.recipe.matches(FakeCraftingInventory.of(craftingInventory), level); } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.CARPENTER.serializer(); @@ -108,46 +106,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public CarpenterRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - int packagingTime = GsonHelper.getAsInt(json, "time"); - FluidStack liquid = json.has("liquid") ? RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "liquid")) : FluidStack.EMPTY; - Ingredient box = RecipeSerializers.deserialize(json.get("box")); - CraftingRecipe internal = (CraftingRecipe) RecipeManager.fromJson(recipeId, GsonHelper.getAsJsonObject(json, "recipe")); - ItemStack result = json.has("result") ? RecipeSerializers.item(GsonHelper.getAsJsonObject(json, "result")) : null; - - return new CarpenterRecipe(recipeId, packagingTime, liquid, box, internal, result); - } - - @Override - public CarpenterRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - int packagingTime = buffer.readVarInt(); - FluidStack liquid = buffer.readBoolean() ? FluidStack.readFromPacket(buffer) : FluidStack.EMPTY; - Ingredient box = Ingredient.fromNetwork(buffer); - CraftingRecipe internal = (CraftingRecipe) ClientboundUpdateRecipesPacket.fromNetwork(buffer); - ItemStack result = buffer.readBoolean() ? buffer.readItem() : null; - - return new CarpenterRecipe(recipeId, packagingTime, liquid, box, internal, result); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, CarpenterRecipe recipe) { - buffer.writeVarInt(recipe.packagingTime); - - if (!recipe.liquid.isEmpty()) { - buffer.writeBoolean(true); - recipe.liquid.writeToPacket(buffer); - } else { - buffer.writeBoolean(false); - } - - recipe.box.toNetwork(buffer); - ClientboundUpdateRecipesPacket.toNetwork(buffer, recipe.recipe); - - boolean hasResult = recipe.result != null; - buffer.writeBoolean(hasResult); - if (hasResult) { - buffer.writeItem(recipe.result); - } + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java b/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java index 9870e87e07..9116547777 100644 --- a/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java +++ b/src/main/java/forestry/factory/recipes/CentrifugeRecipe.java @@ -1,48 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import forestry.api.core.Product; +import forestry.api.recipes.ICentrifugeRecipe; +import forestry.factory.features.FactoryRecipeTypes; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.util.RandomSource; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import forestry.api.core.Product; -import forestry.api.recipes.ICentrifugeRecipe; -import forestry.core.utils.JsonUtil; -import forestry.factory.features.FactoryRecipeTypes; +import java.util.ArrayList; +import java.util.List; public class CentrifugeRecipe implements ICentrifugeRecipe { - private final ResourceLocation id; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Codec.INT.fieldOf("time").forGetter(CentrifugeRecipe::getProcessingTime), + Ingredient.CODEC.fieldOf("input").forGetter(CentrifugeRecipe::getInput), + Product.CODEC.listOf().fieldOf("products").forGetter(CentrifugeRecipe::getAllProducts) + ).apply(inst, CentrifugeRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, + CentrifugeRecipe::getProcessingTime, + Ingredient.CONTENTS_STREAM_CODEC, + CentrifugeRecipe::getInput, + Product.STREAM_CODEC.apply(ByteBufCodecs.list()), + CentrifugeRecipe::getAllProducts, + CentrifugeRecipe::new + ); + private final int processingTime; private final Ingredient input; private final List products; - public CentrifugeRecipe(ResourceLocation id, int processingTime, Ingredient input, List products) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - - this.id = id; + public CentrifugeRecipe(int processingTime, Ingredient input, List products) { this.processingTime = processingTime; this.input = input; this.products = products; @@ -81,15 +78,10 @@ public List getAllProducts() { } @Override - public ItemStack getResultItem(RegistryAccess access) { + public ItemStack getResultItem(HolderLookup.Provider access) { return ItemStack.EMPTY; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.CENTRIFUGE.serializer(); @@ -102,33 +94,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public CentrifugeRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - int processingTime = GsonHelper.getAsInt(json, "time"); - Ingredient input = RecipeSerializers.deserialize(json.get("input")); - NonNullList outputs = NonNullList.create(); - - for (JsonElement element : GsonHelper.getAsJsonArray(json, "products")) { - outputs.add(JsonUtil.deserialize(Product.CODEC, element)); - } - - return new CentrifugeRecipe(recipeId, processingTime, input, outputs); - } - - @Override - public CentrifugeRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - int processingTime = buffer.readVarInt(); - Ingredient input = Ingredient.fromNetwork(buffer); - List outputs = RecipeSerializers.read(buffer, Product::fromNetwork); - - return new CentrifugeRecipe(recipeId, processingTime, input, outputs); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, CentrifugeRecipe recipe) { - buffer.writeVarInt(recipe.processingTime); - recipe.input.toNetwork(buffer); - - RecipeSerializers.write(buffer, recipe.products, Product::toNetwork); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/FabricatorRecipe.java b/src/main/java/forestry/factory/recipes/FabricatorRecipe.java index 67c6d27673..e1b1d77dd3 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorRecipe.java +++ b/src/main/java/forestry/factory/recipes/FabricatorRecipe.java @@ -1,78 +1,76 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.IFabricatorRecipe; +import forestry.core.utils.CodecUtil; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; -public class FabricatorRecipe implements IFabricatorRecipe { +import java.util.Optional; - private final ResourceLocation id; +public class FabricatorRecipe implements IFabricatorRecipe { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Ingredient.CODEC.fieldOf("plan").forGetter(FabricatorRecipe::getPlan), + SizedFluidIngredient.FLAT_CODEC.optionalFieldOf("molten").forGetter(FabricatorRecipe::getRequiredFluid), + CodecUtil.CRAFTING_RECIPE_CODEC.fieldOf("recipe").forGetter(FabricatorRecipe::getCraftingGridRecipe) + ).apply(inst, FabricatorRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + Ingredient.CONTENTS_STREAM_CODEC, + FabricatorRecipe::getPlan, + SizedFluidIngredient.STREAM_CODEC.apply(ByteBufCodecs::optional), + FabricatorRecipe::getRequiredFluid, + CodecUtil.CRAFTING_RECIPE_STREAM_CODEC, + FabricatorRecipe::getCraftingGridRecipe, + FabricatorRecipe::new + ); + + // The plan is a vestigial field; it used to be for wax casts, used to make stained glass in 1.6 private final Ingredient plan; - private final FluidStack resultFluid; - private final ShapedRecipe recipe; - - public FabricatorRecipe(ResourceLocation id, Ingredient plan, FluidStack resultFluid, ShapedRecipe recipe) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(plan); - Preconditions.checkNotNull(resultFluid); + private final Optional resultFluid; + private final CraftingRecipe recipe; - this.id = id; + public FabricatorRecipe(Ingredient plan, Optional resultFluid, CraftingRecipe recipe) { this.plan = plan; this.resultFluid = resultFluid; this.recipe = recipe; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public Ingredient getPlan() { return this.plan; } @Override - public FluidStack getResultFluid() { + public Optional getRequiredFluid() { return this.resultFluid; } @Override - public ShapedRecipe getCraftingGridRecipe() { + public CraftingRecipe getCraftingGridRecipe() { return this.recipe; } @Override public boolean matches(Level level, FluidStack liquid, ItemStack stack, Container inventory) { - return liquid.containsFluid(this.resultFluid) && this.plan.test(stack) && this.recipe.matches(FakeCraftingInventory.of(inventory), level); + return (this.resultFluid.isEmpty() || this.resultFluid.get().test(liquid)) && this.plan.test(stack) && this.recipe.matches(FakeCraftingInventory.of(inventory), level); } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { - return this.recipe.getResultItem(registryAccess); + public ItemStack getResultItem(HolderLookup.Provider registries) { + return this.recipe.getResultItem(registries); } @Override @@ -86,30 +84,14 @@ public RecipeType getType() { } public static class Serializer implements RecipeSerializer { - - @Override - public FabricatorRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - Ingredient plan = RecipeSerializers.deserialize(json.get("plan")); - FluidStack molten = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "molten")); - ShapedRecipe internal = RecipeSerializer.SHAPED_RECIPE.fromJson(recipeId, GsonHelper.getAsJsonObject(json, "recipe")); - - return new FabricatorRecipe(recipeId, plan, molten, internal); - } - @Override - public FabricatorRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - Ingredient plan = Ingredient.fromNetwork(buffer); - FluidStack molten = buffer.readFluidStack(); - ShapedRecipe internal = RecipeSerializer.SHAPED_RECIPE.fromNetwork(recipeId, buffer); - - return new FabricatorRecipe(recipeId, plan, molten, internal); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, FabricatorRecipe recipe) { - recipe.getPlan().toNetwork(buffer); - buffer.writeFluidStack(recipe.getResultFluid()); - RecipeSerializer.SHAPED_RECIPE.toNetwork(buffer, recipe.getCraftingGridRecipe()); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java index b3a8244461..24633b08cf 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java +++ b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java @@ -1,72 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; -import forestry.api.recipes.IFabricatorSmeltingRecipe; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import forestry.api.recipes.IForestryRecipe; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; + +public record FabricatorSmeltingRecipe(Ingredient input, FluidStack result, int meltingPoint) implements IForestryRecipe { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Ingredient.CODEC_NONEMPTY.fieldOf("input").forGetter(FabricatorSmeltingRecipe::input), + FluidStack.CODEC.fieldOf("result").forGetter(FabricatorSmeltingRecipe::result), + Codec.INT.fieldOf("melting_point").forGetter(FabricatorSmeltingRecipe::meltingPoint) + ).apply(inst, FabricatorSmeltingRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + Ingredient.CONTENTS_STREAM_CODEC, + FabricatorSmeltingRecipe::input, + FluidStack.STREAM_CODEC, + FabricatorSmeltingRecipe::result, + ByteBufCodecs.VAR_INT, + FabricatorSmeltingRecipe::meltingPoint, + FabricatorSmeltingRecipe::new + ); -public class FabricatorSmeltingRecipe implements IFabricatorSmeltingRecipe { - private final ResourceLocation id; - private final Ingredient resource; - private final FluidStack product; - private final int meltingPoint; - - public FabricatorSmeltingRecipe(ResourceLocation id, Ingredient resource, FluidStack molten, int meltingPoint) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(resource); - Preconditions.checkArgument(!resource.isEmpty()); - Preconditions.checkNotNull(molten); - - this.id = id; - this.resource = resource; - this.product = molten; - this.meltingPoint = meltingPoint; - } - - @Override - public Ingredient getInput() { - return this.resource; - } - - @Override - public FluidStack getResultFluid() { - return this.product; - } - - @Override - public int getMeltingPoint() { - return this.meltingPoint; - } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { + public ItemStack getResultItem(HolderLookup.Provider registries) { return ItemStack.EMPTY; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.FABRICATOR_SMELTING.serializer(); @@ -79,28 +49,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public FabricatorSmeltingRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - Ingredient resource = RecipeSerializers.deserialize(json.get("resource")); - FluidStack product = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "product")); - int meltingPoint = GsonHelper.getAsInt(json, "melting"); - - return new FabricatorSmeltingRecipe(recipeId, resource, product, meltingPoint); - } - - @Override - public FabricatorSmeltingRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - Ingredient resource = Ingredient.fromNetwork(buffer); - FluidStack product = FluidStack.readFromPacket(buffer); - int meltingPoint = buffer.readVarInt(); - - return new FabricatorSmeltingRecipe(recipeId, resource, product, meltingPoint); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, FabricatorSmeltingRecipe recipe) { - recipe.resource.toNetwork(buffer); - recipe.product.writeToPacket(buffer); - buffer.writeVarInt(recipe.meltingPoint); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/FakeCraftingInventory.java b/src/main/java/forestry/factory/recipes/FakeCraftingInventory.java index 4fb1545964..b7fe574ee0 100644 --- a/src/main/java/forestry/factory/recipes/FakeCraftingInventory.java +++ b/src/main/java/forestry/factory/recipes/FakeCraftingInventory.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; import net.minecraft.world.Container; @@ -16,11 +6,12 @@ import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.inventory.TransientCraftingContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; class FakeCraftingInventory { private static final AbstractContainerMenu EMPTY_CONTAINER = new AbstractContainerMenu(null, -1) { @Override - public ItemStack quickMoveStack(Player p_38941_, int p_38942_) { + public ItemStack quickMoveStack(Player player, int index) { return ItemStack.EMPTY; } @@ -30,13 +21,13 @@ public boolean stillValid(Player playerIn) { } }; - public static CraftingContainer of(Container backing) { + public static CraftingInput of(Container backing) { CraftingContainer inventory = new TransientCraftingContainer(EMPTY_CONTAINER, 3, 3); for (int i = 0; i < 9; i++) { inventory.setItem(i, backing.getItem(i)); } - return inventory; + return inventory.asCraftInput(); } } diff --git a/src/main/java/forestry/factory/recipes/FermenterRecipe.java b/src/main/java/forestry/factory/recipes/FermenterRecipe.java index e7bb6f09e4..85b698e0d5 100644 --- a/src/main/java/forestry/factory/recipes/FermenterRecipe.java +++ b/src/main/java/forestry/factory/recipes/FermenterRecipe.java @@ -1,75 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.IFermenterRecipe; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.FluidIngredient; public class FermenterRecipe implements IFermenterRecipe { - private final ResourceLocation id; - private final Ingredient resource; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Ingredient.CODEC.fieldOf("input").forGetter(FermenterRecipe::getInputItem), + FluidIngredient.CODEC.fieldOf("input_fluid").forGetter(FermenterRecipe::getInputFluid), + Codec.INT.fieldOf("fermentation_value").forGetter(FermenterRecipe::getFermentationValue), + Codec.FLOAT.fieldOf("modifier").forGetter(FermenterRecipe::getModifier), + BuiltInRegistries.FLUID.byNameCodec().fieldOf("output_fluid").forGetter(FermenterRecipe::getOutputFluid) + ).apply(inst, FermenterRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + Ingredient.CONTENTS_STREAM_CODEC, + FermenterRecipe::getInputItem, + FluidIngredient.STREAM_CODEC, + FermenterRecipe::getInputFluid, + ByteBufCodecs.VAR_INT, + FermenterRecipe::getFermentationValue, + ByteBufCodecs.FLOAT, + FermenterRecipe::getModifier, + ByteBufCodecs.registry(Registries.FLUID), + FermenterRecipe::getOutputFluid, + FermenterRecipe::new + ); + + private final Ingredient input; + private final FluidIngredient inputFluid; private final int fermentationValue; private final float modifier; - private final Fluid output; - private final FluidStack fluidResource; + private final Fluid outputFluid; - public FermenterRecipe(ResourceLocation id, Ingredient resource, int fermentationValue, float modifier, Fluid output, FluidStack fluidResource) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(resource, "Fermenter Resource cannot be null!"); - Preconditions.checkArgument(!resource.isEmpty(), "Fermenter Resource item cannot be empty!"); - Preconditions.checkNotNull(output, "Fermenter Output cannot be null!"); - Preconditions.checkNotNull(fluidResource, "Fermenter Liquid cannot be null!"); - - this.id = id; - this.resource = resource; + public FermenterRecipe(Ingredient input, FluidIngredient inputFluid, int fermentationValue, float modifier, Fluid outputFluid) { + this.input = input; + this.inputFluid = inputFluid; this.fermentationValue = fermentationValue; this.modifier = modifier; - this.output = output; - this.fluidResource = fluidResource; - } - - public FermenterRecipe(ResourceLocation id, int fermentationValue, float modifier, Fluid output, FluidStack fluidResource) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(output, "Fermenter output cannot be null!"); - Preconditions.checkNotNull(fluidResource, "Fermenter liquid cannot be null!"); - - this.id = id; - this.resource = Ingredient.EMPTY; - this.fermentationValue = fermentationValue; - this.modifier = modifier; - this.output = output; - this.fluidResource = fluidResource; + this.outputFluid = outputFluid; } @Override public Ingredient getInputItem() { - return this.resource; + return this.input; } @Override - public FluidStack getInputFluid() { - return this.fluidResource; + public FluidIngredient getInputFluid() { + return this.inputFluid; } @Override @@ -83,25 +76,20 @@ public float getModifier() { } @Override - public Fluid getOutput() { - return this.output; + public Fluid getOutputFluid() { + return this.outputFluid; } @Override public boolean matches(ItemStack inputItem, FluidStack inputFluid) { - return this.resource.test(inputItem) && this.fluidResource.isFluidEqual(inputFluid); + return this.input.test(inputItem) && this.inputFluid.test(inputFluid); } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { + public ItemStack getResultItem(HolderLookup.Provider registries) { return ItemStack.EMPTY; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.FERMENTER.serializer(); @@ -114,34 +102,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public FermenterRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - Ingredient resource = RecipeSerializers.deserialize(json.get("resource")); - int fermentationValue = GsonHelper.getAsInt(json, "fermentationValue"); - float modifier = GsonHelper.getAsFloat(json, "modifier"); - Fluid output = ForgeRegistries.FLUIDS.getValue(new ResourceLocation(GsonHelper.getAsString(json, "output"))); - FluidStack fluidResource = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "fluidResource")); - - return new FermenterRecipe(recipeId, resource, fermentationValue, modifier, output, fluidResource); - } - - @Override - public FermenterRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - Ingredient resource = Ingredient.fromNetwork(buffer); - int fermentationValue = buffer.readVarInt(); - float modifier = buffer.readFloat(); - Fluid output = ForgeRegistries.FLUIDS.getValue(buffer.readResourceLocation()); - FluidStack fluidResource = FluidStack.readFromPacket(buffer); - - return new FermenterRecipe(recipeId, resource, fermentationValue, modifier, output, fluidResource); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, FermenterRecipe recipe) { - recipe.resource.toNetwork(buffer); - buffer.writeVarInt(recipe.fermentationValue); - buffer.writeFloat(recipe.modifier); - buffer.writeResourceLocation(ForgeRegistries.FLUIDS.getKey(recipe.output)); - recipe.fluidResource.writeToPacket(buffer); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/MoistenerRecipe.java b/src/main/java/forestry/factory/recipes/MoistenerRecipe.java index 9d1f1f8267..5da1177320 100644 --- a/src/main/java/forestry/factory/recipes/MoistenerRecipe.java +++ b/src/main/java/forestry/factory/recipes/MoistenerRecipe.java @@ -1,40 +1,40 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.IMoistenerRecipe; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; public class MoistenerRecipe implements IMoistenerRecipe { - private final ResourceLocation id; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Codec.INT.fieldOf("time").forGetter(MoistenerRecipe::getTimePerItem), + Ingredient.CODEC_NONEMPTY.fieldOf("input").forGetter(MoistenerRecipe::getInput), + ItemStack.CODEC.fieldOf("result").forGetter(MoistenerRecipe::getProduct) + ).apply(inst, MoistenerRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, + MoistenerRecipe::getTimePerItem, + Ingredient.CONTENTS_STREAM_CODEC, + MoistenerRecipe::getInput, + ItemStack.STREAM_CODEC, + MoistenerRecipe::getProduct, + MoistenerRecipe::new + ); + private final int timePerItem; private final Ingredient resource; private final ItemStack product; - public MoistenerRecipe(ResourceLocation id, Ingredient resource, ItemStack product, int timePerItem) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(resource, "Resource cannot be null"); - Preconditions.checkNotNull(product, "Product cannot be null"); - - this.id = id; + public MoistenerRecipe(int timePerItem, Ingredient resource, ItemStack product) { this.timePerItem = timePerItem; this.resource = resource; this.product = product; @@ -42,27 +42,22 @@ public MoistenerRecipe(ResourceLocation id, Ingredient resource, ItemStack produ @Override public int getTimePerItem() { - return timePerItem; + return this.timePerItem; } @Override public Ingredient getInput() { - return resource; + return this.resource; } @Override public ItemStack getProduct() { - return product; - } - - @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { return this.product; } @Override - public ResourceLocation getId() { - return id; + public ItemStack getResultItem(HolderLookup.Provider registryAccess) { + return this.product; } @Override @@ -77,28 +72,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public MoistenerRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - int timePerItem = GsonHelper.getAsInt(json, "time"); - Ingredient resource = RecipeSerializers.deserialize(json.get("resource")); - ItemStack product = RecipeSerializers.item(GsonHelper.getAsJsonObject(json, "product")); - - return new MoistenerRecipe(recipeId, resource, product, timePerItem); - } - - @Override - public MoistenerRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - int timePerItem = buffer.readVarInt(); - Ingredient resource = Ingredient.fromNetwork(buffer); - ItemStack product = buffer.readItem(); - - return new MoistenerRecipe(recipeId, resource, product, timePerItem); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, MoistenerRecipe recipe) { - buffer.writeVarInt(recipe.timePerItem); - recipe.resource.toNetwork(buffer); - buffer.writeItem(recipe.product); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/RecipeSerializers.java b/src/main/java/forestry/factory/recipes/RecipeSerializers.java deleted file mode 100644 index ef90d86557..0000000000 --- a/src/main/java/forestry/factory/recipes/RecipeSerializers.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.factory.recipes; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mojang.serialization.Dynamic; -import com.mojang.serialization.JsonOps; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.fluids.FluidStack; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiConsumer; -import java.util.function.Function; - -public class RecipeSerializers { - static void write(FriendlyByteBuf buffer, List list, BiConsumer consumer) { - buffer.writeVarInt(list.size()); - - for (E e : list) { - consumer.accept(buffer, e); - } - } - - static List read(FriendlyByteBuf buffer, Function reader) { - int size = buffer.readVarInt(); - - ArrayList list = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - list.add(reader.apply(buffer)); - } - - return list; - } - - public static FluidStack deserializeFluid(JsonObject object) { - return FluidStack.loadFluidStackFromNBT((CompoundTag) Dynamic.convert(JsonOps.INSTANCE, NbtOps.INSTANCE, object)); - } - - public static JsonObject serializeFluid(FluidStack fluid) { - return (JsonObject) Dynamic.convert(NbtOps.INSTANCE, JsonOps.INSTANCE, fluid.writeToNBT(new CompoundTag())); - } - - public static ItemStack item(JsonObject object) { - return ItemStack.of((CompoundTag) Dynamic.convert(JsonOps.INSTANCE, NbtOps.INSTANCE, object)); - } - - public static JsonObject item(ItemStack stack) { - return (JsonObject) Dynamic.convert(NbtOps.INSTANCE, JsonOps.INSTANCE, stack.serializeNBT()); - } - - public static Ingredient deserialize(JsonElement resource) { - if (resource.isJsonArray() && resource.getAsJsonArray().size() == 0) { - return Ingredient.EMPTY; - } - - return Ingredient.fromJson(resource); - } -} diff --git a/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java b/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java index f69611baf1..bf44de8dca 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java +++ b/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java @@ -1,44 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.ISqueezerContainerRecipe; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import java.util.List; public class SqueezerContainerRecipe implements ISqueezerContainerRecipe { - private final ResourceLocation id; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + ItemStack.CODEC.fieldOf("empty_container").forGetter(SqueezerContainerRecipe::getEmptyContainer), + Codec.INT.fieldOf("processing_time").forGetter(SqueezerContainerRecipe::getProcessingTime), + ItemStack.OPTIONAL_CODEC.fieldOf("remnants").forGetter(SqueezerContainerRecipe::getRemnants), + Codec.FLOAT.fieldOf("remnants_chance").forGetter(SqueezerContainerRecipe::getRemnantsChance) + ).apply(inst, SqueezerContainerRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ItemStack.STREAM_CODEC, + SqueezerContainerRecipe::getEmptyContainer, + ByteBufCodecs.VAR_INT, + SqueezerContainerRecipe::getProcessingTime, + ItemStack.OPTIONAL_STREAM_CODEC, + SqueezerContainerRecipe::getRemnants, + ByteBufCodecs.FLOAT, + SqueezerContainerRecipe::getRemnantsChance, + SqueezerContainerRecipe::new + ); + private final ItemStack emptyContainer; private final int processingTime; private final ItemStack remnants; private final float remnantsChance; - public SqueezerContainerRecipe(ResourceLocation id, ItemStack emptyContainer, int processingTime, ItemStack remnants, float remnantsChance) { - this.id = id; - Preconditions.checkNotNull(emptyContainer); - Preconditions.checkArgument(!emptyContainer.isEmpty()); - Preconditions.checkNotNull(remnants); - + public SqueezerContainerRecipe(ItemStack emptyContainer, int processingTime, ItemStack remnants, float remnantsChance) { this.emptyContainer = emptyContainer; this.processingTime = processingTime; this.remnants = remnants; @@ -76,15 +79,10 @@ public FluidStack getFluidOutput() { } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { + public ItemStack getResultItem(HolderLookup.Provider registries) { return this.remnants; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.SQUEEZER_CONTAINER.serializer(); @@ -96,33 +94,14 @@ public RecipeType getType() { } public static class Serializer implements RecipeSerializer { - @Override - public SqueezerContainerRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - ItemStack emptyContainer = RecipeSerializers.item(GsonHelper.getAsJsonObject(json, "container")); - int processingTime = GsonHelper.getAsInt(json, "time"); - ItemStack remnants = RecipeSerializers.item(GsonHelper.getAsJsonObject(json, "remnants")); - float remnantsChance = GsonHelper.getAsFloat(json, "remnantsChance"); - - return new SqueezerContainerRecipe(recipeId, emptyContainer, processingTime, remnants, remnantsChance); - } - - @Override - public SqueezerContainerRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - ItemStack emptyContainer = buffer.readItem(); - int processingTime = buffer.readVarInt(); - ItemStack remnants = buffer.readItem(); - float remnantsChance = buffer.readFloat(); - - return new SqueezerContainerRecipe(recipeId, emptyContainer, processingTime, remnants, remnantsChance); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, SqueezerContainerRecipe recipe) { - buffer.writeItem(recipe.emptyContainer); - buffer.writeVarInt(recipe.processingTime); - buffer.writeItem(recipe.remnants); - buffer.writeFloat(recipe.remnantsChance); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/SqueezerRecipe.java b/src/main/java/forestry/factory/recipes/SqueezerRecipe.java index 01883acc61..87fbf7c62a 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerRecipe.java +++ b/src/main/java/forestry/factory/recipes/SqueezerRecipe.java @@ -1,49 +1,52 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.ISqueezerRecipe; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; -import java.util.ArrayList; import java.util.List; public class SqueezerRecipe implements ISqueezerRecipe { - private final ResourceLocation id; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Codec.INT.fieldOf("time").forGetter(SqueezerRecipe::getProcessingTime), + // todo use SizedIngredient + Ingredient.CODEC.listOf().fieldOf("resources").forGetter(SqueezerRecipe::getInputs), + FluidStack.OPTIONAL_CODEC.fieldOf("output").forGetter(SqueezerRecipe::getFluidOutput), + ItemStack.OPTIONAL_CODEC.fieldOf("remnant").forGetter(SqueezerRecipe::getRemnants), + Codec.FLOAT.fieldOf("chance").forGetter(SqueezerRecipe::getRemnantsChance) + ).apply(inst, SqueezerRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, + SqueezerRecipe::getProcessingTime, + Ingredient.CONTENTS_STREAM_CODEC.apply(ByteBufCodecs.list()), + SqueezerRecipe::getInputs, + FluidStack.OPTIONAL_STREAM_CODEC, + SqueezerRecipe::getFluidOutput, + ItemStack.OPTIONAL_STREAM_CODEC, + SqueezerRecipe::getRemnants, + ByteBufCodecs.FLOAT, + SqueezerRecipe::getRemnantsChance, + SqueezerRecipe::new + ); + private final int processingTime; private final List resources; private final FluidStack fluidOutput; private final ItemStack remnants; private final float remnantsChance; - public SqueezerRecipe(ResourceLocation id, int processingTime, List resources, FluidStack fluidOutput, ItemStack remnants, float remnantsChance) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(resources); - Preconditions.checkArgument(!resources.isEmpty()); - Preconditions.checkNotNull(fluidOutput); - Preconditions.checkNotNull(remnants); - - this.id = id; + public SqueezerRecipe(int processingTime, List resources, FluidStack fluidOutput, ItemStack remnants, float remnantsChance) { this.processingTime = processingTime; this.resources = resources; this.fluidOutput = fluidOutput; @@ -77,15 +80,10 @@ public int getProcessingTime() { } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { + public ItemStack getResultItem(HolderLookup.Provider provider) { return ItemStack.EMPTY; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.SQUEEZER.serializer(); @@ -98,38 +96,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public SqueezerRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - int processingTime = GsonHelper.getAsInt(json, "time"); - ArrayList resources = new ArrayList<>(); - FluidStack fluidOutput = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "output")); - ItemStack remnants = RecipeSerializers.item(GsonHelper.getAsJsonObject(json, "remnant")); - float remnantsChance = GsonHelper.getAsFloat(json, "chance"); - - for (JsonElement element : GsonHelper.getAsJsonArray(json, "resources")) { - resources.add(RecipeSerializers.deserialize(element)); - } - - return new SqueezerRecipe(recipeId, processingTime, resources, fluidOutput, remnants, remnantsChance); - } - - @Override - public SqueezerRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - int processingTime = buffer.readVarInt(); - List resources = RecipeSerializers.read(buffer, Ingredient::fromNetwork); - FluidStack fluidOutput = FluidStack.readFromPacket(buffer); - ItemStack remnants = buffer.readItem(); - float remnantsChance = buffer.readFloat(); - - return new SqueezerRecipe(recipeId, processingTime, resources, fluidOutput, remnants, remnantsChance); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, SqueezerRecipe recipe) { - buffer.writeVarInt(recipe.processingTime); - RecipeSerializers.write(buffer, recipe.resources, (packetBuffer, ingredient) -> ingredient.toNetwork(packetBuffer)); - recipe.fluidOutput.writeToPacket(buffer); - buffer.writeItem(recipe.remnants); - buffer.writeFloat(recipe.remnantsChance); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/StillRecipe.java b/src/main/java/forestry/factory/recipes/StillRecipe.java index 7f1d337abf..7a89e95c37 100644 --- a/src/main/java/forestry/factory/recipes/StillRecipe.java +++ b/src/main/java/forestry/factory/recipes/StillRecipe.java @@ -1,40 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.recipes; -import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.recipes.IStillRecipe; import forestry.factory.features.FactoryRecipeTypes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; public class StillRecipe implements IStillRecipe { - private final ResourceLocation id; + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( + Codec.INT.fieldOf("cycles").forGetter(StillRecipe::getCyclesPerUnit), + SizedFluidIngredient.FLAT_CODEC.fieldOf("input").forGetter(StillRecipe::getInput), + FluidStack.CODEC.fieldOf("output").forGetter(StillRecipe::getOutput) + ).apply(inst, StillRecipe::new)); + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, + StillRecipe::getCyclesPerUnit, + SizedFluidIngredient.STREAM_CODEC, + StillRecipe::getInput, + FluidStack.STREAM_CODEC, + StillRecipe::getOutput, + StillRecipe::new + ); + private final int timePerUnit; - private final FluidStack input; + private final SizedFluidIngredient input; private final FluidStack output; - public StillRecipe(ResourceLocation id, int timePerUnit, FluidStack input, FluidStack output) { - Preconditions.checkNotNull(id, "Recipe identifier cannot be null"); - Preconditions.checkNotNull(input, "Still recipes need an input. Input was null."); - Preconditions.checkNotNull(output, "Still recipes need an output. Output was null."); - - this.id = id; + public StillRecipe(int timePerUnit, SizedFluidIngredient input, FluidStack output) { this.timePerUnit = timePerUnit; this.input = input; this.output = output; @@ -46,7 +47,7 @@ public int getCyclesPerUnit() { } @Override - public FluidStack getInput() { + public SizedFluidIngredient getInput() { return this.input; } @@ -57,19 +58,14 @@ public FluidStack getOutput() { @Override public boolean matches(FluidStack input) { - return input.containsFluid(this.input); + return this.input.test(input); } @Override - public ItemStack getResultItem(RegistryAccess registryAccess) { + public ItemStack getResultItem(HolderLookup.Provider registries) { return ItemStack.EMPTY; } - @Override - public ResourceLocation getId() { - return this.id; - } - @Override public RecipeSerializer getSerializer() { return FactoryRecipeTypes.STILL.serializer(); @@ -82,28 +78,13 @@ public RecipeType getType() { public static class Serializer implements RecipeSerializer { @Override - public StillRecipe fromJson(ResourceLocation recipeId, JsonObject json) { - int timePerUnit = GsonHelper.getAsInt(json, "time"); - FluidStack input = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "input")); - FluidStack output = RecipeSerializers.deserializeFluid(GsonHelper.getAsJsonObject(json, "output")); - - return new StillRecipe(recipeId, timePerUnit, input, output); - } - - @Override - public StillRecipe fromNetwork(ResourceLocation recipeId, FriendlyByteBuf buffer) { - int timePerUnit = buffer.readVarInt(); - FluidStack input = FluidStack.readFromPacket(buffer); - FluidStack output = FluidStack.readFromPacket(buffer); - - return new StillRecipe(recipeId, timePerUnit, input, output); + public MapCodec codec() { + return CODEC; } @Override - public void toNetwork(FriendlyByteBuf buffer, StillRecipe recipe) { - buffer.writeVarInt(recipe.timePerUnit); - recipe.input.writeToPacket(buffer); - recipe.output.writeToPacket(buffer); + public StreamCodec streamCodec() { + return STREAM_CODEC; } } } diff --git a/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java b/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java index 6148504271..75237163fe 100644 --- a/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java +++ b/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java @@ -1,16 +1,16 @@ package forestry.factory.recipes.jei; import forestry.api.fuels.FuelManager; -import forestry.api.fuels.RainSubstrate; +import forestry.api.fuels.RainmakerFuel; import forestry.api.modules.ForestryModuleIds; import forestry.core.ClientsideCode; import forestry.core.features.FluidsItems; import forestry.core.gui.GuiForestry; import forestry.core.gui.widgets.TankWidget; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.core.utils.ModUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.blocks.BlockFactoryPlain; import forestry.factory.blocks.BlockTypeFactoryPlain; import forestry.factory.blocks.BlockTypeFactoryTesr; @@ -30,7 +30,6 @@ import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.constants.VanillaTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.handlers.IGuiContainerHandler; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.helpers.IJeiHelpers; @@ -44,10 +43,8 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; import java.util.Comparator; import java.util.List; @@ -81,16 +78,16 @@ public void registerCategories(IRecipeCategoryRegistration registry) { public void registerRecipes(IRecipeRegistration registry) { RecipeManager manager = ClientsideCode.getRecipeManager(); - registry.addRecipes(ForestryRecipeType.CARPENTER, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.CARPENTER).toList()); - registry.addRecipes(ForestryRecipeType.CENTRIFUGE, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.CENTRIFUGE).toList()); - registry.addRecipes(ForestryRecipeType.FABRICATOR, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.FABRICATOR).toList()); - registry.addRecipes(ForestryRecipeType.FERMENTER, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.FERMENTER).toList()); - registry.addRecipes(ForestryRecipeType.MOISTENER, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.MOISTENER).toList()); + registry.addRecipes(ForestryRecipeType.CARPENTER, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.CARPENTER).toList()); + registry.addRecipes(ForestryRecipeType.CENTRIFUGE, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.CENTRIFUGE).toList()); + registry.addRecipes(ForestryRecipeType.FABRICATOR, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.FABRICATOR).toList()); + registry.addRecipes(ForestryRecipeType.FERMENTER, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.FERMENTER).toList()); + registry.addRecipes(ForestryRecipeType.MOISTENER, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.MOISTENER).toList()); registry.addRecipes(ForestryRecipeType.RAINMAKER, FuelManager.rainSubstrate.values().stream() - .sorted(Comparator.comparing(RainSubstrate::duration)) + .sorted(Comparator.comparing(RainmakerFuel::duration)) .toList()); - registry.addRecipes(ForestryRecipeType.SQUEEZER, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.SQUEEZER).toList()); - registry.addRecipes(ForestryRecipeType.STILL, RecipeUtils.getRecipes(manager, FactoryRecipeTypes.STILL).toList()); + registry.addRecipes(ForestryRecipeType.SQUEEZER, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.SQUEEZER).toList()); + registry.addRecipes(ForestryRecipeType.STILL, RecipeUtil.getRecipes(manager, FactoryRecipeTypes.STILL).toList()); BlockFactoryPlain rainTank = FactoryBlocks.PLAIN.get(BlockTypeFactoryPlain.RAINTANK).block(); JeiUtil.addDescription(registry, rainTank); diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java index 092c8e22b8..7259965031 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java @@ -5,12 +5,11 @@ import forestry.core.config.Constants; import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; -import forestry.core.utils.RecipeUtils; +import forestry.compat.jei.JeiUtil; +import forestry.core.utils.RecipeUtil; import forestry.factory.blocks.BlockTypeFactoryTesr; import forestry.factory.features.FactoryBlocks; import mezz.jei.api.constants.VanillaTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.builder.IRecipeSlotBuilder; import mezz.jei.api.gui.drawable.IDrawable; @@ -19,6 +18,7 @@ import mezz.jei.api.gui.ingredient.ICraftingGridHelper; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.helpers.IGuiHelper; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeType; @@ -26,9 +26,11 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; +import java.util.Arrays; import java.util.List; +import java.util.Optional; public class CarpenterRecipeCategory extends ForestryRecipeCategory { private final static ResourceLocation guiTexture = ForestryConstants.forestry(Constants.TEXTURE_PATH_GUI + "/carpenter.png"); @@ -62,13 +64,13 @@ public IDrawable getIcon() { public void setRecipe(IRecipeLayoutBuilder builder, ICarpenterRecipe recipe, IFocusGroup focuses) { CraftingRecipe craftingGridRecipe = recipe.getCraftingGridRecipe(); - ItemStack processingIngredient = craftingGridRecipe.getResultItem(RecipeUtils.getRegistryAccess()).copy(); + ItemStack processingIngredient = craftingGridRecipe.getResultItem(RecipeUtil.getRegistryAccess()).copy(); processingIngredient.setCount(1); builder.addSlot(RecipeIngredientRole.RENDER_ONLY, 71, 35) .addItemStack(processingIngredient); builder.addSlot(RecipeIngredientRole.OUTPUT, 120 - 9, 56 - 16) - .addItemStack(craftingGridRecipe.getResultItem(RecipeUtils.getRegistryAccess())); + .addItemStack(craftingGridRecipe.getResultItem(RecipeUtil.getRegistryAccess())); List craftingSlots = JeiUtil.layoutSlotGrid(builder, RecipeIngredientRole.INPUT, 3, 3, 1, 4, 18); JeiUtil.setCraftingItems(craftingSlots, craftingGridRecipe, this.craftingGridHelper); @@ -81,10 +83,8 @@ public void setRecipe(IRecipeLayoutBuilder builder, ICarpenterRecipe recipe, IFo .setFluidRenderer(10000, false, 16, 58) .setOverlay(this.tankOverlay, 0, 0); - FluidStack fluidResource = recipe.getInputFluid(); - if (!fluidResource.isEmpty()) { - tankSlot.addIngredient(ForgeTypes.FLUID_STACK, fluidResource); - } + Optional fluidResource = recipe.getInputFluid(); + fluidResource.ifPresent(sizedFluidIngredient -> tankSlot.addIngredients(NeoForgeTypes.FLUID_STACK, Arrays.asList(sizedFluidIngredient.getFluids()))); } @Override diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java index e69934a100..0360ed5bd0 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java @@ -1,11 +1,11 @@ package forestry.factory.recipes.jei.carpenter; +import forestry.api.modules.IForestryPacketServer; import forestry.api.recipes.ICarpenterRecipe; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; -import forestry.core.utils.NetworkUtil; +import forestry.compat.jei.JeiUtil; import forestry.factory.features.FactoryMenuTypes; -import forestry.factory.gui.ContainerCarpenter; +import forestry.factory.gui.CarpenterMenu; import forestry.factory.network.packets.PacketRecipeTransferRequest; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.RecipeType; @@ -16,18 +16,19 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.Optional; -public class CarpenterRecipeTransferHandler implements IRecipeTransferHandler { +public class CarpenterRecipeTransferHandler implements IRecipeTransferHandler { @Override - public Class getContainerClass() { - return ContainerCarpenter.class; + public Class getContainerClass() { + return CarpenterMenu.class; } @Override - public Optional> getMenuType() { + public Optional> getMenuType() { return Optional.of(FactoryMenuTypes.CARPENTER.menuType()); } @@ -38,7 +39,7 @@ public RecipeType getRecipeType() { @Nullable @Override - public IRecipeTransferError transferRecipe(ContainerCarpenter container, ICarpenterRecipe recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { + public IRecipeTransferError transferRecipe(CarpenterMenu container, ICarpenterRecipe recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { if (doTransfer) { Container craftingInventory = container.getCarpenter().getCraftingInventory(); NonNullList items = JeiUtil.getFirstItemStacks(recipeSlots); @@ -46,8 +47,9 @@ public IRecipeTransferError transferRecipe(ContainerCarpenter container, ICarpen for (int i = 0; i < size; i++) { craftingInventory.setItem(i, items.get(i)); } - NetworkUtil.sendToServer(new PacketRecipeTransferRequest(container.getCarpenter().getBlockPos(), items)); - } + IForestryPacketServer packet = new PacketRecipeTransferRequest(container.getCarpenter().getBlockPos(), items); + PacketDistributor.sendToServer(packet); + } return null; } diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java b/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java index 29c4bce279..7c0a8f8920 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.carpenter; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java index 91c2513bd5..2800fda8a2 100644 --- a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java @@ -7,7 +7,7 @@ import forestry.core.recipes.jei.ChanceTooltipCallback; import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.factory.blocks.BlockTypeFactoryTesr; import forestry.factory.features.FactoryBlocks; import mezz.jei.api.constants.VanillaTypes; diff --git a/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java b/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java index 5727cf21e3..3735869c86 100644 --- a/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.centrifuge; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java index 313d4722f2..28d91ce14c 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java @@ -2,24 +2,24 @@ import forestry.api.ForestryConstants; import forestry.api.recipes.IFabricatorRecipe; -import forestry.api.recipes.IFabricatorSmeltingRecipe; +import forestry.compat.jei.JeiUtil; import forestry.core.config.Constants; import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.blocks.BlockFactoryPlain; import forestry.factory.blocks.BlockTypeFactoryPlain; import forestry.factory.features.FactoryBlocks; import forestry.factory.features.FactoryRecipeTypes; +import forestry.factory.recipes.FabricatorSmeltingRecipe; import forestry.modules.features.FeatureBlock; import mezz.jei.api.constants.VanillaTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.builder.IRecipeSlotBuilder; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.ingredient.ICraftingGridHelper; import mezz.jei.api.helpers.IGuiHelper; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeType; @@ -28,7 +28,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; import javax.annotation.Nullable; import java.util.*; @@ -48,9 +48,9 @@ public FabricatorRecipeCategory(IGuiHelper guiHelper) { this.craftingGridHelper = guiHelper.createCraftingGridHelper(); } - private static Map> getSmeltingInputs() { - Map> smeltingInputs = new HashMap<>(); - RecipeUtils.getRecipes(RecipeUtils.getRecipeManager(), FactoryRecipeTypes.FABRICATOR_SMELTING) + private static Map> getSmeltingInputs() { + Map> smeltingInputs = new HashMap<>(); + RecipeUtil.getRecipes(RecipeUtil.getRecipeManager(), FactoryRecipeTypes.FABRICATOR_SMELTING) .forEach(smelting -> { Fluid fluid = smelting.getResultFluid().getFluid(); if (!smeltingInputs.containsKey(fluid)) { @@ -75,16 +75,16 @@ public IDrawable getIcon() { @Override public void setRecipe(IRecipeLayoutBuilder builder, IFabricatorRecipe recipe, IFocusGroup focuses) { - FluidStack recipeLiquid = recipe.getResultFluid(); + Optional recipeLiquid = recipe.getRequiredFluid(); Fluid recipeFluid = recipeLiquid.getFluid(); - List smeltingRecipes = getSmeltingInputs().get(recipeFluid); + List smeltingRecipes = getSmeltingInputs().get(recipeFluid); List smeltingInput = smeltingRecipes.stream() - .flatMap(s -> Arrays.stream(s.getInput().getItems())) + .flatMap(s -> Arrays.stream(s.input().getItems())) .toList(); builder.addSlot(RecipeIngredientRole.INPUT, 6, 32) .setFluidRenderer(2000, false, 16, 16) - .addIngredient(ForgeTypes.FLUID_STACK, recipeLiquid); + .addIngredient(NeoForgeTypes.FLUID_STACK, recipeLiquid); ShapedRecipe craftingGridRecipe = recipe.getCraftingGridRecipe(); List craftingSlots = JeiUtil.layoutSlotGrid(builder, RecipeIngredientRole.INPUT, 3, 3, 47, 1, 18); @@ -100,6 +100,6 @@ public void setRecipe(IRecipeLayoutBuilder builder, IFabricatorRecipe recipe, IF // .addIngredients(plan); builder.addSlot(RecipeIngredientRole.OUTPUT, 119, 37) - .addItemStack(craftingGridRecipe.getResultItem(RecipeUtils.getRegistryAccess())); + .addItemStack(craftingGridRecipe.getResultItem(RecipeUtil.getRegistryAccess())); } } diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java index 198eb43b9b..f23b1ec66a 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java @@ -1,11 +1,11 @@ package forestry.factory.recipes.jei.fabricator; +import forestry.api.modules.IForestryPacketServer; import forestry.api.recipes.IFabricatorRecipe; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; -import forestry.core.utils.NetworkUtil; +import forestry.compat.jei.JeiUtil; import forestry.factory.features.FactoryMenuTypes; -import forestry.factory.gui.ContainerFabricator; +import forestry.factory.gui.FabricatorMenu; import forestry.factory.network.packets.PacketRecipeTransferRequest; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.RecipeType; @@ -16,18 +16,19 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.Optional; -public class FabricatorRecipeTransferHandler implements IRecipeTransferHandler { +public class FabricatorRecipeTransferHandler implements IRecipeTransferHandler { @Override - public Class getContainerClass() { - return ContainerFabricator.class; + public Class getContainerClass() { + return FabricatorMenu.class; } @Override - public Optional> getMenuType() { + public Optional> getMenuType() { return Optional.of(FactoryMenuTypes.FABRICATOR.menuType()); } @@ -38,7 +39,7 @@ public RecipeType getRecipeType() { @Nullable @Override - public IRecipeTransferError transferRecipe(ContainerFabricator container, IFabricatorRecipe recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { + public IRecipeTransferError transferRecipe(FabricatorMenu container, IFabricatorRecipe recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { if (doTransfer) { Container craftingInventory = container.getFabricator().getCraftingInventory(); NonNullList items = JeiUtil.getFirstItemStacks(recipeSlots); @@ -46,8 +47,9 @@ public IRecipeTransferError transferRecipe(ContainerFabricator container, IFabri craftingInventory.setItem(i, items.get(i)); } - NetworkUtil.sendToServer(new PacketRecipeTransferRequest(container.getFabricator().getBlockPos(), items)); - } + IForestryPacketServer packet = new PacketRecipeTransferRequest(container.getFabricator().getBlockPos(), items); + PacketDistributor.sendToServer(packet); + } return null; } diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java b/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java index 292db6aaa4..9426dbf3ec 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.fabricator; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java index 6f2db7bcd3..951bc68746 100644 --- a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java @@ -1,8 +1,7 @@ package forestry.factory.recipes.jei.fermenter; import forestry.api.ForestryConstants; -import forestry.api.fuels.FermenterFuel; -import forestry.api.fuels.FuelManager; +import forestry.api.ForestryDataMaps; import forestry.api.recipes.IFermenterRecipe; import forestry.api.recipes.IVariableFermentable; import forestry.core.config.Constants; @@ -11,7 +10,6 @@ import forestry.factory.blocks.BlockTypeFactoryTesr; import forestry.factory.features.FactoryBlocks; import mezz.jei.api.constants.VanillaTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.builder.IRecipeSlotBuilder; import mezz.jei.api.gui.drawable.IDrawable; @@ -19,16 +17,20 @@ import mezz.jei.api.gui.drawable.IDrawableStatic; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.helpers.IGuiHelper; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeType; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import java.util.Arrays; -import java.util.Collection; import java.util.List; public class FermenterRecipeCategory extends ForestryRecipeCategory { @@ -38,6 +40,7 @@ public class FermenterRecipeCategory extends ForestryRecipeCategory fuels; public FermenterRecipeCategory(IGuiHelper guiHelper) { super(guiHelper.createDrawable(TEXTURE, 34, 18, 108, 60), "block.forestry.fermenter"); @@ -49,6 +52,11 @@ public FermenterRecipeCategory(IGuiHelper guiHelper) { this.tankOverlay = guiHelper.createDrawable(TEXTURE, 192, 0, 16, 58); ItemStack fermenter = new ItemStack(FactoryBlocks.TESR.get(BlockTypeFactoryTesr.FERMENTER).block()); this.icon = guiHelper.createDrawableIngredient(VanillaTypes.ITEM_STACK, fermenter); + + Registry registry = Minecraft.getInstance().level.registryAccess().registryOrThrow(Registries.ITEM); + this.fuels = registry.getDataMap(ForestryDataMaps.FERMENTER_FUELS).keySet().stream() + .map(key -> new ItemStack(registry.getOrThrow(key))) + .toList(); } @Override @@ -66,17 +74,16 @@ public void setRecipe(IRecipeLayoutBuilder builder, IFermenterRecipe recipe, IFo IRecipeSlotBuilder ingredientInputSlot = builder.addSlot(RecipeIngredientRole.INPUT, 51, 5) .addIngredients(recipe.getInputItem()); - Collection fuels = FuelManager.fermenterFuel.values(); - List fuelInputs = fuels.stream().map(FermenterFuel::item).toList(); builder.addSlot(RecipeIngredientRole.INPUT, 41, 39) - .addItemStacks(fuelInputs); + .addItemStacks(this.fuels); - FluidStack fluidInput = recipe.getInputFluid().copy(); - fluidInput.setAmount(recipe.getFermentationValue()); + int fermentationValue = recipe.getFermentationValue(); builder.addSlot(RecipeIngredientRole.INPUT, 1, 1) .setFluidRenderer(3000, false, 16, 58) .setOverlay(this.tankOverlay, 0, 0) - .addIngredient(ForgeTypes.FLUID_STACK, fluidInput); + .addIngredients(NeoForgeTypes.FLUID_STACK, Arrays.stream(recipe.getInputFluid().getStacks()) + .map(stack -> stack.copyWithAmount(fermentationValue)) + .toList()); final int baseAmount = Math.round(recipe.getFermentationValue() * recipe.getModifier()); List outputs = @@ -86,14 +93,14 @@ public void setRecipe(IRecipeLayoutBuilder builder, IFermenterRecipe recipe, IFo if (fermentable.getItem() instanceof IVariableFermentable variableFermentable) { amount *= variableFermentable.getFermentationModifier(fermentable); } - return new FluidStack(recipe.getOutput(), amount); + return new FluidStack(recipe.getOutputFluid(), amount); }) .toList(); IRecipeSlotBuilder fluidOutputSlot = builder.addSlot(RecipeIngredientRole.OUTPUT, 91, 1) .setFluidRenderer(3000, false, 16, 58) .setOverlay(this.tankOverlay, 0, 0) - .addIngredients(ForgeTypes.FLUID_STACK, outputs); + .addIngredients(NeoForgeTypes.FLUID_STACK, outputs); builder.createFocusLink(ingredientInputSlot, fluidOutputSlot); } diff --git a/src/main/java/forestry/factory/recipes/jei/fermenter/package-info.java b/src/main/java/forestry/factory/recipes/jei/fermenter/package-info.java index b005621f1c..1ac3988915 100644 --- a/src/main/java/forestry/factory/recipes/jei/fermenter/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/fermenter/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.fermenter; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeCategory.java index a86e05f961..c2eb4fbbc9 100644 --- a/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeCategory.java @@ -25,7 +25,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import java.util.Collection; import java.util.List; diff --git a/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java b/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java index bec9a302e6..64a2f186fa 100644 --- a/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.moistener; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/package-info.java b/src/main/java/forestry/factory/recipes/jei/package-info.java index 5cc45c9acb..2be9b760ee 100644 --- a/src/main/java/forestry/factory/recipes/jei/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java index 5709e2ebfe..5f706b9525 100644 --- a/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java @@ -1,6 +1,6 @@ package forestry.factory.recipes.jei.rainmaker; -import forestry.api.fuels.RainSubstrate; +import forestry.api.fuels.RainmakerFuel; import forestry.core.ForestryColors; import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeType; @@ -20,7 +20,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; -public class RainmakerRecipeCategory extends ForestryRecipeCategory { +public class RainmakerRecipeCategory extends ForestryRecipeCategory { private final IDrawable slot; private final IDrawable icon; @@ -32,7 +32,7 @@ public RainmakerRecipeCategory(IGuiHelper guiHelper) { } @Override - public RecipeType getRecipeType() { + public RecipeType getRecipeType() { return ForestryRecipeType.RAINMAKER; } @@ -42,14 +42,14 @@ public IDrawable getIcon() { } @Override - public void setRecipe(IRecipeLayoutBuilder builder, RainSubstrate recipe, IFocusGroup focuses) { + public void setRecipe(IRecipeLayoutBuilder builder, RainmakerFuel recipe, IFocusGroup focuses) { builder.addSlot(RecipeIngredientRole.INPUT, 1, 1) .setBackground(this.slot, -1, -1) .addItemStack(recipe.item()); } @Override - public void draw(RainSubstrate recipe, IRecipeSlotsView recipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) { + public void draw(RainmakerFuel recipe, IRecipeSlotsView recipeSlotsView, GuiGraphics graphics, double mouseX, double mouseY) { Component effect = getEffectString(recipe); Component speed = Component.translatable("for.jei.rainmaker.speed", recipe.speed()); @@ -62,7 +62,7 @@ public void draw(RainSubstrate recipe, IRecipeSlotsView recipeSlotsView, GuiGrap } } - private static Component getEffectString(RainSubstrate recipe) { + private static Component getEffectString(RainmakerFuel recipe) { if (recipe.reverse()) { return Component.translatable("for.jei.rainmaker.stops.rain"); } else { diff --git a/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java b/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java index 1f62c7959c..d9405f77bc 100644 --- a/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.rainmaker; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java index ac9f203ca4..43b19ebea8 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java @@ -6,7 +6,7 @@ import forestry.core.recipes.jei.ChanceTooltipCallback; import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeType; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.factory.blocks.BlockTypeFactoryTesr; import forestry.factory.features.FactoryBlocks; import mezz.jei.api.constants.VanillaTypes; diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java b/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java index 350f845173..0460c740fa 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.squeezer; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/jei/still/package-info.java b/src/main/java/forestry/factory/recipes/jei/still/package-info.java index be3d6ddda6..45088d48f1 100644 --- a/src/main/java/forestry/factory/recipes/jei/still/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/still/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.still; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/factory/recipes/package-info.java b/src/main/java/forestry/factory/recipes/package-info.java index 34a8bd508d..032c9265e7 100644 --- a/src/main/java/forestry/factory/recipes/package-info.java +++ b/src/main/java/forestry/factory/recipes/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.recipes; diff --git a/src/main/java/forestry/factory/tiles/TileBottler.java b/src/main/java/forestry/factory/tiles/TileBottler.java index 1da91eff27..72a5aa8492 100644 --- a/src/main/java/forestry/factory/tiles/TileBottler.java +++ b/src/main/java/forestry/factory/tiles/TileBottler.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; import forestry.api.core.ForestryError; @@ -17,19 +7,19 @@ import forestry.core.fluids.FluidHelper.FillStatus; import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; -import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.watchers.ISlotPickupWatcher; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerBottler; +import forestry.factory.gui.BottlerMenu; import forestry.factory.inventory.InventoryBottler; import forestry.factory.recipes.BottlerRecipe; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -37,16 +27,12 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.EnumMap; @@ -62,7 +48,8 @@ public class TileBottler extends TilePowered implements WorldlyContainer, ILiqui private boolean dumpingFluid = false; @Nullable private BottlerRecipe currentRecipe; - @OnlyIn(Dist.CLIENT) + + // CLIENT ONLY public boolean isFillRecipe; public TileBottler(BlockPos pos, BlockState state) { @@ -70,39 +57,38 @@ public TileBottler(BlockPos pos, BlockState state) { setInternalInventory(new InventoryBottler(this)); - this.resourceTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); - this.tankManager = new TankManager(this, this.resourceTank); + this.resourceTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); + this.tankManager = new TankManager(this, this.resourceTank); - this.canDump = new EnumMap<>(Direction.class); + this.canDump = new EnumMap<>(Direction.class); } /* SAVING & LOADING */ @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - this.tankManager.write(compound); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.tankManager.write(nbt, registries); } @Override - public void load(CompoundTag compound) { - super.load(compound); - this.tankManager.read(compound); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); checkEmptyRecipe(); checkFillRecipe(); } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } @Override @@ -130,7 +116,7 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { if (canDump()) { if (this.dumpingFluid || updateOnInterval(20)) { - this.dumpingFluid = dumpFluid(); + this.dumpingFluid = dumpFluid(); } } } @@ -140,7 +126,7 @@ private boolean canDump() { if (fluid != null) { if (this.canDump.isEmpty()) { for (Direction facing : Direction.VALUES) { - this.canDump.put(facing, FluidHelper.canAcceptFluid(this.level, this.worldPosition.relative(facing), facing.getOpposite(), fluid)); + this.canDump.put(facing, FluidHelper.canAcceptFluid(this.level, this.worldPosition.relative(facing), facing.getOpposite(), fluid)); } } @@ -155,14 +141,15 @@ private boolean canDump() { //TODO - a bit ugly atm. Are the new checks worth the perf with the new interface? Can this be written better? //Is there a race condition here? + // ^ what is blud on about private boolean dumpFluid() { if (!this.resourceTank.isEmpty()) { for (Direction facing : Direction.VALUES) { if (this.canDump.get(facing)) { - LazyOptional fluidDestination = FluidUtil.getFluidHandler(this.level, this.worldPosition.relative(facing), facing.getOpposite()); + IFluidHandler fluidDestination = this.level.getCapability(Capabilities.FluidHandler.BLOCK, this.worldPosition.relative(facing), facing.getOpposite()); - if (fluidDestination.isPresent()) { - fluidDestination.ifPresent(f -> FluidUtil.tryFluidTransfer(f, this.tankManager, FluidType.BUCKET_VOLUME / 20, true)); + if (fluidDestination != null) { + FluidUtil.tryFluidTransfer(fluidDestination, this.tankManager, FluidType.BUCKET_VOLUME / 20, true); return true; } } @@ -175,8 +162,8 @@ private boolean dumpFluid() { public boolean workCycle() { FluidHelper.FillStatus status; if (this.currentRecipe != null) { - if (this.currentRecipe.fillRecipe) { - status = FluidHelper.fillContainers(this.tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, this.currentRecipe.fluid.getFluid(), true); + if (this.currentRecipe.isFillRecipe()) { + status = FluidHelper.fillContainers(this.tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, this.currentRecipe.fluid().getFluid(), true); } else { status = FluidHelper.drainContainers(this.tankManager, this, InventoryBottler.SLOT_EMPTYING_PROCESSING, InventoryBottler.SLOT_OUTPUT_EMPTY_CONTAINER, true); } @@ -185,17 +172,17 @@ public boolean workCycle() { } if (status == FluidHelper.FillStatus.SUCCESS) { - this.currentRecipe = null; + this.currentRecipe = null; return true; } return false; } @Override - public void onNeighborTileChange(Level world, BlockPos pos, BlockPos neighbor) { - super.onNeighborTileChange(world, pos, neighbor); + public void onNeighborTileChange(Level level, BlockPos pos, BlockPos neighbor) { + super.onNeighborTileChange(level, pos, neighbor); - this.canDump.clear(); + this.canDump.clear(); } private void checkFillRecipe() { @@ -207,16 +194,16 @@ private void checkFillRecipe() { } //Fill Container if (this.currentRecipe == null || !this.currentRecipe.matchEmpty(emptyCan, resource)) { - this.currentRecipe = BottlerRecipe.createFillingRecipe(resource.getFluid(), emptyCan); + this.currentRecipe = BottlerRecipe.createFillingRecipe(resource.getFluid(), emptyCan); if (this.currentRecipe != null) { float viscosityMultiplier = resource.getFluid().getFluidType().getViscosity(resource) / 1000.0f; viscosityMultiplier = (viscosityMultiplier - 1f) / 20f + 1f; // scale down the effect - int fillAmount = Math.min(this.currentRecipe.fluid.getAmount(), resource.getAmount()); + int fillAmount = Math.min(this.currentRecipe.fluid().getAmount(), resource.getAmount()); float fillTime = fillAmount / (float) FluidType.BUCKET_VOLUME; fillTime *= viscosityMultiplier; - setTicksPerWorkCycle(Math.round(fillTime * TICKS_PER_RECIPE_TIME)); + setStepsPerWorkCycle(Math.round(fillTime * TICKS_PER_RECIPE_TIME)); setEnergyPerWorkCycle(Math.round(fillTime * ENERGY_PER_RECIPE_TIME)); } } @@ -227,18 +214,18 @@ private void checkEmptyRecipe() { ItemStack filledCan = getItem(InventoryBottler.SLOT_EMPTYING_PROCESSING); if (!filledCan.isEmpty()) { //Empty Container - if (this.currentRecipe == null || !this.currentRecipe.matchFilled(filledCan) && !this.currentRecipe.fillRecipe) { - this.currentRecipe = BottlerRecipe.createEmptyingRecipe(filledCan); + if (this.currentRecipe == null || !this.currentRecipe.matchFilled(filledCan) && !this.currentRecipe.isFillRecipe()) { + this.currentRecipe = BottlerRecipe.createEmptyingRecipe(filledCan); if (this.currentRecipe != null) { - FluidStack resource = this.currentRecipe.fluid; + FluidStack resource = this.currentRecipe.fluid(); float viscosityMultiplier = resource.getFluid().getFluidType().getViscosity(resource) / 1000.0f; viscosityMultiplier = (viscosityMultiplier - 1f) / 20f + 1f; // scale down the effect - int fillAmount = Math.min(this.currentRecipe.fluid.getAmount(), resource.getAmount()); + int fillAmount = Math.min(this.currentRecipe.fluid().getAmount(), resource.getAmount()); float fillTime = fillAmount / (float) FluidType.BUCKET_VOLUME; fillTime *= viscosityMultiplier; - setTicksPerWorkCycle(Math.round(fillTime * TICKS_PER_RECIPE_TIME)); + setStepsPerWorkCycle(Math.round(fillTime * TICKS_PER_RECIPE_TIME)); setEnergyPerWorkCycle(0); } } @@ -248,44 +235,32 @@ private void checkEmptyRecipe() { @Override public void onTake(int slotIndex, Player player) { if (slotIndex == InventoryBottler.SLOT_EMPTYING_PROCESSING) { - if (this.currentRecipe != null && !this.currentRecipe.fillRecipe) { - this.currentRecipe = null; - setTicksPerWorkCycle(0); + if (this.currentRecipe != null && !this.currentRecipe.isFillRecipe()) { + this.currentRecipe = null; + setStepsPerWorkCycle(0); } } else if (slotIndex == InventoryBottler.SLOT_FILLING_PROCESSING) { - if (this.currentRecipe != null && this.currentRecipe.fillRecipe) { - this.currentRecipe = null; - setTicksPerWorkCycle(0); + if (this.currentRecipe != null && this.currentRecipe.isFillRecipe()) { + this.currentRecipe = null; + setStepsPerWorkCycle(0); } } } @Override - public void writeGuiData(FriendlyByteBuf data) { - super.writeGuiData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + super.writeGuiData(buffer); if (this.currentRecipe == null) { - data.writeBoolean(false); + buffer.writeBoolean(false); } else { - data.writeBoolean(this.currentRecipe.fillRecipe); + buffer.writeBoolean(this.currentRecipe.isFillRecipe()); } } @Override - @OnlyIn(Dist.CLIENT) - public void readGuiData(FriendlyByteBuf data) { - super.readGuiData(data); - this.isFillRecipe = data.readBoolean(); - } - - @Override - public boolean hasResourcesMin(float percentage) { - IInventoryAdapter inventory = getInternalInventory(); - ItemStack emptyCan = inventory.getItem(InventoryBottler.SLOT_FILLING_PROCESSING); - if (emptyCan.isEmpty()) { - return false; - } - - return (float) emptyCan.getCount() / (float) emptyCan.getMaxStackSize() > percentage; + public void readGuiData(RegistryFriendlyByteBuf buffer) { + super.readGuiData(buffer); + this.isFillRecipe = buffer.readBoolean(); } @Override @@ -311,7 +286,7 @@ public boolean hasWork() { if (this.currentRecipe == null) { return false; } else { - fillStatus = FluidHelper.fillContainers(this.tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, this.currentRecipe.fluid.getFluid(), false); + fillStatus = FluidHelper.fillContainers(this.tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, this.currentRecipe.fluid().getFluid(), false); } } else { return true; @@ -325,7 +300,7 @@ public boolean hasWork() { errorLogic.setCondition(fillStatus == FluidHelper.FillStatus.NO_SPACE, ForestryError.NO_SPACE_INVENTORY); errorLogic.setCondition(emptyStatus == FluidHelper.FillStatus.NO_SPACE_FLUID, ForestryError.NO_SPACE_TANK); if (emptyStatus == FillStatus.INVALID_INPUT || fillStatus == FillStatus.INVALID_INPUT || errorLogic.hasErrors()) { - this.currentRecipe = null; + this.currentRecipe = null; return false; } return true; @@ -336,25 +311,13 @@ public TankRenderInfo getResourceTankInfo() { return new TankRenderInfo(this.resourceTank); } - /* ILIQUIDCONTAINER */ - @Override public TankManager getTankManager() { return this.tankManager; } - - //TODO - is this efficient? or even correct? - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerBottler(windowId, player.getInventory(), this); + return new BottlerMenu(windowId, player.getInventory(), this); } } diff --git a/src/main/java/forestry/factory/tiles/TileCarpenter.java b/src/main/java/forestry/factory/tiles/TileCarpenter.java index 0e95ac2e62..a3c3e86340 100644 --- a/src/main/java/forestry/factory/tiles/TileCarpenter.java +++ b/src/main/java/forestry/factory/tiles/TileCarpenter.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; import forestry.api.core.ForestryError; @@ -26,15 +16,16 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerCarpenter; +import forestry.factory.gui.CarpenterMenu; import forestry.factory.inventory.InventoryCarpenter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; @@ -44,13 +35,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; @@ -86,31 +74,31 @@ public TileCarpenter(BlockPos pos, BlockState state) { /* LOADING & SAVING */ @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - this.tankManager.write(compoundNBT); - this.craftingInventory.write(compoundNBT); + this.tankManager.write(nbt, registries); + this.craftingInventory.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.tankManager.read(compoundNBT); - this.craftingInventory.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); + this.craftingInventory.read(nbt, registries); } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } public void checkRecipe(RegistryAccess registryAccess) { @@ -119,12 +107,12 @@ public void checkRecipe(RegistryAccess registryAccess) { } if (this.currentRecipe == null || !this.currentRecipe.matches(this.resourceTank.getFluid(), getBoxStack(), this.craftingInventory, this.level)) { - ICarpenterRecipe recipe = RecipeUtils.getCarpenterRecipe(this.level.getRecipeManager(), this.resourceTank.getFluid(), getBoxStack(), this.craftingInventory, this.level); + ICarpenterRecipe recipe = RecipeUtil.getCarpenterRecipe(this.level.getRecipeManager(), this.resourceTank.getFluid(), getBoxStack(), this.craftingInventory, this.level); this.currentRecipe = recipe; if (recipe != null) { int recipeTime = this.currentRecipe.getPackagingTime(); - setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); + setStepsPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); ItemStack craftingResult = this.currentRecipe.getResultItem(registryAccess); @@ -244,8 +232,8 @@ public Container getCraftPreviewInventory() { } @Override - public void handleItemStackForDisplay(ItemStack itemStack) { - this.craftPreviewInventory.setItem(0, itemStack); + public void handleItemStackForDisplay(ItemStack stack) { + this.craftPreviewInventory.setItem(0, stack); } @@ -254,17 +242,8 @@ public TankManager getTankManager() { return this.tankManager; } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerCarpenter(windowId, player.getInventory(), this); + return new CarpenterMenu(windowId, player.getInventory(), this); } } diff --git a/src/main/java/forestry/factory/tiles/TileCentrifuge.java b/src/main/java/forestry/factory/tiles/TileCentrifuge.java index dbe74f2614..fcdd200d69 100644 --- a/src/main/java/forestry/factory/tiles/TileCentrifuge.java +++ b/src/main/java/forestry/factory/tiles/TileCentrifuge.java @@ -18,19 +18,21 @@ import forestry.api.recipes.ICentrifugeRecipe; import forestry.core.circuits.ISocketable; import forestry.core.config.Constants; +import forestry.core.features.CoreDataComponents; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InventoryAdapter; import forestry.core.tiles.IItemStackDisplay; import forestry.core.tiles.TilePowered; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerCentrifuge; +import forestry.factory.gui.CentrifugeMenu; import forestry.factory.inventory.InventoryCentrifuge; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; @@ -39,9 +41,10 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ResultContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.ArrayDeque; @@ -68,38 +71,39 @@ public TileCentrifuge(BlockPos pos, BlockState state) { /* LOADING & SAVING */ @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - this.sockets.write(compound); + this.sockets.write(nbt, registries); - ListTag nbttaglist = new ListTag(); + ListTag list = new ListTag(); ItemStack[] offspring = this.pendingProducts.toArray(new ItemStack[0]); for (int i = 0; i < offspring.length; i++) { if (offspring[i] != null) { CompoundTag products = new CompoundTag(); products.putByte("Slot", (byte) i); offspring[i].save(products); - nbttaglist.add(products); + list.add(products); } } - compound.put("PendingProducts", nbttaglist); + nbt.put("PendingProducts", list); } @Override - public void load(CompoundTag compound) { - super.load(compound); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - ListTag nbttaglist = compound.getList("PendingProducts", 10); + ListTag nbttaglist = nbt.getList("PendingProducts", 10); for (int i = 0; i < nbttaglist.size(); i++) { CompoundTag CompoundNBT1 = nbttaglist.getCompound(i); - this.pendingProducts.add(ItemStack.of(CompoundNBT1)); + this.pendingProducts.add(ItemStack.parseOptional(registries, CompoundNBT1)); } - this.sockets.read(compound); + this.sockets.read(nbt, registries); ItemStack chip = this.sockets.getItem(0); if (!chip.isEmpty()) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(chip); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard chipset = chip.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onLoad(this); } @@ -107,16 +111,16 @@ public void load(CompoundTag compound) { } @Override - public void writeGuiData(FriendlyByteBuf data) { - super.writeGuiData(data); - this.sockets.writeData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + super.writeGuiData(buffer); + this.sockets.writeData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readGuiData(FriendlyByteBuf data) { - super.readGuiData(data); - this.sockets.readData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + super.readGuiData(buffer); + this.sockets.readData(buffer); } @Override @@ -149,13 +153,13 @@ public boolean workCycle() { private void checkRecipe() { ItemStack resource = getItem(InventoryCentrifuge.SLOT_RESOURCE); - ICentrifugeRecipe matchingRecipe = RecipeUtils.getCentrifugeRecipe(getLevel().getRecipeManager(), resource); + RecipeHolder matchingRecipe = RecipeUtil.getCentrifugeRecipe(getLevel().getRecipeManager(), resource); if (this.currentRecipe != matchingRecipe) { this.currentRecipe = matchingRecipe; if (this.currentRecipe != null) { int recipeTime = this.currentRecipe.getProcessingTime(); - setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); + setStepsPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); } } @@ -227,7 +231,9 @@ public void setSocket(int slot, ItemStack stack) { // Dispose correctly of old chipsets if (!this.sockets.getItem(slot).isEmpty()) { if (IForestryApi.INSTANCE.getCircuitManager().isCircuitBoard(this.sockets.getItem(slot))) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(this.sockets.getItem(slot)); + IForestryApi.INSTANCE.getCircuitManager(); + ItemStack stack1 = this.sockets.getItem(slot); + ICircuitBoard chipset = stack1.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onRemoval(this); } @@ -239,7 +245,8 @@ public void setSocket(int slot, ItemStack stack) { return; } - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(stack); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard chipset = stack.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onInsertion(this); } @@ -252,7 +259,7 @@ public ResourceLocation getSocketType() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerCentrifuge(windowId, player.getInventory(), this); + return new CentrifugeMenu(windowId, player.getInventory(), this); } public Container getCraftPreviewInventory() { @@ -260,7 +267,7 @@ public Container getCraftPreviewInventory() { } @Override - public void handleItemStackForDisplay(ItemStack itemStack) { - this.craftPreviewInventory.setItem(0, itemStack); + public void handleItemStackForDisplay(ItemStack stack) { + this.craftPreviewInventory.setItem(0, stack); } } diff --git a/src/main/java/forestry/factory/tiles/TileFabricator.java b/src/main/java/forestry/factory/tiles/TileFabricator.java index ec14d69eeb..3c3396d4cc 100755 --- a/src/main/java/forestry/factory/tiles/TileFabricator.java +++ b/src/main/java/forestry/factory/tiles/TileFabricator.java @@ -1,19 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; import forestry.api.recipes.IFabricatorRecipe; -import forestry.api.recipes.IFabricatorSmeltingRecipe; import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidRecipeFilter; import forestry.core.fluids.TankManager; @@ -27,14 +16,15 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerFabricator; +import forestry.factory.gui.FabricatorMenu; import forestry.factory.inventory.InventoryFabricator; +import forestry.factory.recipes.FabricatorSmeltingRecipe; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; @@ -43,23 +33,21 @@ import net.minecraft.world.inventory.ContainerListener; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; import javax.annotation.Nullable; +import java.util.Optional; public class TileFabricator extends TilePowered implements ISlotPickupWatcher, ILiquidTankTile, WorldlyContainer { private static final int MAX_HEAT = 5000; - private final InventoryAdapterTile craftingInventory; + private final InventoryAdapterTile craftingInventory; private final TankManager tankManager; private final FilteredTank moltenTank; private int heat = 0; @@ -68,46 +56,44 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I public TileFabricator(BlockPos pos, BlockState state) { super(FactoryTiles.FABRICATOR.tileType(), pos, state, 1100, 3300); setEnergyPerWorkCycle(200); - this.craftingInventory = new InventoryGhostCrafting<>(this, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + this.craftingInventory = new InventoryGhostCrafting<>(this, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); setInternalInventory(new InventoryFabricator(this)); - this.moltenTank = new FilteredTank(8 * FluidType.BUCKET_VOLUME, false, true).setFilter(FluidRecipeFilter.FABRICATOR_SMELTING_OUTPUT); + this.moltenTank = new FilteredTank(8 * FluidType.BUCKET_VOLUME, false, true).setFilter(FluidRecipeFilter.FABRICATOR_SMELTING_OUTPUT); - this.tankManager = new TankManager(this, this.moltenTank); + this.tankManager = new TankManager(this, this.moltenTank); } /* SAVING & LOADING */ @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); + public void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); compound.putInt("Heat", this.heat); - this.tankManager.write(compound); - this.craftingInventory.write(compound); + this.tankManager.write(compound, registries); + this.craftingInventory.write(compound, registries); } @Override - public void load(CompoundTag compound) { - super.load(compound); + public void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); - this.heat = compound.getInt("Heat"); - this.tankManager.read(compound); - this.craftingInventory.read(compound); + this.heat = compound.getInt("Heat"); + this.tankManager.read(compound, registries); + this.craftingInventory.read(compound, registries); } @Override - public void writeData(FriendlyByteBuf data) { - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + this.tankManager.writeData(buffer); } @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + this.tankManager.readData(buffer); } - /* UPDATING */ @Override public void serverTick(Level level, BlockPos pos, BlockState state) { super.serverTick(level, pos, state); @@ -119,7 +105,7 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { if (!this.moltenTank.isEmpty()) { // Remove smelt if we have gone below melting point if (this.heat < getMeltingPoint() - 100) { - this.moltenTank.drain(5, IFluidHandler.FluidAction.EXECUTE); + this.moltenTank.drain(5, IFluidHandler.FluidAction.EXECUTE); } } @@ -138,16 +124,20 @@ private void trySmelting() { return; } - IFabricatorSmeltingRecipe smelt = RecipeUtils.getFabricatorMeltingRecipe(this.level.getRecipeManager(), smeltResource); - if (smelt == null || smelt.getMeltingPoint() > this.heat) { + RecipeHolder holder = RecipeUtil.getFabricatorMeltingRecipe(this.level.getRecipeManager(), smeltResource); + if (holder == null) { + return; + } + FabricatorSmeltingRecipe smelt = holder.value(); + if (smelt.meltingPoint() > this.heat) { return; } - FluidStack smeltFluid = smelt.getResultFluid(); + FluidStack smeltFluid = smelt.result(); if (this.moltenTank.fillInternal(smeltFluid, IFluidHandler.FluidAction.SIMULATE) == smeltFluid.getAmount()) { this.removeItem(InventoryFabricator.SLOT_METAL, 1); - this.moltenTank.fillInternal(smeltFluid, IFluidHandler.FluidAction.EXECUTE); - this.meltingPoint = smelt.getMeltingPoint(); + this.moltenTank.fillInternal(smeltFluid, IFluidHandler.FluidAction.EXECUTE); + this.meltingPoint = smelt.meltingPoint(); } } @@ -168,11 +158,14 @@ private IFabricatorRecipe getRecipe() { IInventoryAdapter inventory = getInternalInventory(); ItemStack plan = inventory.getItem(InventoryFabricator.SLOT_PLAN); FluidStack liquid = this.moltenTank.getFluid(); - IFabricatorRecipe recipe = RecipeUtils.getFabricatorRecipe(this.level.getRecipeManager(), this.level, liquid, plan, this.craftingInventory); - if (!liquid.isEmpty() && recipe != null && !liquid.containsFluid(recipe.getResultFluid())) { - return null; + RecipeHolder recipe = RecipeUtil.getFabricatorRecipe(this.level.getRecipeManager(), this.level, liquid, plan, this.craftingInventory); + if (!liquid.isEmpty() && recipe != null) { + Optional requiredFluid = recipe.value().getRequiredFluid(); + if (requiredFluid.isPresent() && !requiredFluid.get().test(liquid)) { + return null; + } } - return recipe; + return recipe.value(); } public ItemStack getResult(@Nullable IFabricatorRecipe myRecipe) { @@ -196,20 +189,34 @@ private void craftResult() { ItemStack craftResult = getResult(myRecipe); if (myRecipe != null && !craftResult.isEmpty() && getItem(InventoryFabricator.SLOT_RESULT).isEmpty()) { - FluidStack liquid = myRecipe.getResultFluid(); - // Remove resources if (removeFromInventory(myRecipe, false)) { - FluidStack drained = this.moltenTank.drainInternal(liquid, IFluidHandler.FluidAction.SIMULATE); - if (!drained.isEmpty() && drained.isFluidStackIdentical(liquid)) { + Optional liquid = myRecipe.getRequiredFluid(); + boolean consumedLiquid; + + if (liquid.isPresent()) { + SizedFluidIngredient ingredient = liquid.get(); + int amount = ingredient.amount(); + FluidStack drained = this.moltenTank.drainInternal(amount, IFluidHandler.FluidAction.SIMULATE); + + if (ingredient.test(drained)) { + this.moltenTank.drainInternal(amount, IFluidHandler.FluidAction.EXECUTE); + consumedLiquid = true; + } else { + consumedLiquid = false; + } + } else { + consumedLiquid = true; + } + + if (consumedLiquid) { removeFromInventory(myRecipe, true); - this.moltenTank.drain(liquid.getAmount(), IFluidHandler.FluidAction.EXECUTE); // Damage plan if (!getItem(InventoryFabricator.SLOT_PLAN).isEmpty()) { Item planItem = getItem(InventoryFabricator.SLOT_PLAN).getItem(); - if (planItem instanceof ICraftingPlan) { - ItemStack planUsed = ((ICraftingPlan) planItem).planUsed(getItem(InventoryFabricator.SLOT_PLAN), craftResult); + if (planItem instanceof ICraftingPlan plan) { + ItemStack planUsed = plan.planUsed(getItem(InventoryFabricator.SLOT_PLAN), craftResult); setItem(InventoryFabricator.SLOT_PLAN, planUsed); } } @@ -232,14 +239,19 @@ public boolean hasWork() { boolean hasResources = true; ItemStack plan = getItem(InventoryFabricator.SLOT_PLAN); - IFabricatorRecipe recipe = RecipeUtils.getFabricatorRecipe(this.level.getRecipeManager(), this.level, this.moltenTank.getFluid(), plan, this.craftingInventory); - if (recipe != null) { + RecipeHolder holder = RecipeUtil.getFabricatorRecipe(this.level.getRecipeManager(), this.level, this.moltenTank.getFluid(), plan, this.craftingInventory); + if (holder != null) { + IFabricatorRecipe recipe = holder.value(); hasResources = removeFromInventory(recipe, false); - FluidStack toDrain = recipe.getResultFluid(); - FluidStack drained = this.moltenTank.drainInternal(toDrain, IFluidHandler.FluidAction.SIMULATE); - hasLiquidResources = !drained.isEmpty() && drained.isFluidStackIdentical(toDrain); + + Optional toDrain = recipe.getRequiredFluid(); + if (toDrain.isPresent()) { + SizedFluidIngredient requiredFluid = toDrain.get(); + FluidStack drained = this.moltenTank.drainInternal(requiredFluid.amount(), IFluidHandler.FluidAction.SIMULATE); + hasLiquidResources = requiredFluid.test(drained); + } } else { - hasRecipe = RecipeUtils.getFabricatorMeltingRecipe(this.level.getRecipeManager(), getItem(InventoryFabricator.SLOT_METAL)) != null; + hasRecipe = RecipeUtil.getFabricatorMeltingRecipe(this.level.getRecipeManager(), getItem(InventoryFabricator.SLOT_METAL)) != null; } IErrorLogic errorLogic = getErrorLogic(); @@ -256,8 +268,8 @@ public int getHeatScaled(int i) { private int getMeltingPoint() { if (!this.getItem(InventoryFabricator.SLOT_METAL).isEmpty()) { - IFabricatorSmeltingRecipe meltingRecipe = RecipeUtils.getFabricatorMeltingRecipe(getLevel().getRecipeManager(), this.getItem(InventoryFabricator.SLOT_METAL)); - return meltingRecipe == null ? 0 : meltingRecipe.getMeltingPoint(); + RecipeHolder meltingRecipe = RecipeUtil.getFabricatorMeltingRecipe(getLevel().getRecipeManager(), this.getItem(InventoryFabricator.SLOT_METAL)); + return meltingRecipe == null ? 0 : meltingRecipe.value().meltingPoint(); } else if (this.moltenTank.getFluidAmount() > 0) { return this.meltingPoint; } @@ -278,9 +290,9 @@ public int getMeltingPointScaled(int i) { /* SMP */ public void getGUINetworkData(int i, int j) { if (i == 0) { - this.heat = j; + this.heat = j; } else if (i == 1) { - this.meltingPoint = j; + this.meltingPoint = j; } } @@ -301,16 +313,8 @@ public TankManager getTankManager() { return this.tankManager; } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerFabricator(windowId, player.getInventory(), this); + return new FabricatorMenu(windowId, player.getInventory(), this); } } diff --git a/src/main/java/forestry/factory/tiles/TileFermenter.java b/src/main/java/forestry/factory/tiles/TileFermenter.java index 40b702a72a..8bbcfcdbf5 100755 --- a/src/main/java/forestry/factory/tiles/TileFermenter.java +++ b/src/main/java/forestry/factory/tiles/TileFermenter.java @@ -1,19 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; +import forestry.api.ForestryDataMaps; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; import forestry.api.fuels.FermenterFuel; -import forestry.api.fuels.FuelManager; import forestry.api.recipes.IFermenterRecipe; import forestry.api.recipes.IVariableFermentable; import forestry.core.config.Constants; @@ -24,14 +14,14 @@ import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerFermenter; +import forestry.factory.gui.FermenterMenu; import forestry.factory.inventory.InventoryFermenter; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -41,13 +31,10 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; @@ -76,42 +63,42 @@ public TileFermenter(BlockPos pos, BlockState state) { } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - compoundNBT.putInt("FermentationTime", this.fermentationTime); - compoundNBT.putInt("FermentationTotalTime", this.fermentationTotalTime); - compoundNBT.putInt("FuelBurnTime", this.fuelBurnTime); - compoundNBT.putInt("FuelTotalTime", this.fuelTotalTime); - compoundNBT.putInt("FuelCurrentFerment", this.fuelCurrentFerment); + nbt.putInt("FermentationTime", this.fermentationTime); + nbt.putInt("FermentationTotalTime", this.fermentationTotalTime); + nbt.putInt("FuelBurnTime", this.fuelBurnTime); + nbt.putInt("FuelTotalTime", this.fuelTotalTime); + nbt.putInt("FuelCurrentFerment", this.fuelCurrentFerment); - this.tankManager.write(compoundNBT); + this.tankManager.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - this.fermentationTime = compoundNBT.getInt("FermentationTime"); - this.fermentationTotalTime = compoundNBT.getInt("FermentationTotalTime"); - this.fuelBurnTime = compoundNBT.getInt("FuelBurnTime"); - this.fuelTotalTime = compoundNBT.getInt("FuelTotalTime"); - this.fuelCurrentFerment = compoundNBT.getInt("FuelCurrentFerment"); + this.fermentationTime = nbt.getInt("FermentationTime"); + this.fermentationTotalTime = nbt.getInt("FermentationTotalTime"); + this.fuelBurnTime = nbt.getInt("FuelBurnTime"); + this.fuelTotalTime = nbt.getInt("FuelTotalTime"); + this.fuelCurrentFerment = nbt.getInt("FuelCurrentFerment"); - this.tankManager.read(compoundNBT); + this.tankManager.read(nbt, registries); } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } @Override @@ -136,18 +123,18 @@ public boolean workCycle() { int fermented = Math.min(this.fermentationTime, this.fuelCurrentFerment); int productAmount = Math.round(fermented * this.currentRecipe.getModifier() * this.currentResourceModifier); - this.productTank.fillInternal(new FluidStack(this.currentRecipe.getOutput(), productAmount), IFluidHandler.FluidAction.EXECUTE); + this.productTank.fillInternal(new FluidStack(this.currentRecipe.getOutputFluid(), productAmount), IFluidHandler.FluidAction.EXECUTE); - this.fuelBurnTime--; - this.resourceTank.drain(fermented, IFluidHandler.FluidAction.EXECUTE); - this.fermentationTime -= fermented; + this.fuelBurnTime--; + this.resourceTank.drain(fermented, IFluidHandler.FluidAction.EXECUTE); + this.fermentationTime -= fermented; // Not done yet if (this.fermentationTime > 0) { return false; } - this.currentRecipe = null; + this.currentRecipe = null; return true; } @@ -160,13 +147,13 @@ private void checkRecipe() { FluidStack fluid = this.resourceTank.getFluid(); if (!fluid.isEmpty()) { - this.currentRecipe = RecipeUtils.getFermenterRecipe(this.level.getRecipeManager(), resource, fluid); + this.currentRecipe = RecipeUtil.unwrap(RecipeUtil.getFermenterRecipe(this.level.getRecipeManager(), resource, fluid)); } - this.fermentationTotalTime = this.fermentationTime = this.currentRecipe == null ? 0 : this.currentRecipe.getFermentationValue(); + this.fermentationTotalTime = this.fermentationTime = this.currentRecipe == null ? 0 : this.currentRecipe.getFermentationValue(); if (this.currentRecipe != null) { - this.currentResourceModifier = determineResourceMod(resource); + this.currentResourceModifier = determineResourceMod(resource); removeItem(InventoryFermenter.SLOT_RESOURCE, 1); } } @@ -175,10 +162,10 @@ private void checkFuel() { if (this.fuelBurnTime <= 0) { ItemStack fuel = getItem(InventoryFermenter.SLOT_FUEL); if (!fuel.isEmpty()) { - FermenterFuel fermenterFuel = FuelManager.fermenterFuel.get(fuel); + FermenterFuel fermenterFuel = fuel.getItemHolder().getData(ForestryDataMaps.FERMENTER_FUELS); if (fermenterFuel != null) { - this.fuelBurnTime = this.fuelTotalTime = fermenterFuel.burnDuration(); - this.fuelCurrentFerment = fermenterFuel.fermentPerCycle(); + this.fuelBurnTime = this.fuelTotalTime = fermenterFuel.burnDuration(); + this.fuelCurrentFerment = fermenterFuel.fermentPerCycle(); removeItem(InventoryFermenter.SLOT_FUEL, 1); } @@ -193,26 +180,6 @@ private static float determineResourceMod(ItemStack stack) { return 1.0f; } - @Override - public boolean hasResourcesMin(float percentage) { - ItemStack fermentationStack = getItem(InventoryFermenter.SLOT_RESOURCE); - if (fermentationStack.isEmpty()) { - return false; - } - - return (float) fermentationStack.getCount() / (float) fermentationStack.getMaxStackSize() > percentage; - } - - @Override - public boolean hasFuelMin(float percentage) { - ItemStack fuelStack = getItem(InventoryFermenter.SLOT_FUEL); - if (fuelStack.isEmpty()) { - return false; - } - - return (float) fuelStack.getCount() / (float) fuelStack.getMaxStackSize() > percentage; - } - @Override public boolean hasWork() { checkRecipe(); @@ -229,7 +196,7 @@ public boolean hasWork() { if (hasRecipe) { int productAmount = Math.round(fermented * this.currentRecipe.getModifier() * this.currentResourceModifier); - Fluid output = this.currentRecipe.getOutput(); + Fluid output = this.currentRecipe.getOutputFluid(); FluidStack fluidStack = new FluidStack(output, productAmount); hasFluidSpace = this.productTank.fillInternal(fluidStack, IFluidHandler.FluidAction.SIMULATE) == fluidStack.getAmount(); } @@ -295,14 +262,6 @@ public TankManager getTankManager() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerFermenter(windowId, inv, this); - } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); + return new FermenterMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/factory/tiles/TileMillRainmaker.java b/src/main/java/forestry/factory/tiles/TileMillRainmaker.java index 4e62a5e1b8..9421d2b6d6 100644 --- a/src/main/java/forestry/factory/tiles/TileMillRainmaker.java +++ b/src/main/java/forestry/factory/tiles/TileMillRainmaker.java @@ -1,36 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; -import forestry.api.fuels.FuelManager; -import forestry.api.fuels.RainSubstrate; -import forestry.core.render.ParticleRender; -import forestry.core.tiles.TileMill; -import forestry.factory.features.FactoryTiles; -import forestry.factory.inventory.InventoryRainmaker; +import javax.annotation.Nullable; + import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.ServerLevelData; -import javax.annotation.Nullable; +import forestry.api.ForestryDataMaps; +import forestry.api.fuels.RainmakerFuel; +import forestry.core.render.ParticleRender; +import forestry.core.tiles.TileMill; +import forestry.factory.features.FactoryTiles; +import forestry.factory.inventory.InventoryRainmaker; public class TileMillRainmaker extends TileMill { private int duration; @@ -38,57 +31,62 @@ public class TileMillRainmaker extends TileMill { public TileMillRainmaker(BlockPos pos, BlockState state) { super(FactoryTiles.RAINMAKER.tileType(), pos, state); - this.speed = 0.01f; + this.speed = 0.01f; setInternalInventory(new InventoryRainmaker(this)); } @Override - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { - if (!player.level().isClientSide) { - ItemStack heldItem = player.getItemInHand(hand); - - // We don't have a gui, but we can be activated - if (FuelManager.rainSubstrate.containsKey(heldItem) && this.charge == 0) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(heldItem); - if (ItemStack.isSameItem(substrate.item(), heldItem)) { - addCharge(substrate); + public boolean interactWithItem(Level level, BlockPos pos, Player player, InteractionHand hand, ItemStack stack) { + if (this.charge == 0) { + Holder holder = stack.getItemHolder(); + RainmakerFuel fuel = holder.getData(ForestryDataMaps.RAINMAKER_FUELS); + + if (fuel != null) { + if (!level.isClientSide) { + addCharge(fuel); if (!player.isCreative()) { - heldItem.shrink(1); + stack.shrink(1); } + sendNetworkUpdate(); } } - sendNetworkUpdate(); } + return true; + } + + @Override + public boolean interactNoItem(Level level, Player player, BlockPos pos) { + return false; } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - - this.charge = compoundNBT.getInt("Charge"); - this.progress = compoundNBT.getFloat("Progress"); - this.stage = compoundNBT.getInt("Stage"); - this.duration = compoundNBT.getInt("Duration"); - this.reverse = compoundNBT.getBoolean("Reverse"); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + + this.charge = nbt.getInt("Charge"); + this.progress = nbt.getFloat("Progress"); + this.stage = nbt.getInt("Stage"); + this.duration = nbt.getInt("Duration"); + this.reverse = nbt.getBoolean("Reverse"); } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - - compoundNBT.putInt("Charge", this.charge); - compoundNBT.putFloat("Progress", this.progress); - compoundNBT.putInt("Stage", this.stage); - compoundNBT.putInt("Duration", this.duration); - compoundNBT.putBoolean("Reverse", this.reverse); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + + nbt.putInt("Charge", this.charge); + nbt.putFloat("Progress", this.progress); + nbt.putInt("Stage", this.stage); + nbt.putInt("Duration", this.duration); + nbt.putBoolean("Reverse", this.reverse); } - public void addCharge(RainSubstrate substrate) { - this.charge = 1; - this.speed = substrate.speed(); - this.duration = substrate.duration(); - this.reverse = substrate.reverse(); + public void addCharge(RainmakerFuel substrate) { + this.charge = 1; + this.speed = substrate.speed(); + this.duration = substrate.duration(); + this.reverse = substrate.reverse(); sendNetworkUpdate(); } @@ -114,9 +112,9 @@ public void activate(Level level, BlockPos pos) { level.getLevelData().setRaining(true); ((ServerLevelData) level.getLevelData()).setRainTime(this.duration); } - this.charge = 0; - this.duration = 0; - this.reverse = false; + this.charge = 0; + this.duration = 0; + this.reverse = false; sendNetworkUpdate(); } } @@ -126,9 +124,4 @@ public void activate(Level level, BlockPos pos) { public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { return null; } - - @Override - protected boolean hasGui() { - return false; - } } diff --git a/src/main/java/forestry/factory/tiles/TileMoistener.java b/src/main/java/forestry/factory/tiles/TileMoistener.java index 9b3f5d1c56..ec90bac77f 100755 --- a/src/main/java/forestry/factory/tiles/TileMoistener.java +++ b/src/main/java/forestry/factory/tiles/TileMoistener.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; +import forestry.api.ForestryDataMaps; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; -import forestry.api.fuels.FuelManager; import forestry.api.fuels.MoistenerFuel; import forestry.api.recipes.IMoistenerRecipe; import forestry.core.config.Constants; @@ -27,14 +17,14 @@ import forestry.core.tiles.TileBase; import forestry.core.utils.InventoryUtil; import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerMoistener; +import forestry.factory.gui.MoistenerMenu; import forestry.factory.inventory.InventoryMoistener; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -44,12 +34,9 @@ import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.ArrayList; @@ -72,68 +59,64 @@ public class TileMoistener extends TileBase implements WorldlyContainer, ILiquid public TileMoistener(BlockPos pos, BlockState state) { super(FactoryTiles.MOISTENER.tileType(), pos, state); setInternalInventory(new InventoryMoistener(this)); - this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilter(FluidTagFilter.WATER); - this.tankManager = new TankManager(this, this.resourceTank); + this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilter(FluidTagFilter.WATER); + this.tankManager = new TankManager(this, this.resourceTank); } /* LOADING & SAVING */ @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag compoundNBT, HolderLookup.Provider registries) { + super.saveAdditional(compoundNBT, registries); compoundNBT.putInt("BurnTime", this.burnTime); compoundNBT.putInt("TotalTime", this.totalTime); compoundNBT.putInt("ProductionTime", this.productionTime); - this.tankManager.write(compoundNBT); + this.tankManager.write(compoundNBT, registries); // Write pending product if (this.pendingProduct != null) { - CompoundTag CompoundNBTP = new CompoundTag(); - this.pendingProduct.save(CompoundNBTP); - compoundNBT.put("PendingProduct", CompoundNBTP); + compoundNBT.put("PendingProduct", this.pendingProduct.save(registries)); } if (this.currentProduct != null) { - CompoundTag CompoundNBTP = new CompoundTag(); - this.currentProduct.save(CompoundNBTP); - compoundNBT.put("CurrentProduct", CompoundNBTP); + compoundNBT.put("CurrentProduct", this.currentProduct.save(registries)); } } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); + public void loadAdditional(CompoundTag compoundNBT, HolderLookup.Provider registries) { + super.loadAdditional(compoundNBT, registries); - this.burnTime = compoundNBT.getInt("BurnTime"); - this.totalTime = compoundNBT.getInt("TotalTime"); - this.productionTime = compoundNBT.getInt("ProductionTime"); + this.burnTime = compoundNBT.getInt("BurnTime"); + this.totalTime = compoundNBT.getInt("TotalTime"); + this.productionTime = compoundNBT.getInt("ProductionTime"); - this.tankManager.read(compoundNBT); + this.tankManager.read(compoundNBT, registries); // Load pending product if (compoundNBT.contains("PendingProduct")) { CompoundTag compoundNBTP = compoundNBT.getCompound("PendingProduct"); - this.pendingProduct = ItemStack.of(compoundNBTP); + this.pendingProduct = ItemStack.parseOptional(registries, compoundNBTP); } if (compoundNBT.contains("CurrentProduct")) { CompoundTag compoundNBTP = compoundNBT.getCompound("CurrentProduct"); - this.currentProduct = ItemStack.of(compoundNBTP); + this.currentProduct = ItemStack.parseOptional(registries, compoundNBTP); } checkRecipe(); } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } @Override @@ -182,12 +165,12 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { return; } - this.resourceTank.drain(1, IFluidHandler.FluidAction.EXECUTE); - this.burnTime -= speed; - this.productionTime -= speed; + this.resourceTank.drain(1, IFluidHandler.FluidAction.EXECUTE); + this.burnTime -= speed; + this.productionTime -= speed; if (this.productionTime <= 0) { - this.pendingProduct = this.currentProduct; + this.pendingProduct = this.currentProduct; removeItem(InventoryMoistener.SLOT_RESOURCE, 1); resetRecipe(); tryAddPending(); @@ -202,13 +185,14 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { checkRecipe(); // Let's see if we have a valid resource in the working slot - if (getItem(InventoryMoistener.SLOT_WORKING).isEmpty()) { + ItemStack workingItem = getItem(InventoryMoistener.SLOT_WORKING); + if (workingItem.isEmpty()) { return; } - if (FuelManager.moistenerResource.containsKey(getItem(InventoryMoistener.SLOT_WORKING))) { - MoistenerFuel res = FuelManager.moistenerResource.get(getItem(InventoryMoistener.SLOT_WORKING)); - this.burnTime = this.totalTime = res.moistenerValue(); + MoistenerFuel fuel = workingItem.getItemHolder().getData(ForestryDataMaps.MOISTENER_FUELS); + if (fuel != null) { + this.burnTime = this.totalTime = fuel.moistenerValue(); } } else { rotateReservoir(); @@ -227,20 +211,20 @@ private boolean tryAddPending() { getErrorLogic().setCondition(!added, ForestryError.NO_SPACE_INVENTORY); if (added) { - this.pendingProduct = null; + this.pendingProduct = null; } return added; } public void checkRecipe() { - RecipeManager manager = RecipeUtils.getRecipeManager(); + RecipeManager manager = RecipeUtil.getRecipeManager(); IMoistenerRecipe sameRec = null; if (manager != null) { - sameRec = RecipeUtils.getMoistenerRecipe(manager, getInternalInventory().getItem(InventoryMoistener.SLOT_RESOURCE)); + sameRec = RecipeUtil.unwrap(RecipeUtil.getMoistenerRecipe(manager, getInternalInventory().getItem(InventoryMoistener.SLOT_RESOURCE))); } if (this.currentRecipe != sameRec) { - this.currentRecipe = sameRec; + this.currentRecipe = sameRec; resetRecipe(); } @@ -249,13 +233,13 @@ public void checkRecipe() { private void resetRecipe() { if (this.currentRecipe == null) { - this.currentProduct = null; - this.productionTime = 0; - this.timePerItem = 0; + this.currentProduct = null; + this.productionTime = 0; + this.timePerItem = 0; } else { - this.currentProduct = this.currentRecipe.getProduct(); - this.productionTime = this.currentRecipe.getTimePerItem(); - this.timePerItem = this.currentRecipe.getTimePerItem(); + this.currentProduct = this.currentRecipe.getProduct(); + this.productionTime = this.currentRecipe.getTimePerItem(); + this.timePerItem = this.currentRecipe.getTimePerItem(); } } @@ -308,13 +292,13 @@ private int getNextResourceSlot(int startSlot, int endSlot) { continue; } - if (!FuelManager.moistenerResource.containsKey(slotStack)) { + MoistenerFuel fuel = slotStack.getItemHolder().getData(ForestryDataMaps.MOISTENER_FUELS); + if (fuel == null) { continue; } - MoistenerFuel res = FuelManager.moistenerResource.get(slotStack); - if (stage < 0 || res.stage() < stage) { - stage = res.stage(); + if (stage < 0 || fuel.stage() < stage) { + stage = fuel.stage(); resourceSlot = i; } } @@ -329,11 +313,13 @@ private boolean rotateWorkingSlot() { if (!getItem(InventoryMoistener.SLOT_WORKING).isEmpty()) { // Get the result of the consumed item in the working slot ItemStack deposit; - if (FuelManager.moistenerResource.containsKey(getItem(InventoryMoistener.SLOT_WORKING))) { - MoistenerFuel res = FuelManager.moistenerResource.get(getItem(InventoryMoistener.SLOT_WORKING)); - deposit = res.product().copy(); + ItemStack working = getItem(InventoryMoistener.SLOT_WORKING); + MoistenerFuel fuel = working.getItemHolder().getData(ForestryDataMaps.MOISTENER_FUELS); + + if (fuel != null) { + deposit = fuel.product().copy(); } else { - deposit = getItem(InventoryMoistener.SLOT_WORKING).copy(); + deposit = working.copy(); } int targetSlot = getFreeReservoirSlot(deposit); @@ -370,11 +356,13 @@ private void rotateReservoir() { ArrayList slotsToShift = new ArrayList<>(); for (int i = InventoryMoistener.SLOT_RESERVOIR_1; i < InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT; i++) { - if (getItem(i).isEmpty()) { + ItemStack stack = getItem(i); + if (stack.isEmpty()) { continue; } - if (!FuelManager.moistenerResource.containsKey(getItem(i))) { + MoistenerFuel fuel = stack.getItemHolder().getData(ForestryDataMaps.MOISTENER_FUELS); + if (fuel != null) { slotsToShift.add(i); } } @@ -419,37 +407,6 @@ public boolean isWorking() { return this.burnTime > 0 && this.resourceTank.getFluidAmount() > 0; } - public boolean hasFuelMin(float percentage) { - int max = 0; - int avail = 0; - IInventoryAdapter inventory = getInternalInventory(); - - for (int i = InventoryMoistener.SLOT_STASH_1; i < InventoryMoistener.SLOT_RESERVOIR_1; i++) { - if (inventory.getItem(i).isEmpty()) { - max += 64; - continue; - } - if (FuelManager.moistenerResource.containsKey(inventory.getItem(i))) { - MoistenerFuel res = FuelManager.moistenerResource.get(inventory.getItem(i)); - if (ItemStack.isSameItem(res.resource(), inventory.getItem(i))) { - max += 64; - avail += inventory.getItem(i).getCount(); - } - } - } - - return (float) avail / (float) max > percentage; - } - - public boolean hasResourcesMin(float percentage) { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getItem(InventoryMoistener.SLOT_RESOURCE).isEmpty()) { - return false; - } - - return (float) inventory.getItem(InventoryMoistener.SLOT_RESOURCE).getCount() / (float) inventory.getItem(InventoryMoistener.SLOT_RESOURCE).getMaxStackSize() > percentage; - } - public boolean isProducing() { return this.productionTime > 0; } @@ -512,14 +469,6 @@ public void sendGUINetworkData(AbstractContainerMenu container, ContainerListene @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerMoistener(windowId, inv, this); - } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); //TODO this shouldn't be created every time this method is called... - } - return super.getCapability(capability, facing); + return new MoistenerMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/factory/tiles/TileRaintank.java b/src/main/java/forestry/factory/tiles/TileRaintank.java index adbb17d171..cf92ac65cf 100755 --- a/src/main/java/forestry/factory/tiles/TileRaintank.java +++ b/src/main/java/forestry/factory/tiles/TileRaintank.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; import forestry.api.core.ForestryError; @@ -17,12 +7,13 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TileBase; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerRaintank; +import forestry.factory.gui.RaintankMenu; import forestry.factory.inventory.InventoryRaintank; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -32,15 +23,11 @@ import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidUtil; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; @@ -63,36 +50,35 @@ public TileRaintank(BlockPos pos, BlockState state) { super(FactoryTiles.RAIN_TANK.tileType(), pos, state); setInternalInventory(new InventoryRaintank(this)); - this.resourceTank = new FilteredTank(Constants.RAINTANK_TANK_CAPACITY).setFilter(FluidTagFilter.WATER); + this.resourceTank = new FilteredTank(Constants.RAINTANK_TANK_CAPACITY).setFilter(FluidTagFilter.WATER); - this.tankManager = new TankManager(this, this.resourceTank); + this.tankManager = new TankManager(this, this.resourceTank); - this.containerFiller = new ContainerFiller(this.resourceTank, Constants.RAINTANK_FILLING_TIME, this, InventoryRaintank.SLOT_RESOURCE, InventoryRaintank.SLOT_PRODUCT); + this.containerFiller = new ContainerFiller(this.resourceTank, Constants.RAINTANK_FILLING_TIME, this, InventoryRaintank.SLOT_RESOURCE, InventoryRaintank.SLOT_PRODUCT); } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.tankManager.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.tankManager.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.tankManager.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override - @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } @Override @@ -110,28 +96,28 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { errorLogic.setCondition(!level.isRainingAt(posAbove), ForestryError.NOT_RAINING); if (!errorLogic.hasErrors()) { - this.resourceTank.fillInternal(WATER_PER_UPDATE, IFluidHandler.FluidAction.EXECUTE); + this.resourceTank.fillInternal(WATER_PER_UPDATE, IFluidHandler.FluidAction.EXECUTE); } - this.containerFiller.updateServerSide(); + this.containerFiller.updateServerSide(); } if (this.canDumpBelow == null) { - this.canDumpBelow = FluidHelper.canAcceptFluid(level, getBlockPos().below(), Direction.UP, STACK_WATER); + this.canDumpBelow = FluidHelper.canAcceptFluid(level, getBlockPos().below(), Direction.UP, STACK_WATER); } if (this.canDumpBelow) { if (this.dumpingFluid || updateOnInterval(20)) { - this.dumpingFluid = dumpFluidBelow(); + this.dumpingFluid = dumpFluidBelow(); } } } private boolean dumpFluidBelow() { if (!this.resourceTank.isEmpty()) { - LazyOptional fluidCap = FluidUtil.getFluidHandler(this.level, this.worldPosition.below(), Direction.UP); - if (fluidCap.isPresent()) { - return !FluidUtil.tryFluidTransfer(fluidCap.orElse(null), this.tankManager, FluidType.BUCKET_VOLUME / 20, true).isEmpty(); + IFluidHandler fluidCap = this.level.getCapability(Capabilities.FluidHandler.BLOCK, this.worldPosition.below(), Direction.UP); + if (fluidCap != null) { + return !FluidUtil.tryFluidTransfer(fluidCap, this.tankManager, FluidType.BUCKET_VOLUME / 20, true).isEmpty(); } } return false; @@ -162,29 +148,16 @@ public TankManager getTankManager() { } @Override - public void onNeighborTileChange(Level world, BlockPos pos, BlockPos neighbor) { - super.onNeighborTileChange(world, pos, neighbor); + public void onNeighborTileChange(Level level, BlockPos pos, BlockPos neighbor) { + super.onNeighborTileChange(level, pos, neighbor); if (neighbor.equals(pos.below())) { - this.canDumpBelow = FluidHelper.canAcceptFluid(world, neighbor, Direction.UP, STACK_WATER); + this.canDumpBelow = FluidHelper.canAcceptFluid(level, neighbor, Direction.UP, STACK_WATER); } } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> { - if (facing == Direction.DOWN) { - return new DrainOnlyFluidHandlerWrapper(this.tankManager); - } - return this.tankManager; - }).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerRaintank(windowId, inv, this); + return new RaintankMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/factory/tiles/TileSqueezer.java b/src/main/java/forestry/factory/tiles/TileSqueezer.java index b6b3694978..40e6ab9639 100644 --- a/src/main/java/forestry/factory/tiles/TileSqueezer.java +++ b/src/main/java/forestry/factory/tiles/TileSqueezer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; import forestry.api.IForestryApi; @@ -15,10 +5,12 @@ import forestry.api.circuits.ICircuitBoard; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; +import forestry.api.recipes.ISqueezerContainerRecipe; import forestry.api.recipes.ISqueezerRecipe; import forestry.core.circuits.ISocketable; import forestry.core.circuits.ISpeedUpgradable; import forestry.core.config.Constants; +import forestry.core.features.CoreDataComponents; import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; import forestry.core.inventory.InventoryAdapter; @@ -27,14 +19,15 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerSqueezer; +import forestry.factory.gui.SqueezerMenu; import forestry.factory.inventory.InventorySqueezer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; @@ -42,15 +35,13 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.List; @@ -79,21 +70,22 @@ public TileSqueezer(BlockPos pos, BlockState state) { /* LOADING & SAVING */ @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.tankManager.write(compoundNBT); - this.sockets.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.tankManager.write(nbt, registries); + this.sockets.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.tankManager.read(compoundNBT); - this.sockets.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); + this.sockets.read(nbt, registries); ItemStack chip = this.sockets.getItem(0); if (!chip.isEmpty()) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(chip); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard chipset = chip.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onLoad(this); } @@ -101,29 +93,29 @@ public void load(CompoundTag compoundNBT) { } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } @Override - public void writeGuiData(FriendlyByteBuf data) { - super.writeGuiData(data); - this.sockets.writeData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + super.writeGuiData(buffer); + this.sockets.writeData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readGuiData(FriendlyByteBuf data) { - super.readGuiData(data); - this.sockets.readData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + super.readGuiData(buffer); + this.sockets.readData(buffer); } // / WORKING @@ -175,13 +167,15 @@ private boolean checkRecipe() { if (this.currentRecipe != null && containsSets) { matchingRecipe = this.currentRecipe; } else { - matchingRecipe = RecipeUtils.getSqueezerRecipe(getLevel().getRecipeManager(), resources); + RecipeHolder holder = RecipeUtil.getSqueezerRecipe(getLevel().getRecipeManager(), resources); + matchingRecipe = holder == null ? null : holder.value(); } if (matchingRecipe == null) { for (ItemStack resource : resources) { if (matchingRecipe == null) { - matchingRecipe = RecipeUtils.getSqueezerContainerRecipe(getLevel().getRecipeManager(), resource); + RecipeHolder holder = RecipeUtil.getSqueezerContainerRecipe(getLevel().getRecipeManager(), resource); + matchingRecipe = holder == null ? null : holder.value(); } } } @@ -192,7 +186,7 @@ private boolean checkRecipe() { if (this.currentRecipe != null) { int recipeTime = this.currentRecipe.getProcessingTime(); - setTicksPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); + setStepsPerWorkCycle(recipeTime * TICKS_PER_RECIPE_TIME); setEnergyPerWorkCycle(recipeTime * ENERGY_PER_RECIPE_TIME); } } @@ -259,7 +253,9 @@ public void setSocket(int slot, ItemStack stack) { // Dispose correctly of old chipsets if (!this.sockets.getItem(slot).isEmpty()) { if (IForestryApi.INSTANCE.getCircuitManager().isCircuitBoard(this.sockets.getItem(slot))) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(this.sockets.getItem(slot)); + IForestryApi.INSTANCE.getCircuitManager(); + ItemStack stack1 = this.sockets.getItem(slot); + ICircuitBoard chipset = stack1.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onRemoval(this); } @@ -268,7 +264,8 @@ public void setSocket(int slot, ItemStack stack) { this.sockets.setItem(slot, stack); if (!stack.isEmpty()) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(stack); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard chipset = stack.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onInsertion(this); } @@ -281,16 +278,8 @@ public ResourceLocation getSocketType() { return ForestryCircuitSocketTypes.MACHINE; } - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerSqueezer(windowId, inv, this); + return new SqueezerMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/factory/tiles/TileStill.java b/src/main/java/forestry/factory/tiles/TileStill.java index 8ceb61598b..2aa0578390 100644 --- a/src/main/java/forestry/factory/tiles/TileStill.java +++ b/src/main/java/forestry/factory/tiles/TileStill.java @@ -1,16 +1,5 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.factory.tiles; -import com.google.common.base.Preconditions; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; import forestry.api.recipes.IStillRecipe; @@ -22,25 +11,23 @@ import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.factory.features.FactoryTiles; -import forestry.factory.gui.ContainerStill; +import forestry.factory.gui.StillMenu; import forestry.factory.inventory.InventoryStill; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.Objects; @@ -53,7 +40,7 @@ public class TileStill extends TilePowered implements WorldlyContainer, ILiquidT private final TankManager tankManager; @Nullable - private IStillRecipe currentRecipe = null; + private RecipeHolder currentRecipe = null; private FluidStack bufferedLiquid = FluidStack.EMPTY; public TileStill(BlockPos pos, BlockState state) { @@ -66,38 +53,38 @@ public TileStill(BlockPos pos, BlockState state) { } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); - this.tankManager.write(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); + this.tankManager.write(nbt, registries); if (!this.bufferedLiquid.isEmpty()) { CompoundTag buffer = new CompoundTag(); - this.bufferedLiquid.writeToNBT(buffer); - compoundNBT.put("Buffer", buffer); + this.bufferedLiquid.writeToNBT(buffer); + nbt.put("Buffer", buffer); } } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); - this.tankManager.read(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); + this.tankManager.read(nbt, registries); - if (compoundNBT.contains("Buffer")) { - CompoundTag buffer = compoundNBT.getCompound("Buffer"); - this.bufferedLiquid = FluidStack.loadFluidStackFromNBT(buffer); + if (nbt.contains("Buffer")) { + CompoundTag buffer = nbt.getCompound("Buffer"); + this.bufferedLiquid = FluidStack.loadFluidStackFromNBT(buffer); } } @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.tankManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.tankManager.writeData(buffer); } @Override - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.tankManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.tankManager.readData(buffer); } @Override @@ -116,14 +103,13 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { @Override public boolean workCycle() { - Preconditions.checkNotNull(this.currentRecipe); int cycles = this.currentRecipe.getCyclesPerUnit(); FluidStack output = this.currentRecipe.getOutput(); FluidStack product = new FluidStack(output, output.getAmount() * cycles); - this.productTank.fillInternal(product, IFluidHandler.FluidAction.EXECUTE); + this.productTank.fillInternal(product, IFluidHandler.FluidAction.EXECUTE); - this.bufferedLiquid = FluidStack.EMPTY; + this.bufferedLiquid = FluidStack.EMPTY; return true; } @@ -131,13 +117,13 @@ public boolean workCycle() { private void checkRecipe() { FluidStack recipeLiquid = !this.bufferedLiquid.isEmpty() ? this.bufferedLiquid : this.resourceTank.getFluid(); - if (this.currentRecipe == null || !this.currentRecipe.matches(recipeLiquid)) { + if (this.currentRecipe == null || !this.currentRecipe.value().matches(recipeLiquid)) { Level level = Objects.requireNonNull(this.level); - this.currentRecipe = RecipeUtils.getStillRecipe(level.getRecipeManager(), recipeLiquid); + this.currentRecipe = RecipeUtil.getStillRecipe(level.getRecipeManager(), recipeLiquid); - int recipeTime = this.currentRecipe == null ? 0 : this.currentRecipe.getCyclesPerUnit(); + int recipeTime = this.currentRecipe == null ? 0 : this.currentRecipe.value().getCyclesPerUnit(); setEnergyPerWorkCycle(ENERGY_PER_RECIPE_TIME * recipeTime); - setTicksPerWorkCycle(recipeTime); + setStepsPerWorkCycle(recipeTime); } } @@ -159,8 +145,8 @@ public boolean hasWork() { FluidStack drained = this.resourceTank.drain(drainAmount, IFluidHandler.FluidAction.SIMULATE); hasLiquidResource = !drained.isEmpty() && drained.getAmount() == drainAmount; if (hasLiquidResource) { - this.bufferedLiquid = new FluidStack(input, drainAmount); - this.resourceTank.drain(drainAmount, IFluidHandler.FluidAction.EXECUTE); + this.bufferedLiquid = input.copyWithAmount(drainAmount); + this.resourceTank.drain(drainAmount, IFluidHandler.FluidAction.EXECUTE); } } } @@ -189,18 +175,8 @@ public TankManager getTankManager() { return this.tankManager; } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.FLUID_HANDLER) { - return LazyOptional.of(() -> this.tankManager).cast(); - } - return super.getCapability(capability, facing); - } - @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerStill(windowId, player.getInventory(), this); + return new StillMenu(windowId, player.getInventory(), this); } - } diff --git a/src/main/java/forestry/factory/tiles/package-info.java b/src/main/java/forestry/factory/tiles/package-info.java index 161cae8b78..01650c3312 100644 --- a/src/main/java/forestry/factory/tiles/package-info.java +++ b/src/main/java/forestry/factory/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.factory.tiles; diff --git a/src/main/java/forestry/farming/FarmHelper.java b/src/main/java/forestry/farming/FarmHelper.java index 4f1e712c8d..0a8055a918 100755 --- a/src/main/java/forestry/farming/FarmHelper.java +++ b/src/main/java/forestry/farming/FarmHelper.java @@ -1,16 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming; import forestry.api.farming.*; +import forestry.api.multiblock.IFarmComponent; import forestry.core.utils.VecUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -111,8 +102,8 @@ private static BlockPos getGroundPosition(Level world, IFarmHousing farmHousing, return null; } - public static boolean isCycleCanceledByListeners(IFarmLogic logic, Direction direction, Iterable farmListeners) { - for (IFarmListener listener : farmListeners) { + public static boolean isCycleCanceledByListeners(IFarmLogic logic, Direction direction, Iterable farmListeners) { + for (IFarmComponent.Listener listener : farmListeners) { if (listener.cancelTask(logic, direction)) { return true; } @@ -132,10 +123,10 @@ public static void setExtents(Level world, IFarmHousing farmHousing, Map farmListeners) { + public static boolean cultivateTarget(Level world, IFarmHousing farmHousing, FarmTarget target, IFarmLogic logic, Iterable farmListeners) { BlockPos targetPosition = target.getStart().offset(0, target.getYOffset(), 0); if (logic.cultivate(world, farmHousing, targetPosition, target.getDirection(), target.getExtent())) { - for (IFarmListener listener : farmListeners) { + for (IFarmComponent.Listener listener : farmListeners) { listener.hasCultivated(logic, targetPosition, target.getDirection(), target.getExtent()); } return true; @@ -144,7 +135,7 @@ public static boolean cultivateTarget(Level world, IFarmHousing farmHousing, Far return false; } - public static Collection harvestTargets(Level world, IFarmHousing housing, List farmTargets, IFarmLogic logic, Iterable farmListeners) { + public static Collection harvestTargets(Level world, IFarmHousing housing, List farmTargets, IFarmLogic logic, Iterable farmListeners) { for (FarmTarget target : farmTargets) { Collection harvested = harvestTarget(world, housing, target, logic, farmListeners); if (!harvested.isEmpty()) { @@ -155,12 +146,12 @@ public static Collection harvestTargets(Level world, IFarmHousing housing return Collections.emptyList(); } - public static Collection harvestTarget(Level world, IFarmHousing housing, FarmTarget target, IFarmLogic logic, Iterable farmListeners) { + public static Collection harvestTarget(Level world, IFarmHousing housing, FarmTarget target, IFarmLogic logic, Iterable farmListeners) { BlockPos pos = target.getStart().offset(0, target.getYOffset(), 0); Collection harvested = logic.harvest(world, housing, target.getDirection(), target.getExtent(), pos); if (!harvested.isEmpty()) { // Let event handlers know. - for (IFarmListener listener : farmListeners) { + for (IFarmComponent.Listener listener : farmListeners) { listener.hasScheduledHarvest(harvested, logic, pos, target.getDirection(), target.getExtent()); } } diff --git a/src/main/java/forestry/farming/FarmManager.java b/src/main/java/forestry/farming/FarmManager.java index 55c5c96ef5..12ef4999d7 100644 --- a/src/main/java/forestry/farming/FarmManager.java +++ b/src/main/java/forestry/farming/FarmManager.java @@ -7,6 +7,7 @@ import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.api.farming.*; +import forestry.api.multiblock.IFarmComponent; import forestry.core.config.Constants; import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidTagFilter; @@ -20,12 +21,13 @@ import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import javax.annotation.Nullable; import java.util.*; @@ -41,7 +43,7 @@ public class FarmManager implements INbtReadable, INbtWritable, IStreamable, IEx private FarmingStage stage = FarmingStage.CULTIVATE; - private final Set farmListeners = new HashSet<>(); + private final Set farmListeners = new HashSet<>(); private final FarmHydrationManager hydrationManager; private final FarmFertilizerManager fertilizerManager; @@ -77,11 +79,11 @@ public StandardTank getResourceTank() { return this.resourceTank; } - public void addListener(IFarmListener listener) { + public void addListener(IFarmComponent.Listener listener) { this.farmListeners.add(listener); } - public void removeListener(IFarmListener listener) { + public void removeListener(IFarmComponent.Listener listener) { this.farmListeners.remove(listener); } @@ -118,7 +120,7 @@ public boolean doWork() { // Cultivation and collection FarmWorkStatus farmWorkStatus = new FarmWorkStatus(); - Level level = this.housing.getWorldObj(); + Level level = this.housing.getLevel(); ObjectArrayList farmDirections = new ObjectArrayList<>(HorizontalDirection.VALUES); Util.shuffle(farmDirections, level.random); for (Direction farmSide : farmDirections) { @@ -173,13 +175,13 @@ public boolean doWork() { } private void cultivateTargets(FarmWorkStatus farmWorkStatus, List farmTargets, IFarmLogic logic, Direction farmSide) { - Level level = this.housing.getWorldObj(); + Level level = this.housing.getLevel(); if (farmWorkStatus.hasFarmland && !FarmHelper.isCycleCanceledByListeners(logic, farmSide, this.farmListeners)) { - final float hydrationModifier = this.hydrationManager.getHydrationModifier(); - final int fertilizerConsumption = Math.round(logic.getType().getFertilizerConsumption(this.housing)); - final int liquidConsumption = logic.getType().getWaterConsumption(this.housing, hydrationModifier); - final FluidStack liquid = new FluidStack(Fluids.WATER, liquidConsumption); + float hydrationModifier = this.hydrationManager.getHydrationModifier(); + int fertilizerConsumption = Math.round(logic.getType().getFertilizerConsumption(this.housing)); + int liquidConsumption = logic.getType().getWaterConsumption(this.housing, hydrationModifier); + FluidStack liquid = new FluidStack(Fluids.WATER, liquidConsumption); for (FarmTarget target : farmTargets) { // Check fertilizer and water @@ -205,13 +207,13 @@ private void cultivateTargets(FarmWorkStatus farmWorkStatus, List fa } private boolean collectWindfall(IFarmLogic logic) { - List collected = logic.collect(this.housing.getWorldObj(), this.housing); + List collected = logic.collect(this.housing.getLevel(), this.housing); if (collected.isEmpty()) { return false; } // Let event handlers know. - for (IFarmListener listener : this.farmListeners) { + for (IFarmComponent.Listener listener : this.farmListeners) { listener.hasCollected(collected, logic); } @@ -222,7 +224,7 @@ private boolean collectWindfall(IFarmLogic logic) { private boolean cullCrop(ICrop crop, IFarmLogic provider) { // Let event handlers handle the harvest first. - for (IFarmListener listener : this.farmListeners) { + for (IFarmComponent.Listener listener : this.farmListeners) { if (listener.beforeCropHarvest(crop)) { return true; } @@ -255,7 +257,7 @@ private boolean cullCrop(ICrop crop, IFarmLogic provider) { this.housing.removeLiquid(requiredLiquid); // Let event handlers handle the harvest first. - for (IFarmListener listener : this.farmListeners) { + for (IFarmComponent.Listener listener : this.farmListeners) { listener.afterCropHarvest(harvested, crop); } @@ -265,32 +267,32 @@ private boolean cullCrop(ICrop crop, IFarmLogic provider) { } @Override - public CompoundTag write(CompoundTag data) { - this.hydrationManager.write(data); - this.tankManager.write(data); - this.fertilizerManager.write(data); + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { + this.hydrationManager.write(data, registries); + this.tankManager.write(data, registries); + this.fertilizerManager.write(data, registries); return data; } @Override - public void read(CompoundTag data) { - this.hydrationManager.read(data); - this.tankManager.read(data); - this.fertilizerManager.read(data); + public void read(CompoundTag data, HolderLookup.Provider registries) { + this.hydrationManager.read(data, registries); + this.tankManager.read(data, registries); + this.fertilizerManager.read(data, registries); } @Override - public void writeData(FriendlyByteBuf data) { - this.tankManager.writeData(data); - this.hydrationManager.writeData(data); - this.fertilizerManager.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + this.tankManager.writeData(buffer); + this.hydrationManager.writeData(buffer); + this.fertilizerManager.writeData(buffer); } @Override - public void readData(FriendlyByteBuf data) { - this.tankManager.readData(data); - this.hydrationManager.readData(data); - this.fertilizerManager.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + this.tankManager.readData(buffer); + this.hydrationManager.readData(buffer); + this.fertilizerManager.readData(buffer); } public void clearTargets() { diff --git a/src/main/java/forestry/farming/blocks/EnumFarmBlockType.java b/src/main/java/forestry/farming/blocks/EnumFarmBlockType.java index d930bf95d3..9b30a80196 100644 --- a/src/main/java/forestry/farming/blocks/EnumFarmBlockType.java +++ b/src/main/java/forestry/farming/blocks/EnumFarmBlockType.java @@ -12,7 +12,7 @@ public enum EnumFarmBlockType implements IBlockSubtype { CONTROL; @Override - public String getSerializedName() { + public String identifier() { return name().toLowerCase(Locale.ENGLISH); } } diff --git a/src/main/java/forestry/farming/blocks/EnumFarmMaterial.java b/src/main/java/forestry/farming/blocks/EnumFarmMaterial.java index 122c9e543e..9838f8fe59 100644 --- a/src/main/java/forestry/farming/blocks/EnumFarmMaterial.java +++ b/src/main/java/forestry/farming/blocks/EnumFarmMaterial.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.blocks; import forestry.api.core.IBlockSubtype; @@ -53,7 +43,7 @@ public Component getDisplayName() { } @Override - public String getSerializedName() { + public String identifier() { return name().toLowerCase(Locale.ENGLISH); } diff --git a/src/main/java/forestry/farming/blocks/FarmBlock.java b/src/main/java/forestry/farming/blocks/FarmBlock.java index 2862f16943..9992f6ecea 100644 --- a/src/main/java/forestry/farming/blocks/FarmBlock.java +++ b/src/main/java/forestry/farming/blocks/FarmBlock.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.blocks; import forestry.core.blocks.BlockStructure; @@ -55,11 +45,11 @@ public EnumFarmMaterial getFarmMaterial() { @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return switch (this.type) { - case GEARBOX -> new TileFarmGearbox(pos, state); - case HATCH -> new TileFarmHatch(pos, state); - case VALVE -> new TileFarmValve(pos, state); - case CONTROL -> new TileFarmControl(pos, state); - default -> new TileFarmPlain(pos, state); + case GEARBOX -> new MultifarmGearboxBlockEntity(pos, state); + case HATCH -> new MultifarmHatchBlockEntity(pos, state); + case VALVE -> new MultifarmValveBlockEntity(pos, state); + case CONTROL -> new MultifarmControlBlockEntity(pos, state); + default -> new MultifarmBlockEntity(pos, state); }; } diff --git a/src/main/java/forestry/farming/blocks/package-info.java b/src/main/java/forestry/farming/blocks/package-info.java index d15cd212ba..ca47672f73 100644 --- a/src/main/java/forestry/farming/blocks/package-info.java +++ b/src/main/java/forestry/farming/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.blocks; diff --git a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java index 2d2c3aedd6..03c13b63bc 100755 --- a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java +++ b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java @@ -1,15 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.circuits; +import com.google.common.base.Suppliers; import forestry.api.IForestryApi; import forestry.api.farming.HorizontalDirection; import forestry.api.farming.IFarmCircuit; @@ -18,7 +9,6 @@ import forestry.core.circuits.Circuit; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.common.util.Lazy; import javax.annotation.Nullable; import java.util.function.Supplier; @@ -29,7 +19,7 @@ public class CircuitFarmLogic extends Circuit implements IFarmCircuit { public CircuitFarmLogic(String uid, ResourceLocation farmTypeId, boolean manual) { super(uid); - this.farmType = Lazy.of(() -> IForestryApi.INSTANCE.getFarmingManager().getFarmType(farmTypeId)); + this.farmType = Suppliers.memoize(() -> IForestryApi.INSTANCE.getFarmingManager().getFarmType(farmTypeId)); this.manual = manual; } diff --git a/src/main/java/forestry/farming/circuits/package-info.java b/src/main/java/forestry/farming/circuits/package-info.java index bef3eb74f4..8598626374 100644 --- a/src/main/java/forestry/farming/circuits/package-info.java +++ b/src/main/java/forestry/farming/circuits/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.circuits; diff --git a/src/main/java/forestry/farming/client/FarmingClientHandler.java b/src/main/java/forestry/farming/client/FarmingClientHandler.java index 32bc81de7b..bfccc3d036 100644 --- a/src/main/java/forestry/farming/client/FarmingClientHandler.java +++ b/src/main/java/forestry/farming/client/FarmingClientHandler.java @@ -1,29 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.client; import forestry.api.client.IClientModuleHandler; import forestry.farming.features.FarmingMenuTypes; import forestry.farming.gui.GuiFarm; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; public class FarmingClientHandler implements IClientModuleHandler { @Override public void registerEvents(IEventBus modBus) { - modBus.addListener(FarmingClientHandler::onClientSetup); + modBus.addListener(FarmingClientHandler::registerMenus); } - private static void onClientSetup(FMLClientSetupEvent event) { - event.enqueueWork(() -> MenuScreens.register(FarmingMenuTypes.FARM.menuType(), GuiFarm::new)); + private static void registerMenus(RegisterMenuScreensEvent event) { + event.register(FarmingMenuTypes.FARM.menuType(), GuiFarm::new); } } diff --git a/src/main/java/forestry/farming/client/package-info.java b/src/main/java/forestry/farming/client/package-info.java index a369e432be..c1b68097e4 100644 --- a/src/main/java/forestry/farming/client/package-info.java +++ b/src/main/java/forestry/farming/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.client; diff --git a/src/main/java/forestry/farming/compat/FarmingInfoRecipeCategory.java b/src/main/java/forestry/farming/compat/FarmingInfoRecipeCategory.java index ab6baa3da5..081c6b1d1a 100644 --- a/src/main/java/forestry/farming/compat/FarmingInfoRecipeCategory.java +++ b/src/main/java/forestry/farming/compat/FarmingInfoRecipeCategory.java @@ -10,7 +10,7 @@ import forestry.core.config.Constants; import forestry.core.features.CoreItems; import forestry.core.recipes.jei.ForestryRecipeCategory; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.builder.IRecipeSlotBuilder; diff --git a/src/main/java/forestry/farming/compat/package-info.java b/src/main/java/forestry/farming/compat/package-info.java index 9bfc34b206..4d6c62c8fc 100644 --- a/src/main/java/forestry/farming/compat/package-info.java +++ b/src/main/java/forestry/farming/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.compat; diff --git a/src/main/java/forestry/farming/features/FarmingMenuTypes.java b/src/main/java/forestry/farming/features/FarmingMenuTypes.java index 9f5bab749c..74d5a5486b 100644 --- a/src/main/java/forestry/farming/features/FarmingMenuTypes.java +++ b/src/main/java/forestry/farming/features/FarmingMenuTypes.java @@ -1,7 +1,7 @@ package forestry.farming.features; import forestry.api.modules.ForestryModuleIds; -import forestry.farming.gui.ContainerFarm; +import forestry.farming.gui.FarmMenu; import forestry.modules.features.FeatureMenuType; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; @@ -11,5 +11,5 @@ public class FarmingMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.FARMING); - public static final FeatureMenuType FARM = REGISTRY.menuType(ContainerFarm::fromNetwork, "farm"); + public static final FeatureMenuType FARM = REGISTRY.menuType(FarmMenu::fromNetwork, "farm"); } diff --git a/src/main/java/forestry/farming/features/FarmingTiles.java b/src/main/java/forestry/farming/features/FarmingTiles.java index 7b0608d600..dfd2eff4a6 100644 --- a/src/main/java/forestry/farming/features/FarmingTiles.java +++ b/src/main/java/forestry/farming/features/FarmingTiles.java @@ -12,9 +12,9 @@ public class FarmingTiles { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.FARMING); - public static final FeatureTileType CONTROL = REGISTRY.tile(TileFarmControl::new, "control", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.CONTROL)); - public static final FeatureTileType GEARBOX = REGISTRY.tile(TileFarmGearbox::new, "gearbox", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.GEARBOX)); - public static final FeatureTileType HATCH = REGISTRY.tile(TileFarmHatch::new, "hatch", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.HATCH)); - public static final FeatureTileType PLAIN = REGISTRY.tile(TileFarmPlain::new, "plain", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.PLAIN)); - public static final FeatureTileType VALVE = REGISTRY.tile(TileFarmValve::new, "valve", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.VALVE)); + public static final FeatureTileType CONTROL = REGISTRY.tile(MultifarmControlBlockEntity::new, "control", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.CONTROL)); + public static final FeatureTileType GEARBOX = REGISTRY.tile(MultifarmGearboxBlockEntity::new, "gearbox", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.GEARBOX)); + public static final FeatureTileType HATCH = REGISTRY.tile(MultifarmHatchBlockEntity::new, "hatch", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.HATCH)); + public static final FeatureTileType PLAIN = REGISTRY.tile(MultifarmBlockEntity::new, "plain", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.PLAIN)); + public static final FeatureTileType VALVE = REGISTRY.tile(MultifarmValveBlockEntity::new, "valve", () -> FarmingBlocks.FARM.getRowBlocks(EnumFarmBlockType.VALVE)); } diff --git a/src/main/java/forestry/farming/features/package-info.java b/src/main/java/forestry/farming/features/package-info.java index 1090709e00..dbf33da39c 100644 --- a/src/main/java/forestry/farming/features/package-info.java +++ b/src/main/java/forestry/farming/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.features; diff --git a/src/main/java/forestry/farming/gui/ContainerFarm.java b/src/main/java/forestry/farming/gui/ContainerFarm.java deleted file mode 100755 index 8a0b1a3984..0000000000 --- a/src/main/java/forestry/farming/gui/ContainerFarm.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.gui; - -import forestry.core.gui.ContainerSocketed; -import forestry.core.gui.slots.SlotFiltered; -import forestry.core.gui.slots.SlotLiquidIn; -import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.packets.PacketGuiStream; -import forestry.core.tiles.TileUtil; -import forestry.farming.features.FarmingMenuTypes; -import forestry.farming.multiblock.InventoryFarm; -import forestry.farming.tiles.TileFarm; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.entity.player.Inventory; -import net.minecraftforge.fluids.IFluidTank; - -public class ContainerFarm extends ContainerSocketed { - public static ContainerFarm fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { - TileFarm tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileFarm.class); - return new ContainerFarm(windowId, inv, tile); - } - - public ContainerFarm(int windowId, Inventory playerInventory, TileFarm data) { - super(windowId, FarmingMenuTypes.FARM.menuType(), playerInventory, data, 28, 138); - - // Resources - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 2; j++) { - this.addSlot(new SlotFiltered(this.tile, InventoryFarm.CONFIG.resourcesStart + j + i * 2, 123 + j * 18, 22 + i * 18)); - } - } - - // Germlings - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 2; j++) { - this.addSlot(new SlotFiltered(this.tile, InventoryFarm.CONFIG.germlingsStart + j + i * 2, 164 + j * 18, 22 + i * 18)); - } - } - - // Production 1 - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - this.addSlot(new SlotOutput(this.tile, InventoryFarm.CONFIG.productionStart + j + i * 2, 123 + j * 18, 86 + i * 18)); - } - } - - // Production 2 - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - this.addSlot(new SlotOutput(this.tile, InventoryFarm.CONFIG.productionStart + 4 + j + i * 2, 164 + j * 18, 86 + i * 18)); - } - } - - // Fertilizer - this.addSlot(new SlotFiltered(this.tile, InventoryFarm.CONFIG.fertilizerStart, 63, 95)); - // Can Slot - this.addSlot(new SlotLiquidIn(this.tile, InventoryFarm.CONFIG.canStart, 15, 95)); - } - - @Override - public void broadcastChanges() { - super.broadcastChanges(); - PacketGuiStream packet = new PacketGuiStream(this.tile); - sendPacketToListeners(packet); - } - - public IFluidTank getTank(int slot) { - return this.tile.getMultiblockLogic().getController().getTankManager().getTank(slot); - } -} diff --git a/src/main/java/forestry/farming/gui/FarmLedger.java b/src/main/java/forestry/farming/gui/FarmLedger.java index 5cc94781eb..e041a256a2 100644 --- a/src/main/java/forestry/farming/gui/FarmLedger.java +++ b/src/main/java/forestry/farming/gui/FarmLedger.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.gui; import forestry.core.gui.ledgers.Ledger; @@ -18,8 +8,8 @@ import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.network.chat.Component; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class FarmLedger extends Ledger { private final IFarmLedgerDelegate delegate; diff --git a/src/main/java/forestry/farming/gui/FarmLogicSlot.java b/src/main/java/forestry/farming/gui/FarmLogicSlot.java index d31c1539d7..5fc7b58d1b 100644 --- a/src/main/java/forestry/farming/gui/FarmLogicSlot.java +++ b/src/main/java/forestry/farming/gui/FarmLogicSlot.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.gui; import com.mojang.blaze3d.systems.RenderSystem; diff --git a/src/main/java/forestry/farming/gui/FarmMenu.java b/src/main/java/forestry/farming/gui/FarmMenu.java new file mode 100644 index 0000000000..dcec87f991 --- /dev/null +++ b/src/main/java/forestry/farming/gui/FarmMenu.java @@ -0,0 +1,69 @@ +package forestry.farming.gui; + +import forestry.core.gui.SocketedMenu; +import forestry.core.gui.slots.SlotFiltered; +import forestry.core.gui.slots.SlotLiquidIn; +import forestry.core.gui.slots.SlotOutput; +import forestry.core.network.packets.PacketGuiStream; +import forestry.core.tiles.TileUtil; +import forestry.farming.features.FarmingMenuTypes; +import forestry.farming.multiblock.MultifarmInventory; +import forestry.farming.tiles.AbstractMultifarmBlockEntity; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Inventory; +import net.neoforged.neoforge.fluids.IFluidTank; + +public class FarmMenu extends SocketedMenu { + public static FarmMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + AbstractMultifarmBlockEntity tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), AbstractMultifarmBlockEntity.class); + return new FarmMenu(windowId, inv, tile); + } + + public FarmMenu(int windowId, Inventory playerInventory, AbstractMultifarmBlockEntity data) { + super(windowId, FarmingMenuTypes.FARM.menuType(), playerInventory, data, 28, 138); + + // Resources + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + this.addSlot(new SlotFiltered(this.tile, MultifarmInventory.CONFIG.resourcesStart + j + i * 2, 123 + j * 18, 22 + i * 18)); + } + } + + // Germlings + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 2; j++) { + this.addSlot(new SlotFiltered(this.tile, MultifarmInventory.CONFIG.germlingsStart + j + i * 2, 164 + j * 18, 22 + i * 18)); + } + } + + // Production 1 + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + this.addSlot(new SlotOutput(this.tile, MultifarmInventory.CONFIG.productionStart + j + i * 2, 123 + j * 18, 86 + i * 18)); + } + } + + // Production 2 + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + this.addSlot(new SlotOutput(this.tile, MultifarmInventory.CONFIG.productionStart + 4 + j + i * 2, 164 + j * 18, 86 + i * 18)); + } + } + + // Fertilizer + this.addSlot(new SlotFiltered(this.tile, MultifarmInventory.CONFIG.fertilizerStart, 63, 95)); + // Can Slot + this.addSlot(new SlotLiquidIn(this.tile, MultifarmInventory.CONFIG.canStart, 15, 95)); + } + + @Override + public void broadcastChanges() { + super.broadcastChanges(); + PacketGuiStream packet = new PacketGuiStream(this.tile); + sendPacketToListeners(packet); + } + + public IFluidTank getTank(int slot) { + return this.tile.getMultiblockLogic().getController().getTankManager().getTank(slot); + } +} diff --git a/src/main/java/forestry/farming/gui/GuiFarm.java b/src/main/java/forestry/farming/gui/GuiFarm.java index dc246f9657..381d742704 100755 --- a/src/main/java/forestry/farming/gui/GuiFarm.java +++ b/src/main/java/forestry/farming/gui/GuiFarm.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.gui; import forestry.core.config.Constants; @@ -15,16 +5,16 @@ import forestry.core.gui.widgets.SocketWidget; import forestry.core.gui.widgets.TankWidget; import forestry.farming.multiblock.IFarmControllerInternal; -import forestry.farming.tiles.TileFarm; +import forestry.farming.tiles.AbstractMultifarmBlockEntity; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiFarm extends GuiForestryTitled { - private final TileFarm tile; +public class GuiFarm extends GuiForestryTitled { + private final AbstractMultifarmBlockEntity tile; - public GuiFarm(ContainerFarm container, Inventory inv, Component title) { + public GuiFarm(FarmMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/mfarm.png", container, inv, title); this.tile = container.getTile(); diff --git a/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java b/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java index 545236c839..9de6932de6 100644 --- a/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java +++ b/src/main/java/forestry/farming/gui/IFarmLedgerDelegate.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.gui; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/farming/gui/package-info.java b/src/main/java/forestry/farming/gui/package-info.java index b96e49808c..70a4cf3ef2 100644 --- a/src/main/java/forestry/farming/gui/package-info.java +++ b/src/main/java/forestry/farming/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.gui; diff --git a/src/main/java/forestry/farming/items/ItemBlockFarm.java b/src/main/java/forestry/farming/items/ItemBlockFarm.java index d023e7369c..63376384ef 100755 --- a/src/main/java/forestry/farming/items/ItemBlockFarm.java +++ b/src/main/java/forestry/farming/items/ItemBlockFarm.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.items; import forestry.core.items.ItemBlockForestry; @@ -19,9 +9,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.Level; -import javax.annotation.Nullable; import java.util.List; public class ItemBlockFarm extends ItemBlockForestry { @@ -30,17 +18,17 @@ public ItemBlockFarm(FarmBlock block) { } @Override - public void appendHoverText(ItemStack stack, @Nullable Level world, List tooltip, TooltipFlag flag) { + public void appendHoverText(ItemStack stack, TooltipContext ctx, List tooltip, TooltipFlag advanced) { if (Screen.hasShiftDown()) { tooltip.add(Component.translatable("block.forestry.farm.tooltip").withStyle(ChatFormatting.GRAY)); } else { - ItemTooltipUtil.addShiftInformation(stack, world, tooltip, flag); + ItemTooltipUtil.addShiftInformation(tooltip); } } @Override public String getDescriptionId() { FarmBlock block = getBlock(); - return "block.forestry.farm_" + block.getType().getSerializedName(); + return "block.forestry.farm_" + block.getType().identifier(); } } diff --git a/src/main/java/forestry/farming/items/package-info.java b/src/main/java/forestry/farming/items/package-info.java index 47d621915b..92f5d00b0d 100644 --- a/src/main/java/forestry/farming/items/package-info.java +++ b/src/main/java/forestry/farming/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.items; diff --git a/src/main/java/forestry/farming/logic/FarmLogic.java b/src/main/java/forestry/farming/logic/FarmLogic.java index 9435000876..7277fa67d0 100755 --- a/src/main/java/forestry/farming/logic/FarmLogic.java +++ b/src/main/java/forestry/farming/logic/FarmLogic.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import com.google.common.base.Predicate; diff --git a/src/main/java/forestry/farming/logic/FarmLogicArboreal.java b/src/main/java/forestry/farming/logic/FarmLogicArboreal.java index 19ccc427e6..8c310e273c 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicArboreal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicArboreal.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/FarmLogicCocoa.java b/src/main/java/forestry/farming/logic/FarmLogicCocoa.java index 337e16f8f8..fa1bb34316 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCocoa.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCocoa.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.*; @@ -82,7 +72,7 @@ protected boolean maintainSoil(Level world, IFarmHousing farmHousing, BlockPos p continue; } - if (!BlockUtil.isReplaceableBlock(state, world, location)) { + if (!BlockUtil.isReplaceableBlock(world, location)) { BlockUtil.getBlockDrops(world, location).forEach(farmHousing::addPendingProduct); world.setBlockAndUpdate(location, Blocks.AIR.defaultBlockState()); return trySetSoil(world, farmHousing, location, soil.resource(), soil.soilState()); diff --git a/src/main/java/forestry/farming/logic/FarmLogicCrops.java b/src/main/java/forestry/farming/logic/FarmLogicCrops.java index 1902f645f2..01a9ebb8ec 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCrops.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCrops.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmHousing; @@ -41,7 +31,7 @@ protected boolean maintainCrops(Level world, IFarmHousing farmHousing, BlockPos } BlockState state = world.getBlockState(position); - if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(state, world, position)) { + if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(world, position)) { continue; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicEnder.java b/src/main/java/forestry/farming/logic/FarmLogicEnder.java index 8e14c1debb..285db0b25f 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicEnder.java +++ b/src/main/java/forestry/farming/logic/FarmLogicEnder.java @@ -90,7 +90,7 @@ protected boolean maintainSeedlings(Level world, IFarmHousing farmHousing, Block for (int i = 0; i < extent; i++) { BlockPos position = translateWithOffset(pos, direction, i); BlockState state = world.getBlockState(position); - if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(state, world, position)) { + if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(world, position)) { continue; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicGourd.java b/src/main/java/forestry/farming/logic/FarmLogicGourd.java index bb459cd138..1471116167 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicGourd.java +++ b/src/main/java/forestry/farming/logic/FarmLogicGourd.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmHousing; @@ -33,7 +23,7 @@ protected boolean maintainCrops(Level world, IFarmHousing farmHousing, BlockPos } BlockState state = world.getBlockState(position); - if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(state, world, position) + if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(world, position) || !isValidPosition(farmHousing, direction, position, CultivationType.CROP)) { continue; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java index 8931f5a0af..6aff5b548b 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java +++ b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmHousing; diff --git a/src/main/java/forestry/farming/logic/FarmLogicInfernal.java b/src/main/java/forestry/farming/logic/FarmLogicInfernal.java index 844aebb290..d6cd4c8b61 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicInfernal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicInfernal.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.ICrop; @@ -62,7 +52,7 @@ protected boolean maintainSeedlings(Level world, IFarmHousing farmHousing, Block } BlockState blockState = world.getBlockState(position); - if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(blockState, world, position)) { + if (!world.isEmptyBlock(position) && !BlockUtil.isReplaceableBlock(world, position)) { continue; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicMushroom.java b/src/main/java/forestry/farming/logic/FarmLogicMushroom.java index 873dfcfa79..f35067881d 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicMushroom.java +++ b/src/main/java/forestry/farming/logic/FarmLogicMushroom.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmHousing; diff --git a/src/main/java/forestry/farming/logic/FarmLogicOrchard.java b/src/main/java/forestry/farming/logic/FarmLogicOrchard.java index a42e05d88f..9dc2e1097d 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicOrchard.java +++ b/src/main/java/forestry/farming/logic/FarmLogicOrchard.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/FarmLogicPeat.java b/src/main/java/forestry/farming/logic/FarmLogicPeat.java index d907c32b80..8646378389 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicPeat.java +++ b/src/main/java/forestry/farming/logic/FarmLogicPeat.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/FarmLogicReeds.java b/src/main/java/forestry/farming/logic/FarmLogicReeds.java index 67698966c9..54c90a405c 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicReeds.java +++ b/src/main/java/forestry/farming/logic/FarmLogicReeds.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmType; diff --git a/src/main/java/forestry/farming/logic/FarmLogicSucculent.java b/src/main/java/forestry/farming/logic/FarmLogicSucculent.java index 9d623b5165..fc5d99742e 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicSucculent.java +++ b/src/main/java/forestry/farming/logic/FarmLogicSucculent.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmType; diff --git a/src/main/java/forestry/farming/logic/FarmLogicWatered.java b/src/main/java/forestry/farming/logic/FarmLogicWatered.java index 7c926b5c8c..587a25796b 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicWatered.java +++ b/src/main/java/forestry/farming/logic/FarmLogicWatered.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic; import forestry.api.farming.IFarmHousing; @@ -22,8 +12,8 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; import org.apache.commons.lang3.tuple.Pair; public abstract class FarmLogicWatered extends FarmLogicSoil { @@ -44,7 +34,6 @@ public boolean cultivate(Level level, IFarmHousing farmHousing, BlockPos pos, Di } return maintainCrops(level, farmHousing, pos.above(), direction, extent); - } protected boolean isValidPosition(IFarmHousing housing, Direction direction, BlockPos pos, CultivationType type) { @@ -80,7 +69,7 @@ private boolean maintainSoil(Level world, IFarmHousing farmHousing, BlockPos pos break; } - if (!BlockUtil.isReplaceableBlock(state, world, position)) { + if (!BlockUtil.isReplaceableBlock(world, position)) { BlockUtil.getBlockDrops(world, position).forEach(farmHousing::addPendingProduct); world.removeBlock(position, false); return FarmLogicCocoa.trySetSoil(world, farmHousing, position, soil.resource(), soil.soilState()); diff --git a/src/main/java/forestry/farming/logic/crops/Crop.java b/src/main/java/forestry/farming/logic/crops/Crop.java index 667f885d1d..0558e51316 100644 --- a/src/main/java/forestry/farming/logic/crops/Crop.java +++ b/src/main/java/forestry/farming/logic/crops/Crop.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.crops; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/crops/CropDestroy.java b/src/main/java/forestry/farming/logic/crops/CropDestroy.java index 7d0390b7cf..319f48961a 100644 --- a/src/main/java/forestry/farming/logic/crops/CropDestroy.java +++ b/src/main/java/forestry/farming/logic/crops/CropDestroy.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.crops; import forestry.core.utils.BlockUtil; diff --git a/src/main/java/forestry/farming/logic/crops/CropFruit.java b/src/main/java/forestry/farming/logic/crops/CropFruit.java index dfddd9c9d9..12f2cb9fdf 100644 --- a/src/main/java/forestry/farming/logic/crops/CropFruit.java +++ b/src/main/java/forestry/farming/logic/crops/CropFruit.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.crops; import forestry.api.genetics.IFruitBearer; @@ -39,6 +29,6 @@ protected List harvestBlock(Level level, BlockPos pos) { } BlockUtil.sendDestroyEffects(level, pos, level.getBlockState(pos)); - return tile.pickFruit(ItemStack.EMPTY); + return tile.pickFruit(); } } diff --git a/src/main/java/forestry/farming/logic/crops/CropPeat.java b/src/main/java/forestry/farming/logic/crops/CropPeat.java index 87195cbf97..30835cd209 100644 --- a/src/main/java/forestry/farming/logic/crops/CropPeat.java +++ b/src/main/java/forestry/farming/logic/crops/CropPeat.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.crops; import forestry.core.features.CoreBlocks; diff --git a/src/main/java/forestry/farming/logic/crops/package-info.java b/src/main/java/forestry/farming/logic/crops/package-info.java index abe3e88ab4..18221a297b 100644 --- a/src/main/java/forestry/farming/logic/crops/package-info.java +++ b/src/main/java/forestry/farming/logic/crops/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.logic.crops; diff --git a/src/main/java/forestry/farming/logic/farmables/FarmableCocoa.java b/src/main/java/forestry/farming/logic/farmables/FarmableCocoa.java index 9e661f8487..de16a929c4 100644 --- a/src/main/java/forestry/farming/logic/farmables/FarmableCocoa.java +++ b/src/main/java/forestry/farming/logic/farmables/FarmableCocoa.java @@ -1,16 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.farmables; -import forestry.core.utils.BlockUtil; +import forestry.api.arboriculture.ForestryTreeSpecies; +import forestry.api.genetics.IGenome; +import forestry.api.genetics.alleles.ForestryAlleles; +import forestry.core.utils.SpeciesUtil; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -26,6 +19,7 @@ public FarmableCocoa() { @Override public boolean plantSaplingAt(Player player, ItemStack germling, Level level, BlockPos pos) { - return BlockUtil.tryPlantCocoaPod(level, pos); + IGenome genome = SpeciesUtil.TREE_TYPE.get().getSpecies(ForestryTreeSpecies.JUNGLE).getDefaultGenome(); + return ForestryAlleles.FRUIT_COCOA.value().tryPlace(level, pos, genome); } } diff --git a/src/main/java/forestry/farming/logic/farmables/FarmableGE.java b/src/main/java/forestry/farming/logic/farmables/FarmableGE.java index aec480d1ee..ce80346449 100644 --- a/src/main/java/forestry/farming/logic/farmables/FarmableGE.java +++ b/src/main/java/forestry/farming/logic/farmables/FarmableGE.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.farmables; import com.google.common.collect.ImmutableSet; diff --git a/src/main/java/forestry/farming/logic/farmables/FarmableGourd.java b/src/main/java/forestry/farming/logic/farmables/FarmableGourd.java index 9eb59c3163..83e324b02d 100644 --- a/src/main/java/forestry/farming/logic/farmables/FarmableGourd.java +++ b/src/main/java/forestry/farming/logic/farmables/FarmableGourd.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.farmables; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/farmables/FarmableMushroom.java b/src/main/java/forestry/farming/logic/farmables/FarmableMushroom.java index 60728e9d79..ff796f5a8c 100644 --- a/src/main/java/forestry/farming/logic/farmables/FarmableMushroom.java +++ b/src/main/java/forestry/farming/logic/farmables/FarmableMushroom.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.farmables; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/farmables/FarmableSapling.java b/src/main/java/forestry/farming/logic/farmables/FarmableSapling.java index 5c4999dfaf..c32895bc2e 100644 --- a/src/main/java/forestry/farming/logic/farmables/FarmableSapling.java +++ b/src/main/java/forestry/farming/logic/farmables/FarmableSapling.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.farmables; import com.google.common.collect.ImmutableSet; diff --git a/src/main/java/forestry/farming/logic/farmables/FarmableStacked.java b/src/main/java/forestry/farming/logic/farmables/FarmableStacked.java index 59f7c50396..f189cecb75 100644 --- a/src/main/java/forestry/farming/logic/farmables/FarmableStacked.java +++ b/src/main/java/forestry/farming/logic/farmables/FarmableStacked.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.logic.farmables; import forestry.api.farming.ICrop; diff --git a/src/main/java/forestry/farming/logic/farmables/package-info.java b/src/main/java/forestry/farming/logic/farmables/package-info.java index 05f3a19ad8..b6a76727a8 100644 --- a/src/main/java/forestry/farming/logic/farmables/package-info.java +++ b/src/main/java/forestry/farming/logic/farmables/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.logic.farmables; diff --git a/src/main/java/forestry/farming/logic/package-info.java b/src/main/java/forestry/farming/logic/package-info.java index e608cb0ad3..f759b5b0b7 100644 --- a/src/main/java/forestry/farming/logic/package-info.java +++ b/src/main/java/forestry/farming/logic/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.logic; diff --git a/src/main/java/forestry/farming/multiblock/FakeFarmController.java b/src/main/java/forestry/farming/multiblock/FakeFarmController.java index 373bd85218..77c5fba751 100644 --- a/src/main/java/forestry/farming/multiblock/FakeFarmController.java +++ b/src/main/java/forestry/farming/multiblock/FakeFarmController.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.multiblock; import forestry.api.farming.IFarmLogic; @@ -26,7 +16,7 @@ import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import javax.annotation.Nullable; import java.util.ArrayDeque; @@ -86,7 +76,7 @@ public BlockPos getTopCoord() { } @Override - public BlockPos getCoordinates() { + public BlockPos getBlockPos() { return BlockPos.ZERO; } diff --git a/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java b/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java index 877356434e..36833cb41e 100644 --- a/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java +++ b/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java @@ -1,21 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.multiblock; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.core.network.IStreamable; import forestry.cultivation.IFarmHousingInternal; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; public class FarmFertilizerManager implements INbtWritable, INbtReadable, IStreamable { private static final int BUFFER_FERTILIZER = 200; @@ -24,7 +15,7 @@ public class FarmFertilizerManager implements INbtWritable, INbtReadable, IStrea public FarmFertilizerManager(IFarmHousingInternal housing) { this.inventory = housing.getFarmInventory(); - this.storedFertilizer = 0; + this.storedFertilizer = 0; } public boolean hasFertilizer(int amount) { @@ -40,9 +31,9 @@ public void removeFertilizer(int amount) { return; } - this.storedFertilizer -= amount; + this.storedFertilizer -= amount; if (this.storedFertilizer < 0) { - this.storedFertilizer = 0; + this.storedFertilizer = 0; } } @@ -50,9 +41,9 @@ public boolean maintainFertilizer() { if (this.storedFertilizer <= BUFFER_FERTILIZER) { int fertilizerValue = this.inventory.getFertilizerValue(); if (fertilizerValue < 0) { - this.storedFertilizer += 2000; + this.storedFertilizer += 2000; } else if (this.inventory.useFertilizer()) { - this.storedFertilizer += fertilizerValue; + this.storedFertilizer += fertilizerValue; } } @@ -60,12 +51,12 @@ public boolean maintainFertilizer() { } @Override - public void read(CompoundTag data) { - this.storedFertilizer = data.getInt("StoredFertilizer"); + public void read(CompoundTag data, HolderLookup.Provider registries) { + this.storedFertilizer = data.getInt("StoredFertilizer"); } @Override - public CompoundTag write(CompoundTag data) { + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { data.putInt("StoredFertilizer", this.storedFertilizer); return data; } @@ -79,12 +70,12 @@ public int getStoredFertilizerScaled(IFarmInventoryInternal inventory, int scale } @Override - public void writeData(FriendlyByteBuf data) { - data.writeVarInt(this.storedFertilizer); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeVarInt(this.storedFertilizer); } @Override - public void readData(FriendlyByteBuf data) { - this.storedFertilizer = data.readVarInt(); + public void readData(RegistryFriendlyByteBuf buffer) { + this.storedFertilizer = buffer.readVarInt(); } } diff --git a/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java b/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java index dd4f1bf205..e1894ae568 100644 --- a/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java +++ b/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.multiblock; import forestry.api.core.HumidityType; @@ -18,8 +8,9 @@ import forestry.cultivation.IFarmHousingInternal; import forestry.farming.gui.IFarmLedgerDelegate; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.util.Mth; import net.minecraft.world.level.Level; @@ -37,7 +28,7 @@ public FarmHydrationManager(IFarmHousingInternal housing) { } public void updateServer() { - Level world = this.housing.getWorldObj(); + Level world = this.housing.getLevel(); BlockPos coordinates = this.housing.getTopCoord(); if (world.isRainingAt(coordinates.above())) { if (this.hydrationDelay > 0) { @@ -98,26 +89,26 @@ public double getDrought() { } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { compoundNBT.putInt("HydrationDelay", this.hydrationDelay); compoundNBT.putInt("TicksSinceRainfall", this.ticksSinceRainfall); return compoundNBT; } @Override - public void writeData(FriendlyByteBuf data) { - data.writeVarInt(this.hydrationDelay); - data.writeVarInt(this.ticksSinceRainfall); + public void writeData(RegistryFriendlyByteBuf buffer) { + buffer.writeVarInt(this.hydrationDelay); + buffer.writeVarInt(this.ticksSinceRainfall); } @Override - public void readData(FriendlyByteBuf data) { - this.hydrationDelay = data.readVarInt(); - this.ticksSinceRainfall = data.readVarInt(); + public void readData(RegistryFriendlyByteBuf buffer) { + this.hydrationDelay = buffer.readVarInt(); + this.ticksSinceRainfall = buffer.readVarInt(); } @Override - public void read(CompoundTag nbt) { + public void read(CompoundTag nbt, HolderLookup.Provider registries) { this.hydrationDelay = nbt.getInt("HydrationDelay"); this.ticksSinceRainfall = nbt.getInt("TicksSinceRainfall"); } diff --git a/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java b/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java deleted file mode 100644 index 74e3e9e3ce..0000000000 --- a/src/main/java/forestry/farming/multiblock/FarmMultiblockSizeLimits.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.multiblock; - -import forestry.core.multiblock.IMultiblockSizeLimits; - -enum FarmMultiblockSizeLimits implements IMultiblockSizeLimits { - INSTANCE; - - @Override - public int getMinimumNumberOfBlocksForAssembledMachine() { - return 3 * 3 * 4; - } - - @Override - public int getMaximumXSize() { - return 5; - } - - @Override - public int getMaximumZSize() { - return 5; - } - - @Override - public int getMaximumYSize() { - return 4; - } - - @Override - public int getMinimumXSize() { - return 3; - } - - @Override - public int getMinimumZSize() { - return 3; - } - - @Override - public int getMinimumYSize() { - return 4; - } -} diff --git a/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java index 75517371af..cf631314f9 100644 --- a/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java +++ b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.multiblock; import forestry.api.climate.IClimateProvider; diff --git a/src/main/java/forestry/farming/multiblock/InventoryPlantation.java b/src/main/java/forestry/farming/multiblock/InventoryPlantation.java index 2aeb506884..c83bb16f30 100644 --- a/src/main/java/forestry/farming/multiblock/InventoryPlantation.java +++ b/src/main/java/forestry/farming/multiblock/InventoryPlantation.java @@ -1,10 +1,10 @@ package forestry.farming.multiblock; +import forestry.api.ForestryDataMaps; import forestry.api.IForestryApi; import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmLogic; import forestry.api.farming.IFarmable; -import forestry.core.config.Preference; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; import forestry.core.inventory.InventoryAdapterRestricted; @@ -17,8 +17,9 @@ import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; +import net.neoforged.neoforge.common.ModConfigSpec; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidUtil; import java.util.ArrayDeque; import java.util.List; @@ -30,35 +31,12 @@ * It contains the biggest part of the logic for the inventories like item validation and fertilizer consumption. */ public abstract class InventoryPlantation extends InventoryAdapterRestricted implements IFarmInventoryInternal { - /** - * Config value which modifies the usage of fertilizer. - */ - private static final int FERTILIZER_MODIFIER = Preference.FARM_FERTILIZER_MODIFIER; - - /** - * Farm logic object - */ + private final ModConfigSpec.IntValue fertilizerModifier; protected final H housing; - /** - * Inventory slot config - */ protected final InventoryConfig config; - - /** - * The part of the inventory that contains the resources. - */ protected final Container resourcesInventory; - /** - * The part of the inventory that contains the germlings. - */ protected final Container germlingsInventory; - /** - * The part of the inventory that contains the output resources. - */ protected final Container productInventory; - /** - * The part of the inventory that contains the fertilizer. - */ protected final Container fertilizerInventory; /** @@ -67,7 +45,7 @@ public abstract class InventoryPlantation 0) { - return fertilizerValue * FERTILIZER_MODIFIER; + Integer fertilizerValue = fertilizerStack.getItemHolder().getData(ForestryDataMaps.FARM_FERTILIZERS); + if (fertilizerValue != null && fertilizerValue > 0) { + return fertilizerValue * this.fertilizerModifier.get(); } return 0; } diff --git a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java index 21dba9402a..314b084a93 100644 --- a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java +++ b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java @@ -30,6 +30,6 @@ public IFarmControllerInternal getController() { @Override public IFarmControllerInternal createNewController(Level level) { - return new FarmController(level); + return new MultifarmController(level); } } diff --git a/src/main/java/forestry/farming/multiblock/FarmController.java b/src/main/java/forestry/farming/multiblock/MultifarmController.java old mode 100755 new mode 100644 similarity index 72% rename from src/main/java/forestry/farming/multiblock/FarmController.java rename to src/main/java/forestry/farming/multiblock/MultifarmController.java index 3988197939..8cccf4cc9b --- a/src/main/java/forestry/farming/multiblock/FarmController.java +++ b/src/main/java/forestry/farming/multiblock/MultifarmController.java @@ -1,17 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.multiblock; import com.google.common.base.MoreObjects; -import com.google.common.base.Preconditions; import forestry.api.ForestryTags; import forestry.api.IForestryApi; import forestry.api.circuits.ForestryCircuitSocketTypes; @@ -26,11 +15,13 @@ import forestry.api.multiblock.IFarmComponent; import forestry.api.multiblock.IMultiblockComponent; import forestry.core.config.ForestryConfig; +import forestry.core.features.CoreDataComponents; import forestry.core.fluids.TankManager; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InventoryAdapter; import forestry.core.multiblock.IMultiblockControllerInternal; +import forestry.core.multiblock.MultiblockSizeLimits; import forestry.core.multiblock.MultiblockValidationException; import forestry.core.multiblock.RectangularMultiblockControllerBase; import forestry.core.tiles.ILiquidTankTile; @@ -39,14 +30,11 @@ import forestry.farming.FarmManager; import forestry.farming.FarmTarget; import forestry.farming.gui.IFarmLedgerDelegate; -import forestry.farming.tiles.TileFarmGearbox; -import forestry.farming.tiles.TileFarmPlain; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Holder; -import net.minecraft.core.Vec3i; +import forestry.farming.tiles.MultifarmGearboxBlockEntity; +import forestry.farming.tiles.MultifarmBlockEntity; +import net.minecraft.core.*; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Containers; @@ -56,15 +44,14 @@ import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; import javax.annotation.Nullable; import java.util.*; -public class FarmController extends RectangularMultiblockControllerBase implements IFarmControllerInternal, ILiquidTankTile { - private int allowedExtent = 0; +public class MultifarmController extends RectangularMultiblockControllerBase implements IFarmControllerInternal, ILiquidTankTile { + private static final MultiblockSizeLimits FARM_LIMITS = new MultiblockSizeLimits(3 * 3 * 4, 3, 4, 3, 5, 4, 5); // active components are stored with a tick offset so they do not all tick together private final Map farmActiveComponents = new HashMap<>(); @@ -72,21 +59,21 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private final Map farmLogics = new EnumMap<>(Direction.class); private final InventoryAdapter sockets; - private final InventoryFarm inventory; + private final MultifarmInventory inventory; private final FarmManager manager; // the number of work ticks that this farm has had no power private int noPowerTime = 0; - + private int allowedExtent = 0; @Nullable private Vec3i offset; @Nullable private Vec3i area; - public FarmController(Level world) { - super(world, FarmMultiblockSizeLimits.INSTANCE); + public MultifarmController(Level world) { + super(world, FARM_LIMITS); - this.inventory = new InventoryFarm(this); + this.inventory = new MultifarmInventory(this); this.manager = new FarmManager(this); this.sockets = new InventoryAdapter(1, "sockets"); @@ -114,28 +101,28 @@ public TankManager getTankManager() { @Override public void onAttachedPartWithMultiblockData(IMultiblockComponent part, CompoundTag data) { - this.read(data); + read(data, this.level.registryAccess()); } @Override protected void onBlockAdded(IMultiblockComponent newPart) { if (newPart instanceof IFarmComponent.Listener listenerPart) { - this.manager.addListener(listenerPart.getFarmListener()); + this.manager.addListener(listenerPart); } - if (newPart instanceof IFarmComponent.Active) { - this.farmActiveComponents.put((IFarmComponent.Active) newPart, this.level.random.nextInt(256)); + if (newPart instanceof IFarmComponent.Active active) { + this.farmActiveComponents.put(active, this.level.random.nextInt(256)); } } @Override protected void onBlockRemoved(IMultiblockComponent oldPart) { if (oldPart instanceof IFarmComponent.Listener listenerPart) { - this.manager.removeListener(listenerPart.getFarmListener()); + this.manager.removeListener(listenerPart); } if (oldPart instanceof IFarmComponent.Active) { - this.farmActiveComponents.remove(oldPart); + this.farmActiveComponents.remove(oldPart); } } @@ -145,7 +132,7 @@ protected void isMachineWhole() throws MultiblockValidationException { boolean hasGearbox = false; for (IMultiblockComponent part : this.connectedParts) { - if (part instanceof TileFarmGearbox) { + if (part instanceof MultifarmGearboxBlockEntity) { hasGearbox = true; break; } @@ -159,7 +146,7 @@ protected void isMachineWhole() throws MultiblockValidationException { @Override protected void onMachineDisassembled() { super.onMachineDisassembled(); - this.manager.clearTargets(); + this.manager.clearTargets(); } @Override @@ -170,14 +157,14 @@ public void onDestroyed(BlockPos lastPos) { @Override public void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { - if (level == 2 && !(part instanceof TileFarmPlain)) { + if (level == 2 && !(part instanceof MultifarmBlockEntity)) { throw new MultiblockValidationException(Component.translatable("for.multiblock.farm.error.needPlainBand").getString()); } } @Override public void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { - if (!(part instanceof TileFarmPlain)) { + if (!(part instanceof MultifarmBlockEntity)) { throw new MultiblockValidationException(Component.translatable("for.multiblock.farm.error.needPlainInterior").getString()); } } @@ -194,16 +181,16 @@ public void onAssimilated(IMultiblockControllerInternal assimilator) { @Override protected boolean serverTick(int tickCount) { - this.manager.getHydrationManager().updateServer(); + this.manager.getHydrationManager().updateServer(); if (updateOnInterval(20)) { - this.inventory.drainCan(this.manager.getTankManager()); + this.inventory.drainCan(this.manager.getTankManager()); } boolean hasPower = false; for (Map.Entry entry : this.farmActiveComponents.entrySet()) { IFarmComponent.Active farmComponent = entry.getKey(); - if (farmComponent instanceof TileFarmGearbox gearbox) { + if (farmComponent instanceof MultifarmGearboxBlockEntity gearbox) { hasPower |= gearbox.getEnergyManager().getEnergyStored() > 0; } @@ -212,11 +199,11 @@ protected boolean serverTick(int tickCount) { } if (hasPower) { - this.noPowerTime = 0; + this.noPowerTime = 0; getErrorLogic().setCondition(false, ForestryError.NO_POWER); } else { if (this.noPowerTime <= 4) { - this.noPowerTime++; + this.noPowerTime++; } else { getErrorLogic().setCondition(true, ForestryError.NO_POWER); } @@ -236,40 +223,40 @@ protected void clientTick(int tickCount) { } @Override - public CompoundTag write(CompoundTag data) { - data = super.write(data); - this.sockets.write(data); - this.manager.write(data); - this.inventory.write(data); + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { + data = super.write(data, registries); + this.sockets.write(data, registries); + this.manager.write(data, registries); + this.inventory.write(data, registries); return data; } @Override - public void read(CompoundTag data) { - super.read(data); - this.sockets.read(data); - this.manager.read(data); - this.inventory.read(data); + public void read(CompoundTag data, HolderLookup.Provider registries) { + super.read(data, registries); + this.sockets.read(data, registries); + this.manager.read(data, registries); + this.inventory.read(data, registries); refreshFarmLogics(); } @Override - public void formatDescriptionPacket(CompoundTag data) { - this.sockets.write(data); - this.manager.write(data); + public void encodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries) { + this.sockets.write(data, registries); + this.manager.write(data, registries); } @Override - public void decodeDescriptionPacket(CompoundTag data) { - this.sockets.read(data); - this.manager.read(data); + public void decodeUpdatePacket(CompoundTag data, HolderLookup.Provider registries) { + this.sockets.read(data, registries); + this.manager.read(data, registries); refreshFarmLogics(); } @Override - public BlockPos getCoordinates() { + public BlockPos getBlockPos() { return getReferenceCoord(); } @@ -279,15 +266,15 @@ public BlockPos getTopCoord() { } @Override - public void writeGuiData(FriendlyByteBuf data) { - this.manager.writeData(data); - this.sockets.writeData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + this.manager.writeData(buffer); + this.sockets.writeData(buffer); } @Override - public void readGuiData(FriendlyByteBuf data) { - this.manager.readData(data); - this.sockets.readData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.manager.readData(buffer); + this.sockets.readData(buffer); refreshFarmLogics(); } @@ -300,7 +287,8 @@ private void refreshFarmLogics() { // See whether we have socketed stuff. ItemStack chip = this.sockets.getItem(0); if (!chip.isEmpty()) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(chip); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard chipset = chip.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onLoad(this); } @@ -320,7 +308,7 @@ public HumidityType humidity() { protected Holder getBiome() { BlockPos coords = getReferenceCoord(); if (coords == null) { - return ForgeRegistries.BIOMES.getDelegateOrThrow(Biomes.PLAINS); + return this.level.registryAccess().holderOrThrow(Biomes.PLAINS); } return this.level.getBiome(coords); } @@ -334,7 +322,7 @@ public BlockPos getCoords() { public Vec3i getOffset() { if (this.offset == null) { Vec3i area = getArea(); - this.offset = new Vec3i(-area.getX() / 2, -2, -area.getZ() / 2); + this.offset = new Vec3i(-area.getX() / 2, -2, -area.getZ() / 2); } return this.offset; } @@ -342,7 +330,7 @@ public Vec3i getOffset() { @Override public Vec3i getArea() { if (this.area == null) { - this.area = new Vec3i(7 + this.allowedExtent * 2, 13, 7 + this.allowedExtent * 2); + this.area = new Vec3i(7 + this.allowedExtent * 2, 13, 7 + this.allowedExtent * 2); } return this.area; } @@ -368,7 +356,7 @@ public void setUpFarmlandTargets(Map> targets) { int sizeEastWest = Math.abs(max.getX() - min.getX()) + 1; // Set the maximum allowed extent. - this.allowedExtent = Math.max(sizeNorthSouth, sizeEastWest) * ForestryConfig.SERVER.multiFarmSize.get() + 1; + this.allowedExtent = Math.max(sizeNorthSouth, sizeEastWest) * ForestryConfig.SERVER.multiFarmSize.get() + 1; FarmHelper.createTargets(this.level, this, targets, targetStart, this.allowedExtent, sizeNorthSouth, sizeEastWest, min, max); FarmHelper.setExtents(this.level, this, targets); @@ -387,12 +375,12 @@ public BlockPos getFarmCorner(Direction direction) { @Override public boolean hasLiquid(FluidStack liquid) { FluidStack drained = this.manager.getResourceTank().drainInternal(liquid, IFluidHandler.FluidAction.SIMULATE); - return liquid.isFluidStackIdentical(drained); + return FluidStack.matches(liquid, drained); } @Override public void removeLiquid(FluidStack liquid) { - this.manager.getResourceTank().drain(liquid.getAmount(), IFluidHandler.FluidAction.EXECUTE); + this.manager.getResourceTank().drain(liquid.getAmount(), IFluidHandler.FluidAction.EXECUTE); } @Override @@ -408,14 +396,12 @@ public IFarmInventoryInternal getFarmInventory() { @Override public void addPendingProduct(ItemStack stack) { - this.manager.addPendingProduct(stack); + this.manager.addPendingProduct(stack); } @Override public void setFarmLogic(Direction direction, IFarmLogic logic) { - Preconditions.checkNotNull(direction); - Preconditions.checkNotNull(logic, "logic must not be null"); - this.farmLogics.put(direction, logic); + this.farmLogics.put(direction, logic); cleanExtents(direction); } @@ -450,18 +436,21 @@ public void setSocket(int slot, ItemStack stack) { // Dispose old chipsets correctly if (!this.sockets.getItem(slot).isEmpty()) { if (IForestryApi.INSTANCE.getCircuitManager().isCircuitBoard(this.sockets.getItem(slot))) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(this.sockets.getItem(slot)); + IForestryApi.INSTANCE.getCircuitManager(); + ItemStack stack1 = this.sockets.getItem(slot); + ICircuitBoard chipset = stack1.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onRemoval(this); } } } - this.sockets.setItem(slot, stack); + this.sockets.setItem(slot, stack); refreshFarmLogics(); if (!stack.isEmpty()) { - ICircuitBoard chipset = IForestryApi.INSTANCE.getCircuitManager().getCircuitBoard(stack); + IForestryApi.INSTANCE.getCircuitManager(); + ICircuitBoard chipset = stack.get(CoreDataComponents.CIRCUIT_BOARD); if (chipset != null) { chipset.onInsertion(this); } @@ -497,12 +486,12 @@ public int getExtents(Direction direction, BlockPos pos) { @Override public void setExtents(Direction direction, BlockPos pos, int extend) { - this.manager.setExtents(direction, pos, extend); + this.manager.setExtents(direction, pos, extend); } @Override public void cleanExtents(Direction direction) { - this.manager.cleanExtents(direction); + this.manager.cleanExtents(direction); } // for debugging diff --git a/src/main/java/forestry/farming/multiblock/InventoryFarm.java b/src/main/java/forestry/farming/multiblock/MultifarmInventory.java similarity index 51% rename from src/main/java/forestry/farming/multiblock/InventoryFarm.java rename to src/main/java/forestry/farming/multiblock/MultifarmInventory.java index a733de9689..8fd933c882 100644 --- a/src/main/java/forestry/farming/multiblock/InventoryFarm.java +++ b/src/main/java/forestry/farming/multiblock/MultifarmInventory.java @@ -1,24 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.multiblock; import forestry.api.farming.IFarmable; +import forestry.core.config.ForestryConfig; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -/** - * Inventory of the farm multiblock. - */ -public class InventoryFarm extends InventoryPlantation implements IFarmInventoryInternal { +public class MultifarmInventory extends InventoryPlantation implements IFarmInventoryInternal { public static InventoryPlantation.InventoryConfig CONFIG = new InventoryPlantation.InventoryConfig( 0, 6, 6, 6, @@ -27,8 +15,8 @@ public class InventoryFarm extends InventoryPlantation implement 21, 1 ); - public InventoryFarm(FarmController farmController) { - super(farmController, CONFIG); + public MultifarmInventory(MultifarmController controller) { + super(controller, CONFIG, ForestryConfig.SERVER.multiFarmFertilizerModifier); } @Override diff --git a/src/main/java/forestry/farming/multiblock/package-info.java b/src/main/java/forestry/farming/multiblock/package-info.java index 68f7532c55..86f4a8f4c6 100644 --- a/src/main/java/forestry/farming/multiblock/package-info.java +++ b/src/main/java/forestry/farming/multiblock/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.multiblock; diff --git a/src/main/java/forestry/farming/package-info.java b/src/main/java/forestry/farming/package-info.java index dca6431ae4..87e81e50b4 100644 --- a/src/main/java/forestry/farming/package-info.java +++ b/src/main/java/forestry/farming/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming; diff --git a/src/main/java/forestry/farming/tiles/TileFarm.java b/src/main/java/forestry/farming/tiles/AbstractMultifarmBlockEntity.java similarity index 68% rename from src/main/java/forestry/farming/tiles/TileFarm.java rename to src/main/java/forestry/farming/tiles/AbstractMultifarmBlockEntity.java index ff14d8423b..134036278e 100644 --- a/src/main/java/forestry/farming/tiles/TileFarm.java +++ b/src/main/java/forestry/farming/tiles/AbstractMultifarmBlockEntity.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.tiles; import forestry.api.core.IErrorLogic; @@ -21,10 +11,10 @@ import forestry.core.owner.IOwnedTile; import forestry.core.owner.IOwnerHandler; import forestry.core.tiles.ITitled; -import forestry.farming.gui.ContainerFarm; +import forestry.farming.gui.FarmMenu; import forestry.farming.multiblock.MultiblockLogicFarm; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; @@ -33,11 +23,11 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; -public abstract class TileFarm extends MultiblockTileEntityForestry implements IFarmComponent, ISocketable, IStreamableGui, IErrorLogicSource, IOwnedTile, ITitled { - protected TileFarm(BlockEntityType tileEntityType, BlockPos pos, BlockState state) { +public abstract class AbstractMultifarmBlockEntity extends MultiblockTileEntityForestry implements IFarmComponent, ISocketable, IStreamableGui, IErrorLogicSource, IOwnedTile, ITitled { + protected AbstractMultifarmBlockEntity(BlockEntityType tileEntityType, BlockPos pos, BlockState state) { super(tileEntityType, pos, state, new MultiblockLogicFarm()); } @@ -81,14 +71,14 @@ public ResourceLocation getSocketType() { /* IStreamableGui */ @Override - public void writeGuiData(FriendlyByteBuf data) { - getMultiblockLogic().getController().writeGuiData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + getMultiblockLogic().getController().writeGuiData(buffer); } @Override @OnlyIn(Dist.CLIENT) - public void readGuiData(FriendlyByteBuf data) { - getMultiblockLogic().getController().readGuiData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + getMultiblockLogic().getController().readGuiData(buffer); } /* IErrorLogicSource */ @@ -110,7 +100,7 @@ public Component getTitle() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerFarm(windowId, inv, this); + return new FarmMenu(windowId, inv, this); } @Override diff --git a/src/main/java/forestry/farming/tiles/TileFarmPlain.java b/src/main/java/forestry/farming/tiles/MultifarmBlockEntity.java similarity index 61% rename from src/main/java/forestry/farming/tiles/TileFarmPlain.java rename to src/main/java/forestry/farming/tiles/MultifarmBlockEntity.java index 8dec62f7ee..a2f1aac4e6 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmPlain.java +++ b/src/main/java/forestry/farming/tiles/MultifarmBlockEntity.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.tiles; import forestry.api.multiblock.IMultiblockController; @@ -17,8 +7,8 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -public class TileFarmPlain extends TileFarm { - public TileFarmPlain(BlockPos pos, BlockState state) { +public class MultifarmBlockEntity extends AbstractMultifarmBlockEntity { + public MultifarmBlockEntity(BlockPos pos, BlockState state) { super(FarmingTiles.PLAIN.tileType(), pos, state); } diff --git a/src/main/java/forestry/farming/tiles/MultifarmControlBlockEntity.java b/src/main/java/forestry/farming/tiles/MultifarmControlBlockEntity.java new file mode 100644 index 0000000000..c0a4a49d6e --- /dev/null +++ b/src/main/java/forestry/farming/tiles/MultifarmControlBlockEntity.java @@ -0,0 +1,31 @@ +package forestry.farming.tiles; + +import forestry.api.farming.IFarmLogic; +import forestry.api.multiblock.IFarmComponent; +import forestry.farming.blocks.FarmBlock; +import forestry.farming.features.FarmingTiles; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; + +public class MultifarmControlBlockEntity extends AbstractMultifarmBlockEntity implements IFarmComponent.Listener { + public MultifarmControlBlockEntity(BlockPos pos, BlockState state) { + super(FarmingTiles.CONTROL.tileType(), pos, state); + } + + @Override + public boolean cancelTask(IFarmLogic logic, Direction direction) { + BlockPos pos = this.worldPosition; + Level level = this.level; + + for (Direction facing : new Direction[]{Direction.UP, Direction.DOWN, direction}) { + BlockState blockState = level.getBlockState(pos.relative(facing)); + + if (!(blockState.getBlock() instanceof FarmBlock) && level.getSignal(pos, facing) > 0) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/forestry/farming/tiles/TileFarmGearbox.java b/src/main/java/forestry/farming/tiles/MultifarmGearboxBlockEntity.java similarity index 71% rename from src/main/java/forestry/farming/tiles/TileFarmGearbox.java rename to src/main/java/forestry/farming/tiles/MultifarmGearboxBlockEntity.java index 16c941398f..4a0617f3b0 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmGearbox.java +++ b/src/main/java/forestry/farming/tiles/MultifarmGearboxBlockEntity.java @@ -17,6 +17,7 @@ import forestry.farming.features.FarmingTiles; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; @@ -26,44 +27,42 @@ import javax.annotation.Nullable; -public class TileFarmGearbox extends TileFarm implements IFarmComponent.Active { +public class MultifarmGearboxBlockEntity extends AbstractMultifarmBlockEntity implements IFarmComponent.Active { private static final int WORK_CYCLES = 4; private static final int ENERGY_PER_OPERATION = WORK_CYCLES * 50; private final ForestryEnergyStorage energyStorage; - private final LazyOptional energyCap; private int activationDelay = 0; private int previousDelays = 0; private int workCounter; - public TileFarmGearbox(BlockPos pos, BlockState state) { + public MultifarmGearboxBlockEntity(BlockPos pos, BlockState state) { super(FarmingTiles.GEARBOX.tileType(), pos, state); this.energyStorage = new ForestryEnergyStorage(200, 10000); - this.energyCap = LazyOptional.of(() -> this.energyStorage); } /* SAVING & LOADING */ @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - this.energyStorage.read(compoundNBT); + this.energyStorage.read(nbt, registries); - this.activationDelay = compoundNBT.getInt("ActivationDelay"); - this.previousDelays = compoundNBT.getInt("PrevDelays"); + this.activationDelay = nbt.getInt("ActivationDelay"); + this.previousDelays = nbt.getInt("PrevDelays"); } @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - this.energyStorage.write(compoundNBT); + this.energyStorage.write(nbt, registries); - compoundNBT.putInt("ActivationDelay", this.activationDelay); - compoundNBT.putInt("PrevDelays", this.previousDelays); + nbt.putInt("ActivationDelay", this.activationDelay); + nbt.putInt("PrevDelays", this.previousDelays); } @Override @@ -103,18 +102,4 @@ public void updateClient(int tickCount) { public ForestryEnergyStorage getEnergyManager() { return this.energyStorage; } - - @Override - public LazyOptional getCapability(Capability cap, @Nullable Direction facing) { - if (!this.remove && cap == ForgeCapabilities.ENERGY) { - return this.energyCap.cast(); - } - return super.getCapability(cap, facing); - } - - @Override - public void invalidateCaps() { - super.invalidateCaps(); - this.energyCap.invalidate(); - } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmHatch.java b/src/main/java/forestry/farming/tiles/MultifarmHatchBlockEntity.java similarity index 58% rename from src/main/java/forestry/farming/tiles/TileFarmHatch.java rename to src/main/java/forestry/farming/tiles/MultifarmHatchBlockEntity.java index b9432ef364..2caa87f75a 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmHatch.java +++ b/src/main/java/forestry/farming/tiles/MultifarmHatchBlockEntity.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.farming.tiles; import forestry.api.multiblock.IFarmComponent; @@ -20,24 +10,17 @@ import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.wrapper.InvWrapper; -import net.minecraftforge.items.wrapper.SidedInvWrapper; import javax.annotation.Nullable; -public class TileFarmHatch extends TileFarm implements WorldlyContainer, IFarmComponent.Active { - +public class MultifarmHatchBlockEntity extends AbstractMultifarmBlockEntity implements WorldlyContainer, IFarmComponent.Active { private final AdjacentTileCache tileCache; private final AdjacentInventoryCache inventoryCache; - public TileFarmHatch(BlockPos pos, BlockState state) { + public MultifarmHatchBlockEntity(BlockPos pos, BlockState state) { super(FarmingTiles.HATCH.tileType(), pos, state); this.tileCache = new AdjacentTileCache(this); - this.inventoryCache = new AdjacentInventoryCache(this, this.tileCache, tile -> !(tile instanceof TileFarm) && tile.getBlockPos().getY() < getBlockPos().getY()); + this.inventoryCache = new AdjacentInventoryCache(this, this.tileCache, tile -> !(tile instanceof AbstractMultifarmBlockEntity) && tile.getBlockPos().getY() < getBlockPos().getY()); } @Override diff --git a/src/main/java/forestry/farming/tiles/TileFarmValve.java b/src/main/java/forestry/farming/tiles/MultifarmValveBlockEntity.java similarity index 89% rename from src/main/java/forestry/farming/tiles/TileFarmValve.java rename to src/main/java/forestry/farming/tiles/MultifarmValveBlockEntity.java index 5ee6271f83..d54a6aba85 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmValve.java +++ b/src/main/java/forestry/farming/tiles/MultifarmValveBlockEntity.java @@ -22,8 +22,8 @@ import javax.annotation.Nullable; -public class TileFarmValve extends TileFarm implements ILiquidTankTile { - public TileFarmValve(BlockPos pos, BlockState state) { +public class MultifarmValveBlockEntity extends AbstractMultifarmBlockEntity implements ILiquidTankTile { + public MultifarmValveBlockEntity(BlockPos pos, BlockState state) { super(FarmingTiles.VALVE.tileType(), pos, state); } diff --git a/src/main/java/forestry/farming/tiles/TileFarmControl.java b/src/main/java/forestry/farming/tiles/TileFarmControl.java deleted file mode 100644 index 7a147e3c12..0000000000 --- a/src/main/java/forestry/farming/tiles/TileFarmControl.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.tiles; - -import forestry.api.farming.IFarmListener; -import forestry.api.farming.IFarmLogic; -import forestry.api.multiblock.IFarmComponent; -import forestry.farming.blocks.FarmBlock; -import forestry.farming.features.FarmingTiles; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; - -public class TileFarmControl extends TileFarm implements IFarmComponent.Listener { - private final IFarmListener farmListener; - - public TileFarmControl(BlockPos pos, BlockState state) { - super(FarmingTiles.CONTROL.tileType(), pos, state); - this.farmListener = new ControlFarmListener(this); - } - - @Override - public IFarmListener getFarmListener() { - return this.farmListener; - } - - private static class ControlFarmListener implements IFarmListener { - private final TileFarmControl tile; - - public ControlFarmListener(TileFarmControl tile) { - this.tile = tile; - } - - @Override - public boolean cancelTask(IFarmLogic logic, Direction direction) { - for (Direction facing : new Direction[]{Direction.UP, Direction.DOWN, direction}) { - BlockPos pos = this.tile.getBlockPos(); - Level world = this.tile.getWorldObj(); - BlockState blockState = world.getBlockState(pos.relative(facing)); - if (!(blockState.getBlock() instanceof FarmBlock) && world.getSignal(pos, facing) > 0) { - return true; - } - } - return false; - } - } - -} diff --git a/src/main/java/forestry/farming/tiles/package-info.java b/src/main/java/forestry/farming/tiles/package-info.java index 9f106f1103..137d837d37 100644 --- a/src/main/java/forestry/farming/tiles/package-info.java +++ b/src/main/java/forestry/farming/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.farming.tiles; diff --git a/src/main/java/forestry/lepidopterology/ButterflySpecies.java b/src/main/java/forestry/lepidopterology/ButterflySpecies.java index 5af64aebe1..2a5cd6f006 100644 --- a/src/main/java/forestry/lepidopterology/ButterflySpecies.java +++ b/src/main/java/forestry/lepidopterology/ButterflySpecies.java @@ -6,6 +6,7 @@ import forestry.api.core.tooltips.ToolTip; import forestry.api.genetics.ClimateHelper; import forestry.api.genetics.IGenome; +import forestry.api.genetics.ILifeStage; import forestry.api.genetics.alleles.ButterflyChromosomes; import forestry.api.lepidopterology.genetics.IButterfly; import forestry.api.lepidopterology.genetics.IButterflySpecies; @@ -57,6 +58,13 @@ public IButterfly createIndividual(IGenome genome) { return new Butterfly(genome); } + @Override + public Component getItemDisplayName(ILifeStage stage) { + Component speciesName = getDisplayName(); + Component typeName = Component.translatable("for.butterflies.grammar." + stage.getSerializedName() + ".type"); + return Component.translatable("for.butterflies.grammar." + stage.getSerializedName(), speciesName, typeName); + } + @Override public void addTooltip(IButterfly butterfly, List tooltip) { ToolTip toolTip = new ToolTip(); diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java b/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java index 965e9eff36..c8682fb208 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java @@ -24,6 +24,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.EntityBlock; @@ -74,8 +75,8 @@ public BlockState updateShape(BlockState state, Direction facing, BlockState fac } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, Player player) { - TileCocoon tile = TileUtil.getTile(world, pos, TileCocoon.class); + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { + TileCocoon tile = TileUtil.getTile(level, pos, TileCocoon.class); if (tile == null) { return ItemStack.EMPTY; } @@ -84,9 +85,10 @@ public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGett int age = state.getValue(AGE); ItemStack stack = SpeciesUtil.BUTTERFLY_TYPE.get().createStack(caterpillar, ButterflyLifeStage.COCOON); - if (!stack.isEmpty() && stack.getTag() != null) { - stack.getTag().putInt(ItemButterflyGE.NBT_AGE, age); - } + // todo + //if (!stack.isEmpty() && stack.getTag() != null) { + // stack.getTag().putInt(ItemButterflyGE.NBT_AGE, age); + //} return stack; } diff --git a/src/main/java/forestry/lepidopterology/blocks/package-info.java b/src/main/java/forestry/lepidopterology/blocks/package-info.java index 87a2cd6b05..342e9ba625 100644 --- a/src/main/java/forestry/lepidopterology/blocks/package-info.java +++ b/src/main/java/forestry/lepidopterology/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.blocks; diff --git a/src/main/java/forestry/lepidopterology/commands/package-info.java b/src/main/java/forestry/lepidopterology/commands/package-info.java index e286100001..6c13395319 100644 --- a/src/main/java/forestry/lepidopterology/commands/package-info.java +++ b/src/main/java/forestry/lepidopterology/commands/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.commands; diff --git a/src/main/java/forestry/lepidopterology/compat/LepidopterologyJeiPlugin.java b/src/main/java/forestry/lepidopterology/compat/LepidopterologyJeiPlugin.java index d5ab04a9ed..c0b6aaf4fe 100644 --- a/src/main/java/forestry/lepidopterology/compat/LepidopterologyJeiPlugin.java +++ b/src/main/java/forestry/lepidopterology/compat/LepidopterologyJeiPlugin.java @@ -2,7 +2,7 @@ import forestry.api.genetics.alleles.ButterflyChromosomes; import forestry.api.modules.ForestryModuleIds; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.core.utils.SpeciesUtil; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; @@ -18,6 +18,6 @@ public ResourceLocation getPluginUid() { @Override public void registerItemSubtypes(ISubtypeRegistration registry) { - JeiUtil.registerItemSubtypes(registry, ButterflyChromosomes.SPECIES, SpeciesUtil.BUTTERFLY_TYPE.get()); + JeiUtil.registerItemSubtypes(registry, SpeciesUtil.BUTTERFLY_TYPE.get()); } } diff --git a/src/main/java/forestry/lepidopterology/compat/package-info.java b/src/main/java/forestry/lepidopterology/compat/package-info.java index eacd753938..df51a6a931 100644 --- a/src/main/java/forestry/lepidopterology/compat/package-info.java +++ b/src/main/java/forestry/lepidopterology/compat/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@FieldsAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.compat; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java index 75e43c4427..a769ded36f 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java @@ -18,7 +18,6 @@ import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.IPlantable; import java.util.EnumSet; @@ -109,8 +108,6 @@ private static boolean isPlant(BlockState state) { Block block = state.getBlock(); if (state.is(BlockTags.FLOWERS)) { return true; - } else if (block instanceof IPlantable) { - return true; } else if (block instanceof BonemealableBlock) { return true; } else { diff --git a/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java b/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java index 6f4da4f087..353fe91c26 100755 --- a/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java +++ b/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java @@ -58,8 +58,8 @@ import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import net.minecraftforge.common.IPlantable; import javax.annotation.Nullable; diff --git a/src/main/java/forestry/lepidopterology/entities/package-info.java b/src/main/java/forestry/lepidopterology/entities/package-info.java index 4af50fd58e..5f0c0582d4 100644 --- a/src/main/java/forestry/lepidopterology/entities/package-info.java +++ b/src/main/java/forestry/lepidopterology/entities/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.entities; diff --git a/src/main/java/forestry/lepidopterology/features/LepidopterologyItems.java b/src/main/java/forestry/lepidopterology/features/LepidopterologyItems.java index 7ac72a11e3..b005176389 100644 --- a/src/main/java/forestry/lepidopterology/features/LepidopterologyItems.java +++ b/src/main/java/forestry/lepidopterology/features/LepidopterologyItems.java @@ -12,8 +12,8 @@ public class LepidopterologyItems { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.LEPIDOPTEROLOGY); - public static final FeatureItem BUTTERFLY_GE = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.BUTTERFLY), "butterfly_ge"); - public static final FeatureItem SERUM_GE = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.SERUM), "serum_ge"); - public static final FeatureItem CATERPILLAR_GE = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.CATERPILLAR), "caterpillar_ge"); - public static final FeatureItem COCOON_GE = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.COCOON), "cocoon_ge"); + public static final FeatureItem BUTTERFLY_GE = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.BUTTERFLY), "butterfly"); + public static final FeatureItem SERUM = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.SERUM), "serum"); + public static final FeatureItem CATERPILLAR = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.CATERPILLAR), "caterpillar"); + public static final FeatureItem COCOON_GE = REGISTRY.item(() -> new ItemButterflyGE(ButterflyLifeStage.COCOON), "cocoon"); } diff --git a/src/main/java/forestry/lepidopterology/features/LepidopterologyRecipes.java b/src/main/java/forestry/lepidopterology/features/LepidopterologyRecipes.java index 360f10359e..e3cdcdc6fd 100644 --- a/src/main/java/forestry/lepidopterology/features/LepidopterologyRecipes.java +++ b/src/main/java/forestry/lepidopterology/features/LepidopterologyRecipes.java @@ -1,22 +1,22 @@ package forestry.lepidopterology.features; +import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; - import forestry.api.modules.ForestryModuleIds; import forestry.lepidopterology.recipe.ButterflyMatingRecipe; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; +import net.neoforged.neoforge.registries.DeferredRegister; + @FeatureProvider public class LepidopterologyRecipes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.LEPIDOPTEROLOGY); private static final DeferredRegister> SERIALIZERS = REGISTRY.getRegistry(Registries.RECIPE_SERIALIZER); - public static final RegistryObject> MATING_SERIALIZER = SERIALIZERS.register("butterfly_mating", () -> new SimpleCraftingRecipeSerializer<>(ButterflyMatingRecipe::new)); + public static final Holder> MATING_SERIALIZER = SERIALIZERS.register("butterfly_mating", () -> new SimpleCraftingRecipeSerializer<>(ButterflyMatingRecipe::new)); } diff --git a/src/main/java/forestry/lepidopterology/features/package-info.java b/src/main/java/forestry/lepidopterology/features/package-info.java index 3c54eda088..2b1850e69b 100644 --- a/src/main/java/forestry/lepidopterology/features/package-info.java +++ b/src/main/java/forestry/lepidopterology/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.features; diff --git a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java index 60f3010970..6bd2b50c6a 100755 --- a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java +++ b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java @@ -1,17 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.lepidopterology.genetics; import com.google.common.collect.ImmutableList; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import forestry.api.IForestryApi; import forestry.api.core.HumidityType; @@ -50,7 +41,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { private static final RandomSource rand = RandomSource.create(); - public static final Codec CODEC = RecordCodecBuilder.create(instance -> { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> { Codec genomeCodec = SpeciesUtil.BUTTERFLY_TYPE.get().getKaryotype().getGenomeCodec(); return IndividualLiving.livingFields(instance, genomeCodec).apply(instance, Butterfly::new); @@ -110,12 +101,12 @@ public IButterfly spawnCaterpillar(IButterflyNursery nursery) { } SpeciesUtil.ISpeciesMutator mutator = (p1, p2) -> mutateSpecies(nursery, p1, p2); - return SpeciesUtil.createOffspring(nursery.getWorldObj().random, this.genome, this.mate, mutator, Butterfly::new); + return SpeciesUtil.createOffspring(nursery.getLevel().random, this.genome, this.mate, mutator, Butterfly::new); } @Nullable private static ImmutableList> mutateSpecies(IButterflyNursery nursery, IGenome parent1, IGenome parent2) { - return SpeciesUtil.mutateSpecies(nursery.getWorldObj(), nursery.getCoordinates(), null, parent1, parent2, ButterflyChromosomes.SPECIES, Mutation::getChance); + return SpeciesUtil.mutateSpecies(nursery.getLevel(), nursery.getBlockPos(), null, parent1, parent2, ButterflyChromosomes.SPECIES, Mutation::getChance); } private boolean isActiveThisTime(boolean isDayTime) { diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyAlyzerPlugin.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyAlyzerPlugin.java index 6c747850d6..7c57cc5581 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyAlyzerPlugin.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyAlyzerPlugin.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.lepidopterology.genetics; import forestry.api.core.IProduct; @@ -20,8 +10,8 @@ import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.lepidopterology.genetics.ButterflyLifeStage; import forestry.api.lepidopterology.genetics.IButterflySpecies; -import forestry.core.gui.GuiAlyzer; import forestry.core.gui.GuiForestry; +import forestry.core.gui.PortableAnalyzerScreen; import forestry.core.gui.TextLayoutHelper; import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.WidgetManager; @@ -44,16 +34,16 @@ public enum ButterflyAlyzerPlugin implements IAlyzerPlugin { @Override public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, (butterfly, stage) -> { IGenome genome = butterfly.getGenome(); TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); - textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); textLayout.newLine(); @@ -73,10 +63,10 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack guiAlyzer.drawChromosomeRow(graphics, butterfly, ButterflyChromosomes.METABOLISM); textLayout.newLine(); - textLayout.drawLine(graphics, ButterflyChromosomes.FERTILITY.getChromosomeDisplayName(), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, ButterflyChromosomes.FERTILITY.getChromosomeDisplayName(), PortableAnalyzerScreen.COLUMN_0); AllelePair fertilityPair = genome.getAllelePair(ButterflyChromosomes.FERTILITY); - guiAlyzer.drawFertilityInfo(graphics, fertilityPair.active().value(), GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(fertilityPair.active().dominant()), 8); - guiAlyzer.drawFertilityInfo(graphics, fertilityPair.inactive().value(), GuiAlyzer.COLUMN_2, GuiAlyzer.getColorCoding(fertilityPair.inactive().dominant()), 8); + guiAlyzer.drawFertilityInfo(graphics, fertilityPair.active().value(), PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(fertilityPair.active().dominant()), 8); + guiAlyzer.drawFertilityInfo(graphics, fertilityPair.inactive().value(), PortableAnalyzerScreen.COLUMN_2, PortableAnalyzerScreen.getColorCoding(fertilityPair.inactive().dominant()), 8); textLayout.newLine(); guiAlyzer.drawChromosomeRow(graphics, butterfly, ButterflyChromosomes.FLOWER_TYPE); @@ -92,7 +82,7 @@ public void drawAnalyticsPage1(GuiGraphics graphics, Screen gui, ItemStack stack @Override public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, (individual, stage) -> { IGenome genome = individual.getGenome(); IButterflySpecies primaryAllele = genome.getActiveValue(ButterflyChromosomes.SPECIES); @@ -100,10 +90,10 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.active"), GuiAlyzer.COLUMN_1); - textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, Component.translatable("for.gui.active"), PortableAnalyzerScreen.COLUMN_1); + textLayout.drawLine(graphics, Component.translatable("for.gui.inactive"), PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); textLayout.newLine(); @@ -114,12 +104,12 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack textLayout.newLine(); Component indentedTolerance = Component.literal(" ").append(Component.translatable("for.gui.tolerance")); - IValueAllele tempToleranceActive = genome.getActiveAllele(ButterflyChromosomes.TEMPERATURE_TOLERANCE); - IValueAllele tempToleranceInactive = genome.getInactiveAllele(ButterflyChromosomes.TEMPERATURE_TOLERANCE); + IValueAllele tempToleranceActive = genome.getActiveAllele(ButterflyChromosomes.TEMPERATURE_TOLERANCE); + IValueAllele tempToleranceInactive = genome.getInactiveAllele(ButterflyChromosomes.TEMPERATURE_TOLERANCE); - textLayout.drawLine(graphics, indentedTolerance, GuiAlyzer.COLUMN_0); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceActive, GuiAlyzer.COLUMN_1); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceInactive, GuiAlyzer.COLUMN_2); + textLayout.drawLine(graphics, indentedTolerance, PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceActive, PortableAnalyzerScreen.COLUMN_1); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, tempToleranceInactive, PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); @@ -128,11 +118,11 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack ClimateHelper.toDisplay(secondaryAllele.getHumidity()), individual, ButterflyChromosomes.SPECIES); textLayout.newLine(); - IValueAllele humidToleranceActive = genome.getActiveAllele(ButterflyChromosomes.HUMIDITY_TOLERANCE); - IValueAllele humidToleranceInactive = genome.getInactiveAllele(ButterflyChromosomes.HUMIDITY_TOLERANCE); - textLayout.drawLine(graphics, indentedTolerance, GuiAlyzer.COLUMN_0); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceActive, GuiAlyzer.COLUMN_1); - guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceInactive, GuiAlyzer.COLUMN_2); + IValueAllele humidToleranceActive = genome.getActiveAllele(ButterflyChromosomes.HUMIDITY_TOLERANCE); + IValueAllele humidToleranceInactive = genome.getInactiveAllele(ButterflyChromosomes.HUMIDITY_TOLERANCE); + textLayout.drawLine(graphics, indentedTolerance, PortableAnalyzerScreen.COLUMN_0); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceActive, PortableAnalyzerScreen.COLUMN_1); + guiAlyzer.drawToleranceInfo(graphics, BeeChromosomes.TEMPERATURE_TOLERANCE, humidToleranceInactive, PortableAnalyzerScreen.COLUMN_2); textLayout.newLine(); textLayout.newLine(); @@ -154,14 +144,14 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack diurnal1 = !secondaryAllele.isNocturnal() ? yes : no; } - textLayout.drawLine(graphics, Component.translatable("for.gui.diurnal"), GuiAlyzer.COLUMN_0); - textLayout.drawLine(graphics, diurnal0, GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(false)); - textLayout.drawLine(graphics, diurnal1, GuiAlyzer.COLUMN_2, GuiAlyzer.getColorCoding(false)); + textLayout.drawLine(graphics, Component.translatable("for.gui.diurnal"), PortableAnalyzerScreen.COLUMN_0); + textLayout.drawLine(graphics, diurnal0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(false)); + textLayout.drawLine(graphics, diurnal1, PortableAnalyzerScreen.COLUMN_2, PortableAnalyzerScreen.getColorCoding(false)); textLayout.newLine(); - textLayout.drawLine(graphics, Component.translatable("for.gui.nocturnal"), GuiAlyzer.COLUMN_0); - textLayout.drawLine(graphics, nocturnal0, GuiAlyzer.COLUMN_1, GuiAlyzer.getColorCoding(false)); - textLayout.drawLine(graphics, nocturnal1, GuiAlyzer.COLUMN_2, GuiAlyzer.getColorCoding(false)); + textLayout.drawLine(graphics, Component.translatable("for.gui.nocturnal"), PortableAnalyzerScreen.COLUMN_0); + textLayout.drawLine(graphics, nocturnal0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.getColorCoding(false)); + textLayout.drawLine(graphics, nocturnal1, PortableAnalyzerScreen.COLUMN_2, PortableAnalyzerScreen.getColorCoding(false)); textLayout.newLine(); Component primary = genome.getActiveValue(ButterflyChromosomes.TOLERATES_RAIN) ? yes : no; @@ -182,24 +172,24 @@ public void drawAnalyticsPage2(GuiGraphics graphics, Screen gui, ItemStack stack @Override public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack stack) { - if (gui instanceof GuiAlyzer guiAlyzer) { + if (gui instanceof PortableAnalyzerScreen guiAlyzer) { IIndividualHandlerItem.ifPresent(stack, individual -> { IGenome genome = individual.getGenome(); TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); WidgetManager widgetManager = guiAlyzer.getWidgetManager(); - textLayout.startPage(graphics, GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); + textLayout.startPage(graphics, PortableAnalyzerScreen.COLUMN_0, PortableAnalyzerScreen.COLUMN_1, PortableAnalyzerScreen.COLUMN_2); - textLayout.drawLine(graphics, Component.translatable("for.gui.loot.butterfly").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.loot.butterfly").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - int x = GuiAlyzer.COLUMN_0; + int x = PortableAnalyzerScreen.COLUMN_0; for (IProduct product : genome.getActiveValue(ButterflyChromosomes.SPECIES).getButterflyLoot()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), product.createStack())); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } @@ -207,15 +197,15 @@ public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack stack textLayout.newLine(); textLayout.newLine(); - textLayout.drawLine(graphics, Component.translatable("for.gui.loot.caterpillar").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.loot.caterpillar").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; for (IProduct product : genome.getActiveValue(ButterflyChromosomes.SPECIES).getCaterpillarProducts()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), product.createStack())); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } @@ -223,15 +213,15 @@ public void drawAnalyticsPage3(GuiGraphics graphics, Screen gui, ItemStack stack textLayout.newLine(); textLayout.newLine(); - textLayout.drawLine(graphics, Component.translatable("for.gui.loot.cocoon").append(":"), GuiAlyzer.COLUMN_0); + textLayout.drawLine(graphics, Component.translatable("for.gui.loot.cocoon").append(":"), PortableAnalyzerScreen.COLUMN_0); textLayout.newLine(); - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; for (IProduct product : genome.getActiveValue(ButterflyChromosomes.COCOON).getProducts()) { widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), product.createStack())); x += 18; if (x > 148) { - x = GuiAlyzer.COLUMN_0; + x = PortableAnalyzerScreen.COLUMN_0; textLayout.newLine(); } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflySpeciesType.java b/src/main/java/forestry/lepidopterology/genetics/ButterflySpeciesType.java index 90003e59c7..1aa367b314 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflySpeciesType.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflySpeciesType.java @@ -1,19 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.lepidopterology.genetics; import com.google.common.collect.ImmutableMap; -import com.mojang.authlib.GameProfile; import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import forestry.api.core.IProduct; import forestry.api.genetics.*; import forestry.api.genetics.alleles.ButterflyChromosomes; @@ -45,6 +34,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; @@ -164,13 +154,13 @@ public boolean isMated(ItemStack stack) { } @Override - public ILepidopteristTracker getBreedingTracker(LevelAccessor level, @Nullable GameProfile profile) { + public ILepidopteristTracker getBreedingTracker(LevelAccessor level, @Nullable ResolvableProfile profile) { return BreedingTrackerManager.INSTANCE.getTracker(this, level, profile); } @Override - public String getBreedingTrackerFile(@Nullable GameProfile profile) { - return "LepidopteristTracker." + (profile == null ? "common" : profile.getId()); + public String getBreedingTrackerFile(@Nullable ResolvableProfile profile) { + return "LepidopteristTracker." + ((profile == null || profile.id().isEmpty()) ? "common" : profile.id().get()); } @Override @@ -179,9 +169,9 @@ public IBreedingTracker createBreedingTracker() { } @Override - public void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level world, @Nullable GameProfile profile) { + public void initializeBreedingTracker(IBreedingTracker tracker, @Nullable Level level, @Nullable ResolvableProfile profile) { if (tracker instanceof LepidopteristTracker butterflyTracker) { - butterflyTracker.setLevel(world); + butterflyTracker.setLevel(level); butterflyTracker.setUsername(profile); } } @@ -207,14 +197,14 @@ public float getResearchSuitability(IButterflySpecies species, ItemStack stack) } @Override - public List getResearchBounty(IButterflySpecies species, Level level, GameProfile researcher, IButterfly individual, int bountyLevel) { + public List getResearchBounty(IButterflySpecies species, Level level, ResolvableProfile researcher, IButterfly individual, int bountyLevel) { List bounty = super.getResearchBounty(species, level, researcher, individual, bountyLevel); bounty.add(individual.createStack(ButterflyLifeStage.SERUM)); return bounty; } @Override - public Codec getIndividualCodec() { + public MapCodec getIndividualCodec() { return Butterfly.CODEC; } } diff --git a/src/main/java/forestry/lepidopterology/genetics/package-info.java b/src/main/java/forestry/lepidopterology/genetics/package-info.java index a8fdb65afc..69972a4733 100644 --- a/src/main/java/forestry/lepidopterology/genetics/package-info.java +++ b/src/main/java/forestry/lepidopterology/genetics/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.genetics; diff --git a/src/main/java/forestry/lepidopterology/items/package-info.java b/src/main/java/forestry/lepidopterology/items/package-info.java index 352ed65e40..92f8238ffa 100644 --- a/src/main/java/forestry/lepidopterology/items/package-info.java +++ b/src/main/java/forestry/lepidopterology/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.items; diff --git a/src/main/java/forestry/lepidopterology/package-info.java b/src/main/java/forestry/lepidopterology/package-info.java index 7d4a4df92d..e0dda10667 100644 --- a/src/main/java/forestry/lepidopterology/package-info.java +++ b/src/main/java/forestry/lepidopterology/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology; diff --git a/src/main/java/forestry/lepidopterology/proxy/package-info.java b/src/main/java/forestry/lepidopterology/proxy/package-info.java index 35f317e892..0f8ea1a5dd 100644 --- a/src/main/java/forestry/lepidopterology/proxy/package-info.java +++ b/src/main/java/forestry/lepidopterology/proxy/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.proxy; diff --git a/src/main/java/forestry/lepidopterology/recipe/ButterflyMatingRecipe.java b/src/main/java/forestry/lepidopterology/recipe/ButterflyMatingRecipe.java index 6545693b50..039fade455 100644 --- a/src/main/java/forestry/lepidopterology/recipe/ButterflyMatingRecipe.java +++ b/src/main/java/forestry/lepidopterology/recipe/ButterflyMatingRecipe.java @@ -6,28 +6,27 @@ import forestry.api.lepidopterology.genetics.ButterflyLifeStage; import forestry.api.lepidopterology.genetics.IButterfly; import forestry.lepidopterology.features.LepidopterologyRecipes; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.core.HolderLookup; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.CustomRecipe; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.level.Level; public class ButterflyMatingRecipe extends CustomRecipe { - public ButterflyMatingRecipe(ResourceLocation id, CraftingBookCategory category) { - super(id, category); + public ButterflyMatingRecipe(CraftingBookCategory category) { + super(category); } @Override - public boolean matches(CraftingContainer grid, Level level) { - int containerSize = grid.getContainerSize(); + public boolean matches(CraftingInput input, Level level) { + int containerSize = input.size(); boolean hasButterfly = false; boolean hasSerum = false; for (int i = 0; i < containerSize; ++i) { - ItemStack stack = grid.getItem(i); + ItemStack stack = input.getItem(i); if (!stack.isEmpty()) { IIndividualHandlerItem handler = IIndividualHandlerItem.get(stack); @@ -58,13 +57,13 @@ public boolean matches(CraftingContainer grid, Level level) { } @Override - public ItemStack assemble(CraftingContainer grid, RegistryAccess lookup) { + public ItemStack assemble(CraftingInput input, HolderLookup.Provider registries) { IButterfly butterfly = null; IIndividual serum = null; - int containerSize = grid.getContainerSize(); + int containerSize = input.size(); for (int i = 0; i < containerSize; i++) { - IIndividualHandlerItem handler = IIndividualHandlerItem.get(grid.getItem(i)); + IIndividualHandlerItem handler = IIndividualHandlerItem.get(input.getItem(i)); if (handler != null) { if (handler.getStage() == ButterflyLifeStage.BUTTERFLY) { @@ -92,6 +91,6 @@ public boolean canCraftInDimensions(int width, int height) { @Override public RecipeSerializer getSerializer() { - return LepidopterologyRecipes.MATING_SERIALIZER.get(); + return LepidopterologyRecipes.MATING_SERIALIZER.value(); } } diff --git a/src/main/java/forestry/lepidopterology/recipe/package-info.java b/src/main/java/forestry/lepidopterology/recipe/package-info.java index 055304b7eb..68e03dcaaa 100644 --- a/src/main/java/forestry/lepidopterology/recipe/package-info.java +++ b/src/main/java/forestry/lepidopterology/recipe/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.recipe; diff --git a/src/main/java/forestry/lepidopterology/render/ButterflyItemModel.java b/src/main/java/forestry/lepidopterology/render/ButterflyItemModel.java index 82789f4916..e7da9ae2ff 100644 --- a/src/main/java/forestry/lepidopterology/render/ButterflyItemModel.java +++ b/src/main/java/forestry/lepidopterology/render/ButterflyItemModel.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.lepidopterology.render; import com.google.common.cache.Cache; @@ -40,10 +30,10 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.client.model.SeparateTransformsModel; -import net.minecraftforge.client.model.geometry.IGeometryBakingContext; -import net.minecraftforge.client.model.geometry.IGeometryLoader; -import net.minecraftforge.client.model.geometry.IUnbakedGeometry; +import net.neoforged.neoforge.client.model.SeparateTransformsModel; +import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; +import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; +import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; import javax.annotation.Nullable; import java.util.IdentityHashMap; @@ -89,7 +79,7 @@ public BakedModel resolve(BakedModel model, ItemStack stack, @Nullable ClientLev public record Geometry( IdentityHashMap subModels) implements IUnbakedGeometry { @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { UnbakedModel modelButterfly = baker.getModel(ForestryConstants.forestry("item/butterfly")); if (!(modelButterfly instanceof BlockModel modelBlock)) { @@ -104,15 +94,14 @@ public BakedModel bake(IGeometryBakingContext context, ModelBaker baker, Functio ResourceLocation texture = subModel.getValue(); BlockModel model = new BlockModel(parentLocation, elements, ImmutableMap.of("butterfly", Either.left(new Material(InventoryMenu.BLOCK_ATLAS, texture))), modelBlock.hasAmbientOcclusion, modelBlock.getGuiLight(), modelBlock.getTransforms(), modelBlock.getOverrides()); - ResourceLocation location = ForestryConstants.forestry("item/butterfly"); ModelState transform = ResourceUtil.loadTransform(ForestryConstants.forestry("item/butterfly")); - subModelBuilder.put(identifier, model.bake(baker, model, spriteGetter, transform, location, true)); + subModelBuilder.put(identifier, model.bake(baker, model, spriteGetter, transform, true)); } return new ButterflyItemModel(subModelBuilder); } } - public static class Loader implements IGeometryLoader { + public static class Loader implements IGeometryLoader { @Override public ButterflyItemModel.Geometry read(JsonObject modelContents, JsonDeserializationContext context) throws JsonParseException { IdentityHashMap subModels = new IdentityHashMap<>(); diff --git a/src/main/java/forestry/lepidopterology/render/ButterflyModel.java b/src/main/java/forestry/lepidopterology/render/ButterflyModel.java index a1b95fe141..b387266bf7 100644 --- a/src/main/java/forestry/lepidopterology/render/ButterflyModel.java +++ b/src/main/java/forestry/lepidopterology/render/ButterflyModel.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.lepidopterology.render; import com.mojang.blaze3d.vertex.PoseStack; @@ -68,11 +58,11 @@ public void setScale(float scale) { } @Override - public void renderToBuffer(PoseStack poseStack, VertexConsumer builder, int light, int overlay, float ageInTicks, float netHeadYaw, float headPitch, float alpha) { + public void renderToBuffer(PoseStack poseStack, VertexConsumer buffer, int light, int overlay, int color) { poseStack.scale(this.scale, this.scale, this.scale); poseStack.translate(0.0F, 1.45f / this.scale, 0.0F); - this.root.render(poseStack, builder, light, overlay); + this.root.render(poseStack, buffer, light, overlay, color); } @Override diff --git a/src/main/java/forestry/lepidopterology/render/package-info.java b/src/main/java/forestry/lepidopterology/render/package-info.java index 56d40106d6..167fe66982 100644 --- a/src/main/java/forestry/lepidopterology/render/package-info.java +++ b/src/main/java/forestry/lepidopterology/render/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.render; diff --git a/src/main/java/forestry/lepidopterology/tiles/package-info.java b/src/main/java/forestry/lepidopterology/tiles/package-info.java index 2df9bdaaae..e1a4130b89 100644 --- a/src/main/java/forestry/lepidopterology/tiles/package-info.java +++ b/src/main/java/forestry/lepidopterology/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.lepidopterology.tiles; diff --git a/src/main/java/forestry/mail/Letter.java b/src/main/java/forestry/mail/Letter.java index 9d0d5cd32f..d0e30c3280 100755 --- a/src/main/java/forestry/mail/Letter.java +++ b/src/main/java/forestry/mail/Letter.java @@ -1,21 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; -import forestry.api.mail.IStamps; +import forestry.api.mail.IStampItem; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.InventoryUtil; import net.minecraft.ChatFormatting; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; @@ -50,34 +41,33 @@ public Letter(IMailAddress sender, IMailAddress recipient) { this.uid = rand.nextInt(); } - public Letter(CompoundTag compoundNBT) { - this.isProcessed = compoundNBT.getBoolean("PRC"); - this.sender = new MailAddress(compoundNBT.getCompound("SDR")); - this.recipient = new MailAddress(compoundNBT.getCompound("RC")); + public Letter(CompoundTag nbt, HolderLookup.Provider registries) { + this.isProcessed = nbt.getBoolean("PRC"); + this.sender = new MailAddress(nbt.getCompound("SDR")); + this.recipient = new MailAddress(nbt.getCompound("RC")); - this.text = compoundNBT.getString("TXT"); - this.uid = compoundNBT.getInt("UID"); - this.inventory.read(compoundNBT); + this.text = nbt.getString("TXT"); + this.uid = nbt.getInt("UID"); + this.inventory.read(nbt, registries); } @Override - public CompoundTag write(CompoundTag compoundNBT) { - + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { compoundNBT.putBoolean("PRC", this.isProcessed); CompoundTag subcompound = new CompoundTag(); - this.sender.write(subcompound); + this.sender.write(subcompound, registries); compoundNBT.put("SDR", subcompound); if (this.recipient != null) { subcompound = new CompoundTag(); - this.recipient.write(subcompound); + this.recipient.write(subcompound, registries); compoundNBT.put("RC", subcompound); } compoundNBT.putString("TXT", this.text); compoundNBT.putInt("UID", this.uid); - this.inventory.write(compoundNBT); + this.inventory.write(compoundNBT, registries); return compoundNBT; } @@ -148,11 +138,11 @@ public boolean isPostPaid() { if (stamp.isEmpty()) { continue; } - if (!(stamp.getItem() instanceof IStamps)) { + if (!(stamp.getItem() instanceof IStampItem)) { continue; } - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); + posted += ((IStampItem) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); } return posted >= requiredPostage(); diff --git a/src/main/java/forestry/mail/LetterProperties.java b/src/main/java/forestry/mail/LetterProperties.java index aeeefc0c6d..dd11cf8063 100644 --- a/src/main/java/forestry/mail/LetterProperties.java +++ b/src/main/java/forestry/mail/LetterProperties.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail; import forestry.api.mail.ILetter; @@ -49,7 +39,7 @@ public static ItemStack closeLetter(ItemStack parent, ILetter letter) { } ItemStack ret = MailItems.LETTERS.stack(size, state, parent.getCount()); ret.setTag(parent.getTag()); - letter.write(parent.getTag()); + letter.write(parent.getTag(), IDK); return ret; } diff --git a/src/main/java/forestry/mail/LetterUtils.java b/src/main/java/forestry/mail/LetterUtils.java index 7597d949ef..d66c682ede 100644 --- a/src/main/java/forestry/mail/LetterUtils.java +++ b/src/main/java/forestry/mail/LetterUtils.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail; import forestry.api.mail.ILetter; @@ -25,7 +15,7 @@ public static ILetter createLetter(IMailAddress sender, IMailAddress recipient) public static ItemStack createLetterStack(ILetter letter) { CompoundTag compoundNBT = new CompoundTag(); - letter.write(compoundNBT); + letter.write(compoundNBT, IDK); ItemStack letterStack = LetterProperties.createStampedLetterStack(letter); letterStack.setTag(compoundNBT); diff --git a/src/main/java/forestry/mail/MailAddress.java b/src/main/java/forestry/mail/MailAddress.java index 71e5658afa..a0423bb88b 100644 --- a/src/main/java/forestry/mail/MailAddress.java +++ b/src/main/java/forestry/mail/MailAddress.java @@ -1,21 +1,13 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail; import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; +import forestry.api.ForestryRegistries; import forestry.api.mail.IMailAddress; import forestry.api.mail.IPostalCarrier; import forestry.core.utils.PlayerUtil; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.resources.ResourceLocation; @@ -25,16 +17,15 @@ import java.util.UUID; public class MailAddress implements IMailAddress { + private static final GameProfile INVALID_GAME_PROFILE = new GameProfile(new UUID(0, 0), ""); - private static final GameProfile invalidGameProfile = new GameProfile(new UUID(0, 0), ""); - public static final MailAddress INVALID = new MailAddress(invalidGameProfile); + public static final MailAddress INVALID = new MailAddress(INVALID_GAME_PROFILE); private final IPostalCarrier carrier; private final GameProfile gameProfile; // gameProfile is a fake GameProfile for traders, and real for players public MailAddress(GameProfile gameProfile) { - - this.carrier = PostalCarriers.PLAYER.get(); + this.carrier = PostalCarriers.PLAYER.value(); this.gameProfile = gameProfile; } @@ -42,25 +33,24 @@ public MailAddress(String name) { Preconditions.checkNotNull(name, "name must not be null"); Preconditions.checkArgument(StringUtils.isNotBlank(name), "name must not be blank"); - this.carrier = PostalCarriers.TRADER.get(); + this.carrier = PostalCarriers.TRADER.value(); this.gameProfile = new GameProfile(null, name); } public MailAddress(CompoundTag nbt) { IPostalCarrier carrier = null; - GameProfile gameProfile = invalidGameProfile; + GameProfile gameProfile = INVALID_GAME_PROFILE; if (nbt.contains("carrier")) { - carrier = PostalCarriers.REGISTRY.get().getValue(ResourceLocation.tryParse(nbt.getString("carrier"))); + carrier = ForestryRegistries.POSTAL_CARRIER.get(ResourceLocation.tryParse(nbt.getString("carrier"))); } if (carrier == null) { - carrier = PostalCarriers.PLAYER.get(); - gameProfile = invalidGameProfile; - } else if (nbt.contains("profile")) { + carrier = PostalCarriers.PLAYER.value(); + } else if (nbt.contains("profile")) { CompoundTag profileTag = nbt.getCompound("profile"); gameProfile = NbtUtils.readGameProfile(profileTag); if (gameProfile == null) { - gameProfile = invalidGameProfile; + gameProfile = INVALID_GAME_PROFILE; } } @@ -80,13 +70,13 @@ public String getName() { @Override public boolean isValid() { - return this.gameProfile.getName() != null && !PlayerUtil.isSameGameProfile(this.gameProfile, invalidGameProfile); + return this.gameProfile.getName() != null && !PlayerUtil.isSameGameProfile(this.gameProfile, INVALID_GAME_PROFILE); } @Override public GameProfile getPlayerProfile() { if (!this.carrier.equals(PostalCarriers.PLAYER.get())) { - return invalidGameProfile; + return INVALID_GAME_PROFILE; } return this.gameProfile; } @@ -116,10 +106,10 @@ public String toString() { } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { compoundNBT.putString("carrier", PostalCarriers.REGISTRY.get().getKey(this.carrier).toString()); - if (this.gameProfile != invalidGameProfile) { + if (this.gameProfile != INVALID_GAME_PROFILE) { CompoundTag profileNbt = new CompoundTag(); NbtUtils.writeGameProfile(profileNbt, this.gameProfile); compoundNBT.put("profile", profileNbt); diff --git a/src/main/java/forestry/mail/ModuleMail.java b/src/main/java/forestry/mail/ModuleMail.java index 0739a3a198..b73290523e 100644 --- a/src/main/java/forestry/mail/ModuleMail.java +++ b/src/main/java/forestry/mail/ModuleMail.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail; import com.mojang.brigadier.builder.LiteralArgumentBuilder; @@ -15,11 +5,8 @@ import forestry.api.mail.IMailAddress; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.api.modules.IPacketRegistry; import forestry.core.network.PacketIdClient; import forestry.core.network.PacketIdServer; -import forestry.core.utils.NetworkUtil; -import forestry.mail.carriers.PostalCarriers; import forestry.mail.carriers.players.POBox; import forestry.mail.carriers.players.POBoxRegistry; import forestry.mail.client.MailClientHandler; @@ -27,13 +14,16 @@ import forestry.mail.network.packets.*; import forestry.modules.BlankForestryModule; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.function.Consumer; @@ -46,8 +36,7 @@ public ResourceLocation getId() { @Override public void registerEvents(IEventBus modBus) { - MinecraftForge.EVENT_BUS.addListener(ModuleMail::handlePlayerLoggedIn); - PostalCarriers.register(modBus); + NeoForge.EVENT_BUS.addListener(ModuleMail::handlePlayerLoggedIn); } public static void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { @@ -59,7 +48,7 @@ public static void handlePlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { IMailAddress address = new MailAddress(player.getGameProfile()); POBox pobox = POBoxRegistry.getOrCreate((ServerLevel) player.level()).getOrCreatePOBox(address); PacketPOBoxInfoResponse packet = new PacketPOBoxInfoResponse(pobox.getPOBoxInfo(), false); - NetworkUtil.sendToPlayer(packet, (ServerPlayer) player); + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); } @Override @@ -68,15 +57,15 @@ public void addToRootCommand(LiteralArgumentBuilder command) } @Override - public void registerPackets(IPacketRegistry registry) { - registry.serverbound(PacketIdServer.LETTER_INFO_REQUEST, PacketLetterInfoRequest.class, PacketLetterInfoRequest::decode, PacketLetterInfoRequest::handle); - registry.serverbound(PacketIdServer.TRADING_ADDRESS_REQUEST, PacketTraderAddressRequest.class, PacketTraderAddressRequest::decode, PacketTraderAddressRequest::handle); - registry.serverbound(PacketIdServer.LETTER_TEXT_SET, PacketLetterTextSet.class, PacketLetterTextSet::decode, PacketLetterTextSet::handle); + public void registerPackets(PayloadRegistrar registrar) { + registrar.playToServer(PacketIdServer.LETTER_INFO_REQUEST, StreamCodec.of(PacketLetterInfoRequest::encode, PacketLetterInfoRequest::decode), PacketLetterInfoRequest::handle); + registrar.playToServer(PacketIdServer.TRADING_ADDRESS_REQUEST, StreamCodec.of(PacketTraderAddressRequest::encode, PacketTraderAddressRequest::decode), PacketTraderAddressRequest::handle); + registrar.playToServer(PacketIdServer.LETTER_TEXT_SET, StreamCodec.of(PacketLetterTextSet::encode, PacketLetterTextSet::decode), PacketLetterTextSet::handle); - registry.clientbound(PacketIdClient.LETTER_INFO_RESPONSE_PLAYER, PacketLetterInfoResponsePlayer.class, PacketLetterInfoResponsePlayer::decode, PacketLetterInfoResponsePlayer::handle); - registry.clientbound(PacketIdClient.LETTER_INFO_RESPONSE_TRADER, PacketLetterInfoResponseTrader.class, PacketLetterInfoResponseTrader::decode, PacketLetterInfoResponseTrader::handle); - registry.clientbound(PacketIdClient.TRADING_ADDRESS_RESPONSE, PacketTraderAddressResponse.class, PacketTraderAddressResponse::decode, PacketTraderAddressResponse::handle); - registry.clientbound(PacketIdClient.POBOX_INFO_RESPONSE, PacketPOBoxInfoResponse.class, PacketPOBoxInfoResponse::decode, PacketPOBoxInfoResponse::handle); + registrar.playToClient(PacketIdClient.LETTER_INFO_RESPONSE_PLAYER, StreamCodec.of(PacketLetterInfoResponsePlayer::encode, PacketLetterInfoResponsePlayer::decode), PacketLetterInfoResponsePlayer::handle); + registrar.playToClient(PacketIdClient.LETTER_INFO_RESPONSE_TRADER, StreamCodec.of(PacketLetterInfoResponseTrader::encode, PacketLetterInfoResponseTrader::decode), PacketLetterInfoResponseTrader::handle); + registrar.playToClient(PacketIdClient.TRADING_ADDRESS_RESPONSE, StreamCodec.of(PacketTraderAddressResponse::encode, PacketTraderAddressResponse::decode), PacketTraderAddressResponse::handle); + registrar.playToClient(PacketIdClient.POBOX_INFO_RESPONSE, StreamCodec.of(PacketPOBoxInfoResponse::encode, PacketPOBoxInfoResponse::decode), PacketPOBoxInfoResponse::handle); } @Override diff --git a/src/main/java/forestry/mail/PostOffice.java b/src/main/java/forestry/mail/PostOffice.java index 7060135a33..f3d605f422 100644 --- a/src/main/java/forestry/mail/PostOffice.java +++ b/src/main/java/forestry/mail/PostOffice.java @@ -114,8 +114,8 @@ public void collectPostage(NonNullList stamps) { continue; } - if (stamp.getItem() instanceof IStamps) { - EnumPostage postage = ((IStamps) stamp.getItem()).getPostage(stamp); + if (stamp.getItem() instanceof IStampItem) { + EnumPostage postage = ((IStampItem) stamp.getItem()).getPostage(stamp); this.collectedPostage[postage.ordinal()] += stamp.getCount(); } } diff --git a/src/main/java/forestry/mail/blocks/BlockMail.java b/src/main/java/forestry/mail/blocks/BlockMail.java index 2dc5e6afd7..a29f04c4f4 100644 --- a/src/main/java/forestry/mail/blocks/BlockMail.java +++ b/src/main/java/forestry/mail/blocks/BlockMail.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.blocks; import forestry.core.blocks.BlockBase; diff --git a/src/main/java/forestry/mail/blocks/package-info.java b/src/main/java/forestry/mail/blocks/package-info.java index 19c240ac42..380dcdb585 100644 --- a/src/main/java/forestry/mail/blocks/package-info.java +++ b/src/main/java/forestry/mail/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.blocks; diff --git a/src/main/java/forestry/mail/carriers/PostalCarriers.java b/src/main/java/forestry/mail/carriers/PostalCarriers.java deleted file mode 100644 index 419cdbd634..0000000000 --- a/src/main/java/forestry/mail/carriers/PostalCarriers.java +++ /dev/null @@ -1,29 +0,0 @@ -package forestry.mail.carriers; - -import forestry.api.ForestryConstants; -import forestry.api.mail.IPostalCarrier; -import forestry.mail.carriers.players.CarrierPlayer; -import forestry.mail.carriers.trading.CarrierTrader; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.IForgeRegistry; -import net.minecraftforge.registries.RegistryBuilder; -import net.minecraftforge.registries.RegistryObject; - -import java.util.function.Supplier; - -public class PostalCarriers { - private static final ResourceKey> REGISTRY_KEY = ResourceKey.createRegistryKey(new ResourceLocation(ForestryConstants.MOD_ID, "postal_carriers")); - private static final DeferredRegister POSTAL_CARRIERS = DeferredRegister.create(REGISTRY_KEY, ForestryConstants.MOD_ID); - public static final Supplier> REGISTRY = POSTAL_CARRIERS.makeRegistry(() -> new RegistryBuilder().disableSaving()); - - public static final RegistryObject PLAYER = POSTAL_CARRIERS.register("player", CarrierPlayer::new); - public static final RegistryObject TRADER = POSTAL_CARRIERS.register("trader", CarrierTrader::new); - - public static void register(IEventBus bus) { - POSTAL_CARRIERS.register(bus); - } -} diff --git a/src/main/java/forestry/mail/carriers/package-info.java b/src/main/java/forestry/mail/carriers/package-info.java new file mode 100644 index 0000000000..4f84464859 --- /dev/null +++ b/src/main/java/forestry/mail/carriers/package-info.java @@ -0,0 +1,4 @@ +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault +package forestry.mail.carriers; diff --git a/src/main/java/forestry/mail/carriers/players/CarrierPlayer.java b/src/main/java/forestry/mail/carriers/players/CarrierPlayer.java index e22e36d72b..2a063978a5 100644 --- a/src/main/java/forestry/mail/carriers/players/CarrierPlayer.java +++ b/src/main/java/forestry/mail/carriers/players/CarrierPlayer.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.carriers.players; import forestry.api.ForestryConstants; @@ -16,7 +6,7 @@ import forestry.api.mail.IPostOffice; import forestry.api.mail.IPostalCarrier; import forestry.api.mail.IPostalState; -import forestry.core.utils.NetworkUtil; +import forestry.api.modules.IForestryPacketClient; import forestry.core.utils.PlayerUtil; import forestry.mail.MailAddress; import forestry.mail.network.packets.PacketPOBoxInfoResponse; @@ -28,8 +18,9 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.PacketDistributor; public class CarrierPlayer implements IPostalCarrier { private final ResourceLocation iconID; @@ -50,8 +41,8 @@ public TextureAtlasSprite getSprite() { } @Override - public IPostalState deliverLetter(ServerLevel world, IPostOffice office, IMailAddress recipient, ItemStack letterStack, boolean doDeliver) { - POBox pobox = POBoxRegistry.getOrCreate(world).getOrCreatePOBox(recipient); + public IPostalState deliverLetter(ServerLevel level, IPostOffice office, IMailAddress recipient, ItemStack letterStack, boolean doDeliver) { + POBox pobox = POBoxRegistry.getOrCreate(level).getOrCreatePOBox(recipient); if (pobox == null) { return EnumDeliveryState.NO_MAILBOX; } @@ -59,9 +50,10 @@ public IPostalState deliverLetter(ServerLevel world, IPostOffice office, IMailAd if (!pobox.storeLetter(letterStack.copy())) { return EnumDeliveryState.MAILBOX_FULL; } else { - Player player = PlayerUtil.getPlayer(world, recipient.getPlayerProfile()); + Player player = PlayerUtil.getPlayer(level, recipient.getPlayerProfile()); if (player instanceof ServerPlayer) { - NetworkUtil.sendToPlayer(new PacketPOBoxInfoResponse(pobox.getPOBoxInfo(), false), (ServerPlayer) player); + IForestryPacketClient packet = new PacketPOBoxInfoResponse(pobox.getPOBoxInfo(), false); + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); } } @@ -70,7 +62,7 @@ public IPostalState deliverLetter(ServerLevel world, IPostOffice office, IMailAd @Override public IMailAddress getRecipient(MinecraftServer minecraftServer, String recipientName) { - return minecraftServer.getProfileCache().get(recipientName).map(MailAddress::new).orElse(null); + return minecraftServer.getProfileCache().get(recipientName).map(MailAddress::new).orElseThrow(); } @Override diff --git a/src/main/java/forestry/mail/carriers/players/POBox.java b/src/main/java/forestry/mail/carriers/players/POBox.java index 0b37f77ab4..f6fcfe63fe 100644 --- a/src/main/java/forestry/mail/carriers/players/POBox.java +++ b/src/main/java/forestry/mail/carriers/players/POBox.java @@ -15,13 +15,14 @@ import forestry.api.core.INbtWritable; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; +import forestry.core.features.CoreDataComponents; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.InventoryUtil; import forestry.mail.IWatchable; -import forestry.mail.Letter; import forestry.mail.LetterUtils; import forestry.mail.MailAddress; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; @@ -49,42 +50,44 @@ public POBox(IMailAddress address) { this.address = address; } - public POBox(CompoundTag tag) { - read(tag); + public POBox(CompoundTag tag, HolderLookup.Provider registries) { + read(tag, registries); } - public void read(CompoundTag tag) { + @Override + public void read(CompoundTag tag, HolderLookup.Provider registries) { if (tag.contains("address")) { this.address = new MailAddress(tag.getCompound("address")); } - this.letters.read(tag); + this.letters.read(tag, registries); } - public CompoundTag write(CompoundTag compoundNBT) { + @Override + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { if (this.address != null) { CompoundTag nbt = new CompoundTag(); - this.address.write(nbt); + this.address.write(nbt, registries); compoundNBT.put("address", nbt); } - this.letters.write(compoundNBT); + this.letters.write(compoundNBT, registries); return compoundNBT; } - public boolean storeLetter(ItemStack letterstack) { - ILetter letter = LetterUtils.getLetter(letterstack); + public boolean storeLetter(ItemStack stack) { + ILetter letter = LetterUtils.getLetter(stack); Preconditions.checkNotNull(letter, "Letter stack must be a valid letter"); // Mark letter as processed letter.setProcessed(true); letter.invalidatePostage(); CompoundTag compoundNBT = new CompoundTag(); - letter.write(compoundNBT); - letterstack.setTag(compoundNBT); + letter.write(compoundNBT, IDK); + stack.setTag(compoundNBT); this.setDirty(); - return InventoryUtil.tryAddStack(this.letters, letterstack, true); + return InventoryUtil.tryAddStack(this.letters, stack, true); } public POBoxInfo getPOBoxInfo() { @@ -94,10 +97,9 @@ public POBoxInfo getPOBoxInfo() { if (this.letters.getItem(i).isEmpty()) { continue; } - CompoundTag tagCompound = this.letters.getItem(i).getTag(); - if (tagCompound != null) { - ILetter letter = new Letter(tagCompound); - if (letter.getSender().getCarrier().equals(PostalCarriers.PLAYER.get())) { + ILetter letter = this.letters.getItem(i).get(CoreDataComponents.LETTER); + if (letter != null) { + if (letter.getSender().getCarrier().equals(PostalCarriers.PLAYER.value())) { playerLetters++; } else { tradeLetters++; @@ -108,8 +110,6 @@ public POBoxInfo getPOBoxInfo() { return new POBoxInfo(playerLetters, tradeLetters); } - /* IINVENTORY */ - @Override public boolean isEmpty() { return this.letters.isEmpty(); diff --git a/src/main/java/forestry/mail/carriers/players/POBoxRegistry.java b/src/main/java/forestry/mail/carriers/players/POBoxRegistry.java index 136df160d3..f25900601b 100644 --- a/src/main/java/forestry/mail/carriers/players/POBoxRegistry.java +++ b/src/main/java/forestry/mail/carriers/players/POBoxRegistry.java @@ -3,12 +3,14 @@ import forestry.api.mail.IMailAddress; import forestry.mail.IWatchable; import forestry.mail.MailAddress; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.saveddata.SavedData; +import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -22,7 +24,7 @@ public class POBoxRegistry extends SavedData implements IWatchable.Watcher { * @return true if the passed address is valid for PO Boxes. */ public boolean isValidPOBox(IMailAddress address) { - return address.getCarrier().equals(PostalCarriers.PLAYER.get()) && address.getName().matches("^[a-zA-Z0-9]+$"); + return address.getCarrier().equals(PostalCarriers.PLAYER.value()) && address.getName().matches("^[a-zA-Z0-9]+$"); } private void registerPOBOx(IMailAddress address, POBox box) { @@ -31,6 +33,7 @@ private void registerPOBOx(IMailAddress address, POBox box) { setDirty(); } + @Nullable public POBox getPOBox(IMailAddress address) { return this.cachedPOBoxes.get(address); } @@ -56,26 +59,26 @@ private static POBoxRegistry create() { return new POBoxRegistry(); } - private static POBoxRegistry load(CompoundTag compoundTag) { + private static POBoxRegistry load(CompoundTag compoundTag, HolderLookup.Provider registries) { POBoxRegistry registry = new POBoxRegistry(); ListTag tradeStations = compoundTag.getList("poboxes", 10); for (int i = 0; i < tradeStations.size(); ++i) { CompoundTag stationTag = tradeStations.getCompound(i); IMailAddress address = new MailAddress(stationTag.getCompound("address")); - POBox pobox = new POBox(stationTag.getCompound("pobox")); + POBox pobox = new POBox(stationTag.getCompound("pobox"), registries); registry.registerPOBOx(address, pobox); } return registry; } @Override - public CompoundTag save(CompoundTag compoundTag) { + public CompoundTag save(CompoundTag compoundTag, HolderLookup.Provider registries) { ListTag poboxes = new ListTag(); for (Map.Entry entry : this.cachedPOBoxes.entrySet()) { CompoundTag entryTag = new CompoundTag(); - entryTag.put("address", entry.getKey().write(new CompoundTag())); - entryTag.put("pobox", entry.getValue().write(new CompoundTag())); + entryTag.put("address", entry.getKey().write(new CompoundTag(), registries)); + entryTag.put("pobox", entry.getValue().write(new CompoundTag(), registries)); poboxes.add(entryTag); } compoundTag.put("poboxes", poboxes); @@ -83,6 +86,10 @@ public CompoundTag save(CompoundTag compoundTag) { } public static POBoxRegistry getOrCreate(ServerLevel level) { - return level.getDataStorage().computeIfAbsent(POBoxRegistry::load, POBoxRegistry::create, SAVE_NAME); + return level.getDataStorage().computeIfAbsent(POBoxRegistry.factory(), SAVE_NAME); + } + + public static SavedData.Factory factory() { + return new Factory<>(POBoxRegistry::create, POBoxRegistry::load); } } diff --git a/src/main/java/forestry/apiculture/network/package-info.java b/src/main/java/forestry/mail/carriers/players/package-info.java similarity index 52% rename from src/main/java/forestry/apiculture/network/package-info.java rename to src/main/java/forestry/mail/carriers/players/package-info.java index b0cf3930a5..6fe3ec56d5 100644 --- a/src/main/java/forestry/apiculture/network/package-info.java +++ b/src/main/java/forestry/mail/carriers/players/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault -package forestry.apiculture.network; +package forestry.mail.carriers.players; diff --git a/src/main/java/forestry/mail/carriers/trading/CarrierTrader.java b/src/main/java/forestry/mail/carriers/trading/CarrierTrader.java index e173c34ea1..494d736892 100644 --- a/src/main/java/forestry/mail/carriers/trading/CarrierTrader.java +++ b/src/main/java/forestry/mail/carriers/trading/CarrierTrader.java @@ -20,8 +20,8 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class CarrierTrader implements IPostalCarrier { private final ResourceLocation iconID; @@ -42,13 +42,13 @@ public TextureAtlasSprite getSprite() { } @Override - public IPostalState deliverLetter(ServerLevel world, IPostOffice office, IMailAddress recipient, ItemStack letterStack, boolean doDeliver) { - ITradeStation trade = TradeStationRegistry.getOrCreate(world).getTradeStation(recipient); + public IPostalState deliverLetter(ServerLevel level, IPostOffice office, IMailAddress recipient, ItemStack letterStack, boolean doDeliver) { + ITradeStation trade = TradeStationRegistry.getOrCreate(level).getTradeStation(recipient); if (trade == null) { return EnumDeliveryState.NO_MAILBOX; } - return trade.handleLetter(world, recipient, letterStack, doDeliver); + return trade.handleLetter(level, recipient, letterStack, doDeliver); } @Override diff --git a/src/main/java/forestry/mail/carriers/trading/TradeStation.java b/src/main/java/forestry/mail/carriers/trading/TradeStation.java index 59dca4f061..de605d294a 100644 --- a/src/main/java/forestry/mail/carriers/trading/TradeStation.java +++ b/src/main/java/forestry/mail/carriers/trading/TradeStation.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.carriers.trading; import com.mojang.authlib.GameProfile; @@ -16,13 +6,14 @@ import forestry.core.utils.InventoryUtil; import forestry.core.utils.ItemStackUtil; import forestry.mail.*; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; import forestry.mail.features.MailItems; import forestry.mail.inventory.InventoryTradeStation; import forestry.mail.items.EnumStampDefinition; import forestry.mail.postalstates.EnumDeliveryState; import forestry.mail.postalstates.ResponseNotMailable; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; @@ -64,7 +55,7 @@ public class TradeStation implements ITradeStation { private final Set updateWatchers = new HashSet<>(); public TradeStation(@Nullable GameProfile owner, IMailAddress address) { - if (!address.getCarrier().equals(PostalCarriers.TRADER.get())) { + if (!address.getCarrier().equals(PostalCarriers.TRADER.value())) { throw new IllegalArgumentException("TradeStation address must be a trader"); } @@ -72,8 +63,8 @@ public TradeStation(@Nullable GameProfile owner, IMailAddress address) { this.address = address; } - public TradeStation(CompoundTag tag) { - read(tag); + public TradeStation(CompoundTag tag, HolderLookup.Provider registries) { + read(tag, registries); } @Override @@ -81,33 +72,28 @@ public TradeStation(CompoundTag tag) { return this.address; } - // / SAVING & LOADING - public CompoundTag save(CompoundTag compoundNBT) { + @Override + public CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries) { if (this.owner != null) { - CompoundTag nbt = new CompoundTag(); - NbtUtils.writeGameProfile(nbt, this.owner); - compoundNBT.put("owner", nbt); + CompoundTag ownerNbt = new CompoundTag(); + NbtUtils.writeGameProfile(ownerNbt, this.owner); + compoundNBT.put("owner", ownerNbt); } if (this.address != null) { - CompoundTag nbt = new CompoundTag(); - this.address.write(nbt); - compoundNBT.put("address", nbt); + CompoundTag addressNbt = new CompoundTag(); + this.address.write(addressNbt, registries); + nbt.put("address", addressNbt); } - compoundNBT.putBoolean("VRT", this.isVirtual); - compoundNBT.putBoolean("IVL", this.isInvalid); - this.inventory.write(compoundNBT); - return compoundNBT; - } - - @Override - public CompoundTag write(CompoundTag nbt) { - return save(nbt); + nbt.putBoolean("VRT", this.isVirtual); + nbt.putBoolean("IVL", this.isInvalid); + this.inventory.write(nbt, registries); + return nbt; } @Override - public void read(CompoundTag nbt) { + public void read(CompoundTag nbt, HolderLookup.Provider registries) { if (nbt.contains("owner")) { this.owner = NbtUtils.readGameProfile(nbt.getCompound("owner")); } @@ -118,7 +104,7 @@ public void read(CompoundTag nbt) { this.isVirtual = nbt.getBoolean("VRT"); this.isInvalid = nbt.getBoolean("IVL"); - this.inventory.read(nbt); + this.inventory.read(nbt, registries); } /* INVALIDATING */ @@ -172,7 +158,7 @@ public TradeStationInfo getTradeInfo() { /* ILETTERHANDLER */ @Override - public IPostalState handleLetter(ServerLevel world, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { + public IPostalState handleLetter(ServerLevel level, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { boolean sendOwnerNotice = doLodge && this.owner != null; ILetter letter = LetterUtils.getLetter(letterstack); @@ -241,12 +227,12 @@ public IPostalState handleLetter(ServerLevel world, IMailAddress recipient, Item // Send the letter CompoundTag compoundNBT = new CompoundTag(); - mail.write(compoundNBT); + mail.write(compoundNBT, IDK); ItemStack mailstack = LetterProperties.createStampedLetterStack(mail); mailstack.setTag(compoundNBT); - IPostalState responseState = PostOffice.getOrCreate(world).lodgeLetter(world, mailstack, doLodge); + IPostalState responseState = PostOffice.getOrCreate(level).lodgeLetter(level, mailstack, doLodge); if (!responseState.isOk()) { return new ResponseNotMailable(responseState); @@ -286,12 +272,12 @@ public IPostalState handleLetter(ServerLevel world, IMailAddress recipient, Item confirm.setText(orderFilledMessage); confirm.addStamps(MailItems.STAMPS.stack(EnumStampDefinition.P_1, 1)); - confirm.write(compoundNBT); + confirm.write(compoundNBT, IDK); ItemStack confirmstack = LetterProperties.createStampedLetterStack(confirm); confirmstack.setTag(compoundNBT); - PostOffice.getOrCreate(world).lodgeLetter(world, confirmstack, doLodge); + PostOffice.getOrCreate(level).lodgeLetter(level, confirmstack, doLodge); removePaper(); removeStamps(new int[]{0, 1}); @@ -402,11 +388,11 @@ private boolean canPayPostage(int postage) { continue; } - if (!(stamp.getItem() instanceof IStamps)) { + if (!(stamp.getItem() instanceof IStampItem)) { continue; } - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); + posted += ((IStampItem) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); if (posted >= postage) { return true; @@ -485,11 +471,11 @@ private int getNumStamps(EnumPostage postage) { if (stamp == null) { continue; } - if (!(stamp.getItem() instanceof IStamps)) { + if (!(stamp.getItem() instanceof IStampItem)) { continue; } - if (((IStamps) stamp.getItem()).getPostage(stamp) == postage) { + if (((IStampItem) stamp.getItem()).getPostage(stamp) == postage) { count += stamp.getCount(); } @@ -515,11 +501,11 @@ private void removeStamps(int[] stampCount) { continue; } - if (!(stamp.getItem() instanceof IStamps)) { + if (!(stamp.getItem() instanceof IStampItem)) { continue; } - if (((IStamps) stamp.getItem()).getPostage(stamp) == EnumPostage.values()[i]) { + if (((IStampItem) stamp.getItem()).getPostage(stamp) == EnumPostage.values()[i]) { ItemStack decrease = this.inventory.removeItem(j, stampCount[i]); stampCount[i] -= decrease.getCount(); } diff --git a/src/main/java/forestry/mail/carriers/trading/TradeStationInfo.java b/src/main/java/forestry/mail/carriers/trading/TradeStationInfo.java deleted file mode 100644 index 39195bb139..0000000000 --- a/src/main/java/forestry/mail/carriers/trading/TradeStationInfo.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.carriers.trading; - -import com.mojang.authlib.GameProfile; -import forestry.api.mail.EnumTradeStationState; -import forestry.api.mail.IMailAddress; -import forestry.api.mail.ITradeStationInfo; -import forestry.mail.carriers.PostalCarriers; -import net.minecraft.world.item.ItemStack; - -import java.util.List; - -public record TradeStationInfo(IMailAddress address, GameProfile owner, ItemStack tradegood, List required, - EnumTradeStationState state) implements ITradeStationInfo { - public TradeStationInfo { - if (!address.getCarrier().equals(PostalCarriers.TRADER.get())) { - throw new IllegalArgumentException("TradeStation address must be a trader"); - } - } -} diff --git a/src/main/java/forestry/mail/carriers/trading/TradeStationRegistry.java b/src/main/java/forestry/mail/carriers/trading/TradeStationRegistry.java index cffb83b0fa..3a0ff9f9e8 100644 --- a/src/main/java/forestry/mail/carriers/trading/TradeStationRegistry.java +++ b/src/main/java/forestry/mail/carriers/trading/TradeStationRegistry.java @@ -5,7 +5,8 @@ import forestry.api.mail.ITradeStation; import forestry.mail.IWatchable; import forestry.mail.MailAddress; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.server.level.ServerLevel; @@ -28,7 +29,7 @@ public class TradeStationRegistry extends SavedData implements IWatchable.Watche * @return true if the passed address can be an address for a trade station */ public boolean isValidTradeAddress(IMailAddress address) { - return address.getCarrier().equals(PostalCarriers.TRADER.get()) && TRADE_STATION_NAME_REGEX.matcher(address.getName()).matches(); + return address.getCarrier().equals(PostalCarriers.TRADER.value()) && TRADE_STATION_NAME_REGEX.matcher(address.getName()).matches(); } /** @@ -90,26 +91,26 @@ private static TradeStationRegistry create() { return new TradeStationRegistry(); } - private static TradeStationRegistry load(CompoundTag compoundTag) { + private static TradeStationRegistry load(CompoundTag compoundTag, HolderLookup.Provider registries) { TradeStationRegistry registry = new TradeStationRegistry(); ListTag tradeStations = compoundTag.getList("tradeStations", 10); for (int i = 0; i < tradeStations.size(); ++i) { CompoundTag stationTag = tradeStations.getCompound(i); IMailAddress address = new MailAddress(stationTag.getCompound("address")); - ITradeStation station = new TradeStation(stationTag.getCompound("station")); + ITradeStation station = new TradeStation(stationTag.getCompound("station"), registries); registry.registerTradeStation(address, station); } return registry; } @Override - public CompoundTag save(CompoundTag compoundTag) { + public CompoundTag save(CompoundTag compoundTag, HolderLookup.Provider registries) { ListTag tradeStations = new ListTag(); for (Map.Entry entry : this.cachedTradeStations.entrySet()) { CompoundTag entryTag = new CompoundTag(); - entryTag.put("address", entry.getKey().write(new CompoundTag())); - entryTag.put("station", entry.getValue().write(new CompoundTag())); + entryTag.put("address", entry.getKey().write(new CompoundTag(), registries)); + entryTag.put("station", entry.getValue().write(new CompoundTag(), registries)); tradeStations.add(entryTag); } compoundTag.put("tradeStations", tradeStations); @@ -117,6 +118,10 @@ public CompoundTag save(CompoundTag compoundTag) { } public static TradeStationRegistry getOrCreate(ServerLevel level) { - return level.getDataStorage().computeIfAbsent(TradeStationRegistry::load, TradeStationRegistry::create, SAVE_NAME); + return level.getDataStorage().computeIfAbsent(TradeStationRegistry.factory(), SAVE_NAME); + } + + public static SavedData.Factory factory() { + return new Factory<>(TradeStationRegistry::create, TradeStationRegistry::load); } } diff --git a/src/main/java/forestry/mail/carriers/trading/package-info.java b/src/main/java/forestry/mail/carriers/trading/package-info.java new file mode 100644 index 0000000000..79ded8712f --- /dev/null +++ b/src/main/java/forestry/mail/carriers/trading/package-info.java @@ -0,0 +1,4 @@ +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault +package forestry.mail.carriers.trading; diff --git a/src/main/java/forestry/mail/client/package-info.java b/src/main/java/forestry/mail/client/package-info.java index e47089dae4..adde464a28 100644 --- a/src/main/java/forestry/mail/client/package-info.java +++ b/src/main/java/forestry/mail/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.client; diff --git a/src/main/java/forestry/mail/commands/CommandMail.java b/src/main/java/forestry/mail/commands/CommandMail.java index 36c357e81b..7e7ce4690e 100644 --- a/src/main/java/forestry/mail/commands/CommandMail.java +++ b/src/main/java/forestry/mail/commands/CommandMail.java @@ -16,7 +16,7 @@ import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import forestry.api.mail.ITradeStation; -import forestry.api.mail.ITradeStationInfo; +import forestry.api.mail.TradeStationInfo; import forestry.core.commands.CommandHelpers; import forestry.core.utils.StringUtil; import forestry.mail.MailAddress; @@ -54,7 +54,7 @@ public static int execute(CommandContext context) throws Com return 1; } - private static Component makeTradeListEntry(ITradeStationInfo info) { + private static Component makeTradeListEntry(TradeStationInfo info) { ChatFormatting formatting = info.state().isOk() ? ChatFormatting.GREEN : ChatFormatting.RED; String tradegood = "[ ? ]"; diff --git a/src/main/java/forestry/mail/commands/package-info.java b/src/main/java/forestry/mail/commands/package-info.java index 7b0b06d1a0..5933fc4a98 100644 --- a/src/main/java/forestry/mail/commands/package-info.java +++ b/src/main/java/forestry/mail/commands/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.commands; diff --git a/src/main/java/forestry/mail/compat/MailJeiPlugin.java b/src/main/java/forestry/mail/compat/MailJeiPlugin.java index 6a8e543168..0dbca8a46b 100644 --- a/src/main/java/forestry/mail/compat/MailJeiPlugin.java +++ b/src/main/java/forestry/mail/compat/MailJeiPlugin.java @@ -1,7 +1,7 @@ package forestry.mail.compat; import forestry.api.modules.ForestryModuleIds; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.mail.blocks.BlockTypeMail; import forestry.mail.features.MailBlocks; import mezz.jei.api.IModPlugin; diff --git a/src/main/java/forestry/mail/compat/package-info.java b/src/main/java/forestry/mail/compat/package-info.java index c05db09deb..08457f6ea0 100644 --- a/src/main/java/forestry/mail/compat/package-info.java +++ b/src/main/java/forestry/mail/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.compat; diff --git a/src/main/java/forestry/mail/features/MailMenuTypes.java b/src/main/java/forestry/mail/features/MailMenuTypes.java index 2cae84fb15..cdb59b3197 100644 --- a/src/main/java/forestry/mail/features/MailMenuTypes.java +++ b/src/main/java/forestry/mail/features/MailMenuTypes.java @@ -12,9 +12,9 @@ public class MailMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.MAIL); public static final FeatureMenuType CATALOGUE = REGISTRY.menuType(ContainerCatalogue::fromNetwork, "catalogue"); - public static final FeatureMenuType LETTER = REGISTRY.menuType(ContainerLetter::fromNetwork, "letter"); - public static final FeatureMenuType MAILBOX = REGISTRY.menuType(ContainerMailbox::fromNetwork, "mailbox"); - public static final FeatureMenuType STAMP_COLLECTOR = REGISTRY.menuType(ContainerStampCollector::fromNetwork, "stamp_collector"); - public static final FeatureMenuType TRADE_NAME = REGISTRY.menuType(ContainerTradeName::fromNetwork, "trade_name"); - public static final FeatureMenuType TRADER = REGISTRY.menuType(ContainerTrader::fromNetwork, "trader"); + public static final FeatureMenuType LETTER = REGISTRY.menuType(LetterMenu::fromNetwork, "letter"); + public static final FeatureMenuType MAILBOX = REGISTRY.menuType(MailboxMenu::fromNetwork, "mailbox"); + public static final FeatureMenuType STAMP_COLLECTOR = REGISTRY.menuType(StampCollectorMenu::fromNetwork, "stamp_collector"); + public static final FeatureMenuType TRADE_NAME = REGISTRY.menuType(TradeNameMenu::fromNetwork, "trade_name"); + public static final FeatureMenuType TRADER = REGISTRY.menuType(TraderMenu::fromNetwork, "trader"); } diff --git a/src/main/java/forestry/mail/features/PostalCarriers.java b/src/main/java/forestry/mail/features/PostalCarriers.java new file mode 100644 index 0000000000..5a91f3e92e --- /dev/null +++ b/src/main/java/forestry/mail/features/PostalCarriers.java @@ -0,0 +1,19 @@ +package forestry.mail.features; + +import forestry.api.ForestryRegistries; +import forestry.api.mail.IPostalCarrier; +import forestry.api.modules.ForestryModuleIds; +import forestry.mail.carriers.players.CarrierPlayer; +import forestry.mail.carriers.trading.CarrierTrader; +import forestry.modules.features.FeatureProvider; +import forestry.modules.features.ModFeatureRegistry; +import net.minecraft.core.Holder; +import net.neoforged.neoforge.registries.DeferredRegister; + +@FeatureProvider +public class PostalCarriers { + private static final DeferredRegister POSTAL_CARRIERS = ModFeatureRegistry.get(ForestryModuleIds.MAIL).getRegistry(ForestryRegistries.POSTAL_CARRIER.key()); + + public static final Holder PLAYER = POSTAL_CARRIERS.register("player", CarrierPlayer::new); + public static final Holder TRADER = POSTAL_CARRIERS.register("trader", CarrierTrader::new); +} diff --git a/src/main/java/forestry/mail/features/package-info.java b/src/main/java/forestry/mail/features/package-info.java index a37b3264a1..100fcc74fb 100644 --- a/src/main/java/forestry/mail/features/package-info.java +++ b/src/main/java/forestry/mail/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.features; diff --git a/src/main/java/forestry/mail/gui/AddresseeSlot.java b/src/main/java/forestry/mail/gui/AddresseeSlot.java index d92d149117..7e11cc21dc 100644 --- a/src/main/java/forestry/mail/gui/AddresseeSlot.java +++ b/src/main/java/forestry/mail/gui/AddresseeSlot.java @@ -21,9 +21,9 @@ public class AddresseeSlot extends Widget { - private final ContainerLetter containerLetter; + private final LetterMenu containerLetter; - public AddresseeSlot(WidgetManager widgetManager, int xPos, int yPos, ContainerLetter containerLetter) { + public AddresseeSlot(WidgetManager widgetManager, int xPos, int yPos, LetterMenu containerLetter) { super(widgetManager, xPos, yPos); this.containerLetter = containerLetter; this.width = 26; diff --git a/src/main/java/forestry/mail/gui/ContainerCatalogue.java b/src/main/java/forestry/mail/gui/ContainerCatalogue.java index fcf5d23c76..e6ea81db29 100755 --- a/src/main/java/forestry/mail/gui/ContainerCatalogue.java +++ b/src/main/java/forestry/mail/gui/ContainerCatalogue.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.gui; import forestry.api.mail.*; +import forestry.api.modules.IForestryPacketClient; import forestry.core.gui.IGuiSelectable; -import forestry.core.utils.NetworkUtil; import forestry.mail.carriers.trading.TradeStationRegistry; import forestry.mail.features.MailMenuTypes; import forestry.mail.network.packets.PacketLetterInfoResponseTrader; @@ -24,6 +14,7 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.*; @@ -33,7 +24,7 @@ public class ContainerCatalogue extends AbstractContainerMenu implements IGuiSel private final List stations = new ArrayList<>(); @Nullable - private ITradeStationInfo currentTrade = null; + private TradeStationInfo currentTrade = null; private final DataSlot stationIndex = DataSlot.standalone(); @@ -98,7 +89,7 @@ private void rebuildStationsList() { Map tradeStations = TradeStationRegistry.getOrCreate((ServerLevel) this.player.level()).getActiveTradeStations(); for (ITradeStation station : tradeStations.values()) { - ITradeStationInfo info = station.getTradeInfo(); + TradeStationInfo info = station.getTradeInfo(); // Filter out any trade stations which do not actually offer anything. if (FILTERS.get(this.currentFilter.get()).contains(info.state())) { @@ -147,16 +138,16 @@ private void updateTradeInfo() { } @Override - public void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddress address, @Nullable ITradeStationInfo tradeInfo) { + public void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddress address, @Nullable TradeStationInfo tradeInfo) { setTradeInfo(tradeInfo); } @Nullable - public ITradeStationInfo getTradeInfo() { + public TradeStationInfo getTradeInfo() { return this.currentTrade; } - private void setTradeInfo(@Nullable ITradeStationInfo info) { + private void setTradeInfo(@Nullable TradeStationInfo info) { this.currentTrade = info; } @@ -165,7 +156,8 @@ public void broadcastChanges() { super.broadcastChanges(); if (this.needsSync) { - NetworkUtil.sendToPlayer(new PacketLetterInfoResponseTrader(this.currentTrade), (ServerPlayer) this.player); + IForestryPacketClient packet = new PacketLetterInfoResponseTrader(this.currentTrade); + PacketDistributor.sendToPlayer((ServerPlayer) this.player, packet); this.needsSync = false; } } diff --git a/src/main/java/forestry/mail/gui/GuiCatalogue.java b/src/main/java/forestry/mail/gui/GuiCatalogue.java index 8e4c016c2c..2282e67623 100755 --- a/src/main/java/forestry/mail/gui/GuiCatalogue.java +++ b/src/main/java/forestry/mail/gui/GuiCatalogue.java @@ -10,15 +10,15 @@ ******************************************************************************/ package forestry.mail.gui; -import forestry.api.mail.ITradeStationInfo; +import forestry.api.mail.TradeStationInfo; +import forestry.api.modules.IForestryPacketServer; import forestry.core.config.SessionVars; import forestry.core.gui.GuiForestry; import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.Widget; import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.render.ColourProperties; -import forestry.core.utils.NetworkUtil; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; @@ -30,6 +30,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.ArrayList; @@ -76,7 +77,7 @@ protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseY, in clearTradeInfoWidgets(); - ITradeStationInfo tradeInfo = this.menu.getTradeInfo(); + TradeStationInfo tradeInfo = this.menu.getTradeInfo(); if (this.buttonUse != null) { if (tradeInfo != null) { @@ -97,7 +98,7 @@ private void drawNoTrade(GuiGraphics graphics, int x, int y) { graphics.drawWordWrap(this.font, Component.translatable("for.gui.mail.notrades"), x, y + 18, 119, ColourProperties.INSTANCE.get("gui.book")); } - private void drawTradePreview(GuiGraphics graphics, ITradeStationInfo tradeInfo, int x, int y) { + private void drawTradePreview(GuiGraphics graphics, TradeStationInfo tradeInfo, int x, int y) { Font font = this.font; graphics.drawString(font, BOLD_UNDERLINE + tradeInfo.address().getName(), x, y, ColourProperties.INSTANCE.get("gui.book"), false); @@ -137,13 +138,22 @@ protected void actionPerformed(int id) { switch (id) { case 0 -> player.closeContainer(); case 2 -> // next page - NetworkUtil.sendToServer(new PacketGuiSelectRequest(0, 0)); + { + IForestryPacketServer packet = new PacketGuiSelectRequest(0, 0); + PacketDistributor.sendToServer(packet); + } case 3 -> // previous page - NetworkUtil.sendToServer(new PacketGuiSelectRequest(1, 0)); + { + IForestryPacketServer packet = new PacketGuiSelectRequest(1, 0); + PacketDistributor.sendToServer(packet); + } case 4 -> // cycle filter - NetworkUtil.sendToServer(new PacketGuiSelectRequest(2, 0)); + { + IForestryPacketServer packet = new PacketGuiSelectRequest(2, 0); + PacketDistributor.sendToServer(packet); + } case 5 -> { - ITradeStationInfo info = this.menu.getTradeInfo(); + TradeStationInfo info = this.menu.getTradeInfo(); if (info != null) { SessionVars.setStringVar("mail.letter.recipient", info.address().getName()); SessionVars.setStringVar("mail.letter.carrier", PostalCarriers.TRADER.getKey().location().toString()); diff --git a/src/main/java/forestry/mail/gui/GuiLetter.java b/src/main/java/forestry/mail/gui/GuiLetter.java index 67e245b81a..2bca7b7f19 100755 --- a/src/main/java/forestry/mail/gui/GuiLetter.java +++ b/src/main/java/forestry/mail/gui/GuiLetter.java @@ -19,8 +19,7 @@ import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.Widget; import forestry.core.render.ColourProperties; -import forestry.core.utils.NetworkUtil; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; import forestry.mail.inventory.ItemInventoryLetter; import forestry.mail.network.packets.PacketLetterInfoRequest; import net.minecraft.client.Minecraft; @@ -29,15 +28,16 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.PacketDistributor; import org.apache.commons.lang3.StringUtils; import org.lwjgl.glfw.GLFW; import java.util.ArrayList; import java.util.Locale; -public class GuiLetter extends GuiForestry { +public class GuiLetter extends GuiForestry { private final ItemInventoryLetter itemInventory; private final boolean isProcessedLetter; private boolean checkedSessionVars; @@ -50,7 +50,7 @@ public class GuiLetter extends GuiForestry { private final ArrayList tradeInfoWidgets; - public GuiLetter(ContainerLetter container, Inventory inv, Component title) { + public GuiLetter(LetterMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/letter.png", container, inv, title); this.minecraft = Minecraft.getInstance(); //not 100% why this is needed, maybe side issues @@ -254,8 +254,8 @@ private void setRecipient(String recipientName, IPostalCarrier carrier) { } PacketLetterInfoRequest packet = new PacketLetterInfoRequest(recipientName, carrier); - NetworkUtil.sendToServer(packet); - } + PacketDistributor.sendToServer(packet); + } @OnlyIn(Dist.CLIENT) private void setText() { diff --git a/src/main/java/forestry/mail/gui/GuiMailbox.java b/src/main/java/forestry/mail/gui/GuiMailbox.java index 6a807b07a6..63cc78011f 100755 --- a/src/main/java/forestry/mail/gui/GuiMailbox.java +++ b/src/main/java/forestry/mail/gui/GuiMailbox.java @@ -16,10 +16,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiMailbox extends GuiForestry { +public class GuiMailbox extends GuiForestry { private final TileMailbox tile; - public GuiMailbox(ContainerMailbox container, Inventory inv, Component title) { + public GuiMailbox(MailboxMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/mailbox.png", container, inv, title); this.tile = container.getTile(); this.imageWidth = 230; diff --git a/src/main/java/forestry/mail/gui/GuiStampCollector.java b/src/main/java/forestry/mail/gui/GuiStampCollector.java index 824b5c61d6..6031620d30 100644 --- a/src/main/java/forestry/mail/gui/GuiStampCollector.java +++ b/src/main/java/forestry/mail/gui/GuiStampCollector.java @@ -16,10 +16,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiStampCollector extends GuiForestry { +public class GuiStampCollector extends GuiForestry { private final TileStampCollector tile; - public GuiStampCollector(ContainerStampCollector container, Inventory inv, Component title) { + public GuiStampCollector(StampCollectorMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/philatelist.png", container, inv, title); this.tile = container.getTile(); this.imageWidth = 176; diff --git a/src/main/java/forestry/mail/gui/GuiTradeName.java b/src/main/java/forestry/mail/gui/GuiTradeName.java index 654026b0aa..f1c526d86c 100755 --- a/src/main/java/forestry/mail/gui/GuiTradeName.java +++ b/src/main/java/forestry/mail/gui/GuiTradeName.java @@ -13,21 +13,21 @@ import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.render.ColourProperties; -import forestry.core.utils.NetworkUtil; import forestry.mail.network.packets.PacketTraderAddressRequest; import forestry.mail.tiles.TileTrader; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.EditBox; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; +import net.neoforged.neoforge.network.PacketDistributor; import org.apache.commons.lang3.StringUtils; import org.lwjgl.glfw.GLFW; -public class GuiTradeName extends GuiForestry { +public class GuiTradeName extends GuiForestry { private final TileTrader tile; private EditBox addressNameField; - public GuiTradeName(ContainerTradeName container, Inventory inv, Component title) { + public GuiTradeName(TradeNameMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/tradername.png", container, inv, title); this.tile = container.getTile(); this.imageWidth = 176; @@ -83,8 +83,8 @@ private void setAddress() { String address = this.addressNameField.getValue(); if (StringUtils.isNotBlank(address)) { PacketTraderAddressRequest packet = new PacketTraderAddressRequest(this.tile, address); - NetworkUtil.sendToServer(packet); - } + PacketDistributor.sendToServer(packet); + } } @Override diff --git a/src/main/java/forestry/mail/gui/GuiTrader.java b/src/main/java/forestry/mail/gui/GuiTrader.java index e63465c803..3bff20addf 100755 --- a/src/main/java/forestry/mail/gui/GuiTrader.java +++ b/src/main/java/forestry/mail/gui/GuiTrader.java @@ -18,10 +18,10 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiTrader extends GuiForestry { +public class GuiTrader extends GuiForestry { private final TileTrader tile; - public GuiTrader(ContainerTrader container, Inventory inv, Component title) { + public GuiTrader(TraderMenu container, Inventory inv, Component title) { super(Constants.TEXTURE_PATH_GUI + "/mailtrader2.png", container, inv, title); this.tile = container.getTile(); this.imageWidth = 226; diff --git a/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java b/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java index 6bd5da8ebf..8f3464c401 100644 --- a/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java +++ b/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java @@ -12,10 +12,10 @@ import forestry.api.mail.IMailAddress; import forestry.api.mail.IPostalCarrier; -import forestry.api.mail.ITradeStationInfo; +import forestry.api.mail.TradeStationInfo; import javax.annotation.Nullable; public interface ILetterInfoReceiver { - void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddress address, @Nullable ITradeStationInfo tradeInfo); + void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddress address, @Nullable TradeStationInfo tradeInfo); } diff --git a/src/main/java/forestry/mail/gui/ContainerLetter.java b/src/main/java/forestry/mail/gui/LetterMenu.java old mode 100755 new mode 100644 similarity index 73% rename from src/main/java/forestry/mail/gui/ContainerLetter.java rename to src/main/java/forestry/mail/gui/LetterMenu.java index b7c96bb58e..b56d057111 --- a/src/main/java/forestry/mail/gui/ContainerLetter.java +++ b/src/main/java/forestry/mail/gui/LetterMenu.java @@ -1,23 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.gui; import forestry.Forestry; import forestry.api.mail.*; -import forestry.core.gui.ContainerItemInventory; +import forestry.api.modules.IForestryPacketClient; +import forestry.api.modules.IForestryPacketServer; +import forestry.core.gui.ItemInventoryMenu; import forestry.core.gui.slots.SlotFiltered; -import forestry.core.utils.NetworkUtil; import forestry.mail.Letter; import forestry.mail.MailAddress; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; import forestry.mail.carriers.trading.TradeStationRegistry; import forestry.mail.features.MailMenuTypes; import forestry.mail.inventory.ItemInventoryLetter; @@ -32,26 +23,27 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; import java.util.Iterator; -public class ContainerLetter extends ContainerItemInventory implements ILetterInfoReceiver { - private IPostalCarrier carrier = PostalCarriers.PLAYER.get(); +public class LetterMenu extends ItemInventoryMenu implements ILetterInfoReceiver { + private IPostalCarrier carrier = PostalCarriers.PLAYER.value(); @Nullable - private ITradeStationInfo tradeInfo = null; + private TradeStationInfo tradeInfo = null; - public static ContainerLetter fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { + public static LetterMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf extraData) { InteractionHand hand = extraData.readBoolean() ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; Player player = playerInv.player; ItemInventoryLetter inv = new ItemInventoryLetter(player, player.getItemInHand(hand)); - return new ContainerLetter(windowId, player, inv); + return new LetterMenu(windowId, player, inv); } - public ContainerLetter(int windowId, Player player, ItemInventoryLetter inventory) { - super(windowId, inventory, player.getInventory(), 17, 145, MailMenuTypes.LETTER.menuType()); + public LetterMenu(int windowId, Player player, ItemInventoryLetter inventory) { + super(MailMenuTypes.LETTER.menuType(), windowId, inventory, player.getInventory(), 17, 145); // Init slots @@ -145,10 +137,12 @@ public void handleRequestLetterInfo(Player player, String recipientName, IPostal // TODO: Move this to the carrier to make it more extensible // Update info on client if (carrier.equals(PostalCarriers.PLAYER.get())) { - NetworkUtil.sendToPlayer(new PacketLetterInfoResponsePlayer(recipient), (ServerPlayer) player); - } else { - NetworkUtil.sendToPlayer(new PacketLetterInfoResponseTrader(this.tradeInfo), (ServerPlayer) player); - } + IForestryPacketClient packet = new PacketLetterInfoResponsePlayer(recipient); + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); + } else { + IForestryPacketClient packet = new PacketLetterInfoResponseTrader(this.tradeInfo); + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); + } } private static IMailAddress getRecipient(MinecraftServer minecraftServer, String recipientName, IPostalCarrier carrier) { @@ -168,7 +162,8 @@ public String getText() { public void setText(String text) { getLetter().setText(text); - NetworkUtil.sendToServer(new PacketLetterTextSet(text)); + IForestryPacketServer packet = new PacketLetterTextSet(text); + PacketDistributor.sendToServer(packet); } public void handleSetText(String text) { @@ -197,7 +192,7 @@ private void updateTradeInfo(Level world, @Nullable IMailAddress address) { } @Override - public void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddress address, @Nullable ITradeStationInfo tradeInfo) { + public void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddress address, @Nullable TradeStationInfo tradeInfo) { this.carrier = carrier; if (carrier.equals(PostalCarriers.PLAYER.get())) { getLetter().setRecipient(address); @@ -207,11 +202,11 @@ public void handleLetterInfoUpdate(IPostalCarrier carrier, @Nullable IMailAddres } @Nullable - public ITradeStationInfo getTradeInfo() { + public TradeStationInfo getTradeInfo() { return this.tradeInfo; } - private void setTradeInfo(@Nullable ITradeStationInfo info) { + private void setTradeInfo(@Nullable TradeStationInfo info) { this.tradeInfo = info; if (this.tradeInfo == null) { getLetter().setRecipient(null); diff --git a/src/main/java/forestry/mail/gui/ContainerMailbox.java b/src/main/java/forestry/mail/gui/MailboxMenu.java old mode 100755 new mode 100644 similarity index 79% rename from src/main/java/forestry/mail/gui/ContainerMailbox.java rename to src/main/java/forestry/mail/gui/MailboxMenu.java index 44d6c5c96e..4283528ee1 --- a/src/main/java/forestry/mail/gui/ContainerMailbox.java +++ b/src/main/java/forestry/mail/gui/MailboxMenu.java @@ -10,10 +10,10 @@ ******************************************************************************/ package forestry.mail.gui; -import forestry.core.gui.ContainerTile; +import forestry.api.modules.IForestryPacketClient; +import forestry.core.gui.TileMenu; import forestry.core.gui.slots.SlotOutput; import forestry.core.tiles.TileUtil; -import forestry.core.utils.NetworkUtil; import forestry.core.utils.SlotUtil; import forestry.mail.carriers.players.POBox; import forestry.mail.carriers.players.POBoxInfo; @@ -26,10 +26,11 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ClickType; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; -public class ContainerMailbox extends ContainerTile { +public class MailboxMenu extends TileMenu { public static final short SLOT_LETTERS = 0; public static final short SLOT_LETTERS_COUNT = 7 * 12; @@ -37,12 +38,12 @@ public class ContainerMailbox extends ContainerTile { private final POBox mailInventory; - public static ContainerMailbox fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + public static MailboxMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileMailbox tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileMailbox.class); - return new ContainerMailbox(windowId, inv, tile); //TODO nullability. + return new MailboxMenu(windowId, inv, tile); //TODO nullability. } - public ContainerMailbox(int windowId, Inventory playerInventory, TileMailbox tile) { + public MailboxMenu(int windowId, Inventory playerInventory, TileMailbox tile) { super(windowId, MailMenuTypes.MAILBOX.menuType(), playerInventory, tile, 35, 145); Container inventory = tile.getOrCreateMailInventory(playerInventory.player.level(), playerInventory.player.getGameProfile()); @@ -66,8 +67,9 @@ public void clicked(int slotId, int button, ClickType clickTypeIn, Player player if (SlotUtil.isSlotInRange(slotId, SLOT_LETTERS, SLOT_LETTERS_COUNT)) { if (!player.level().isClientSide && this.mailInventory != null) { POBoxInfo info = this.mailInventory.getPOBoxInfo(); - NetworkUtil.sendToPlayer(new PacketPOBoxInfoResponse(info, true), (ServerPlayer) player); - } + IForestryPacketClient packet = new PacketPOBoxInfoResponse(info, true); + PacketDistributor.sendToPlayer((ServerPlayer) player, packet); + } } } } diff --git a/src/main/java/forestry/mail/gui/ContainerStampCollector.java b/src/main/java/forestry/mail/gui/StampCollectorMenu.java similarity index 79% rename from src/main/java/forestry/mail/gui/ContainerStampCollector.java rename to src/main/java/forestry/mail/gui/StampCollectorMenu.java index 15522362d8..059e89910e 100644 --- a/src/main/java/forestry/mail/gui/ContainerStampCollector.java +++ b/src/main/java/forestry/mail/gui/StampCollectorMenu.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.mail.gui; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.tiles.TileUtil; @@ -20,13 +20,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerStampCollector extends ContainerTile { - public static ContainerStampCollector fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class StampCollectorMenu extends TileMenu { + public static StampCollectorMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileStampCollector tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileStampCollector.class); - return new ContainerStampCollector(windowId, inv, tile); + return new StampCollectorMenu(windowId, inv, tile); } - public ContainerStampCollector(int windowId, Inventory inv, TileStampCollector tile) { + public StampCollectorMenu(int windowId, Inventory inv, TileStampCollector tile) { super(windowId, MailMenuTypes.STAMP_COLLECTOR.menuType(), inv, tile, 8, 111); // Filter diff --git a/src/main/java/forestry/mail/gui/ToastMailboxInfo.java b/src/main/java/forestry/mail/gui/ToastMailboxInfo.java index e6ee96c93a..4202293e46 100644 --- a/src/main/java/forestry/mail/gui/ToastMailboxInfo.java +++ b/src/main/java/forestry/mail/gui/ToastMailboxInfo.java @@ -12,8 +12,8 @@ import net.minecraft.client.gui.components.toasts.ToastComponent; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/forestry/mail/gui/ContainerTradeName.java b/src/main/java/forestry/mail/gui/TradeNameMenu.java old mode 100755 new mode 100644 similarity index 74% rename from src/main/java/forestry/mail/gui/ContainerTradeName.java rename to src/main/java/forestry/mail/gui/TradeNameMenu.java index 7a40a78219..23729c6a96 --- a/src/main/java/forestry/mail/gui/ContainerTradeName.java +++ b/src/main/java/forestry/mail/gui/TradeNameMenu.java @@ -11,23 +11,22 @@ package forestry.mail.gui; import forestry.api.mail.IMailAddress; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.tiles.TileUtil; import forestry.mail.features.MailMenuTypes; import forestry.mail.tiles.TileTrader; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; -public class ContainerTradeName extends ContainerTile { - public static ContainerTradeName fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class TradeNameMenu extends TileMenu { + public static TradeNameMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileTrader tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileTrader.class); - return new ContainerTradeName(windowId, inv.player, tile); + return new TradeNameMenu(windowId, inv.player, tile); } - public ContainerTradeName(int windowId, Player player, TileTrader tile) { + public TradeNameMenu(int windowId, Player player, TileTrader tile) { super(windowId, MailMenuTypes.TRADE_NAME.menuType(), tile, player); } @@ -42,7 +41,7 @@ public void broadcastChanges() { if (this.tile.isLinked()) { for (Object crafter : this.containerListeners) { if (crafter instanceof ServerPlayer player) { - this.tile.openGui(player, InteractionHand.MAIN_HAND, this.tile.getBlockPos()); + this.tile.interactNoItem(player.level(), player, this.tile.getBlockPos()); } } } diff --git a/src/main/java/forestry/mail/gui/ContainerTrader.java b/src/main/java/forestry/mail/gui/TraderMenu.java old mode 100755 new mode 100644 similarity index 88% rename from src/main/java/forestry/mail/gui/ContainerTrader.java rename to src/main/java/forestry/mail/gui/TraderMenu.java index 2d80edb6a7..6c15728d03 --- a/src/main/java/forestry/mail/gui/ContainerTrader.java +++ b/src/main/java/forestry/mail/gui/TraderMenu.java @@ -11,7 +11,7 @@ package forestry.mail.gui; import forestry.api.mail.IMailAddress; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotForestry; import forestry.core.gui.slots.SlotOutput; @@ -22,13 +22,13 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerTrader extends ContainerTile { - public static ContainerTrader fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { +public class TraderMenu extends TileMenu { + public static TraderMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileTrader tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileTrader.class); - return new ContainerTrader(windowId, inv, tile); + return new TraderMenu(windowId, inv, tile); } - public ContainerTrader(int windowId, Inventory inv, TileTrader tile) { + public TraderMenu(int windowId, Inventory inv, TileTrader tile) { super(windowId, MailMenuTypes.TRADER.menuType(), inv, tile, 33, 138); // Trade good diff --git a/src/main/java/forestry/mail/gui/package-info.java b/src/main/java/forestry/mail/gui/package-info.java index 7ff679e430..463d180607 100644 --- a/src/main/java/forestry/mail/gui/package-info.java +++ b/src/main/java/forestry/mail/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.gui; diff --git a/src/main/java/forestry/mail/inventory/InventoryStampCollector.java b/src/main/java/forestry/mail/inventory/InventoryStampCollector.java index 2b43102e32..826ebe09bf 100644 --- a/src/main/java/forestry/mail/inventory/InventoryStampCollector.java +++ b/src/main/java/forestry/mail/inventory/InventoryStampCollector.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.mail.inventory; -import forestry.api.mail.IStamps; +import forestry.api.mail.IStampItem; import forestry.core.inventory.InventoryAdapterTile; import forestry.mail.tiles.TileStampCollector; import net.minecraft.world.item.ItemStack; @@ -26,6 +26,6 @@ public InventoryStampCollector(TileStampCollector tile) { @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { - return stack.getItem() instanceof IStamps; + return stack.getItem() instanceof IStampItem; } } diff --git a/src/main/java/forestry/mail/inventory/InventoryTradeStation.java b/src/main/java/forestry/mail/inventory/InventoryTradeStation.java index e68e46800c..08ae2919f3 100644 --- a/src/main/java/forestry/mail/inventory/InventoryTradeStation.java +++ b/src/main/java/forestry/mail/inventory/InventoryTradeStation.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.mail.inventory; -import forestry.api.mail.IStamps; +import forestry.api.mail.IStampItem; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.SlotUtil; @@ -73,7 +73,7 @@ public boolean canSlotAccept(int slotIndex, ItemStack stack) { return item == Items.PAPER; } else if (SlotUtil.isSlotInRange(slotIndex, TradeStation.SLOT_STAMPS_1, TradeStation.SLOT_STAMPS_COUNT)) { Item item = stack.getItem(); - return item instanceof IStamps; + return item instanceof IStampItem; } return false; diff --git a/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java b/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java index 18a9cf1935..e3e15a46e2 100644 --- a/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java +++ b/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.inventory; import com.google.common.base.Preconditions; @@ -31,7 +21,7 @@ public class ItemInventoryLetter extends ItemInventory implements IErrorSource { private final ILetter letter; public ItemInventoryLetter(Player player, ItemStack itemstack) { - super(player, 0, itemstack); + super(0, itemstack); CompoundTag tagCompound = itemstack.getTag(); Preconditions.checkNotNull(tagCompound); this.letter = new Letter(tagCompound); @@ -55,8 +45,7 @@ public void onLetterOpened() { public ItemStack removeItem(int index, int count) { ItemStack result = this.letter.removeItem(index, count); CompoundTag tagCompound = getParent().getTag(); - Preconditions.checkNotNull(tagCompound); - this.letter.write(tagCompound); + this.letter.write(tagCompound, IDK); return result; } @@ -64,8 +53,7 @@ public ItemStack removeItem(int index, int count) { public void setItem(int index, ItemStack itemstack) { this.letter.setItem(index, itemstack); CompoundTag tagCompound = getParent().getTag(); - Preconditions.checkNotNull(tagCompound); - this.letter.write(tagCompound); + this.letter.write(tagCompound, IDK); } @Override diff --git a/src/main/java/forestry/mail/inventory/package-info.java b/src/main/java/forestry/mail/inventory/package-info.java index 38994f7c2c..927057f387 100644 --- a/src/main/java/forestry/mail/inventory/package-info.java +++ b/src/main/java/forestry/mail/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.inventory; diff --git a/src/main/java/forestry/mail/items/ItemCatalogue.java b/src/main/java/forestry/mail/items/ItemCatalogue.java index dfa2e8843d..20fea7a125 100644 --- a/src/main/java/forestry/mail/items/ItemCatalogue.java +++ b/src/main/java/forestry/mail/items/ItemCatalogue.java @@ -12,10 +12,9 @@ import forestry.core.items.ItemWithGui; import forestry.mail.gui.ContainerCatalogue; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; @@ -26,7 +25,7 @@ public ItemCatalogue() { @Nullable @Override - public AbstractContainerMenu getContainer(int windowId, Player player, ItemStack heldItem) { - return new ContainerCatalogue(windowId, player.getInventory()); + public AbstractContainerMenu createMenu(int containerId, Inventory playerInv, int slotIndex) { + return new ContainerCatalogue(containerId, playerInv.getInventory()); } } diff --git a/src/main/java/forestry/mail/items/ItemLetter.java b/src/main/java/forestry/mail/items/ItemLetter.java index 0ba882943d..2de837ad58 100755 --- a/src/main/java/forestry/mail/items/ItemLetter.java +++ b/src/main/java/forestry/mail/items/ItemLetter.java @@ -14,21 +14,22 @@ import forestry.api.mail.ILetter; import forestry.core.items.ItemWithGui; import forestry.mail.Letter; -import forestry.mail.gui.ContainerLetter; +import forestry.mail.gui.LetterMenu; import forestry.mail.inventory.ItemInventoryLetter; import net.minecraft.ChatFormatting; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import javax.annotation.Nullable; import java.util.List; @@ -76,10 +77,10 @@ public String getDescriptionId() { } @Override - public InteractionResultHolder use(Level worldIn, Player player, InteractionHand handIn) { - ItemStack heldItem = player.getItemInHand(handIn); + public InteractionResultHolder use(Level level, Player player, InteractionHand hand) { + ItemStack heldItem = player.getItemInHand(hand); if (heldItem.getCount() == 1) { - return super.use(worldIn, player, handIn); + return super.use(level, player, hand); } else { player.sendSystemMessage(Component.translatable("for.chat.mail.wrongstacksize")); return InteractionResultHolder.fail(heldItem); @@ -104,7 +105,7 @@ public void appendHoverText(ItemStack itemstack, @Nullable Level world, List type() { return PacketIdServer.LETTER_INFO_REQUEST; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeUtf(this.recipientName); - buffer.writeUtf(PostalCarriers.REGISTRY.get().getKey(this.addressType).toString()); + public static void encode(RegistryFriendlyByteBuf buffer, PacketLetterInfoRequest msg) { + buffer.writeUtf(msg.recipientName); + buffer.writeUtf(ForestryRegistries.POSTAL_CARRIER.getKey(msg.addressType).toString()); } - public static PacketLetterInfoRequest decode(FriendlyByteBuf buffer) { - return new PacketLetterInfoRequest(buffer.readUtf(), PostalCarriers.REGISTRY.get().getValue(ResourceLocation.tryParse(buffer.readUtf()))); + public static PacketLetterInfoRequest decode(RegistryFriendlyByteBuf buffer) { + return new PacketLetterInfoRequest(buffer.readUtf(), ForestryRegistries.POSTAL_CARRIER.get(ResourceLocation.tryParse(buffer.readUtf()))); } } diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponsePlayer.java b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponsePlayer.java index e24cb63752..8a5ec97ecc 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponsePlayer.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponsePlayer.java @@ -5,31 +5,28 @@ import forestry.api.modules.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.mail.MailAddress; -import forestry.mail.carriers.PostalCarriers; +import forestry.mail.features.PostalCarriers; import forestry.mail.gui.ILetterInfoReceiver; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketLetterInfoResponsePlayer(IMailAddress address) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.LETTER_INFO_RESPONSE_PLAYER; } - @Override - public void write(FriendlyByteBuf buffer) { + public void write(RegistryFriendlyByteBuf buffer) { GameProfile profile = this.address.getPlayerProfile(); buffer.writeUUID(profile.getId()); buffer.writeUtf(profile.getName()); } - public static PacketLetterInfoResponsePlayer decode(FriendlyByteBuf buffer) { + public static PacketLetterInfoResponsePlayer decode(RegistryFriendlyByteBuf buffer) { return new PacketLetterInfoResponsePlayer(new MailAddress(new GameProfile(buffer.readUUID(), buffer.readUtf()))); } - public static void handle(PacketLetterInfoResponsePlayer msg, Player player) { - if (player.containerMenu instanceof ILetterInfoReceiver receiver) { + public static void handle(PacketLetterInfoResponsePlayer msg, IPayloadContext ctx) { + if (ctx.player().containerMenu instanceof ILetterInfoReceiver receiver) { receiver.handleLetterInfoUpdate(PostalCarriers.PLAYER.get(), msg.address, null); } } diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponseTrader.java b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponseTrader.java index a5426d30fe..5b02be5d59 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponseTrader.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponseTrader.java @@ -3,53 +3,49 @@ import com.mojang.authlib.GameProfile; import forestry.api.mail.EnumTradeStationState; import forestry.api.mail.IMailAddress; -import forestry.api.mail.ITradeStationInfo; +import forestry.api.mail.TradeStationInfo; import forestry.api.modules.IForestryPacketClient; import forestry.core.network.PacketIdClient; import forestry.core.utils.NetworkUtil; import forestry.mail.MailAddress; -import forestry.mail.carriers.PostalCarriers; -import forestry.mail.carriers.trading.TradeStationInfo; +import forestry.mail.features.PostalCarriers; import forestry.mail.gui.ILetterInfoReceiver; -import net.minecraft.core.NonNullList; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; import javax.annotation.Nullable; +import java.util.List; -public record PacketLetterInfoResponseTrader(@Nullable ITradeStationInfo info) implements IForestryPacketClient { - @Override - public ResourceLocation id() { +public record PacketLetterInfoResponseTrader(@Nullable TradeStationInfo info) implements IForestryPacketClient { + public Type type() { return PacketIdClient.LETTER_INFO_RESPONSE_TRADER; } - @Override - public void write(FriendlyByteBuf buffer) { - if (this.info == null) { + public static void encode(RegistryFriendlyByteBuf buffer, PacketLetterInfoResponseTrader msg) { + if (msg.info == null) { buffer.writeBoolean(false); } else { buffer.writeBoolean(true); - buffer.writeUtf(this.info.address().getName()); + buffer.writeUtf(msg.info.address().getName()); - GameProfile profile = this.info.owner(); + GameProfile profile = msg.info.owner(); buffer.writeUUID(profile.getId()); buffer.writeUtf(profile.getName()); - buffer.writeItem(this.info.tradegood()); - NetworkUtil.writeItemStacks(buffer, this.info.required()); + ItemStack.STREAM_CODEC.encode(buffer, msg.info.tradegood()); + NetworkUtil.writeItemStacks(buffer, msg.info.required()); - buffer.writeEnum(this.info.state()); + buffer.writeEnum(msg.info.state()); } } - public static PacketLetterInfoResponseTrader decode(FriendlyByteBuf buffer) { + public static PacketLetterInfoResponseTrader decode(RegistryFriendlyByteBuf buffer) { if (buffer.readBoolean()) { IMailAddress address = new MailAddress(buffer.readUtf()); GameProfile owner = new GameProfile(buffer.readUUID(), buffer.readUtf()); - ItemStack tradegood = buffer.readItem(); - NonNullList required = NetworkUtil.readItemStacks(buffer); + ItemStack tradegood = ItemStack.STREAM_CODEC.decode(buffer); + List required = NetworkUtil.readItemStacks(buffer); EnumTradeStationState state = buffer.readEnum(EnumTradeStationState.class); return new PacketLetterInfoResponseTrader(new TradeStationInfo(address, owner, tradegood, required, state)); } else { @@ -57,9 +53,9 @@ public static PacketLetterInfoResponseTrader decode(FriendlyByteBuf buffer) { } } - public static void handle(PacketLetterInfoResponseTrader msg, Player player) { - if (player.containerMenu instanceof ILetterInfoReceiver receiver) { - receiver.handleLetterInfoUpdate(PostalCarriers.TRADER.get(), null, msg.info); + public static void handle(PacketLetterInfoResponseTrader msg, IPayloadContext ctx) { + if (ctx.player().containerMenu instanceof ILetterInfoReceiver receiver) { + receiver.handleLetterInfoUpdate(PostalCarriers.TRADER.value(), null, msg.info); } } } diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java b/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java index dbacaf433b..f6348c8fae 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java @@ -12,14 +12,14 @@ import forestry.api.modules.IForestryPacketServer; import forestry.core.network.PacketIdServer; -import forestry.mail.gui.ContainerLetter; +import forestry.mail.gui.LetterMenu; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; public record PacketLetterTextSet(String string) implements IForestryPacketServer { public static void handle(PacketLetterTextSet msg, ServerPlayer player) { - if (player.containerMenu instanceof ContainerLetter letterMenu) { + if (player.containerMenu instanceof LetterMenu letterMenu) { letterMenu.handleSetText(msg.string()); } } diff --git a/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java b/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java index 491750ab6a..645d410b81 100644 --- a/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java +++ b/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.network.packets; import forestry.api.modules.IForestryPacketClient; @@ -16,9 +6,8 @@ import forestry.mail.carriers.players.POBoxInfo; import forestry.mail.gui.ToastMailboxInfo; import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketPOBoxInfoResponse(int playerLetters, int tradeLetters, boolean silent) implements IForestryPacketClient { @@ -26,23 +15,21 @@ public PacketPOBoxInfoResponse(POBoxInfo info, boolean silent) { this(info.playerLetters(), info.tradeLetters(), silent); } - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.POBOX_INFO_RESPONSE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(this.playerLetters); - buffer.writeInt(this.tradeLetters); - buffer.writeBoolean(this.silent); + public static void write(RegistryFriendlyByteBuf buffer, PacketPOBoxInfoResponse msg) { + buffer.writeInt(msg.playerLetters); + buffer.writeInt(msg.tradeLetters); + buffer.writeBoolean(msg.silent); } - public static PacketPOBoxInfoResponse decode(FriendlyByteBuf buffer) { + public static PacketPOBoxInfoResponse decode(RegistryFriendlyByteBuf buffer) { return new PacketPOBoxInfoResponse(buffer.readInt(), buffer.readInt(), buffer.readBoolean()); } - public static void handle(PacketPOBoxInfoResponse msg, Player player) { + public static void handle(PacketPOBoxInfoResponse msg, IPayloadContext ctx) { POBoxInfo poBox = new POBoxInfo(msg.playerLetters, msg.tradeLetters); if (player.equals(Minecraft.getInstance().player) && ForestryConfig.CLIENT.mailAlertsEnabled.get()) { ToastMailboxInfo.addOrUpdate(Minecraft.getInstance().getToasts(), poBox, msg.silent); diff --git a/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java b/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java index 366c4a648b..8767360bdc 100644 --- a/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java +++ b/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.network.packets; import forestry.api.modules.IForestryPacketServer; @@ -15,36 +5,33 @@ import forestry.core.tiles.TileUtil; import forestry.mail.tiles.TileTrader; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.network.NetworkHooks; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketTraderAddressRequest(BlockPos pos, String addressName) implements IForestryPacketServer { public PacketTraderAddressRequest(TileTrader tile, String addressName) { this(tile.getBlockPos(), addressName); } - public static void handle(PacketTraderAddressRequest msg, ServerPlayer player) { - TileUtil.actOnTile(player.level(), msg.pos(), TileTrader.class, tile -> { + public static void handle(PacketTraderAddressRequest msg, IPayloadContext context) { + TileUtil.actOnTile(context.player().level(), msg.pos(), TileTrader.class, tile -> { if (tile.handleSetAddressRequest(msg.addressName())) { - NetworkHooks.openScreen(player, tile, msg.pos()); + context.player().openMenu(tile, msg.pos()); } }); } @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.TRADING_ADDRESS_REQUEST; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeUtf(this.addressName); + public static void encode(RegistryFriendlyByteBuf buffer, PacketTraderAddressRequest msg) { + buffer.writeBlockPos(msg.pos); + buffer.writeUtf(msg.addressName); } - public static PacketTraderAddressRequest decode(FriendlyByteBuf buffer) { + public static PacketTraderAddressRequest decode(RegistryFriendlyByteBuf buffer) { return new PacketTraderAddressRequest(buffer.readBlockPos(), buffer.readUtf()); } } diff --git a/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java b/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java index 85c6b80c3b..d02c9ec930 100644 --- a/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java +++ b/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.network.packets; import forestry.api.mail.IMailAddress; @@ -17,27 +7,24 @@ import forestry.mail.MailAddress; import forestry.mail.tiles.TileTrader; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketTraderAddressResponse(BlockPos pos, IMailAddress address) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.TRADING_ADDRESS_RESPONSE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeUtf(this.address.getName()); + public static void encode(RegistryFriendlyByteBuf buffer, PacketTraderAddressResponse msg) { + buffer.writeBlockPos(msg.pos); + buffer.writeUtf(msg.address.getName()); } - public static PacketTraderAddressResponse decode(FriendlyByteBuf buffer) { + public static PacketTraderAddressResponse decode(RegistryFriendlyByteBuf buffer) { return new PacketTraderAddressResponse(buffer.readBlockPos(), new MailAddress(buffer.readUtf())); } - public static void handle(PacketTraderAddressResponse msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, TileTrader.class, tile -> tile.setAddress(msg.address)); + public static void handle(PacketTraderAddressResponse msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, TileTrader.class, tile -> tile.setAddress(msg.address)); } } diff --git a/src/main/java/forestry/mail/network/packets/package-info.java b/src/main/java/forestry/mail/network/packets/package-info.java index f77f5241a9..14c6a78ceb 100644 --- a/src/main/java/forestry/mail/network/packets/package-info.java +++ b/src/main/java/forestry/mail/network/packets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.network.packets; diff --git a/src/main/java/forestry/mail/package-info.java b/src/main/java/forestry/mail/package-info.java index 7d33b82bf4..16fc0ec117 100644 --- a/src/main/java/forestry/mail/package-info.java +++ b/src/main/java/forestry/mail/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail; diff --git a/src/main/java/forestry/mail/tiles/TileMailbox.java b/src/main/java/forestry/mail/tiles/TileMailbox.java index d4f4add4ec..65d27fe89f 100644 --- a/src/main/java/forestry/mail/tiles/TileMailbox.java +++ b/src/main/java/forestry/mail/tiles/TileMailbox.java @@ -22,13 +22,11 @@ import forestry.mail.carriers.players.POBox; import forestry.mail.carriers.players.POBoxRegistry; import forestry.mail.features.MailTiles; -import forestry.mail.gui.ContainerMailbox; +import forestry.mail.gui.MailboxMenu; import forestry.mail.postalstates.EnumDeliveryState; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.Container; -import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; @@ -45,9 +43,9 @@ public TileMailbox(BlockPos pos, BlockState state) { /* GUI */ @Override - public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { + public boolean interactNoItem(Level level, Player player, BlockPos pos) { if (this.level.isClientSide) { - return; + return false; } ItemStack heldItem = player.getItemInHand(player.getUsedItemHand()); @@ -60,8 +58,9 @@ public void openGui(ServerPlayer player, InteractionHand hand, BlockPos pos) { heldItem.shrink(1); } } else { - super.openGui(player, hand, pos); + super.interactNoItem(level, player, pos); } + return false; } /* MAIL HANDLING */ @@ -91,6 +90,6 @@ private IPostalState tryDispatchLetter(ItemStack letterStack) { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerMailbox(windowId, inv, this); + return new MailboxMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/mail/tiles/TileStampCollector.java b/src/main/java/forestry/mail/tiles/TileStampCollector.java index 7375b7d5ee..5bde8ef24d 100644 --- a/src/main/java/forestry/mail/tiles/TileStampCollector.java +++ b/src/main/java/forestry/mail/tiles/TileStampCollector.java @@ -10,13 +10,13 @@ ******************************************************************************/ package forestry.mail.tiles; -import forestry.api.mail.IStamps; +import forestry.api.mail.IStampItem; import forestry.core.inventory.IInventoryAdapter; import forestry.core.tiles.TileBase; import forestry.core.utils.InventoryUtil; import forestry.mail.PostOffice; import forestry.mail.features.MailTiles; -import forestry.mail.gui.ContainerStampCollector; +import forestry.mail.gui.StampCollectorMenu; import forestry.mail.inventory.InventoryStampCollector; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; @@ -47,8 +47,8 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { stamp = PostOffice.getOrCreate((ServerLevel) level).getAnyStamp(1); } else { ItemStack filter = inventory.getItem(InventoryStampCollector.SLOT_FILTER); - if (filter.getItem() instanceof IStamps) { - stamp = PostOffice.getOrCreate((ServerLevel) level).getAnyStamp(((IStamps) filter.getItem()).getPostage(filter), 1); + if (filter.getItem() instanceof IStampItem) { + stamp = PostOffice.getOrCreate((ServerLevel) level).getAnyStamp(((IStampItem) filter.getItem()).getPostage(filter), 1); } } @@ -62,6 +62,6 @@ public void serverTick(Level level, BlockPos pos, BlockState state) { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerStampCollector(windowId, inv, this); + return new StampCollectorMenu(windowId, inv, this); } } diff --git a/src/main/java/forestry/mail/tiles/TileTrader.java b/src/main/java/forestry/mail/tiles/TileTrader.java index 586367073d..4eaef9eaeb 100644 --- a/src/main/java/forestry/mail/tiles/TileTrader.java +++ b/src/main/java/forestry/mail/tiles/TileTrader.java @@ -1,20 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.mail.tiles; import com.google.common.base.Preconditions; import forestry.api.core.ForestryError; import forestry.api.core.IErrorLogic; import forestry.api.mail.IMailAddress; -import forestry.api.mail.IStamps; +import forestry.api.mail.IStampItem; import forestry.core.inventory.IInventoryAdapter; import forestry.core.owner.IOwnedTile; import forestry.core.owner.IOwnerHandler; @@ -26,13 +16,14 @@ import forestry.mail.carriers.trading.TradeStation; import forestry.mail.carriers.trading.TradeStationRegistry; import forestry.mail.features.MailTiles; -import forestry.mail.gui.ContainerTradeName; -import forestry.mail.gui.ContainerTrader; +import forestry.mail.gui.TradeNameMenu; +import forestry.mail.gui.TraderMenu; import forestry.mail.inventory.InventoryTradeStation; import forestry.mail.network.packets.PacketTraderAddressResponse; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Inventory; @@ -42,8 +33,8 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class TileTrader extends TileBase implements IOwnedTile { private final OwnerHandler ownerHandler = new OwnerHandler(); @@ -69,42 +60,42 @@ public void onDropContents(ServerLevel level) { /* SAVING & LOADING */ @Override - public void saveAdditional(CompoundTag compoundNBT) { - super.saveAdditional(compoundNBT); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - CompoundTag nbt = new CompoundTag(); - this.address.write(nbt); - compoundNBT.put("address", nbt); + CompoundTag address = new CompoundTag(); + this.address.write(address, registries); + nbt.put("address", nbt); - this.ownerHandler.write(compoundNBT); + this.ownerHandler.write(nbt, registries); } @Override - public void load(CompoundTag compoundNBT) { - super.load(compoundNBT); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - if (compoundNBT.contains("address")) { - this.address = new MailAddress(compoundNBT.getCompound("address")); + if (nbt.contains("address")) { + this.address = new MailAddress(nbt.getCompound("address")); } - this.ownerHandler.read(compoundNBT); + this.ownerHandler.read(nbt, registries); } /* NETWORK */ @Override - public void writeData(FriendlyByteBuf data) { - super.writeData(data); - this.ownerHandler.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + super.writeData(buffer); + this.ownerHandler.writeData(buffer); String addressName = this.address.getName(); - data.writeUtf(addressName); + buffer.writeUtf(addressName); } @Override @OnlyIn(Dist.CLIENT) - public void readData(FriendlyByteBuf data) { - super.readData(data); - this.ownerHandler.readData(data); - String addressName = data.readUtf(); + public void readData(RegistryFriendlyByteBuf buffer) { + super.readData(buffer); + this.ownerHandler.readData(buffer); + String addressName = buffer.readUtf(); if (!addressName.isEmpty()) { this.address = new MailAddress(addressName); } @@ -230,8 +221,8 @@ public boolean hasPostageMin(int postage) { for (int i = TradeStation.SLOT_STAMPS_1; i < TradeStation.SLOT_STAMPS_1 + TradeStation.SLOT_STAMPS_COUNT; i++) { ItemStack stamp = tradeInventory.getItem(i); if (!stamp.isEmpty()) { - if (stamp.getItem() instanceof IStamps) { - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); + if (stamp.getItem() instanceof IStampItem) { + posted += ((IStampItem) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); if (posted >= postage) { return true; } @@ -253,7 +244,7 @@ public boolean handleSetAddressRequest(String addressName) { if (updated) { PacketTraderAddressResponse packetResponse = new PacketTraderAddressResponse(this.worldPosition, address); - NetworkUtil.sendNetworkPacket(packetResponse, this.worldPosition, this.level); + NetworkUtil.sendToPlayersTrackingPos(packetResponse, this.worldPosition, (ServerLevel) this.level); } return updated; @@ -303,9 +294,9 @@ public IInventoryAdapter getInternalInventory() { @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { if (isLinked()) { - return new ContainerTrader(windowId, inv, this); + return new TraderMenu(windowId, inv, this); } else { - return new ContainerTradeName(windowId, inv.player, this); + return new TradeNameMenu(windowId, inv.player, this); } } } diff --git a/src/main/java/forestry/mail/tiles/package-info.java b/src/main/java/forestry/mail/tiles/package-info.java index 097a569724..dbdd2a55c4 100644 --- a/src/main/java/forestry/mail/tiles/package-info.java +++ b/src/main/java/forestry/mail/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.mail.tiles; diff --git a/src/main/java/forestry/modules/ForestryModuleManager.java b/src/main/java/forestry/modules/ForestryModuleManager.java index 36e2960463..29e9fc750b 100644 --- a/src/main/java/forestry/modules/ForestryModuleManager.java +++ b/src/main/java/forestry/modules/ForestryModuleManager.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.modules; import forestry.Forestry; @@ -16,10 +6,12 @@ import forestry.api.modules.IModuleManager; import forestry.core.utils.ModUtil; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.loading.FMLEnvironment; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.ModList; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; import org.objectweb.asm.Type; import java.util.*; @@ -109,10 +101,13 @@ public void init() { loadModules(); for (Map.Entry entry : this.loadedModules.entrySet()) { - IEventBus modBus = ModuleUtil.getModBus(entry.getKey().getNamespace()); + String modid = entry.getKey().getNamespace(); + IEventBus modBus = ModuleUtil.getModBus(modid); + ModContainer mod = ModList.get().getModContainerById(modid).orElseThrow(); IForestryModule module = entry.getValue(); module.registerEvents(modBus); + modBus.addListener((RegisterPayloadHandlersEvent event) -> module.registerPackets(event.registrar(mod.getModInfo().getVersion().toString()))); if (FMLEnvironment.dist == Dist.CLIENT) { module.registerClientHandler(handler -> handler.registerEvents(modBus)); @@ -145,7 +140,7 @@ private static LinkedHashMap> discoverModules() { List modModules = modules.computeIfAbsent(modId, k -> new ArrayList<>()); // Core modules load first if (module.isCore()) { - modModules.add(0, module); + modModules.addFirst(module); } else { modModules.add(module); } @@ -153,16 +148,4 @@ private static LinkedHashMap> discoverModules() { return modules; } - - public void setupApi() { - for (IForestryModule module : getLoadedModules()) { - try { - module.setupApi(); - } catch (Throwable t) { - // this exception normally gets swallowed, so log it and rethrow - Forestry.LOGGER.fatal("Module {} threw an error in its IForestryModule.setupApi method", module.getId(), t); - throw new RuntimeException(t); - } - } - } } diff --git a/src/main/java/forestry/modules/ModuleUtil.java b/src/main/java/forestry/modules/ModuleUtil.java index f3b7c00896..2f7583a94e 100644 --- a/src/main/java/forestry/modules/ModuleUtil.java +++ b/src/main/java/forestry/modules/ModuleUtil.java @@ -2,10 +2,10 @@ import forestry.Forestry; import forestry.modules.features.FeatureProvider; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.forgespi.language.ModFileScanData; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.ModList; +import net.neoforged.neoforgespi.language.ModFileScanData; import org.objectweb.asm.Type; import java.lang.reflect.Field; diff --git a/src/main/java/forestry/modules/features/FeatureBlock.java b/src/main/java/forestry/modules/features/FeatureBlock.java index 0758a1b2c3..9694837da0 100644 --- a/src/main/java/forestry/modules/features/FeatureBlock.java +++ b/src/main/java/forestry/modules/features/FeatureBlock.java @@ -1,15 +1,18 @@ package forestry.modules.features; import forestry.api.ForestryConstants; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredBlock; +import net.neoforged.neoforge.registries.DeferredItem; import javax.annotation.Nullable; import java.util.Objects; @@ -17,18 +20,22 @@ import java.util.function.Supplier; public class FeatureBlock extends ModFeature implements IBlockFeature { - private final RegistryObject blockObject; + private final DeferredBlock blockObject; @Nullable - private final RegistryObject itemObject; + private final DeferredItem itemObject; public FeatureBlock(IFeatureRegistry features, ResourceLocation moduleId, String identifier, Supplier constructorBlock, @Nullable Function constructorItem) { super(moduleId, identifier); - this.blockObject = features.getRegistry(Registries.BLOCK).register(identifier, constructorBlock); - this.itemObject = constructorItem == null ? null : features.getRegistry(Registries.ITEM).register(identifier, () -> constructorItem.apply(this.blockObject.get())); + this.blockObject = features.getBlockRegistry().register(identifier, constructorBlock); + this.itemObject = constructorItem == null ? null : features.getItemRegistry().register(identifier, () -> constructorItem.apply(this.blockObject.get())); } public String getTranslationKey() { - return this.blockObject.map(Block::getDescriptionId).orElseGet(() -> "block." + ForestryConstants.MOD_ID + "." + this.name.replace('/', '.')); + if (this.blockObject.isBound()) { + return this.blockObject.get().getDescriptionId(); + } else { + return "block." + ForestryConstants.MOD_ID + "." + this.name.replace('/', '.'); + } } @Override @@ -55,4 +62,9 @@ public I item() { public ResourceKey> getRegistry() { return Registries.BLOCK; } + + @Override + public Holder holder() { + return this.itemObject; + } } diff --git a/src/main/java/forestry/modules/features/FeatureBlockGroup.java b/src/main/java/forestry/modules/features/FeatureBlockGroup.java index c57404a2e5..ef4b7afba1 100644 --- a/src/main/java/forestry/modules/features/FeatureBlockGroup.java +++ b/src/main/java/forestry/modules/features/FeatureBlockGroup.java @@ -1,17 +1,15 @@ package forestry.modules.features; +import forestry.api.core.IBlockSubtype; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.level.block.Block; + import javax.annotation.Nullable; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.level.block.Block; - -import forestry.api.core.IBlockSubtype; - public class FeatureBlockGroup extends FeatureGroup, FeatureBlock, S> { private FeatureBlockGroup(Builder builder) { super(builder); @@ -22,13 +20,7 @@ protected FeatureBlock createFeature(Builder builder, S type return builder.registry.block(() -> builder.constructor.apply(type), builder.itemConstructor != null ? (block) -> builder.itemConstructor.apply(block, type) : null, builder.getIdentifier(type)); } - // todo remove in 1.21 - public Collection getBlocks() { - return getList(); - } - - // todo use immutable collection? - public List getList() { + public List getBlocks() { ArrayList blocks = new ArrayList<>(this.featureByType.size()); for (FeatureBlock value : this.featureByType.values()) { blocks.add(value.block()); @@ -36,7 +28,7 @@ public List getList() { return blocks; } - public Collection getItems() { + public List getItems() { ArrayList items = new ArrayList<>(this.featureByType.size()); for (FeatureBlock value : this.featureByType.values()) { items.add(value.item()); diff --git a/src/main/java/forestry/modules/features/FeatureBlockTable.java b/src/main/java/forestry/modules/features/FeatureBlockTable.java index 0cd84d9e2b..bd157b72bd 100644 --- a/src/main/java/forestry/modules/features/FeatureBlockTable.java +++ b/src/main/java/forestry/modules/features/FeatureBlockTable.java @@ -1,7 +1,7 @@ package forestry.modules.features; +import com.mojang.datafixers.util.Function3; import forestry.api.core.IBlockSubtype; -import forestry.core.utils.datastructures.TriFunction; import net.minecraft.world.item.BlockItem; import net.minecraft.world.level.block.Block; @@ -50,7 +50,7 @@ public static class Builder constructor; @Nullable - private TriFunction itemConstructor; + private Function3 itemConstructor; public Builder(IFeatureRegistry registry, BiFunction constructor) { super(registry); @@ -58,7 +58,7 @@ public Builder(IFeatureRegistry registry, BiFunction constructor) { this.constructor = constructor; } - public Builder itemWithType(TriFunction itemConstructor) { + public Builder itemWithType(Function3 itemConstructor) { this.itemConstructor = itemConstructor; return this; } diff --git a/src/main/java/forestry/modules/features/FeatureCreativeTab.java b/src/main/java/forestry/modules/features/FeatureCreativeTab.java index d95fce8bc2..a16e72abfd 100644 --- a/src/main/java/forestry/modules/features/FeatureCreativeTab.java +++ b/src/main/java/forestry/modules/features/FeatureCreativeTab.java @@ -6,13 +6,13 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; import java.util.Objects; import java.util.function.Consumer; public class FeatureCreativeTab extends ModFeature { - private final RegistryObject creativeTabObject; + private final DeferredHolder creativeTabObject; public FeatureCreativeTab(IFeatureRegistry registry, ResourceLocation moduleId, String name, Consumer builder) { super(moduleId, name); diff --git a/src/main/java/forestry/modules/features/FeatureEntityType.java b/src/main/java/forestry/modules/features/FeatureEntityType.java index 963ffa7839..0083c10082 100644 --- a/src/main/java/forestry/modules/features/FeatureEntityType.java +++ b/src/main/java/forestry/modules/features/FeatureEntityType.java @@ -8,7 +8,7 @@ import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; import java.util.function.Supplier; import java.util.function.UnaryOperator; @@ -17,7 +17,7 @@ public class FeatureEntityType extends ModFeature implements I protected final Supplier attributes; protected final EntityType.EntityFactory factory; protected final MobCategory classification; - private final RegistryObject> entityTypeObject; + private final DeferredHolder, EntityType> entityTypeObject; public FeatureEntityType(IFeatureRegistry registry, ResourceLocation moduleId, String name, UnaryOperator> consumer, EntityType.EntityFactory factory, MobCategory classification, Supplier attributes) { super(moduleId, name); diff --git a/src/main/java/forestry/modules/features/FeatureFluid.java b/src/main/java/forestry/modules/features/FeatureFluid.java index adc9290e47..2fbc90e0f7 100644 --- a/src/main/java/forestry/modules/features/FeatureFluid.java +++ b/src/main/java/forestry/modules/features/FeatureFluid.java @@ -12,12 +12,12 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.ForgeFlowingFluid; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.BaseFlowingFluid; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; import javax.annotation.Nullable; import java.util.function.Consumer; @@ -26,23 +26,23 @@ public class FeatureFluid extends ModFeature implements IFluidFeature { private final IBlockFeature block; private final FluidProperties properties; - private final ForgeFlowingFluid.Properties internal; + private final BaseFlowingFluid.Properties internal; - private final RegistryObject fluidObject; - private final RegistryObject flowingFluidObject; + private final DeferredHolder fluidObject; + private final DeferredHolder flowingFluidObject; public FeatureFluid(Builder builder) { super(builder.moduleId, builder.identifier); this.block = builder.registry.block(() -> new BlockForestryFluid(this), "fluid_" + builder.identifier); this.properties = new FluidProperties(builder); - RegistryObject attributes = builder.registry.getRegistry(ForgeRegistries.Keys.FLUID_TYPES).register(this.name, () -> new ForestryFluidType(this.properties, FluidType.Properties.create() + DeferredHolder attributes = builder.registry.getRegistry(NeoForgeRegistries.Keys.FLUID_TYPES).register(this.name, () -> new ForestryFluidType(this.properties, FluidType.Properties.create() .density(this.properties.density) .viscosity(this.properties.viscosity) .temperature(this.properties.temperature))); DeferredRegister fluidRegistry = builder.registry.getRegistry(Registries.FLUID); - this.internal = new ForgeFlowingFluid.Properties(attributes, this::fluid, this::flowing).block(this.block::block).bucket(properties().bucket); - this.fluidObject = fluidRegistry.register(this.name, () -> new ForgeFlowingFluid.Source(this.internal)); - this.flowingFluidObject = fluidRegistry.register(this.name + "_flowing", () -> new ForgeFlowingFluid.Flowing(this.internal)); + this.internal = new BaseFlowingFluid.Properties(attributes, this::fluid, this::flowing).block(this.block::block).bucket(properties().bucket); + this.fluidObject = fluidRegistry.register(this.name, () -> new BaseFlowingFluid.Source(this.internal)); + this.flowingFluidObject = fluidRegistry.register(this.name + "_flowing", () -> new BaseFlowingFluid.Flowing(this.internal)); } @Override diff --git a/src/main/java/forestry/modules/features/FeatureGroup.java b/src/main/java/forestry/modules/features/FeatureGroup.java index 754fb5a8eb..f4644ec9da 100644 --- a/src/main/java/forestry/modules/features/FeatureGroup.java +++ b/src/main/java/forestry/modules/features/FeatureGroup.java @@ -5,7 +5,6 @@ import forestry.api.core.IItemProvider; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Collection; @@ -19,7 +18,7 @@ public abstract class FeatureGroup mapBuilder = new ImmutableMap.Builder<>(); builder.subTypes.forEach(subType -> mapBuilder.put(subType, createFeature(builder, subType))); - this.featureByType = mapBuilder.build(); + this.featureByType = mapBuilder.build(); } protected abstract F createFeature(B builder, S type); @@ -76,7 +75,7 @@ public static abstract class Builder { protected final IFeatureRegistry registry; protected final Set subTypes = new LinkedHashSet<>(); protected IdentifierType identifierType = IdentifierType.TYPE_ONLY; - protected String identifier = StringUtils.EMPTY; + protected String identifier = ""; public Builder(IFeatureRegistry registry) { this.registry = registry; @@ -93,7 +92,7 @@ public Builder identifier(String identifier, IdentifierType type) { } public Builder type(S type) { - this.subTypes.add(type); + this.subTypes.add(type); return this; } @@ -102,12 +101,12 @@ public Builder types(S[] types) { } public Builder types(Collection types) { - this.subTypes.addAll(types); + this.subTypes.addAll(types); return this; } protected String getIdentifier(IFeatureSubtype type) { - return this.identifierType.apply(this.identifier, type.getSerializedName()); + return this.identifierType.apply(this.identifier, type.identifier()); } public abstract G create(); diff --git a/src/main/java/forestry/modules/features/FeatureItem.java b/src/main/java/forestry/modules/features/FeatureItem.java index db9f2d0bff..61b808061a 100644 --- a/src/main/java/forestry/modules/features/FeatureItem.java +++ b/src/main/java/forestry/modules/features/FeatureItem.java @@ -1,16 +1,18 @@ package forestry.modules.features; +import java.util.function.Supplier; + +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; -import net.minecraftforge.registries.RegistryObject; -import java.util.function.Supplier; +import net.neoforged.neoforge.registries.DeferredHolder; public class FeatureItem extends ModFeature implements IItemFeature { - private final RegistryObject itemObject; + private final DeferredHolder itemObject; public FeatureItem(IFeatureRegistry registry, ResourceLocation moduleId, String identifier, Supplier constructor) { super(moduleId, identifier); @@ -26,4 +28,9 @@ public ResourceKey> getRegistry() { public I item() { return this.itemObject.get(); } + + @Override + public Holder holder() { + return this.itemObject; + } } diff --git a/src/main/java/forestry/modules/features/FeatureItemTable.java b/src/main/java/forestry/modules/features/FeatureItemTable.java index f5ecab27dd..2572de30cc 100644 --- a/src/main/java/forestry/modules/features/FeatureItemTable.java +++ b/src/main/java/forestry/modules/features/FeatureItemTable.java @@ -4,6 +4,7 @@ import net.minecraft.world.item.Item; import java.util.Collection; +import java.util.List; import java.util.function.BiFunction; import java.util.stream.Collectors; @@ -17,7 +18,7 @@ protected FeatureItem createFeature(Builder builder, R rowType, C co return builder.registry.item(() -> builder.constructor.apply(rowType, columnType), builder.getIdentifier(rowType, columnType)); } - public Collection getBlocks() { + public List getBlocks() { return this.featureByTypes.values().stream().map(IItemFeature::item).collect(Collectors.toList()); } diff --git a/src/main/java/forestry/modules/features/FeatureMenuType.java b/src/main/java/forestry/modules/features/FeatureMenuType.java index e97b07f8c0..e0c3aadc6f 100644 --- a/src/main/java/forestry/modules/features/FeatureMenuType.java +++ b/src/main/java/forestry/modules/features/FeatureMenuType.java @@ -7,11 +7,11 @@ import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; -import net.minecraftforge.network.IContainerFactory; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.network.IContainerFactory; +import net.neoforged.neoforge.registries.DeferredHolder; public class FeatureMenuType extends ModFeature implements IMenuTypeFeature { - private final RegistryObject> menuTypeObject; + private final DeferredHolder, MenuType> menuTypeObject; public FeatureMenuType(IFeatureRegistry registry, ResourceLocation moduleId, String identifier, IContainerFactory containerFactory) { super(moduleId, identifier); diff --git a/src/main/java/forestry/modules/features/FeatureProvider.java b/src/main/java/forestry/modules/features/FeatureProvider.java index eeaae2062e..55279e77b9 100644 --- a/src/main/java/forestry/modules/features/FeatureProvider.java +++ b/src/main/java/forestry/modules/features/FeatureProvider.java @@ -1,7 +1,7 @@ package forestry.modules.features; import forestry.modules.ModuleUtil; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/forestry/modules/features/FeatureRecipeType.java b/src/main/java/forestry/modules/features/FeatureRecipeType.java index e4d85e41b3..4b12cdb629 100644 --- a/src/main/java/forestry/modules/features/FeatureRecipeType.java +++ b/src/main/java/forestry/modules/features/FeatureRecipeType.java @@ -7,18 +7,18 @@ import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; import java.util.function.Supplier; public class FeatureRecipeType> extends ModFeature implements IModFeature { - private final RegistryObject> type; - private final RegistryObject> serializer; + private final DeferredHolder, RecipeType> type; + private final DeferredHolder, RecipeSerializer> serializer; protected FeatureRecipeType(IFeatureRegistry registry, ResourceLocation moduleId, String name, Supplier> serializer) { super(moduleId, name); - this.type = registry.getRegistry(Registries.RECIPE_TYPE).register(name, () -> RecipeType.simple(new ResourceLocation(moduleId.getNamespace(), name))); + this.type = registry.getRegistry(Registries.RECIPE_TYPE).register(name, () -> RecipeType.simple(moduleId.withPath(name))); this.serializer = registry.getRegistry(Registries.RECIPE_SERIALIZER).register(name, serializer); } diff --git a/src/main/java/forestry/modules/features/FeatureTable.java b/src/main/java/forestry/modules/features/FeatureTable.java index 65dac63427..983199b002 100644 --- a/src/main/java/forestry/modules/features/FeatureTable.java +++ b/src/main/java/forestry/modules/features/FeatureTable.java @@ -6,7 +6,6 @@ import forestry.modules.features.FeatureGroup.IdentifierType; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Collection; @@ -23,7 +22,7 @@ public FeatureTable(B builder) { mapBuilder.put(row, column, createFeature(builder, row, column)); } } - this.featureByTypes = mapBuilder.build(); + this.featureByTypes = mapBuilder.build(); } protected abstract F createFeature(B builder, R rowType, C columnType); @@ -89,7 +88,7 @@ public static abstract class Builder rowTypes = new LinkedHashSet<>(); protected final Set columnTypes = new LinkedHashSet<>(); protected IdentifierType identifierType = IdentifierType.TYPE_ONLY; - protected String identifier = StringUtils.EMPTY; + protected String identifier = ""; public Builder(IFeatureRegistry registry) { this.registry = registry; @@ -106,7 +105,7 @@ public Builder identifier(String identifier, IdentifierType type) { } public Builder rowType(R type) { - this.rowTypes.add(type); + this.rowTypes.add(type); return this; } @@ -115,12 +114,12 @@ public Builder rowTypes(R[] types) { } public Builder rowTypes(Collection types) { - this.rowTypes.addAll(types); + this.rowTypes.addAll(types); return this; } public Builder columnType(C type) { - this.columnTypes.add(type); + this.columnTypes.add(type); return this; } @@ -129,12 +128,12 @@ public Builder columnTypes(C[] types) { } public Builder columnTypes(Collection types) { - this.columnTypes.addAll(types); + this.columnTypes.addAll(types); return this; } protected String getIdentifier(IFeatureSubtype rowType, IFeatureSubtype columnType) { - return this.identifierType.apply(this.identifier, rowType.getSerializedName() + "_" + columnType.getSerializedName()); + return this.identifierType.apply(this.identifier, rowType.identifier() + "_" + columnType.identifier()); } public abstract G create(); diff --git a/src/main/java/forestry/modules/features/FeatureTileType.java b/src/main/java/forestry/modules/features/FeatureTileType.java index 753594de69..8b4acf6bb0 100644 --- a/src/main/java/forestry/modules/features/FeatureTileType.java +++ b/src/main/java/forestry/modules/features/FeatureTileType.java @@ -7,13 +7,13 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; import java.util.Collection; import java.util.function.Supplier; public class FeatureTileType extends ModFeature implements ITileTypeFeature { - private final RegistryObject> blockEntityObject; + private final DeferredHolder, BlockEntityType> blockEntityObject; public FeatureTileType(IFeatureRegistry registry, ResourceLocation moduleId, String name, BlockEntityType.BlockEntitySupplier constructorTileEntity, Supplier> validBlocks) { super(moduleId, name); diff --git a/src/main/java/forestry/modules/features/FluidProperties.java b/src/main/java/forestry/modules/features/FluidProperties.java index 6e2796bef0..df120912cd 100644 --- a/src/main/java/forestry/modules/features/FluidProperties.java +++ b/src/main/java/forestry/modules/features/FluidProperties.java @@ -4,9 +4,9 @@ import forestry.core.items.definitions.DrinkProperties; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.data.loading.DatagenModLoader; -import net.minecraftforge.fml.loading.FMLEnvironment; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.data.loading.DatagenModLoader; import javax.annotation.Nullable; import java.util.function.Supplier; diff --git a/src/main/java/forestry/modules/features/IBlockFeature.java b/src/main/java/forestry/modules/features/IBlockFeature.java index f6125dfd29..e8c1aef6be 100644 --- a/src/main/java/forestry/modules/features/IBlockFeature.java +++ b/src/main/java/forestry/modules/features/IBlockFeature.java @@ -1,7 +1,9 @@ package forestry.modules.features; import forestry.api.core.IBlockProvider; +import net.minecraft.core.Holder; import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; @@ -23,4 +25,7 @@ default T cast() { BlockState defaultState(); > BlockState setValue(Property property, V value); + + @Override + Holder holder(); } diff --git a/src/main/java/forestry/modules/features/IFeatureRegistry.java b/src/main/java/forestry/modules/features/IFeatureRegistry.java index 59e9bf833e..403f7b2c3b 100644 --- a/src/main/java/forestry/modules/features/IFeatureRegistry.java +++ b/src/main/java/forestry/modules/features/IFeatureRegistry.java @@ -2,8 +2,6 @@ import forestry.api.core.IBlockSubtype; import forestry.api.core.IItemSubtype; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; @@ -20,9 +18,8 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraftforge.network.IContainerFactory; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegisterEvent; +import net.neoforged.neoforge.network.IContainerFactory; +import net.neoforged.neoforge.registries.DeferredRegister; import javax.annotation.Nullable; import java.util.Collection; @@ -37,6 +34,10 @@ public interface IFeatureRegistry { */ DeferredRegister getRegistry(ResourceKey> registry); + DeferredRegister.Blocks getBlockRegistry(); + + DeferredRegister.Items getItemRegistry(); + /** * @return The internal deferred registry for the given key, {@code null} if one has not been created. */ @@ -51,7 +52,6 @@ public interface IFeatureRegistry { FeatureBlockGroup.Builder blockGroup(Function constructor, Collection types); - // Note: use the Collection variant whenever possible FeatureBlockGroup.Builder blockGroup(Function constructor, S[] types); FeatureItem item(Supplier constructor, String identifier); @@ -60,13 +60,8 @@ default FeatureItem item(String identifier) { return item(() -> new Item(new Item.Properties()), identifier); } - FeatureItem backpack(IBackpackDefinition definition, EnumBackpackType type, String identifier); - - FeatureItem naturalistBackpack(IBackpackDefinition definition, ResourceLocation speciesTypeId, CreativeModeTab tab, String identifier); - FeatureItemGroup itemGroup(Function constructor, String identifier, S[] subTypes); - // Note: use the Collection variant whenever possible FeatureItemGroup.Builder itemGroup(Function constructor, S[] subTypes); FeatureItemTable itemTable(BiFunction constructor, R[] rowTypes, C[] columnTypes, String identifier); @@ -91,12 +86,6 @@ default FeatureItem item(String identifier) { FeatureCreativeTab creativeTab(String id, Consumer builder); - /** - * @deprecated Use {@link #addRegistryListener(ResourceKey, Runnable)} which is more stable - */ - @Deprecated(forRemoval = true) - void addRegistryListener(ResourceKey> type, Consumer listener); - /** * Invokes the runnable after all entries have completed registration for the given registry. * diff --git a/src/main/java/forestry/modules/features/IFluidFeature.java b/src/main/java/forestry/modules/features/IFluidFeature.java index 115f07c471..3352222e86 100644 --- a/src/main/java/forestry/modules/features/IFluidFeature.java +++ b/src/main/java/forestry/modules/features/IFluidFeature.java @@ -3,8 +3,8 @@ import forestry.core.fluids.BlockForestryFluid; import net.minecraft.world.item.BlockItem; import net.minecraft.world.level.material.FlowingFluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; public interface IFluidFeature extends IModFeature { IBlockFeature fluidBlock(); diff --git a/src/main/java/forestry/modules/features/IItemFeature.java b/src/main/java/forestry/modules/features/IItemFeature.java index a1c25f144b..231ef23e08 100644 --- a/src/main/java/forestry/modules/features/IItemFeature.java +++ b/src/main/java/forestry/modules/features/IItemFeature.java @@ -1,9 +1,11 @@ package forestry.modules.features; -import forestry.api.core.IItemProvider; +import java.util.function.Supplier; + +import net.minecraft.core.Holder; import net.minecraft.world.item.Item; -import java.util.function.Supplier; +import forestry.api.core.IItemProvider; public interface IItemFeature extends IModFeature, IItemProvider, net.minecraft.world.level.ItemLike, Supplier { @Override @@ -15,4 +17,6 @@ default Item asItem() { default I get() { return item(); } + + Holder holder(); } diff --git a/src/main/java/forestry/modules/features/ModFeatureRegistry.java b/src/main/java/forestry/modules/features/ModFeatureRegistry.java index fcec24ffb5..c94f9c54e3 100644 --- a/src/main/java/forestry/modules/features/ModFeatureRegistry.java +++ b/src/main/java/forestry/modules/features/ModFeatureRegistry.java @@ -1,15 +1,12 @@ package forestry.modules.features; import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.LinkedListMultimap; import forestry.api.core.IBlockSubtype; import forestry.api.core.IItemSubtype; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; import forestry.core.utils.ModUtil; import forestry.modules.ModuleUtil; -import forestry.storage.ModuleStorage; import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; @@ -26,11 +23,9 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.network.IContainerFactory; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegisterEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.network.IContainerFactory; +import net.neoforged.neoforge.registries.DeferredRegister; import javax.annotation.Nullable; import java.util.*; @@ -45,20 +40,12 @@ public class ModFeatureRegistry { private ModFeatureRegistry(String modId) { this.modBus = ModuleUtil.getModBus(modId); - - this.modBus.addListener(EventPriority.LOWEST, this::postRegistry); } public void register(IModFeature feature) { getRegistry(feature.getModuleId()).register(feature); } - public void postRegistry(RegisterEvent event) { - for (ModuleFeatureRegistry features : this.modules.values()) { - features.postRegistry(event); - } - } - public static IFeatureRegistry get(ResourceLocation moduleId) { return MOD_REGISTRY.computeIfAbsent(moduleId.getNamespace(), ModFeatureRegistry::new).getRegistry(moduleId); } @@ -80,7 +67,6 @@ private static class ModuleFeatureRegistry implements IFeatureRegistry { private final ArrayListMultimap>, IModFeature> featureByRegistry = ArrayListMultimap.create(); @SuppressWarnings("rawtypes") private final HashMap registries = new HashMap<>(); - private final LinkedListMultimap>, Consumer> registryListeners = LinkedListMultimap.create(); private final ResourceLocation moduleId; private final IEventBus modBus; @@ -95,12 +81,32 @@ public ModuleFeatureRegistry(ResourceLocation moduleId, IEventBus modBus) { public DeferredRegister getRegistry(ResourceKey> registryKey) { String modId = this.moduleId.getNamespace(); return this.registries.computeIfAbsent(registryKey, key -> { - DeferredRegister registry = DeferredRegister.create(key, modId); + @SuppressWarnings("rawtypes") + DeferredRegister registry; + + if (registryKey.equals(Registries.BLOCK)) { + registry = DeferredRegister.createBlocks(modId); + } else if (registryKey.equals(Registries.ITEM)) { + registry = DeferredRegister.createItems(modId); + } else { + registry = DeferredRegister.create(key, modId); + } + registry.register(this.modBus); return registry; }); } + @Override + public DeferredRegister.Blocks getBlockRegistry() { + return (DeferredRegister.Blocks) getRegistry(Registries.BLOCK); + } + + @Override + public DeferredRegister.Items getItemRegistry() { + return (DeferredRegister.Items) getRegistry(Registries.ITEM); + } + @Nullable @Override @SuppressWarnings("unchecked") @@ -138,16 +144,6 @@ public FeatureItem item(Supplier constructor, String name return register(new FeatureItem<>(this, this.moduleId, name, constructor)); } - @Override - public FeatureItem backpack(IBackpackDefinition definition, EnumBackpackType type, String identifier) { - return item(() -> ModuleStorage.BACKPACK_INTERFACE.createBackpack(definition, type), identifier); - } - - @Override - public FeatureItem naturalistBackpack(IBackpackDefinition definition, ResourceLocation speciesTypeId, CreativeModeTab tab, String identifier) { - return item(() -> ModuleStorage.BACKPACK_INTERFACE.createNaturalistBackpack(definition, speciesTypeId, tab), identifier); - } - @Override public FeatureItemGroup itemGroup(Function constructor, String identifier, S[] subTypes) { return itemGroup(constructor, subTypes).identifier(identifier).create(); @@ -183,20 +179,14 @@ public > FeatureRecipeType recipeType(String name, Suppli return new FeatureRecipeType<>(this, this.moduleId, name, serializer); } - // TODO REMOVE - @Override - public void addRegistryListener(ResourceKey> type, Consumer listener) { - this.registryListeners.put(type, listener); - } - @Override public void addRegistryListener(ResourceKey> type, Runnable listener) { ModUtil.addRegistryListener(type, listener); } public F register(F feature) { - this.features.add(feature); - this.featureByRegistry.put(feature.getRegistry(), feature); + this.features.add(feature); + this.featureByRegistry.put(feature.getRegistry(), feature); return feature; } @@ -244,12 +234,5 @@ public Collection getFeatures(ResourceKey> ty public ResourceLocation getModuleId() { return this.moduleId; } - - // this method is called at a LOW priority - public void postRegistry(RegisterEvent event) { - for (Consumer listener : this.registryListeners.get(event.getRegistryKey())) { - listener.accept(event); - } - } } } diff --git a/src/main/java/forestry/modules/features/package-info.java b/src/main/java/forestry/modules/features/package-info.java index 6ba1218fee..d3f56df5d9 100644 --- a/src/main/java/forestry/modules/features/package-info.java +++ b/src/main/java/forestry/modules/features/package-info.java @@ -1,9 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -@FieldsAreNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.modules.features; - -import forestry.core.utils.FieldsAreNonnullByDefault; -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/modules/package-info.java b/src/main/java/forestry/modules/package-info.java index b3556492c2..f408577949 100644 --- a/src/main/java/forestry/modules/package-info.java +++ b/src/main/java/forestry/modules/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.modules; diff --git a/src/main/java/forestry/package-info.java b/src/main/java/forestry/package-info.java index ae6ee9ce27..543db3ca8f 100644 --- a/src/main/java/forestry/package-info.java +++ b/src/main/java/forestry/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry; diff --git a/src/main/java/forestry/plugin/DefaultBeeSpecies.java b/src/main/java/forestry/plugin/DefaultBeeSpecies.java index 912bd0b85a..478ba0895f 100644 --- a/src/main/java/forestry/plugin/DefaultBeeSpecies.java +++ b/src/main/java/forestry/plugin/DefaultBeeSpecies.java @@ -22,9 +22,8 @@ import net.minecraft.tags.BiomeTags; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; -import java.awt.*; import java.time.Month; import static forestry.api.genetics.ForestryTaxa.*; @@ -37,7 +36,7 @@ public static void register(IApicultureRegistration apiculture) { ResourceLocation[] overworldHiveBees = new ResourceLocation[]{ForestryBeeSpecies.FOREST, ForestryBeeSpecies.MARSHY, ForestryBeeSpecies.MEADOWS, ForestryBeeSpecies.MODEST, ForestryBeeSpecies.SAVANNA, ForestryBeeSpecies.TROPICAL, ForestryBeeSpecies.VALIANT, ForestryBeeSpecies.WINTRY, ForestryBeeSpecies.LUSH, ForestryBeeSpecies.AQUATIC}; // Forest - apiculture.registerSpecies(ForestryBeeSpecies.FOREST, GENUS_HONEY, SPECIES_FOREST, true, new Color(0x19d0ec)) + apiculture.registerSpecies(ForestryBeeSpecies.FOREST, GENUS_HONEY, SPECIES_FOREST, true, TextColor.fromRgb(0x19d0ec)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.30f) .setGenome(genome -> { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOWER); @@ -46,7 +45,7 @@ public static void register(IApicultureRegistration apiculture) { }); // Meadows - apiculture.registerSpecies(ForestryBeeSpecies.MEADOWS, GENUS_HONEY, SPECIES_MEADOWS, true, new Color(0xef131e)) + apiculture.registerSpecies(ForestryBeeSpecies.MEADOWS, GENUS_HONEY, SPECIES_MEADOWS, true, TextColor.fromRgb(0xef131e)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.30f) .setGenome(genome -> { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOWER); @@ -54,7 +53,7 @@ public static void register(IApicultureRegistration apiculture) { }); // Common - apiculture.registerSpecies(ForestryBeeSpecies.COMMON, GENUS_HONEY, SPECIES_COMMON, true, new Color(0xb2b2b2)) + apiculture.registerSpecies(ForestryBeeSpecies.COMMON, GENUS_HONEY, SPECIES_COMMON, true, TextColor.fromRgb(0xb2b2b2)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.35f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); @@ -63,13 +62,13 @@ public static void register(IApicultureRegistration apiculture) { for (int i = 0; i < overworldHiveBees.length; i++) { ResourceLocation firstParent = overworldHiveBees[i]; for (int j = i + 1; j < overworldHiveBees.length; j++) { - mutations.add(firstParent, overworldHiveBees[j], 15); + mutations.add(firstParent, overworldHiveBees[j], 0.15f); } } }); // Cultivated - apiculture.registerSpecies(ForestryBeeSpecies.CULTIVATED, GENUS_HONEY, SPECIES_CULTIVATED, true, new Color(0x5734ec)) + apiculture.registerSpecies(ForestryBeeSpecies.CULTIVATED, GENUS_HONEY, SPECIES_CULTIVATED, true, TextColor.fromRgb(0x5734ec)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.40f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_FAST); @@ -77,12 +76,12 @@ public static void register(IApicultureRegistration apiculture) { }) .addMutations(mutations -> { for (ResourceLocation secondParent : overworldHiveBees) { - mutations.add(ForestryBeeSpecies.COMMON, secondParent, 12); + mutations.add(ForestryBeeSpecies.COMMON, secondParent, 0.12f); } }); // Noble - apiculture.registerSpecies(ForestryBeeSpecies.NOBLE, GENUS_NOBLE, SPECIES_NOBLE, false, new Color(0xec9a19)) + apiculture.registerSpecies(ForestryBeeSpecies.NOBLE, GENUS_NOBLE, SPECIES_NOBLE, false, TextColor.fromRgb(0xec9a19)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.DRIPPING), 0.20f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); @@ -90,11 +89,11 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOW); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.COMMON, ForestryBeeSpecies.CULTIVATED, 10); + mutations.add(ForestryBeeSpecies.COMMON, ForestryBeeSpecies.CULTIVATED, 0.10f); }); // Majestic - apiculture.registerSpecies(ForestryBeeSpecies.MAJESTIC, GENUS_NOBLE, SPECIES_MAJESTIC, true, new Color(0x7f0000)) + apiculture.registerSpecies(ForestryBeeSpecies.MAJESTIC, GENUS_NOBLE, SPECIES_MAJESTIC, true, TextColor.fromRgb(0x7f0000)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.DRIPPING), 0.30f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_NORMAL); @@ -102,11 +101,11 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.FERTILITY, ForestryAlleles.FERTILITY_4); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.NOBLE, ForestryBeeSpecies.CULTIVATED, 8); + mutations.add(ForestryBeeSpecies.NOBLE, ForestryBeeSpecies.CULTIVATED, 0.08f); }); // Imperial - apiculture.registerSpecies(ForestryBeeSpecies.IMPERIAL, GENUS_NOBLE, SPECIES_IMPERIAL, false, new Color(0xa3e02f)) + apiculture.registerSpecies(ForestryBeeSpecies.IMPERIAL, GENUS_NOBLE, SPECIES_IMPERIAL, false, TextColor.fromRgb(0xa3e02f)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.DRIPPING), 0.20f) .addProduct(ApicultureItems.ROYAL_JELLY.stack(), 0.15f) .setGenome(genome -> { @@ -115,12 +114,12 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_BEATIFIC); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.NOBLE, ForestryBeeSpecies.MAJESTIC, 8); + mutations.add(ForestryBeeSpecies.NOBLE, ForestryBeeSpecies.MAJESTIC, 0.08f); }) .setGlint(true); // Diligent - apiculture.registerSpecies(ForestryBeeSpecies.DILIGENT, GENUS_INDUSTRIOUS, SPECIES_DILIGENT, false, new Color(0xc219ec)) + apiculture.registerSpecies(ForestryBeeSpecies.DILIGENT, GENUS_INDUSTRIOUS, SPECIES_DILIGENT, false, TextColor.fromRgb(0xc219ec)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.STRINGY), 0.20f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); @@ -128,21 +127,21 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOW); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.COMMON, ForestryBeeSpecies.CULTIVATED, 10); + mutations.add(ForestryBeeSpecies.COMMON, ForestryBeeSpecies.CULTIVATED, 0.10f); }); // Unweary - apiculture.registerSpecies(ForestryBeeSpecies.UNWEARY, GENUS_INDUSTRIOUS, SPECIES_UNWEARY, true, new Color(0x19ec5a)) + apiculture.registerSpecies(ForestryBeeSpecies.UNWEARY, GENUS_INDUSTRIOUS, SPECIES_UNWEARY, true, TextColor.fromRgb(0x19ec5a)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.STRINGY), 0.30f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_NORMAL); genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORTENED); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.DILIGENT, ForestryBeeSpecies.CULTIVATED, 8); + mutations.add(ForestryBeeSpecies.DILIGENT, ForestryBeeSpecies.CULTIVATED, 0.08f); }); // Industrious - apiculture.registerSpecies(ForestryBeeSpecies.INDUSTRIOUS, GENUS_INDUSTRIOUS, SPECIES_INDUSTRIOUS, false, new Color(0xffffff)) + apiculture.registerSpecies(ForestryBeeSpecies.INDUSTRIOUS, GENUS_INDUSTRIOUS, SPECIES_INDUSTRIOUS, false, TextColor.fromRgb(0xffffff)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.STRINGY), 0.20f) .addProduct(POLLEN_CLUSTER.stack(EnumPollenCluster.NORMAL), 0.15f) .setGenome(genome -> { @@ -151,13 +150,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_FAST); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.DILIGENT, ForestryBeeSpecies.UNWEARY, 8); + mutations.add(ForestryBeeSpecies.DILIGENT, ForestryBeeSpecies.UNWEARY, 0.08f); }) .setGlint(true); // Sinister - apiculture.registerSpecies(ForestryBeeSpecies.SINISTER, GENUS_INFERNAL, SPECIES_SINISTER, false, new Color(0xb3d5e4)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.SINISTER, GENUS_INFERNAL, SPECIES_SINISTER, false, TextColor.fromRgb(0xb3d5e4)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.45f) @@ -171,14 +170,14 @@ public static void register(IApicultureRegistration apiculture) { ResourceLocation[] parents = new ResourceLocation[]{ForestryBeeSpecies.MODEST, ForestryBeeSpecies.TROPICAL}; for (ResourceLocation parent : parents) { - mutations.add(ForestryBeeSpecies.CULTIVATED, parent, 60) + mutations.add(ForestryBeeSpecies.CULTIVATED, parent, 0.60f) .restrictBiomeType(BiomeTags.IS_NETHER); } }); // Fiendish - apiculture.registerSpecies(ForestryBeeSpecies.FIENDISH, GENUS_INFERNAL, SPECIES_FIENDISH, true, new Color(0xd7bee5)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.FIENDISH, GENUS_INFERNAL, SPECIES_FIENDISH, true, TextColor.fromRgb(0xd7bee5)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.55f) @@ -192,14 +191,14 @@ public static void register(IApicultureRegistration apiculture) { ResourceLocation[] parents = new ResourceLocation[]{ForestryBeeSpecies.CULTIVATED, ForestryBeeSpecies.MODEST, ForestryBeeSpecies.TROPICAL}; for (ResourceLocation parent : parents) { - mutations.add(ForestryBeeSpecies.SINISTER, parent, 40) + mutations.add(ForestryBeeSpecies.SINISTER, parent, 0.40f) .restrictBiomeType(BiomeTags.IS_NETHER); } }); // Demonic - apiculture.registerSpecies(ForestryBeeSpecies.DEMONIC, GENUS_INFERNAL, SPECIES_DEMONIC, false, new Color(0xf4e400)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.DEMONIC, GENUS_INFERNAL, SPECIES_DEMONIC, false, TextColor.fromRgb(0xf4e400)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.45f) @@ -210,13 +209,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_IGNITION); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.SINISTER, ForestryBeeSpecies.FIENDISH, 25) + mutations.add(ForestryBeeSpecies.SINISTER, ForestryBeeSpecies.FIENDISH, 0.25f) .restrictBiomeType(BiomeTags.IS_NETHER); }) .setGlint(true); // Modest - apiculture.registerSpecies(ForestryBeeSpecies.MODEST, GENUS_AUSTERE, SPECIES_MODEST, false, new Color(0xc5be86)) + apiculture.registerSpecies(ForestryBeeSpecies.MODEST, GENUS_AUSTERE, SPECIES_MODEST, false, TextColor.fromRgb(0xc5be86)) .setTemperature(TemperatureType.HOT) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.PARCHED), 0.20f) @@ -226,7 +225,7 @@ public static void register(IApicultureRegistration apiculture) { }); // Frugal - apiculture.registerSpecies(ForestryBeeSpecies.FRUGAL, GENUS_AUSTERE, SPECIES_FRUGAL, true, new Color(0xe8dcb1)) + apiculture.registerSpecies(ForestryBeeSpecies.FRUGAL, GENUS_AUSTERE, SPECIES_FRUGAL, true, TextColor.fromRgb(0xe8dcb1)) .setTemperature(TemperatureType.HOT) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.PARCHED), 0.30f) @@ -235,16 +234,16 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONG); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MODEST, ForestryBeeSpecies.SINISTER, 16) + mutations.add(ForestryBeeSpecies.MODEST, ForestryBeeSpecies.SINISTER, 0.16f) .restrictTemperature(TemperatureType.HOT, TemperatureType.HELLISH) .restrictHumidity(HumidityType.ARID); - mutations.add(ForestryBeeSpecies.MODEST, ForestryBeeSpecies.FIENDISH, 10) + mutations.add(ForestryBeeSpecies.MODEST, ForestryBeeSpecies.FIENDISH, 0.10f) .restrictTemperature(TemperatureType.HOT, TemperatureType.HELLISH) .restrictHumidity(HumidityType.ARID); }); // Austere - apiculture.registerSpecies(ForestryBeeSpecies.AUSTERE, GENUS_AUSTERE, SPECIES_AUSTERE, false, new Color(0xfffac2)) + apiculture.registerSpecies(ForestryBeeSpecies.AUSTERE, GENUS_AUSTERE, SPECIES_AUSTERE, false, TextColor.fromRgb(0xfffac2)) .setTemperature(TemperatureType.HOT) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.PARCHED), 0.20f) @@ -256,14 +255,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_CREEPER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MODEST, ForestryBeeSpecies.FRUGAL, 8) + mutations.add(ForestryBeeSpecies.MODEST, ForestryBeeSpecies.FRUGAL, 0.08f) .restrictTemperature(TemperatureType.HOT, TemperatureType.HELLISH) .restrictHumidity(HumidityType.ARID); }) .setGlint(true); // Tropical - apiculture.registerSpecies(ForestryBeeSpecies.TROPICAL, GENUS_TROPICAL, SPECIES_TROPICAL, false, new Color(0x378020)) + apiculture.registerSpecies(ForestryBeeSpecies.TROPICAL, GENUS_TROPICAL, SPECIES_TROPICAL, false, TextColor.fromRgb(0x378020)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SILKY), 0.20f) @@ -273,7 +272,7 @@ public static void register(IApicultureRegistration apiculture) { }); // Exotic - apiculture.registerSpecies(ForestryBeeSpecies.EXOTIC, GENUS_TROPICAL, SPECIES_EXOTIC, true, new Color(0x304903)) + apiculture.registerSpecies(ForestryBeeSpecies.EXOTIC, GENUS_TROPICAL, SPECIES_EXOTIC, true, TextColor.fromRgb(0x304903)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SILKY), 0.30f) @@ -282,11 +281,11 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONG); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.AUSTERE, ForestryBeeSpecies.TROPICAL, 12); + mutations.add(ForestryBeeSpecies.AUSTERE, ForestryBeeSpecies.TROPICAL, 0.12f); }); // Edenic - apiculture.registerSpecies(ForestryBeeSpecies.EDENIC, GENUS_TROPICAL, SPECIES_EDENIC, false, new Color(0x393d0d)) + apiculture.registerSpecies(ForestryBeeSpecies.EDENIC, GENUS_TROPICAL, SPECIES_EDENIC, false, TextColor.fromRgb(0x393d0d)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SILKY), 0.20f) @@ -297,29 +296,29 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_EXPLORATION); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.EXOTIC, ForestryBeeSpecies.TROPICAL, 8); + mutations.add(ForestryBeeSpecies.EXOTIC, ForestryBeeSpecies.TROPICAL, 0.08f); }) .setGlint(true); // Monastic (Only obtainable from villagers) - apiculture.registerSpecies(ForestryBeeSpecies.MONASTIC, GENUS_MONASTIC, SPECIES_MONASTIC, false, new Color(0x42371c)) + apiculture.registerSpecies(ForestryBeeSpecies.MONASTIC, GENUS_MONASTIC, SPECIES_MONASTIC, false, TextColor.fromRgb(0x42371c)) .setJubilance(HermitBeeJubilance.INSTANCE) .addProduct(BEE_COMBS.stack(EnumHoneyComb.WHEATEN), 0.30f) .addSpecialty(BEE_COMBS.stack(EnumHoneyComb.MELLOW), 0.10f); // Secluded - apiculture.registerSpecies(ForestryBeeSpecies.SECLUDED, GENUS_MONASTIC, SPECIES_SECLUDED, true, new Color(0x7b6634)) + apiculture.registerSpecies(ForestryBeeSpecies.SECLUDED, GENUS_MONASTIC, SPECIES_SECLUDED, true, TextColor.fromRgb(0x7b6634)) .setJubilance(HermitBeeJubilance.INSTANCE) .addSpecialty(BEE_COMBS.stack(EnumHoneyComb.MELLOW), 0.20f) .setGenome(genome -> { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_FASTEST); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.AUSTERE, 12); + mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.AUSTERE, 0.12f); }); // Hermitic - apiculture.registerSpecies(ForestryBeeSpecies.HERMITIC, GENUS_MONASTIC, SPECIES_HERMITIC, false, new Color(0xffd46c)) + apiculture.registerSpecies(ForestryBeeSpecies.HERMITIC, GENUS_MONASTIC, SPECIES_HERMITIC, false, TextColor.fromRgb(0xffd46c)) .setJubilance(HermitBeeJubilance.INSTANCE) .addSpecialty(BEE_COMBS.stack(EnumHoneyComb.MELLOW), 0.20f) .setGenome(genome -> { @@ -327,12 +326,12 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_REPULSION); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.SECLUDED, 8); + mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.SECLUDED, 0.08f); }) .setGlint(true); // SHULKING - apiculture.registerSpecies(ForestryBeeSpecies.SHULKING, GENUS_END, SPECIES_SHULKING, false, new Color(0x896D74)) + apiculture.registerSpecies(ForestryBeeSpecies.SHULKING, GENUS_END, SPECIES_SHULKING, false, TextColor.fromRgb(0x896D74)) .setBody(TextColor.fromRgb(0xd9de9e)) .setTemperature(TemperatureType.COLD) .setHumidity(HumidityType.ARID) @@ -345,15 +344,15 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // Ended - apiculture.registerSpecies(ForestryBeeSpecies.ENDED, GENUS_END, SPECIES_ENDED, false, new Color(0xe079fa)) - .setBody(new Color(0xd9de9e)) + apiculture.registerSpecies(ForestryBeeSpecies.ENDED, GENUS_END, SPECIES_ENDED, false, TextColor.fromRgb(0xe079fa)) + .setBody(TextColor.fromRgb(0xd9de9e)) .setTemperature(TemperatureType.COLD) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.MYSTERIOUS), 0.30f); // Spectral - apiculture.registerSpecies(ForestryBeeSpecies.SPECTRAL, GENUS_END, SPECIES_SPECTRAL, true, new Color(0xa98bed)) - .setBody(new Color(0xd9de9e)) + apiculture.registerSpecies(ForestryBeeSpecies.SPECTRAL, GENUS_END, SPECIES_SPECTRAL, true, TextColor.fromRgb(0xa98bed)) + .setBody(TextColor.fromRgb(0xd9de9e)) .setTemperature(TemperatureType.COLD) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.MYSTERIOUS), 0.50f) @@ -361,12 +360,12 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_REANIMATION); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.HERMITIC, ForestryBeeSpecies.ENDED, 4); + mutations.add(ForestryBeeSpecies.HERMITIC, ForestryBeeSpecies.ENDED, 0.04f); }); // Phantasmal - apiculture.registerSpecies(ForestryBeeSpecies.PHANTASMAL, GENUS_END, SPECIES_PHANTASMAL, false, new Color(0xcc00fa)) - .setBody(new Color(0xd9de9e)) + apiculture.registerSpecies(ForestryBeeSpecies.PHANTASMAL, GENUS_END, SPECIES_PHANTASMAL, false, TextColor.fromRgb(0xcc00fa)) + .setBody(TextColor.fromRgb(0xd9de9e)) .setTemperature(TemperatureType.COLD) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.MYSTERIOUS), 0.40f) @@ -376,13 +375,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_RESURRECTION); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.SPECTRAL, ForestryBeeSpecies.ENDED, 2); + mutations.add(ForestryBeeSpecies.SPECTRAL, ForestryBeeSpecies.ENDED, 0.02f); }) .setGlint(true); // Wintry - apiculture.registerSpecies(ForestryBeeSpecies.WINTRY, GENUS_FROZEN, SPECIES_WINTRY, false, new Color(0xa0ffc8)) - .setBody(new Color(0xdaf5f3)) + apiculture.registerSpecies(ForestryBeeSpecies.WINTRY, GENUS_FROZEN, SPECIES_WINTRY, false, TextColor.fromRgb(0xa0ffc8)) + .setBody(TextColor.fromRgb(0xdaf5f3)) .setTemperature(TemperatureType.ICY) .addProduct(BEE_COMBS.stack(EnumHoneyComb.FROZEN), 0.30f) .setGenome(genome -> { @@ -392,8 +391,8 @@ public static void register(IApicultureRegistration apiculture) { }); // Icy - apiculture.registerSpecies(ForestryBeeSpecies.ICY, GENUS_FROZEN, SPECIES_ICY, true, new Color(0xa0ffff)) - .setBody(new Color(0xdaf5f3)) + apiculture.registerSpecies(ForestryBeeSpecies.ICY, GENUS_FROZEN, SPECIES_ICY, true, TextColor.fromRgb(0xa0ffff)) + .setBody(TextColor.fromRgb(0xdaf5f3)) .setTemperature(TemperatureType.ICY) .addProduct(BEE_COMBS.stack(EnumHoneyComb.FROZEN), 0.20f) .addProduct(CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.ICE_SHARD), 0.20f) @@ -402,13 +401,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORT); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.INDUSTRIOUS, ForestryBeeSpecies.WINTRY, 12) + mutations.add(ForestryBeeSpecies.INDUSTRIOUS, ForestryBeeSpecies.WINTRY, 0.12f) .restrictTemperature(TemperatureType.ICY, TemperatureType.COLD); }); // Glacial - apiculture.registerSpecies(ForestryBeeSpecies.GLACIAL, GENUS_FROZEN, SPECIES_GLACIAL, false, new Color(0xefffff)) - .setBody(new Color(0xdaf5f3)) + apiculture.registerSpecies(ForestryBeeSpecies.GLACIAL, GENUS_FROZEN, SPECIES_GLACIAL, false, TextColor.fromRgb(0xefffff)) + .setBody(TextColor.fromRgb(0xdaf5f3)) .setTemperature(TemperatureType.ICY) .addProduct(BEE_COMBS.stack(EnumHoneyComb.FROZEN), 0.20f) .addProduct(CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.ICE_SHARD), 0.40f) @@ -417,18 +416,18 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORT); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.ICY, ForestryBeeSpecies.WINTRY, 8) + mutations.add(ForestryBeeSpecies.ICY, ForestryBeeSpecies.WINTRY, 0.08f) .restrictTemperature(TemperatureType.ICY, TemperatureType.COLD); }) .setGlint(true); // Marshy - apiculture.registerSpecies(ForestryBeeSpecies.MARSHY, GENUS_BOGGY, SPECIES_MARSHY, true, new Color(0x546626)) + apiculture.registerSpecies(ForestryBeeSpecies.MARSHY, GENUS_BOGGY, SPECIES_MARSHY, true, TextColor.fromRgb(0x546626)) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.MOSSY), 0.30f); // Miry - apiculture.registerSpecies(ForestryBeeSpecies.MIRY, GENUS_BOGGY, SPECIES_MIRY, true, new Color(0x92AF42)) + apiculture.registerSpecies(ForestryBeeSpecies.MIRY, GENUS_BOGGY, SPECIES_MIRY, true, TextColor.fromRgb(0x92AF42)) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.MOSSY), 0.36f) .setGenome(genome -> { @@ -437,14 +436,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.ACTIVITY, ForestryAlleles.ACTIVITY_METATURNAL); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MARSHY, ForestryBeeSpecies.NOBLE, 15) + mutations.add(ForestryBeeSpecies.MARSHY, ForestryBeeSpecies.NOBLE, 0.15f) .restrictTemperature(TemperatureType.WARM) .restrictHumidity(HumidityType.DAMP); }) .setAuthority("MysteriousAges"); // Boggy - apiculture.registerSpecies(ForestryBeeSpecies.BOGGY, GENUS_BOGGY, SPECIES_BOGGY, true, new Color(0x698948)) + apiculture.registerSpecies(ForestryBeeSpecies.BOGGY, GENUS_BOGGY, SPECIES_BOGGY, true, TextColor.fromRgb(0x698948)) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.MOSSY), 0.39f) .addSpecialty(CoreItems.PEAT.stack(), 0.08f) @@ -455,14 +454,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.TERRITORY, ForestryAlleles.TERRITORY_LARGER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MARSHY, ForestryBeeSpecies.MIRY, 9) + mutations.add(ForestryBeeSpecies.MARSHY, ForestryBeeSpecies.MIRY, 0.09f) .restrictTemperature(TemperatureType.WARM) .restrictHumidity(HumidityType.DAMP); }) .setAuthority("MysteriousAges"); // Savanna - apiculture.registerSpecies(ForestryBeeSpecies.SAVANNA, GENUS_SAVANNA, SPECIES_SAVANNA, true, new Color(0xb04e0f)) + apiculture.registerSpecies(ForestryBeeSpecies.SAVANNA, GENUS_SAVANNA, SPECIES_SAVANNA, true, TextColor.fromRgb(0xb04e0f)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.PARCHED), 0.20f) @@ -475,7 +474,7 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // Argil - apiculture.registerSpecies(ForestryBeeSpecies.ARGIL, GENUS_SAVANNA, SPECIES_ARGIL, true, new Color(0x96afd2)) + apiculture.registerSpecies(ForestryBeeSpecies.ARGIL, GENUS_SAVANNA, SPECIES_ARGIL, true, TextColor.fromRgb(0x96afd2)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.KAOLIN), 0.30f) @@ -487,14 +486,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_SIFTER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.SAVANNA, ForestryBeeSpecies.DILIGENT, 15) + mutations.add(ForestryBeeSpecies.SAVANNA, ForestryBeeSpecies.DILIGENT, 0.15f) .restrictTemperature(TemperatureType.WARM, TemperatureType.HOT) .restrictHumidity(HumidityType.ARID); }) .setAuthority("EnderiumSmith"); // Pride - apiculture.registerSpecies(ForestryBeeSpecies.PRIDE, GENUS_SAVANNA, SPECIES_PRIDE, true, new Color(0x650021)) + apiculture.registerSpecies(ForestryBeeSpecies.PRIDE, GENUS_SAVANNA, SPECIES_PRIDE, true, TextColor.fromRgb(0x650021)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.KAOLIN), 0.20f) @@ -506,14 +505,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_HAKUNA_MATATA); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.SAVANNA, ForestryBeeSpecies.ARGIL, 9) + mutations.add(ForestryBeeSpecies.SAVANNA, ForestryBeeSpecies.ARGIL, 0.09f) .restrictBiomeType(ForestryTags.Biomes.SHATTERED_SAVANNA); }) .setGlint(true) .setAuthority("EnderiumSmith"); // Steadfast - apiculture.registerSpecies(ForestryBeeSpecies.STEADFAST, GENUS_HEROIC, SPECIES_STEADFAST, false, new Color(0x4d2b15)) + apiculture.registerSpecies(ForestryBeeSpecies.STEADFAST, GENUS_HEROIC, SPECIES_STEADFAST, false, TextColor.fromRgb(0x4d2b15)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.COCOA), 0.20f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); @@ -522,7 +521,7 @@ public static void register(IApicultureRegistration apiculture) { .setGlint(true); // Valiant - apiculture.registerSpecies(ForestryBeeSpecies.VALIANT, GENUS_HEROIC, SPECIES_VALIANT, true, new Color(0x626bdd)) + apiculture.registerSpecies(ForestryBeeSpecies.VALIANT, GENUS_HEROIC, SPECIES_VALIANT, true, TextColor.fromRgb(0x626bdd)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.COCOA), 0.30f) .addSpecialty(new ItemStack(Items.SUGAR), 0.15f) .setGenome(genome -> { @@ -533,7 +532,7 @@ public static void register(IApicultureRegistration apiculture) { }); // Heroic - apiculture.registerSpecies(ForestryBeeSpecies.HEROIC, GENUS_HEROIC, SPECIES_HEROIC, false, new Color(0xb3d5e4)) + apiculture.registerSpecies(ForestryBeeSpecies.HEROIC, GENUS_HEROIC, SPECIES_HEROIC, false, TextColor.fromRgb(0xb3d5e4)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.COCOA), 0.40f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOW); @@ -541,13 +540,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_HEROIC); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.STEADFAST, ForestryBeeSpecies.VALIANT, 6) + mutations.add(ForestryBeeSpecies.STEADFAST, ForestryBeeSpecies.VALIANT, 0.06f) .restrictBiomeType(BiomeTags.IS_FOREST); }) .setGlint(true); // Lush - apiculture.registerSpecies(ForestryBeeSpecies.LUSH, GENUS_LUSH, SPECIES_LUSH, true, new Color(0x70922D)) + apiculture.registerSpecies(ForestryBeeSpecies.LUSH, GENUS_LUSH, SPECIES_LUSH, true, TextColor.fromRgb(0x70922D)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.35F) @@ -559,7 +558,7 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // Verdant - apiculture.registerSpecies(ForestryBeeSpecies.VERDANT, GENUS_LUSH, SPECIES_VERDANT, true, new Color(0x1C5B3A)) + apiculture.registerSpecies(ForestryBeeSpecies.VERDANT, GENUS_LUSH, SPECIES_VERDANT, true, TextColor.fromRgb(0x1C5B3A)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.45F) @@ -570,12 +569,12 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOWER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.LUSH, ForestryBeeSpecies.VALIANT, 10).addMutationCondition(new MutationConditionCave()); + mutations.add(ForestryBeeSpecies.LUSH, ForestryBeeSpecies.VALIANT, 0.10f).addMutationCondition(new MutationConditionCave()); }) .setAuthority("EnderiumSmith"); // LUXURIANT - apiculture.registerSpecies(ForestryBeeSpecies.LUXURIANT, GENUS_LUSH, SPECIES_LUXURIANT, false, new Color(0xEB8931)) + apiculture.registerSpecies(ForestryBeeSpecies.LUXURIANT, GENUS_LUSH, SPECIES_LUXURIANT, false, TextColor.fromRgb(0xEB8931)) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.55F) @@ -587,54 +586,54 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_GLOW_BERRY_GROW); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.LUSH, ForestryBeeSpecies.VERDANT, 8).addMutationCondition(new MutationConditionCave()); + mutations.add(ForestryBeeSpecies.LUSH, ForestryBeeSpecies.VERDANT, 0.08f).addMutationCondition(new MutationConditionCave()); }) .setAuthority("EnderiumSmith") .setGlint(true); // KLEPTOPLASTIC - apiculture.registerSpecies(ForestryBeeSpecies.KLEPTOPLASTIC, GENUS_KLEPTOPLASTIC, SPECIES_KLEPTOPLASTIC, false, new Color(0xffc987)) - .setBody(new Color(0x64E986)) + apiculture.registerSpecies(ForestryBeeSpecies.KLEPTOPLASTIC, GENUS_KLEPTOPLASTIC, SPECIES_KLEPTOPLASTIC, false, TextColor.fromRgb(0xffc987)) + .setBody(TextColor.fromRgb(0x64E986)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.30F) .setGenome(genome -> { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONGER); genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_NORMAL); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.LUXURIANT, ForestryBeeSpecies.MONASTIC, 12); + mutations.add(ForestryBeeSpecies.LUXURIANT, ForestryBeeSpecies.MONASTIC, 0.12f); }) .setAuthority("EnderiumSmith"); // PHOTOSYNTHETIC - apiculture.registerSpecies(ForestryBeeSpecies.PHOTOSYNTHETIC, GENUS_KLEPTOPLASTIC, SPECIES_PHOTOSYNTHETIC, true, new Color(0xB6C9FF)) - .setBody(new Color(0x64E986)) + apiculture.registerSpecies(ForestryBeeSpecies.PHOTOSYNTHETIC, GENUS_KLEPTOPLASTIC, SPECIES_PHOTOSYNTHETIC, true, TextColor.fromRgb(0xB6C9FF)) + .setBody(TextColor.fromRgb(0x64E986)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.40F) .setGenome(genome -> { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONGER); genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_FAST); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.KLEPTOPLASTIC, ForestryBeeSpecies.LUXURIANT, 8); - mutations.add(ForestryBeeSpecies.KLEPTOPLASTIC, ForestryBeeSpecies.MONASTIC, 8); + mutations.add(ForestryBeeSpecies.KLEPTOPLASTIC, ForestryBeeSpecies.LUXURIANT, 0.08f); + mutations.add(ForestryBeeSpecies.KLEPTOPLASTIC, ForestryBeeSpecies.MONASTIC, 0.08f); }) .setAuthority("EnderiumSmith"); // AUTOTROPHIC - apiculture.registerSpecies(ForestryBeeSpecies.AUTOTROPHIC, GENUS_KLEPTOPLASTIC, SPECIES_AUTOTROPHIC, false, new Color(0xFFF5EC)) - .setBody(new Color(0x64E986)) + apiculture.registerSpecies(ForestryBeeSpecies.AUTOTROPHIC, GENUS_KLEPTOPLASTIC, SPECIES_AUTOTROPHIC, false, TextColor.fromRgb(0xFFF5EC)) + .setBody(TextColor.fromRgb(0x64E986)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.30F) .setGenome(genome -> { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONGEST); genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_FASTER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.KLEPTOPLASTIC, ForestryBeeSpecies.PHOTOSYNTHETIC, 4); + mutations.add(ForestryBeeSpecies.KLEPTOPLASTIC, ForestryBeeSpecies.PHOTOSYNTHETIC, 0.04f); }) .setGlint(true) .setAuthority("EnderiumSmith"); // AQUATIC - apiculture.registerSpecies(ForestryBeeSpecies.AQUATIC, GENUS_AQUATIC, SPECIES_AQUATIC, true, new Color(0x3F76E4)) + apiculture.registerSpecies(ForestryBeeSpecies.AQUATIC, GENUS_AQUATIC, SPECIES_AQUATIC, true, TextColor.fromRgb(0x3F76E4)) .setTemperature(TemperatureType.WARM) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SPONGE), 0.30F) .setGenome(genome -> { @@ -647,7 +646,7 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // PIRATE - apiculture.registerSpecies(ForestryBeeSpecies.PIRATE, GENUS_AQUATIC, SPECIES_PIRATE, true, new Color(0x3F605B)) + apiculture.registerSpecies(ForestryBeeSpecies.PIRATE, GENUS_AQUATIC, SPECIES_PIRATE, true, TextColor.fromRgb(0x3F605B)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SPONGE), 0.20F) .addSpecialty(new ItemStack(Items.GOLD_NUGGET), 0.15F) .addSpecialty(new ItemStack(Items.LAPIS_LAZULI), 0.02F) @@ -662,7 +661,7 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // PRISMATIC - apiculture.registerSpecies(ForestryBeeSpecies.PRISMATIC, GENUS_AQUATIC, SPECIES_PRISMATIC, false, new Color(0x539882)) + apiculture.registerSpecies(ForestryBeeSpecies.PRISMATIC, GENUS_AQUATIC, SPECIES_PRISMATIC, false, TextColor.fromRgb(0x539882)) .setTemperature(TemperatureType.WARM) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SPONGE), 0.20F) .addSpecialty(new ItemStack(Items.PRISMARINE_SHARD), 0.40F) @@ -676,13 +675,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_DOWN_1); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.AQUATIC, ForestryBeeSpecies.PIRATE, 8); + mutations.add(ForestryBeeSpecies.AQUATIC, ForestryBeeSpecies.PIRATE, 0.08f); }) .setGlint(true) .setAuthority("EnderiumSmith"); // ABYSSAL - apiculture.registerSpecies(ForestryBeeSpecies.ABYSSAL, GENUS_AQUATIC, SPECIES_ABYSSAL, false, new Color(0x050533)) + apiculture.registerSpecies(ForestryBeeSpecies.ABYSSAL, GENUS_AQUATIC, SPECIES_ABYSSAL, false, TextColor.fromRgb(0x050533)) .setTemperature(TemperatureType.COLD) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SPONGE), 0.20F) .addSpecialty(new ItemStack(Items.GLOW_INK_SAC), 0.15F) @@ -695,17 +694,17 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.CAVE_DWELLING, ForestryAlleles.TRUE); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.PIRATE, ForestryBeeSpecies.ENDED, 40).addMutationCondition(new CaveMutationCondition()); - mutations.add(ForestryBeeSpecies.AQUATIC, ForestryBeeSpecies.ENDED, 40).addMutationCondition(new CaveMutationCondition()); - mutations.add(ForestryBeeSpecies.PIRATE, ForestryBeeSpecies.SHULKING, 60).addMutationCondition(new CaveMutationCondition()); - mutations.add(ForestryBeeSpecies.AQUATIC, ForestryBeeSpecies.SHULKING, 60).addMutationCondition(new CaveMutationCondition()); + mutations.add(ForestryBeeSpecies.PIRATE, ForestryBeeSpecies.ENDED, 0.40f).addMutationCondition(new CaveMutationCondition()); + mutations.add(ForestryBeeSpecies.AQUATIC, ForestryBeeSpecies.ENDED, 0.40f).addMutationCondition(new CaveMutationCondition()); + mutations.add(ForestryBeeSpecies.PIRATE, ForestryBeeSpecies.SHULKING, 0.60f).addMutationCondition(new CaveMutationCondition()); + mutations.add(ForestryBeeSpecies.AQUATIC, ForestryBeeSpecies.SHULKING, 0.60f).addMutationCondition(new CaveMutationCondition()); }) .setGlint(true) .setAuthority("EnderiumSmith"); // EMBITTERED - apiculture.registerSpecies(ForestryBeeSpecies.EMBITTERED, GENUS_EMBITTERED, SPECIES_EMBITTERED, true, new Color(0x894344)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.EMBITTERED, GENUS_EMBITTERED, SPECIES_EMBITTERED, true, TextColor.fromRgb(0x894344)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.45F) @@ -717,8 +716,8 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // SPITEFUL - apiculture.registerSpecies(ForestryBeeSpecies.SPITEFUL, GENUS_EMBITTERED, SPECIES_SPITEFUL, false, new Color(0xFEAC6D)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.SPITEFUL, GENUS_EMBITTERED, SPECIES_SPITEFUL, false, TextColor.fromRgb(0xFEAC6D)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.55F) @@ -728,13 +727,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_AGGRESSIVE); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.EMBITTERED, ForestryBeeSpecies.FIENDISH, 12); + mutations.add(ForestryBeeSpecies.EMBITTERED, ForestryBeeSpecies.FIENDISH, 0.12f); }) .setAuthority("EnderiumSmith"); // SEETHING - apiculture.registerSpecies(ForestryBeeSpecies.SEETHING, GENUS_EMBITTERED, SPECIES_SEETHING, false, new Color(0xff8f00)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.SEETHING, GENUS_EMBITTERED, SPECIES_SEETHING, false, TextColor.fromRgb(0xff8f00)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.45F) @@ -744,14 +743,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_IGNITION); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.SPITEFUL, ForestryBeeSpecies.EMBITTERED, 8); + mutations.add(ForestryBeeSpecies.SPITEFUL, ForestryBeeSpecies.EMBITTERED, 0.08f); }) .setGlint(true) .setAuthority("EnderiumSmith"); // WARPED - apiculture.registerSpecies(ForestryBeeSpecies.WARPED, GENUS_EMBITTERED, SPECIES_WARPED, true, new Color(0x14B485)) - .setBody(new Color(0x9a2323)) + apiculture.registerSpecies(ForestryBeeSpecies.WARPED, GENUS_EMBITTERED, SPECIES_WARPED, true, TextColor.fromRgb(0x14B485)) + .setBody(TextColor.fromRgb(0x9a2323)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.15F) @@ -762,16 +761,16 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_PHASING); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.EMBITTERED, ForestryBeeSpecies.ENDED, 40).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); - mutations.add(ForestryBeeSpecies.SPITEFUL, ForestryBeeSpecies.ENDED, 40).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); - mutations.add(ForestryBeeSpecies.EMBITTERED, ForestryBeeSpecies.SHULKING, 40).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); - mutations.add(ForestryBeeSpecies.SPITEFUL, ForestryBeeSpecies.SHULKING, 40).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); + mutations.add(ForestryBeeSpecies.EMBITTERED, ForestryBeeSpecies.ENDED, 0.40f).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); + mutations.add(ForestryBeeSpecies.SPITEFUL, ForestryBeeSpecies.ENDED, 0.40f).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); + mutations.add(ForestryBeeSpecies.EMBITTERED, ForestryBeeSpecies.SHULKING, 0.40f).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); + mutations.add(ForestryBeeSpecies.SPITEFUL, ForestryBeeSpecies.SHULKING, 0.40f).restrictBiomeType(ForestryTags.Biomes.WARPED_FOREST); }) .setAuthority("EnderiumSmith"); // ZOMBIFIED - apiculture.registerSpecies(ForestryBeeSpecies.ZOMBIFIED, GENUS_ABOMINATION, SPECIES_ZOMBIFIED, true, new Color(0x698E45)) - .setBody(new Color(0xE4686A)) + apiculture.registerSpecies(ForestryBeeSpecies.ZOMBIFIED, GENUS_ABOMINATION, SPECIES_ZOMBIFIED, true, TextColor.fromRgb(0x698E45)) + .setBody(TextColor.fromRgb(0xE4686A)) .setTemperature(TemperatureType.HELLISH) .setHumidity(HumidityType.ARID) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SIMMERING), 0.20F) @@ -790,8 +789,8 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // SCULK - apiculture.registerSpecies(ForestryBeeSpecies.SCULK, GENUS_ABOMINATION, SPECIES_SCULK, true, new Color(0xD1D6B6)) - .setBody(new Color(0x05625D))//0x034150//0x111B21 + apiculture.registerSpecies(ForestryBeeSpecies.SCULK, GENUS_ABOMINATION, SPECIES_SCULK, true, TextColor.fromRgb(0xD1D6B6)) + .setBody(TextColor.fromRgb(0x05625D))//0x034150//0x111B21 .addProduct(BEE_COMBS.stack(EnumHoneyComb.SCULKEN), 0.30F) .setGenome(genome -> { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONGER); @@ -807,35 +806,35 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.CAVE_DWELLING, ForestryAlleles.TRUE); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.ABYSSAL, ForestryBeeSpecies.PHANTASMAL, 4).restrictBiomeType(ForestryTags.Biomes.DEEP_DARK); + mutations.add(ForestryBeeSpecies.ABYSSAL, ForestryBeeSpecies.PHANTASMAL, 0.04f).restrictBiomeType(ForestryTags.Biomes.DEEP_DARK); }) .setGlint(true) .setAuthority("EnderiumSmith"); // Rural - apiculture.registerSpecies(ForestryBeeSpecies.RURAL, GENUS_AGRARIAN, SPECIES_RURAL, false, new Color(0xfeff8f)) + apiculture.registerSpecies(ForestryBeeSpecies.RURAL, GENUS_AGRARIAN, SPECIES_RURAL, false, TextColor.fromRgb(0xfeff8f)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.WHEATEN), 0.20f) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MEADOWS, ForestryBeeSpecies.DILIGENT, 12) + mutations.add(ForestryBeeSpecies.MEADOWS, ForestryBeeSpecies.DILIGENT, 0.12f) .restrictBiomeType(Tags.Biomes.IS_PLAINS); }); // Farmerly - apiculture.registerSpecies(ForestryBeeSpecies.FARMERLY, GENUS_AGRARIAN, SPECIES_FARMERLY, true, new Color(0xD39728)) + apiculture.registerSpecies(ForestryBeeSpecies.FARMERLY, GENUS_AGRARIAN, SPECIES_FARMERLY, true, TextColor.fromRgb(0xD39728)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.WHEATEN), 0.27f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOW); genome.set(BeeChromosomes.TERRITORY, ForestryAlleles.TERRITORY_LARGE); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.RURAL, ForestryBeeSpecies.UNWEARY, 10) + mutations.add(ForestryBeeSpecies.RURAL, ForestryBeeSpecies.UNWEARY, 0.10f) .restrictBiomeType(Tags.Biomes.IS_PLAINS); }) .setAuthority("MysteriousAges"); // Agrarian - apiculture.registerSpecies(ForestryBeeSpecies.AGRARIAN, GENUS_AGRARIAN, SPECIES_AGRARIAN, true, new Color(0xFFCA75)) - .setBody(new Color(0xFFE047)) + apiculture.registerSpecies(ForestryBeeSpecies.AGRARIAN, GENUS_AGRARIAN, SPECIES_AGRARIAN, true, TextColor.fromRgb(0xFFCA75)) + .setBody(TextColor.fromRgb(0xFFE047)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.WHEATEN), 0.35f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOW); @@ -844,14 +843,14 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.TERRITORY, ForestryAlleles.TERRITORY_LARGE); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.FARMERLY, ForestryBeeSpecies.INDUSTRIOUS, 6) + mutations.add(ForestryBeeSpecies.FARMERLY, ForestryBeeSpecies.INDUSTRIOUS, 0.06f) .restrictBiomeType(Tags.Biomes.IS_PLAINS); }) .setGlint(true) .setAuthority("MysteriousAges"); // PRIMEVAL - apiculture.registerSpecies(ForestryBeeSpecies.PRIMEVAL, GENUS_RELIC, SPECIES_PRIMEVAL, true, new Color(0x653F33)) + apiculture.registerSpecies(ForestryBeeSpecies.PRIMEVAL, GENUS_RELIC, SPECIES_PRIMEVAL, true, TextColor.fromRgb(0x653F33)) .setTemperature(TemperatureType.WARM) .addProduct(BEE_COMBS.stack(EnumHoneyComb.VINTAGE), 0.30F) .setGenome(genome -> { @@ -861,12 +860,12 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.FERTILITY, ForestryAlleles.FERTILITY_2); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.ANACHRONE, ForestryBeeSpecies.STEADFAST, 15); + mutations.add(ForestryBeeSpecies.ANACHRONE, ForestryBeeSpecies.STEADFAST, 0.15f); }) .setAuthority("EnderiumSmith"); // ANACHRONE - apiculture.registerSpecies(ForestryBeeSpecies.ANACHRONE, GENUS_RELIC, SPECIES_ANACHRONE, false, new Color(5636095)) + apiculture.registerSpecies(ForestryBeeSpecies.ANACHRONE, GENUS_RELIC, SPECIES_ANACHRONE, false, TextColor.fromRgb(5636095)) .setTemperature(TemperatureType.WARM) .addProduct(BEE_COMBS.stack(EnumHoneyComb.VINTAGE), 0.20F) .setGenome(genome -> { @@ -877,13 +876,13 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_CHRONOPHAGE); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.RELIC, ForestryBeeSpecies.STEADFAST, 10); + mutations.add(ForestryBeeSpecies.RELIC, ForestryBeeSpecies.STEADFAST, 0.10f); }) .setGlint(true) .setAuthority("EnderiumSmith"); // RELIC - apiculture.registerSpecies(ForestryBeeSpecies.RELIC, GENUS_RELIC, SPECIES_RELIC, false, new Color(16733695)) + apiculture.registerSpecies(ForestryBeeSpecies.RELIC, GENUS_RELIC, SPECIES_RELIC, false, TextColor.fromRgb(16733695)) .setTemperature(TemperatureType.WARM) .addProduct(BEE_COMBS.stack(EnumHoneyComb.VINTAGE), 0.20F) .addSpecialty(ApicultureItems.ROYAL_JELLY.stack(), 0.15F) @@ -898,7 +897,7 @@ public static void register(IApicultureRegistration apiculture) { .setAuthority("EnderiumSmith"); // VANILLA - apiculture.registerSpecies(ForestryBeeSpecies.VANILLA, GENUS_VANILLA, SPECIES_VANILLA, false, new Color(0xEDC343)) + apiculture.registerSpecies(ForestryBeeSpecies.VANILLA, GENUS_VANILLA, SPECIES_VANILLA, false, TextColor.fromRgb(0xEDC343)) .addProduct(new ItemStack(Items.HONEYCOMB), 0.65F) .setGenome(genome -> { genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORTENED); @@ -913,62 +912,62 @@ public static void register(IApicultureRegistration apiculture) { /* // Vindictive - apiculture.registerSpecies(ForestryBeeSpecies.VINDICTIVE, GENUS_VENGEFUL, SPECIES_VINDICTIVE, false, new Color(0xeafff3)) + apiculture.registerSpecies(ForestryBeeSpecies.VINDICTIVE, GENUS_VENGEFUL, SPECIES_VINDICTIVE, false, TextColor.fromRgb(0xeafff3)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.IRRADIATED), 0.25f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_NORMAL); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.DEMONIC, 4); + mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.DEMONIC, 0.04f); }) .setSecret(true); // Vengeful - apiculture.registerSpecies(ForestryBeeSpecies.VENGEFUL, GENUS_VENGEFUL, SPECIES_VENGEFUL, false, new Color(0xc2de00)) + apiculture.registerSpecies(ForestryBeeSpecies.VENGEFUL, GENUS_VENGEFUL, SPECIES_VENGEFUL, false, TextColor.fromRgb(0xc2de00)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.IRRADIATED), 0.40f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_NORMAL); genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONGER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.DEMONIC, ForestryBeeSpecies.VINDICTIVE, 8); - mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.VINDICTIVE, 8); + mutations.add(ForestryBeeSpecies.DEMONIC, ForestryBeeSpecies.VINDICTIVE, 0.08f); + mutations.add(ForestryBeeSpecies.MONASTIC, ForestryBeeSpecies.VINDICTIVE, 0.08f); }) .setSecret(true); // Avenging - apiculture.registerSpecies(ForestryBeeSpecies.AVENGING, GENUS_VENGEFUL, SPECIES_AVENGING, false, new Color(0xddff00)) + apiculture.registerSpecies(ForestryBeeSpecies.AVENGING, GENUS_VENGEFUL, SPECIES_AVENGING, false, TextColor.fromRgb(0xddff00)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.IRRADIATED), 0.40f) .setGenome(genome -> { genome.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWEST); genome.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_LONGEST); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.VENGEFUL, ForestryBeeSpecies.VINDICTIVE, 4); + mutations.add(ForestryBeeSpecies.VENGEFUL, ForestryBeeSpecies.VINDICTIVE, 0.04f); }) .setGlint(true) .setSecret(true); */ // Leporine (Easter secret) - apiculture.registerSpecies(ForestryBeeSpecies.LEPORINE, GENUS_FESTIVE, SPECIES_LEPORINE, false, new Color(0xfeff8f)) - .setBody(new Color(0x3cd757)) + apiculture.registerSpecies(ForestryBeeSpecies.LEPORINE, GENUS_FESTIVE, SPECIES_LEPORINE, false, TextColor.fromRgb(0xfeff8f)) + .setBody(TextColor.fromRgb(0x3cd757)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.SILKY), 0.30f) .addProduct(new ItemStack(Items.EGG), 0.10F) .setGenome(genome -> { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_EASTER); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.MEADOWS, ForestryBeeSpecies.FOREST, 10) + mutations.add(ForestryBeeSpecies.MEADOWS, ForestryBeeSpecies.FOREST, 0.10f) .restrictDateRange(Month.MARCH, 29, Month.APRIL, 15); }) .setGlint(true) .setSecret(true); // Merry (Christmas secret) - apiculture.registerSpecies(ForestryBeeSpecies.MERRY, GENUS_FESTIVE, SPECIES_MERRY, false, new Color(0xffffff)) - .setBody(new Color(0xd40000)) + apiculture.registerSpecies(ForestryBeeSpecies.MERRY, GENUS_FESTIVE, SPECIES_MERRY, false, TextColor.fromRgb(0xffffff)) + .setBody(TextColor.fromRgb(0xd40000)) .setTemperature(TemperatureType.ICY) .addProduct(BEE_COMBS.stack(EnumHoneyComb.FROZEN), 0.30f) .addProduct(CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.ICE_SHARD), 0.20f) @@ -977,15 +976,15 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_SNOWING); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.WINTRY, ForestryBeeSpecies.FOREST, 10) + mutations.add(ForestryBeeSpecies.WINTRY, ForestryBeeSpecies.FOREST, 0.10f) .restrictDateRange(Month.DECEMBER, 21, Month.DECEMBER, 27); }) .setGlint(true) .setSecret(true); // Tipsy (New Year's secret) - apiculture.registerSpecies(ForestryBeeSpecies.TIPSY, GENUS_FESTIVE, SPECIES_TIPSY, false, new Color(0xffffff)) - .setBody(new Color(0xc219ec)) + apiculture.registerSpecies(ForestryBeeSpecies.TIPSY, GENUS_FESTIVE, SPECIES_TIPSY, false, TextColor.fromRgb(0xffffff)) + .setBody(TextColor.fromRgb(0xc219ec)) .setTemperature(TemperatureType.ICY) .addProduct(BEE_COMBS.stack(EnumHoneyComb.FROZEN), 0.30f) .addProduct(CoreItems.CRAFTING_MATERIALS.stack(EnumCraftingMaterial.ICE_SHARD), 0.20f) @@ -994,7 +993,7 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_DRUNKARD); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.WINTRY, ForestryBeeSpecies.MEADOWS, 10) + mutations.add(ForestryBeeSpecies.WINTRY, ForestryBeeSpecies.MEADOWS, 0.10f) .restrictDateRange(Month.DECEMBER, 27, Month.JANUARY, 2); }) .setGlint(true) @@ -1003,8 +1002,8 @@ public static void register(IApicultureRegistration apiculture) { // todo Solstice (Winter Solstice secret) // Tricky (Halloween secret) - apiculture.registerSpecies(ForestryBeeSpecies.TRICKY, GENUS_FESTIVE, SPECIES_TRICKY, false, new Color(0x49413B)) - .setBody(new Color(0xFF6A00)) + apiculture.registerSpecies(ForestryBeeSpecies.TRICKY, GENUS_FESTIVE, SPECIES_TRICKY, false, TextColor.fromRgb(0x49413B)) + .setBody(TextColor.fromRgb(0xFF6A00)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.HONEY), 0.40f) .addProduct(new ItemStack(Items.COOKIE), 0.15f) .addSpecialty(new ItemStack(Items.SKELETON_SKULL), 0.02f) @@ -1017,7 +1016,7 @@ public static void register(IApicultureRegistration apiculture) { genome.set(BeeChromosomes.FLOWER_TYPE, ForestryAlleles.FLOWER_TYPE_GOURD); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.SINISTER, ForestryBeeSpecies.COMMON, 10) + mutations.add(ForestryBeeSpecies.SINISTER, ForestryBeeSpecies.COMMON, 0.10f) .restrictDateRange(Month.OCTOBER, 15, Month.NOVEMBER, 3); }) .setGlint(true) @@ -1028,12 +1027,11 @@ public static void register(IApicultureRegistration apiculture) { // todo Bissextile (Leap Year secret) // American (July 4th secret) - apiculture.registerSpecies(ForestryBeeSpecies.PATRIOTIC, GENUS_FESTIVE, SPECIES_PATRIOTIC, true, new Color(0x0a3161)) - .setBody(new Color(0xb31942)) - .setStripes(new Color(0xffffff)) + apiculture.registerSpecies(ForestryBeeSpecies.PATRIOTIC, GENUS_FESTIVE, SPECIES_PATRIOTIC, true, TextColor.fromRgb(0x0a3161)) + .setBody(TextColor.fromRgb(0xb31942)) + .setStripes(TextColor.fromRgb(0xffffff)) .addProduct(BEE_COMBS.stack(EnumHoneyComb.POWDERY), 0.45f) .addProduct(new FireworkProduct(0.20f)) - // todo specialty is a random firework .setGenome(genome -> { genome.set(BeeChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_UP_2); genome.set(BeeChromosomes.HUMIDITY_TOLERANCE, ForestryAlleles.TOLERANCE_UP_1); @@ -1043,7 +1041,7 @@ public static void register(IApicultureRegistration apiculture) { //genome.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_PATRIOTIC); }) .addMutations(mutations -> { - mutations.add(ForestryBeeSpecies.RURAL, ForestryBeeSpecies.NOBLE, 15) + mutations.add(ForestryBeeSpecies.RURAL, ForestryBeeSpecies.NOBLE, 0.15f) .restrictDateRange(Month.JULY, 1, Month.JULY, 17); }) .setAuthority("TheDarkColour") diff --git a/src/main/java/forestry/plugin/DefaultButterflySpecies.java b/src/main/java/forestry/plugin/DefaultButterflySpecies.java index 37a6a98e84..7195c73f84 100644 --- a/src/main/java/forestry/plugin/DefaultButterflySpecies.java +++ b/src/main/java/forestry/plugin/DefaultButterflySpecies.java @@ -6,8 +6,7 @@ import forestry.api.genetics.alleles.ForestryAlleles; import forestry.api.lepidopterology.ForestryButterflySpecies; import forestry.api.plugin.ILepidopterologyRegistration; - -import java.awt.*; +import net.minecraft.network.chat.TextColor; import static forestry.api.genetics.ForestryTaxa.*; @@ -15,39 +14,39 @@ public class DefaultButterflySpecies { @SuppressWarnings("CodeBlock2Expr") public static void register(ILepidopterologyRegistration butterflies) { // Cabbage White - butterflies.registerSpecies(ForestryButterflySpecies.CABBAGE_WHITE, GENUS_PIERIS, SPECIES_CABBAGE_WHITE, true, new Color(0xccffee), 1.0f) + butterflies.registerSpecies(ForestryButterflySpecies.CABBAGE_WHITE, GENUS_PIERIS, SPECIES_CABBAGE_WHITE, true, TextColor.fromRgb(0xccffee), 1.0f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_AVERAGE); }); // Brimstone (Common Brimstone) - butterflies.registerSpecies(ForestryButterflySpecies.BRIMSTONE, GENUS_GONEPTERYX, SPECIES_BRIMSTONE, true, new Color(0xf0ee38), 1.0f); + butterflies.registerSpecies(ForestryButterflySpecies.BRIMSTONE, GENUS_GONEPTERYX, SPECIES_BRIMSTONE, true, TextColor.fromRgb(0xf0ee38), 1.0f); - butterflies.registerSpecies(ForestryButterflySpecies.AURORA, GENUS_ANTHOCHARIS, SPECIES_AURORA, true, new Color(0xe34f05), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.AURORA, GENUS_ANTHOCHARIS, SPECIES_AURORA, true, TextColor.fromRgb(0xe34f05), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLER); }); // Clouded Yellow - butterflies.registerSpecies(ForestryButterflySpecies.CLOUDED_YELLOW, GENUS_COLIAS, SPECIES_CLOUDED_YELLOW, true, new Color(0xd77e04), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.CLOUDED_YELLOW, GENUS_COLIAS, SPECIES_CLOUDED_YELLOW, true, TextColor.fromRgb(0xd77e04), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOW); }); // Palaeno Sulphur - butterflies.registerSpecies(ForestryButterflySpecies.PALAENO_SULPHUR, GENUS_COLIAS, SPECIES_PALAENO_SULPHUR, true, new Color(0xf8fba3), 0.4f) + butterflies.registerSpecies(ForestryButterflySpecies.PALAENO_SULPHUR, GENUS_COLIAS, SPECIES_PALAENO_SULPHUR, true, TextColor.fromRgb(0xf8fba3), 0.4f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); }); // Reseda (Eastern Bath White) - butterflies.registerSpecies(ForestryButterflySpecies.RESEDA, GENUS_PONTIA, SPECIES_RESEDA, true, new Color(0x747d48), 0.3f) + butterflies.registerSpecies(ForestryButterflySpecies.RESEDA, GENUS_PONTIA, SPECIES_RESEDA, true, TextColor.fromRgb(0x747d48), 0.3f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); }); // Spring Azure - butterflies.registerSpecies(ForestryButterflySpecies.SPRING_AZURE, GENUS_CELASTRINA, SPECIES_SPRING_AZURE, true, new Color(0xb8cae2), 0.3f) + butterflies.registerSpecies(ForestryButterflySpecies.SPRING_AZURE, GENUS_CELASTRINA, SPECIES_SPRING_AZURE, true, TextColor.fromRgb(0xb8cae2), 0.3f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLER); genome.set(ButterflyChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORT); @@ -55,14 +54,14 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Gozora Azure (Mexican Azure) - butterflies.registerSpecies(ForestryButterflySpecies.GOZORA_AZURE, GENUS_CELASTRINA, SPECIES_GOZORA_AZURE, true, new Color(0x6870e7), 0.2f) + butterflies.registerSpecies(ForestryButterflySpecies.GOZORA_AZURE, GENUS_CELASTRINA, SPECIES_GOZORA_AZURE, true, TextColor.fromRgb(0x6870e7), 0.2f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLER); genome.set(ButterflyChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORT); }); // Citrus Swallowtail - butterflies.registerSpecies(ForestryButterflySpecies.CITRUS_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_CITRUS_SWALLOWTAIL, false, new Color(0xeae389), 1.0f) + butterflies.registerSpecies(ForestryButterflySpecies.CITRUS_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_CITRUS_SWALLOWTAIL, false, TextColor.fromRgb(0xeae389), 1.0f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -76,7 +75,7 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Emerald Peacock (Emerald Swallowtail) - butterflies.registerSpecies(ForestryButterflySpecies.EMERALD_PEACOCK, GENUS_PAPILIO, SPECIES_EMERALD_PEACOCK, true, new Color(0x7cfe80), 0.1f) + butterflies.registerSpecies(ForestryButterflySpecies.EMERALD_PEACOCK, GENUS_PAPILIO, SPECIES_EMERALD_PEACOCK, true, TextColor.fromRgb(0x7cfe80), 0.1f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -88,7 +87,7 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // King Swallowtail - butterflies.registerSpecies(ForestryButterflySpecies.THOAS_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_THOAS_SWALLOWTAIL, false, new Color(0xeac783), 0.2f) + butterflies.registerSpecies(ForestryButterflySpecies.THOAS_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_THOAS_SWALLOWTAIL, false, TextColor.fromRgb(0xeac783), 0.2f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -98,7 +97,7 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Spicebush Swallowtail - butterflies.registerSpecies(ForestryButterflySpecies.SPICEBUSH_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_SPICEBUSH_SWALLOWTAIL, true, new Color(0xeefeff), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.SPICEBUSH_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_SPICEBUSH_SWALLOWTAIL, true, TextColor.fromRgb(0xeefeff), 0.5f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -106,7 +105,7 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Black Swallowtail - butterflies.registerSpecies(ForestryButterflySpecies.BLACK_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_BLACK_SWALLOWTAIL, true, new Color(0xeac783), 1.0f) + butterflies.registerSpecies(ForestryButterflySpecies.BLACK_SWALLOWTAIL, GENUS_PAPILIO, SPECIES_BLACK_SWALLOWTAIL, true, TextColor.fromRgb(0xeac783), 1.0f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOW); genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_LARGE); @@ -116,14 +115,14 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Zebra Swallowtail - butterflies.registerSpecies(ForestryButterflySpecies.ZEBRA_SWALLOWTAIL, GENUS_PROTOGRAPHIUM, SPECIES_ZEBRA_SWALLOWTAIL, true, new Color(0xeafeff), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.ZEBRA_SWALLOWTAIL, GENUS_PROTOGRAPHIUM, SPECIES_ZEBRA_SWALLOWTAIL, true, TextColor.fromRgb(0xeafeff), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_AVERAGE); }); // Glasswing - butterflies.registerSpecies(ForestryButterflySpecies.GLASSWING, GENUS_GRETA, SPECIES_GLASSWING, true, new Color(0x583732), 0.1f) + butterflies.registerSpecies(ForestryButterflySpecies.GLASSWING, GENUS_GRETA, SPECIES_GLASSWING, true, TextColor.fromRgb(0x583732), 0.1f) .setTemperature(TemperatureType.WARM) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLER); @@ -133,25 +132,25 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Speckled Wood - butterflies.registerSpecies(ForestryButterflySpecies.SPECKLED_WOOD, GENUS_PARARGE, SPECIES_SPECKLED_WOOD, true, new Color(0x947245), 1.0f) + butterflies.registerSpecies(ForestryButterflySpecies.SPECKLED_WOOD, GENUS_PARARGE, SPECIES_SPECKLED_WOOD, true, TextColor.fromRgb(0x947245), 1.0f) .setGenome(genome -> { genome.set(ButterflyChromosomes.FERTILITY, ForestryAlleles.FERTILITY_2); }); // Madeiran Speckled Wood - butterflies.registerSpecies(ForestryButterflySpecies.MADEIRAN_SPECKLED_WOOD, GENUS_PARARGE, SPECIES_MADEIRAN_SPECKLED_WOOD, true, new Color(0x402919), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.MADEIRAN_SPECKLED_WOOD, GENUS_PARARGE, SPECIES_MADEIRAN_SPECKLED_WOOD, true, TextColor.fromRgb(0x402919), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.FERTILITY, ForestryAlleles.FERTILITY_2); }); // Canary Speckled Wood - butterflies.registerSpecies(ForestryButterflySpecies.CANARY_SPECKLED_WOOD, GENUS_PARARGE, SPECIES_CANARY_SPECKLED_WOOD, true, new Color(0x51372a), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.CANARY_SPECKLED_WOOD, GENUS_PARARGE, SPECIES_CANARY_SPECKLED_WOOD, true, TextColor.fromRgb(0x51372a), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.FERTILITY, ForestryAlleles.FERTILITY_2); }); // Menelaus Blue Morpho - butterflies.registerSpecies(ForestryButterflySpecies.MENELAUS_BLUE_MORPHO, GENUS_MORPHO, SPECIES_MENELAUS_BLUE_MORPHO, true, new Color(0x72e1fd), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.MENELAUS_BLUE_MORPHO, GENUS_MORPHO, SPECIES_MENELAUS_BLUE_MORPHO, true, TextColor.fromRgb(0x72e1fd), 0.5f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -161,7 +160,7 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Peleides Blue Morpho - butterflies.registerSpecies(ForestryButterflySpecies.PELEIDES_BLUE_MORPHO, GENUS_MORPHO, SPECIES_PELEIDES_BLUE_MORPHO, true, new Color(0x6ecce8), 0.25f) + butterflies.registerSpecies(ForestryButterflySpecies.PELEIDES_BLUE_MORPHO, GENUS_MORPHO, SPECIES_PELEIDES_BLUE_MORPHO, true, TextColor.fromRgb(0x6ecce8), 0.25f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -171,7 +170,7 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Rhetenor Blue Morpho - butterflies.registerSpecies(ForestryButterflySpecies.RHETENOR_BLUE_MORPHO, GENUS_MORPHO, SPECIES_RHETENOR_BLUE_MORPHO, true, new Color(0x00bef8), 0.1f) + butterflies.registerSpecies(ForestryButterflySpecies.RHETENOR_BLUE_MORPHO, GENUS_MORPHO, SPECIES_RHETENOR_BLUE_MORPHO, true, TextColor.fromRgb(0x00bef8), 0.1f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -181,13 +180,13 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Comma - butterflies.registerSpecies(ForestryButterflySpecies.COMMA, GENUS_POLYGONIA, SPECIES_COMMA, true, new Color(0xf89505), 0.3f) + butterflies.registerSpecies(ForestryButterflySpecies.COMMA, GENUS_POLYGONIA, SPECIES_COMMA, true, TextColor.fromRgb(0xf89505), 0.3f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); }); // Batesia hypochlora - butterflies.registerSpecies(ForestryButterflySpecies.BATESIA, GENUS_BATESIA, SPECIES_BATESIA, true, new Color(0xfe7763), 0.3f) + butterflies.registerSpecies(ForestryButterflySpecies.BATESIA, GENUS_BATESIA, SPECIES_BATESIA, true, TextColor.fromRgb(0xfe7763), 0.3f) .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.DAMP) .setGenome(genome -> { @@ -195,36 +194,36 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Mexican Bluewing - butterflies.registerSpecies(ForestryButterflySpecies.BLUE_WING, GENUS_MYSCELIA, SPECIES_BLUE_WING, true, new Color(0x3a93cc), 0.3f) + butterflies.registerSpecies(ForestryButterflySpecies.BLUE_WING, GENUS_MYSCELIA, SPECIES_BLUE_WING, true, TextColor.fromRgb(0x3a93cc), 0.3f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_AVERAGE); genome.set(ButterflyChromosomes.METABOLISM, ForestryAlleles.METABOLISM_NORMAL); }); // Monarch - butterflies.registerSpecies(ForestryButterflySpecies.MONARCH, GENUS_DANAUS, SPECIES_MONARCH, true, new Color(0xffa722), 0.2f) + butterflies.registerSpecies(ForestryButterflySpecies.MONARCH, GENUS_DANAUS, SPECIES_MONARCH, true, TextColor.fromRgb(0xffa722), 0.2f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_AVERAGE); }); // Blue Duke - butterflies.registerSpecies(ForestryButterflySpecies.BLUE_DUKE, GENUS_BASSARONA, SPECIES_BLUE_DUKE, true, new Color(0x304240), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.BLUE_DUKE, GENUS_BASSARONA, SPECIES_BLUE_DUKE, true, TextColor.fromRgb(0x304240), 0.5f) .setTemperature(TemperatureType.COLD) .setGenome(genome -> { genome.set(ButterflyChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_BOTH_1); }); // Glassy Tiger - butterflies.registerSpecies(ForestryButterflySpecies.GLASSY_TIGER, GENUS_PARANTICA, SPECIES_GLASSY_TIGER, true, new Color(0x5b3935), 0.3f) + butterflies.registerSpecies(ForestryButterflySpecies.GLASSY_TIGER, GENUS_PARANTICA, SPECIES_GLASSY_TIGER, true, TextColor.fromRgb(0x5b3935), 0.3f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_AVERAGE); }); // Postman - butterflies.registerSpecies(ForestryButterflySpecies.POSTMAN, GENUS_HELICONIUS, SPECIES_POSTMAN, true, new Color(0xf7302d), 0.3f); + butterflies.registerSpecies(ForestryButterflySpecies.POSTMAN, GENUS_HELICONIUS, SPECIES_POSTMAN, true, TextColor.fromRgb(0xf7302d), 0.3f); // Malachite - butterflies.registerSpecies(ForestryButterflySpecies.MALACHITE, GENUS_SIPROETA, SPECIES_MALACHITE, true, new Color(0xbdff53), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.MALACHITE, GENUS_SIPROETA, SPECIES_MALACHITE, true, TextColor.fromRgb(0xbdff53), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_AVERAGE); genome.set(ButterflyChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_DOWN_1); @@ -232,36 +231,36 @@ public static void register(ILepidopterologyRegistration butterflies) { }); // Leopard Lacewing - butterflies.registerSpecies(ForestryButterflySpecies.LEOPARD_LACEWING, GENUS_CETHOSIA, SPECIES_LEOPARD_LACEWING, true, new Color(0xfb8a06), 0.7f) + butterflies.registerSpecies(ForestryButterflySpecies.LEOPARD_LACEWING, GENUS_CETHOSIA, SPECIES_LEOPARD_LACEWING, true, TextColor.fromRgb(0xfb8a06), 0.7f) .setGenome(genome -> { genome.set(ButterflyChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_UP_1); genome.set(ButterflyChromosomes.HUMIDITY_TOLERANCE, ForestryAlleles.TOLERANCE_UP_1); }); // Diana Fritillary - butterflies.registerSpecies(ForestryButterflySpecies.DIANA_FRITILLARY, GENUS_SPEYERIA, SPECIES_DIANA_FRITILLARY, true, new Color(0xffac05), 0.6f) + butterflies.registerSpecies(ForestryButterflySpecies.DIANA_FRITILLARY, GENUS_SPEYERIA, SPECIES_DIANA_FRITILLARY, true, TextColor.fromRgb(0xffac05), 0.6f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLER); }); // Brimstone Moth (different than the Common Brimstone Butterfly) - butterflies.registerSpecies(ForestryButterflySpecies.BRIMSTONE_MOTH, GENUS_OPISTHOGRAPTIS, SPECIES_BRIMSTONE_MOTH, true, new Color(0xffea40), 1.0f); + butterflies.registerSpecies(ForestryButterflySpecies.BRIMSTONE_MOTH, GENUS_OPISTHOGRAPTIS, SPECIES_BRIMSTONE_MOTH, true, TextColor.fromRgb(0xffea40), 1.0f); // Latticed Heath Moth - butterflies.registerSpecies(ForestryButterflySpecies.LATTICED_HEATH, GENUS_CHIASMIA, SPECIES_LATTICED_HEATH, true, new Color(0xf2f0be), 0.5f) + butterflies.registerSpecies(ForestryButterflySpecies.LATTICED_HEATH, GENUS_CHIASMIA, SPECIES_LATTICED_HEATH, true, TextColor.fromRgb(0xf2f0be), 0.5f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLEST); }); // Atlas Moth - butterflies.registerSpecies(ForestryButterflySpecies.ATLAS, GENUS_ATTACUS, SPECIES_ATLAS, false, new Color(0xd96e3d), 0.1f) + butterflies.registerSpecies(ForestryButterflySpecies.ATLAS, GENUS_ATTACUS, SPECIES_ATLAS, false, TextColor.fromRgb(0xd96e3d), 0.1f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_LARGEST); }); // Domestic Silk Moth - butterflies.registerSpecies(ForestryButterflySpecies.BOMBYX_MORI, GENUS_BOMBYX, SPECIES_BOMBYX_MORI, false, new Color(0xDADADA), 0.1f) + butterflies.registerSpecies(ForestryButterflySpecies.BOMBYX_MORI, GENUS_BOMBYX, SPECIES_BOMBYX_MORI, false, TextColor.fromRgb(0xDADADA), 0.1f) .setGenome(genome -> { genome.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALLEST); genome.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWER); diff --git a/src/main/java/forestry/plugin/DefaultFarms.java b/src/main/java/forestry/plugin/DefaultFarms.java index d3e7cf92ec..af23370023 100644 --- a/src/main/java/forestry/plugin/DefaultFarms.java +++ b/src/main/java/forestry/plugin/DefaultFarms.java @@ -1,6 +1,6 @@ package forestry.plugin; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.core.IProduct; diff --git a/src/main/java/forestry/plugin/DefaultForestryPlugin.java b/src/main/java/forestry/plugin/DefaultForestryPlugin.java index d4b6d1ba13..a0e941d3b9 100644 --- a/src/main/java/forestry/plugin/DefaultForestryPlugin.java +++ b/src/main/java/forestry/plugin/DefaultForestryPlugin.java @@ -2,11 +2,12 @@ import forestry.api.ForestryConstants; import forestry.api.ForestryTags; -import forestry.api.apiculture.*; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.ForestryActivityTypes; +import forestry.api.apiculture.ForestryBeeEffects; +import forestry.api.apiculture.ForestryBeeSpecies; +import forestry.api.apiculture.ForestryFlowerTypes; +import forestry.api.apiculture.bee.LightPreference; import forestry.api.arboriculture.ForestryFruits; -import forestry.api.arboriculture.ForestryTreeSpecies; -import forestry.api.arboriculture.genetics.TreeLifeStage; import forestry.api.circuits.ForestryCircuitLayouts; import forestry.api.circuits.ForestryCircuitSocketTypes; import forestry.api.client.plugin.IClientRegistration; @@ -14,30 +15,20 @@ import forestry.api.core.IError; import forestry.api.core.Product; import forestry.api.farming.ForestryFarmTypes; -import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.genetics.alleles.BeeChromosomes; -import forestry.api.genetics.alleles.ButterflyChromosomes; import forestry.api.genetics.alleles.ForestryAlleles; -import forestry.api.genetics.alleles.TreeChromosomes; -import forestry.api.lepidopterology.ForestryButterflySpecies; -import forestry.api.lepidopterology.genetics.ButterflyLifeStage; import forestry.api.plugin.*; import forestry.apiculture.*; import forestry.apiculture.features.ApicultureEffects; import forestry.apiculture.features.ApicultureItems; -import forestry.apiculture.genetics.BeeSpeciesType; import forestry.apiculture.genetics.effects.*; import forestry.apiculture.hives.HiveDefinition; import forestry.apiculture.items.EnumHoneyComb; -import forestry.arboriculture.ArboricultureFilterRuleType; -import forestry.arboriculture.DummyFruit; -import forestry.arboriculture.PodFruit; -import forestry.arboriculture.RipeningFruit; +import forestry.arboriculture.*; import forestry.arboriculture.blocks.ForestryPodType; import forestry.arboriculture.genetics.BlossomingTreeEffect; import forestry.arboriculture.genetics.DummyTreeEffect; import forestry.arboriculture.genetics.TreePollenType; -import forestry.arboriculture.genetics.TreeSpeciesType; import forestry.core.features.CoreItems; import forestry.core.items.ItemFruit; import forestry.core.items.definitions.EnumCraftingMaterial; @@ -47,7 +38,6 @@ import forestry.lepidopterology.DummyButterflyEffect; import forestry.lepidopterology.LepidopterologyFilterRule; import forestry.lepidopterology.LepidopterologyFilterRuleType; -import forestry.lepidopterology.genetics.ButterflySpeciesType; import forestry.lepidopterology.genetics.DefaultCocoon; import forestry.plugin.client.DefaultForestryClientRegistration; import forestry.sorting.DefaultFilterRuleType; @@ -67,94 +57,6 @@ public class DefaultForestryPlugin implements IForestryPlugin { @Override public void registerGenetics(IGeneticRegistration genetics) { - // Bee type - genetics.registerSpeciesType(ForestrySpeciesTypes.BEE, BeeSpeciesType::new) - .setKaryotype(karyotype -> { - karyotype.setSpecies(BeeChromosomes.SPECIES, ForestryBeeSpecies.FOREST); - karyotype.set(BeeChromosomes.SPEED, ForestryAlleles.SPEED_SLOWEST) - .addAlleles(ForestryAlleles.DEFAULT_SPEEDS); - karyotype.set(BeeChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORTER) - .addAlleles(ForestryAlleles.DEFAULT_LIFESPANS); - karyotype.set(BeeChromosomes.FERTILITY, ForestryAlleles.FERTILITY_2) - .addAlleles(ForestryAlleles.DEFAULT_BEE_FERTILITIES); - karyotype.set(BeeChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) - .addAlleles(ForestryAlleles.DEFAULT_TEMPERATURE_TOLERANCES) - .setWeaklyInherited(true); - karyotype.set(BeeChromosomes.HUMIDITY_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) - .addAlleles(ForestryAlleles.DEFAULT_HUMIDITY_TOLERANCES) - .setWeaklyInherited(true); - karyotype.set(BeeChromosomes.ACTIVITY, ForestryAlleles.ACTIVITY_DIURNAL) - .setWeaklyInherited(true); - karyotype.set(BeeChromosomes.CAVE_DWELLING, false) - .setWeaklyInherited(true); - karyotype.set(BeeChromosomes.TOLERATES_RAIN, false) - .setWeaklyInherited(true); - karyotype.set(BeeChromosomes.FLOWER_TYPE, ForestryAlleles.FLOWER_TYPE_VANILLA); - karyotype.set(BeeChromosomes.TERRITORY, ForestryAlleles.TERRITORY_AVERAGE) - .addAlleles(ForestryAlleles.DEFAULT_TERRITORIES); - karyotype.set(BeeChromosomes.EFFECT, ForestryAlleles.EFFECT_NONE); - karyotype.set(BeeChromosomes.POLLINATION, ForestryAlleles.POLLINATION_SLOWEST) - .addAlleles(ForestryAlleles.DEFAULT_POLLINATIONS); - }) - .addStages(BeeLifeStage.DRONE, BeeLifeStage.PRINCESS, BeeLifeStage.QUEEN, BeeLifeStage.LARVAE) - .setDefaultStage(BeeLifeStage.DRONE); - - // Tree type - genetics.registerSpeciesType(ForestrySpeciesTypes.TREE, TreeSpeciesType::new) - .setKaryotype(karyotype -> { - karyotype.setSpecies(TreeChromosomes.SPECIES, ForestryTreeSpecies.OAK); - karyotype.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_SMALL) - .addAlleles(ForestryAlleles.DEFAULT_HEIGHTS); - karyotype.set(TreeChromosomes.SAPLINGS, ForestryAlleles.SAPLINGS_LOWER) - .addAlleles(ForestryAlleles.DEFAULT_SAPLINGS); - karyotype.set(TreeChromosomes.FRUIT, ForestryAlleles.FRUIT_NONE); - karyotype.set(TreeChromosomes.YIELD, ForestryAlleles.YIELD_LOWEST) - .addAlleles(ForestryAlleles.DEFAULT_YIELDS); - karyotype.set(TreeChromosomes.SAPPINESS, ForestryAlleles.SAPPINESS_LOWEST) - .addAlleles(ForestryAlleles.DEFAULT_SAPPINESSES); - karyotype.set(TreeChromosomes.EFFECT, ForestryAlleles.TREE_EFFECT_NONE); - karyotype.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_AVERAGE) - .addAlleles(ForestryAlleles.DEFAULT_MATURATIONS); - karyotype.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_1) - .addAlleles(ForestryAlleles.DEFAULT_GIRTHS); - karyotype.set(TreeChromosomes.FIREPROOF, false); - }) - .addStages(TreeLifeStage.SAPLING, TreeLifeStage.POLLEN) - .setDefaultStage(TreeLifeStage.SAPLING); - - // Butterfly type - genetics.registerSpeciesType(ForestrySpeciesTypes.BUTTERFLY, ButterflySpeciesType::new) - .setKaryotype(karyotype -> { - karyotype.setSpecies(ButterflyChromosomes.SPECIES, ForestryButterflySpecies.MONARCH); - karyotype.set(ButterflyChromosomes.SIZE, ForestryAlleles.SIZE_SMALL) - .addAlleles(ForestryAlleles.DEFAULT_SIZES); - karyotype.set(ButterflyChromosomes.SPEED, ForestryAlleles.SPEED_SLOWEST) - .addAlleles(ForestryAlleles.DEFAULT_SPEEDS); - karyotype.set(ButterflyChromosomes.LIFESPAN, ForestryAlleles.LIFESPAN_SHORTER) - .addAlleles(ForestryAlleles.DEFAULT_LIFESPANS); - karyotype.set(ButterflyChromosomes.METABOLISM, ForestryAlleles.METABOLISM_SLOWER) - .addAlleles(ForestryAlleles.DEFAULT_METABOLISMS); - karyotype.set(ButterflyChromosomes.FERTILITY, ForestryAlleles.FERTILITY_3) - .addAlleles(ForestryAlleles.DEFAULT_BUTTERFLY_FERTILITIES); - karyotype.set(ButterflyChromosomes.TEMPERATURE_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) - .addAlleles(ForestryAlleles.DEFAULT_TEMPERATURE_TOLERANCES) - .setWeaklyInherited(true); - karyotype.set(ButterflyChromosomes.HUMIDITY_TOLERANCE, ForestryAlleles.TOLERANCE_NONE) - .addAlleles(ForestryAlleles.DEFAULT_HUMIDITY_TOLERANCES) - .setWeaklyInherited(true); - karyotype.set(ButterflyChromosomes.NEVER_SLEEPS, false) - .setWeaklyInherited(true); - karyotype.set(ButterflyChromosomes.TOLERATES_RAIN, false) - .setWeaklyInherited(true); - karyotype.set(ButterflyChromosomes.FIREPROOF, false); - karyotype.set(ButterflyChromosomes.FLOWER_TYPE, ForestryAlleles.FLOWER_TYPE_VANILLA); - karyotype.set(ButterflyChromosomes.EFFECT, ForestryAlleles.BUTTERFLY_EFFECT_NONE); - karyotype.set(ButterflyChromosomes.COCOON, ForestryAlleles.COCOON_DEFAULT); - }) - .addStages(ButterflyLifeStage.BUTTERFLY, ButterflyLifeStage.SERUM, ButterflyLifeStage.CATERPILLAR, ButterflyLifeStage.COCOON) - .setDefaultStage(ButterflyLifeStage.BUTTERFLY) - .addResearchMaterials(map -> map.put(Items.GLASS_BOTTLE, 0.9f)); - // Taxonomy BeeTaxonomy.defineTaxa(genetics); TreeTaxonomy.defineTaxa(genetics); @@ -282,7 +184,7 @@ public void registerApiculture(IApicultureRegistration apiculture) { apiculture.registerBeeEffect(ForestryBeeEffects.FERTILE, new FertileBeeEffect()); apiculture.registerBeeEffect(ForestryBeeEffects.MYCOPHILIC, new FungificationBeeEffect()); apiculture.registerBeeEffect(ForestryBeeEffects.SIFTER, new SifterBeeEffect()); - apiculture.registerBeeEffect(ForestryBeeEffects.HAKUNA_MATATA, new PotionBeeEffectExclusive(false, ApicultureEffects.HAKUNA_MATATA.get(), 20 * 60 * 3, 100, 1.0f, ApicultureEffects.MATATA.get())); + apiculture.registerBeeEffect(ForestryBeeEffects.HAKUNA_MATATA, new PotionBeeEffectExclusive(false, ApicultureEffects.HAKUNA_MATATA, 20 * 60 * 3, 100, 1.0f, ApicultureEffects.MATATA)); apiculture.registerBeeEffect(ForestryBeeEffects.GLOW_BERRY_GROW, new GlowBerryGrowEffect()); apiculture.registerBeeEffect(ForestryBeeEffects.REJUVENATION, new AgingBeeEffect(false, false)); apiculture.registerBeeEffect(ForestryBeeEffects.CHRONOPHAGE, new AgingBeeEffect(false, true)); @@ -316,8 +218,7 @@ public void registerArboriculture(IArboricultureRegistration arboriculture) { arboriculture.registerFruit(ForestryFruits.NONE, new DummyFruit(false)); arboriculture.registerFruit(ForestryFruits.APPLE, new RipeningFruit(false, 10, pomes, 0xff2e2e, 0xe3f49c, List.of(Product.of(Items.APPLE)))); - // todo match vanilla cocoa and use fortune OR better yet, make pod fruits use actual loot tables - arboriculture.registerFruit(ForestryFruits.COCOA, new PodFruit(false, ForestryPodType.COCOA, List.of(Product.of(Items.COCOA_BEANS)))); + arboriculture.registerFruit(ForestryFruits.COCOA, new VanillaCocoaPodFruit(List.of(Product.of(Items.COCOA_BEANS)))); arboriculture.registerFruit(ForestryFruits.CHESTNUT, new RipeningFruit(true, 6, nuts, 0x7f333d, 0xc4d24a, List.of(Product.of(CoreItems.FRUITS.item(ItemFruit.EnumFruit.CHESTNUT))))); arboriculture.registerFruit(ForestryFruits.WALNUT, new RipeningFruit(true, 8, nuts, 0xfba248, 0xc4d24a, List.of(Product.of(CoreItems.FRUITS.item(ItemFruit.EnumFruit.WALNUT))))); arboriculture.registerFruit(ForestryFruits.CHERRY, new RipeningFruit(true, 10, berries, 0xff2e2e, 0xc4d24a, List.of(Product.of(CoreItems.FRUITS.item(ItemFruit.EnumFruit.CHERRY))))); diff --git a/src/main/java/forestry/plugin/DefaultTreeSpecies.java b/src/main/java/forestry/plugin/DefaultTreeSpecies.java index 2637636419..0419d6db39 100644 --- a/src/main/java/forestry/plugin/DefaultTreeSpecies.java +++ b/src/main/java/forestry/plugin/DefaultTreeSpecies.java @@ -11,19 +11,18 @@ import forestry.arboriculture.blocks.ForestryLeafType; import forestry.arboriculture.features.ArboricultureBlocks; import forestry.arboriculture.worldgen.*; +import net.minecraft.network.chat.TextColor; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Blocks; -import java.awt.*; - import static forestry.api.genetics.ForestryTaxa.*; // todo fix IRL inaccuracies public class DefaultTreeSpecies { public static void register(IArboricultureRegistration arboriculture) { // Oak (English Oak) - arboriculture.registerSpecies(ForestryTreeSpecies.OAK, GENUS_QUERCUS, SPECIES_OAK, false, new Color(4764952), VanillaWoodType.OAK) + arboriculture.registerSpecies(ForestryTreeSpecies.OAK, GENUS_QUERCUS, SPECIES_OAK, false, TextColor.fromRgb(4764952), VanillaWoodType.OAK) .setTreeFeature(FeatureTreeVanilla::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.OAK)) .addVanillaStates(Blocks.OAK_LEAVES.getStateDefinition().getPossibleStates()) @@ -37,7 +36,7 @@ public static void register(IArboricultureRegistration arboriculture) { }); // Dark Oak (Black Oak) - arboriculture.registerSpecies(ForestryTreeSpecies.DARK_OAK, GENUS_QUERCUS, SPECIES_DARK_OAK, false, new Color(4764952), VanillaWoodType.DARK_OAK) + arboriculture.registerSpecies(ForestryTreeSpecies.DARK_OAK, GENUS_QUERCUS, SPECIES_DARK_OAK, false, TextColor.fromRgb(4764952), VanillaWoodType.DARK_OAK) .setTreeFeature(FeatureTreeVanilla::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.DARK_OAK)) .addVanillaStates(Blocks.DARK_OAK_LEAVES.getStateDefinition().getPossibleStates()) @@ -52,7 +51,7 @@ public static void register(IArboricultureRegistration arboriculture) { .setAuthority("Binnie"); // Birch (Silver Birch) - arboriculture.registerSpecies(ForestryTreeSpecies.BIRCH, GENUS_BETULA, SPECIES_BIRCH, false, new Color(8431445), VanillaWoodType.BIRCH) + arboriculture.registerSpecies(ForestryTreeSpecies.BIRCH, GENUS_BETULA, SPECIES_BIRCH, false, TextColor.fromRgb(8431445), VanillaWoodType.BIRCH) .setTreeFeature(FeatureTreeVanilla::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.BIRCH)) .addVanillaStates(Blocks.BIRCH_LEAVES.getStateDefinition().getPossibleStates()) @@ -65,7 +64,7 @@ public static void register(IArboricultureRegistration arboriculture) { }); // Silver Lime - arboriculture.registerSpecies(ForestryTreeSpecies.LIME, GENUS_TILIA, SPECIES_LIME, true, new Color(0x5ea107), ForestryWoodType.LIME) + arboriculture.registerSpecies(ForestryTreeSpecies.LIME, GENUS_TILIA, SPECIES_LIME, true, TextColor.fromRgb(0x5ea107), ForestryWoodType.LIME) .setTreeFeature(FeatureSilverLime::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.LIME)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.LIME).block().getStateDefinition().getPossibleStates()) @@ -76,12 +75,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.YIELD, ForestryAlleles.YIELD_LOWER); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.BIRCH, ForestryTreeSpecies.OAK, 15); + mutations.add(ForestryTreeSpecies.BIRCH, ForestryTreeSpecies.OAK, 0.15f); }) .setRarity(0.005f); // Walnut (English Walnut) - arboriculture.registerSpecies(ForestryTreeSpecies.WALNUT, GENUS_JUGLANS, SPECIES_WALNUT, true, new Color(0x798c55), ForestryWoodType.WALNUT) + arboriculture.registerSpecies(ForestryTreeSpecies.WALNUT, GENUS_JUGLANS, SPECIES_WALNUT, true, TextColor.fromRgb(0x798c55), ForestryWoodType.WALNUT) .setTreeFeature(FeatureWalnut::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.WALNUT)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.WALNUT).block().getStateDefinition().getPossibleStates()) @@ -95,11 +94,11 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_2); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.HILL_CHERRY, 10); + mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.HILL_CHERRY, 0.10f); }); // Chestnut (Spanish Chestnut) - arboriculture.registerSpecies(ForestryTreeSpecies.CHESTNUT, GENUS_CASTANEA, SPECIES_CHESTNUT, true, new Color(0x5ea107), ForestryWoodType.CHESTNUT) + arboriculture.registerSpecies(ForestryTreeSpecies.CHESTNUT, GENUS_CASTANEA, SPECIES_CHESTNUT, true, TextColor.fromRgb(0x5ea107), ForestryWoodType.CHESTNUT) .setTreeFeature(FeatureChestnut::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.CHESTNUT)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.CHESTNUT).block().getStateDefinition().getPossibleStates()) @@ -112,13 +111,13 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_2); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.WALNUT, ForestryTreeSpecies.LIME, 10); - mutations.add(ForestryTreeSpecies.WALNUT, ForestryTreeSpecies.HILL_CHERRY, 10); + mutations.add(ForestryTreeSpecies.WALNUT, ForestryTreeSpecies.LIME, 0.10f); + mutations.add(ForestryTreeSpecies.WALNUT, ForestryTreeSpecies.HILL_CHERRY, 0.10f); }); // Hill Cherry (East Asian Cherry) // The real life version of this tree doesn't actually produce fruit. - arboriculture.registerSpecies(ForestryTreeSpecies.HILL_CHERRY, GENUS_PRUNUS, SPECIES_HILL_CHERRY, true, new Color(0xe691da), ForestryWoodType.HILL_CHERRY) + arboriculture.registerSpecies(ForestryTreeSpecies.HILL_CHERRY, GENUS_PRUNUS, SPECIES_HILL_CHERRY, true, TextColor.fromRgb(0xe691da), ForestryWoodType.HILL_CHERRY) .setTreeFeature(FeatureBushCherry::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.HILL_CHERRY)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.HILL_CHERRY).block().getStateDefinition().getPossibleStates()) @@ -131,14 +130,14 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_SMALLER); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.OAK, 10); - mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.BIRCH, 10); + mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.OAK, 0.10f); + mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.BIRCH, 0.10f); }) .setRarity(0.0015f); // Cherry Blossom (East Asian Cherry) // In real life, this is the same species as Hill Cherry. For the sake of keeping old content, we'll pretend they're different. - arboriculture.registerSpecies(ForestryTreeSpecies.CHERRY_VANILLA, GENUS_PRUNUS, SPECIES_CHERRY_VANILLA, true, new Color(0xf7b9dc), VanillaWoodType.CHERRY) + arboriculture.registerSpecies(ForestryTreeSpecies.CHERRY_VANILLA, GENUS_PRUNUS, SPECIES_CHERRY_VANILLA, true, TextColor.fromRgb(0xf7b9dc), VanillaWoodType.CHERRY) .setTreeFeature(FeatureCherryVanilla::new) .setDecorativeLeaves(new ItemStack(Items.CHERRY_LEAVES)) .addVanillaStates(Blocks.CHERRY_LEAVES.getStateDefinition().getPossibleStates()) @@ -153,7 +152,7 @@ public static void register(IArboricultureRegistration arboriculture) { }); // Lemon - arboriculture.registerSpecies(ForestryTreeSpecies.LEMON, GENUS_CITRUS, SPECIES_LEMON, true, new Color(0x88af54), ForestryWoodType.CITRUS) + arboriculture.registerSpecies(ForestryTreeSpecies.LEMON, GENUS_CITRUS, SPECIES_LEMON, true, TextColor.fromRgb(0x88af54), ForestryWoodType.CITRUS) .setTreeFeature(FeatureLemon::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.LEMON)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.LEMON).block().getStateDefinition().getPossibleStates()) @@ -166,11 +165,11 @@ public static void register(IArboricultureRegistration arboriculture) { }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.HILL_CHERRY, 5); + mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.HILL_CHERRY, 0.05f); }); // Plum (Common Plum) - arboriculture.registerSpecies(ForestryTreeSpecies.PLUM, GENUS_PRUNUS, SPECIES_PLUM, true, new Color(0x589246), ForestryWoodType.PLUM) + arboriculture.registerSpecies(ForestryTreeSpecies.PLUM, GENUS_PRUNUS, SPECIES_PLUM, true, TextColor.fromRgb(0x589246), ForestryWoodType.PLUM) .setTreeFeature(FeaturePlum::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.PLUM)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.PLUM).block().getStateDefinition().getPossibleStates()) @@ -184,12 +183,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_SMALLEST); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.LEMON, ForestryTreeSpecies.HILL_CHERRY, 5); + mutations.add(ForestryTreeSpecies.LEMON, ForestryTreeSpecies.HILL_CHERRY, 0.05f); }) .setRarity(0.005f); // Maple (Sugar Maple) - arboriculture.registerSpecies(ForestryTreeSpecies.MAPLE, GENUS_ACER, SPECIES_MAPLE, true, new Color(0xd4f425), ForestryWoodType.MAPLE) + arboriculture.registerSpecies(ForestryTreeSpecies.MAPLE, GENUS_ACER, SPECIES_MAPLE, true, TextColor.fromRgb(0xd4f425), ForestryWoodType.MAPLE) .setTreeFeature(FeatureMaple::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.MAPLE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.MAPLE).block().getStateDefinition().getPossibleStates()) @@ -200,12 +199,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_AVERAGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.LARCH, 5); + mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.LARCH, 0.05f); }) .setRarity(0.0025f); // Spruce (Norway Spruce) - arboriculture.registerSpecies(ForestryTreeSpecies.SPRUCE, GENUS_PICEA, SPECIES_SPRUCE, false, new Color(6396257), VanillaWoodType.SPRUCE) + arboriculture.registerSpecies(ForestryTreeSpecies.SPRUCE, GENUS_PICEA, SPECIES_SPRUCE, false, TextColor.fromRgb(6396257), VanillaWoodType.SPRUCE) .setTreeFeature(FeatureSpruce::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.SPRUCE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.SPRUCE).block().getStateDefinition().getPossibleStates()) @@ -221,7 +220,7 @@ public static void register(IArboricultureRegistration arboriculture) { }); // Larch (European Larch) - arboriculture.registerSpecies(ForestryTreeSpecies.LARCH, GENUS_LARIX, SPECIES_LARCH, true, new Color(0x698f90), ForestryWoodType.LARCH) + arboriculture.registerSpecies(ForestryTreeSpecies.LARCH, GENUS_LARIX, SPECIES_LARCH, true, TextColor.fromRgb(0x698f90), ForestryWoodType.LARCH) .setTreeFeature(FeatureLarch::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.LARCH)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.LARCH).block().getStateDefinition().getPossibleStates()) @@ -233,13 +232,13 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_AVERAGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.BIRCH, 10); - mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.OAK, 10); + mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.BIRCH, 0.10f); + mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.OAK, 0.10f); }) .setRarity(0.0025f); // Pine (Bull Pine) - arboriculture.registerSpecies(ForestryTreeSpecies.PINE, GENUS_PINUS, SPECIES_PINE, true, new Color(0xfeff8f), ForestryWoodType.PINE) + arboriculture.registerSpecies(ForestryTreeSpecies.PINE, GENUS_PINUS, SPECIES_PINE, true, TextColor.fromRgb(0xfeff8f), ForestryWoodType.PINE) .setTreeFeature(FeaturePine::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.PINE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.PINE).block().getStateDefinition().getPossibleStates()) @@ -251,12 +250,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_AVERAGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.LARCH, 10); + mutations.add(ForestryTreeSpecies.SPRUCE, ForestryTreeSpecies.LARCH, 0.10f); }) .setRarity(0.0025f); // Sequoia (Coast Redwood) - arboriculture.registerSpecies(ForestryTreeSpecies.SEQUOIA, GENUS_SEQUOIA, SPECIES_SEQUOIA, false, new Color(0x418e71), ForestryWoodType.SEQUOIA) + arboriculture.registerSpecies(ForestryTreeSpecies.SEQUOIA, GENUS_SEQUOIA, SPECIES_SEQUOIA, false, TextColor.fromRgb(0x418e71), ForestryWoodType.SEQUOIA) .setTreeFeature(FeatureSequoia::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.SEQUOIA)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.SEQUOIA).block().getStateDefinition().getPossibleStates()) @@ -269,11 +268,11 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.FIREPROOF, true); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.LARCH, ForestryTreeSpecies.PINE, 5); + mutations.add(ForestryTreeSpecies.LARCH, ForestryTreeSpecies.PINE, 0.05f); }); // Giant Sequoia - arboriculture.registerSpecies(ForestryTreeSpecies.GIANT_SEQUOIA, GENUS_SEQUOIADENDRON, SPECIES_GIANT_SEQUOIA, false, new Color(0x738434), ForestryWoodType.GIGANTEUM) + arboriculture.registerSpecies(ForestryTreeSpecies.GIANT_SEQUOIA, GENUS_SEQUOIADENDRON, SPECIES_GIANT_SEQUOIA, false, TextColor.fromRgb(0x738434), ForestryWoodType.GIGANTEUM) .setTreeFeature(FeatureGiganteum::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.GIANT_SEQUOIA)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.GIANT_SEQUOIA).block().getStateDefinition().getPossibleStates()) @@ -292,7 +291,7 @@ public static void register(IArboricultureRegistration arboriculture) { }); // Jungle (Might be based on Teak, not sure) - arboriculture.registerSpecies(ForestryTreeSpecies.JUNGLE, GENUS_TROPICAL, SPECIES_JUNGLE, false, new Color(4764952), VanillaWoodType.JUNGLE) + arboriculture.registerSpecies(ForestryTreeSpecies.JUNGLE, GENUS_TROPICAL, SPECIES_JUNGLE, false, TextColor.fromRgb(4764952), VanillaWoodType.JUNGLE) .setTreeFeature(FeatureJungle::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.JUNGLE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.JUNGLE).block().getStateDefinition().getPossibleStates()) @@ -308,7 +307,7 @@ public static void register(IArboricultureRegistration arboriculture) { }); // Teak - arboriculture.registerSpecies(ForestryTreeSpecies.TEAK, GENUS_TECTONA, SPECIES_TEAK, true, new Color(0xfeff8f), ForestryWoodType.TEAK) + arboriculture.registerSpecies(ForestryTreeSpecies.TEAK, GENUS_TECTONA, SPECIES_TEAK, true, TextColor.fromRgb(0xfeff8f), ForestryWoodType.TEAK) .setTreeFeature(FeatureTeak::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.TEAK)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.TEAK).block().getStateDefinition().getPossibleStates()) @@ -319,12 +318,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.SAPPINESS, ForestryAlleles.SAPPINESS_LOWER); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.DARK_OAK, ForestryTreeSpecies.JUNGLE, 10); + mutations.add(ForestryTreeSpecies.DARK_OAK, ForestryTreeSpecies.JUNGLE, 0.10f); }) .setRarity(0.0025f); // Ipe (Yellow Ipe) - arboriculture.registerSpecies(ForestryTreeSpecies.IPE, GENUS_HANDROANTHUS, SPECIES_IPE, true, new Color(0xfdd207), ForestryWoodType.IPE) + arboriculture.registerSpecies(ForestryTreeSpecies.IPE, GENUS_HANDROANTHUS, SPECIES_IPE, true, TextColor.fromRgb(0xfdd207), ForestryWoodType.IPE) .setTreeFeature(FeatureIpe::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.IPE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.IPE).block().getStateDefinition().getPossibleStates()) @@ -335,11 +334,11 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_2); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.TEAK, ForestryTreeSpecies.DARK_OAK, 10); + mutations.add(ForestryTreeSpecies.TEAK, ForestryTreeSpecies.DARK_OAK, 0.10f); }); // Kapok - arboriculture.registerSpecies(ForestryTreeSpecies.KAPOK, GENUS_CEIBA, SPECIES_KAPOK, true, new Color(0x89987b), ForestryWoodType.KAPOK) + arboriculture.registerSpecies(ForestryTreeSpecies.KAPOK, GENUS_CEIBA, SPECIES_KAPOK, true, TextColor.fromRgb(0x89987b), ForestryWoodType.KAPOK) .setTreeFeature(FeatureKapok::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.KAPOK)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.KAPOK).block().getStateDefinition().getPossibleStates()) @@ -350,11 +349,11 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_SLOW); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.JUNGLE, ForestryTreeSpecies.TEAK, 10); + mutations.add(ForestryTreeSpecies.JUNGLE, ForestryTreeSpecies.TEAK, 0.10f); }); // Ebony (Myrtle Ebony) - arboriculture.registerSpecies(ForestryTreeSpecies.EBONY, GENUS_DIOSPYROS, SPECIES_EBONY, true, new Color(0xa2d24a), ForestryWoodType.EBONY) + arboriculture.registerSpecies(ForestryTreeSpecies.EBONY, GENUS_DIOSPYROS, SPECIES_EBONY, true, TextColor.fromRgb(0xa2d24a), ForestryWoodType.EBONY) .setTreeFeature(FeatureEbony::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.EBONY)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.EBONY).block().getStateDefinition().getPossibleStates()) @@ -368,12 +367,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_3); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.DARK_OAK, ForestryTreeSpecies.KAPOK, 10); + mutations.add(ForestryTreeSpecies.DARK_OAK, ForestryTreeSpecies.KAPOK, 0.10f); }) .setRarity(0.0005f); // Zebrawood (Wood is called "zebrawood" but species is glassywood. should this be changed?) - arboriculture.registerSpecies(ForestryTreeSpecies.ZEBRAWOOD, GENUS_ASTRONIUM, SPECIES_ZEBRAWOOD, false, new Color(0xa2d24a), ForestryWoodType.ZEBRAWOOD) + arboriculture.registerSpecies(ForestryTreeSpecies.ZEBRAWOOD, GENUS_ASTRONIUM, SPECIES_ZEBRAWOOD, false, TextColor.fromRgb(0xa2d24a), ForestryWoodType.ZEBRAWOOD) .setTreeFeature(FeatureZebrawood::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.ZEBRAWOOD)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.ZEBRAWOOD).block().getStateDefinition().getPossibleStates()) @@ -385,12 +384,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_2); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.EBONY, ForestryTreeSpecies.POPLAR, 5); + mutations.add(ForestryTreeSpecies.EBONY, ForestryTreeSpecies.POPLAR, 0.05f); }) .setRarity(0.0005f); // Mahogany TODO taxonomy is wrong - arboriculture.registerSpecies(ForestryTreeSpecies.MAHOGANY, GENUS_MAHOGANY, SPECIES_MAHOGONY, true, new Color(0x8ab154), ForestryWoodType.MAHOGANY) + arboriculture.registerSpecies(ForestryTreeSpecies.MAHOGANY, GENUS_MAHOGANY, SPECIES_MAHOGONY, true, TextColor.fromRgb(0x8ab154), ForestryWoodType.MAHOGANY) .setTreeFeature(FeatureMahogany::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.MAHOGANY)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.MAHOGANY).block().getStateDefinition().getPossibleStates()) @@ -404,12 +403,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_2); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.KAPOK, ForestryTreeSpecies.EBONY, 10); + mutations.add(ForestryTreeSpecies.KAPOK, ForestryTreeSpecies.EBONY, 0.10f); }) .setRarity(0.0005f); // Vanilla Acacia TODO should probably switch with desert acacia since aneura are from Australia - arboriculture.registerSpecies(ForestryTreeSpecies.ACACIA_VANILLA, GENUS_ACACIA, SPECIES_ACACIA, true, new Color(0x616101), VanillaWoodType.ACACIA) + arboriculture.registerSpecies(ForestryTreeSpecies.ACACIA_VANILLA, GENUS_ACACIA, SPECIES_ACACIA, true, TextColor.fromRgb(0x616101), VanillaWoodType.ACACIA) .setTreeFeature(FeatureTreeVanilla::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.ACACIA_VANILLA)) .addVanillaStates(Blocks.ACACIA_LEAVES.getStateDefinition().getPossibleStates()) @@ -419,7 +418,7 @@ public static void register(IArboricultureRegistration arboriculture) { .setAuthority("Binnie"); // Desert Acacia - arboriculture.registerSpecies(ForestryTreeSpecies.DESERT_ACACIA, GENUS_ACACIA, SPECIES_DESERT_ACACIA, true, new Color(0x748C1C), ForestryWoodType.ACACIA_DESERT) + arboriculture.registerSpecies(ForestryTreeSpecies.DESERT_ACACIA, GENUS_ACACIA, SPECIES_DESERT_ACACIA, true, TextColor.fromRgb(0x748C1C), ForestryWoodType.ACACIA_DESERT) .setTreeFeature(FeatureAcacia::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.DESERT_ACACIA)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.DESERT_ACACIA).block().getStateDefinition().getPossibleStates()) @@ -427,12 +426,12 @@ public static void register(IArboricultureRegistration arboriculture) { .setTemperature(TemperatureType.WARM) .setHumidity(HumidityType.ARID) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.TEAK, ForestryTreeSpecies.BALSA, 10); + mutations.add(ForestryTreeSpecies.TEAK, ForestryTreeSpecies.BALSA, 0.10f); }) .setRarity(0.005f); // Padauk (African Padauk) - arboriculture.registerSpecies(ForestryTreeSpecies.PADAUK, GENUS_PTEROCARPUS, SPECIES_PADAUK, true, new Color(0xd0df8c), ForestryWoodType.PADAUK) + arboriculture.registerSpecies(ForestryTreeSpecies.PADAUK, GENUS_PTEROCARPUS, SPECIES_PADAUK, true, TextColor.fromRgb(0xd0df8c), ForestryWoodType.PADAUK) .setTreeFeature(FeaturePadauk::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.PADAUK)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.PADAUK).block().getStateDefinition().getPossibleStates()) @@ -443,12 +442,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_LARGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.ACACIA_VANILLA, ForestryTreeSpecies.JUNGLE, 10); + mutations.add(ForestryTreeSpecies.ACACIA_VANILLA, ForestryTreeSpecies.JUNGLE, 0.10f); }) .setRarity(0.005f); // Balsa - arboriculture.registerSpecies(ForestryTreeSpecies.BALSA, GENUS_OCHROMA, SPECIES_BALSA, true, new Color(0x59ac00), ForestryWoodType.BALSA) + arboriculture.registerSpecies(ForestryTreeSpecies.BALSA, GENUS_OCHROMA, SPECIES_BALSA, true, TextColor.fromRgb(0x59ac00), ForestryWoodType.BALSA) .setTreeFeature(FeatureBalsa::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.BALSA)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.BALSA).block().getStateDefinition().getPossibleStates()) @@ -461,12 +460,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_LARGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.TEAK, ForestryTreeSpecies.ACACIA_VANILLA, 10); + mutations.add(ForestryTreeSpecies.TEAK, ForestryTreeSpecies.ACACIA_VANILLA, 0.10f); }) .setRarity(0.0005f); // Cocobolo - arboriculture.registerSpecies(ForestryTreeSpecies.COCOBOLO, GENUS_DALBERGIA, SPECIES_COCOBOLO, false, new Color(0x6aa17a), ForestryWoodType.COCOBOLO) + arboriculture.registerSpecies(ForestryTreeSpecies.COCOBOLO, GENUS_DALBERGIA, SPECIES_COCOBOLO, false, TextColor.fromRgb(0x6aa17a), ForestryWoodType.COCOBOLO) .setTreeFeature(FeatureCocobolo::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.COCOBOLO)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.COCOBOLO).block().getStateDefinition().getPossibleStates()) @@ -476,12 +475,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_LARGEST); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.DESERT_ACACIA, ForestryTreeSpecies.DARK_OAK, 10); + mutations.add(ForestryTreeSpecies.DESERT_ACACIA, ForestryTreeSpecies.DARK_OAK, 0.10f); }) .setRarity(0.0005f); // Wenge - arboriculture.registerSpecies(ForestryTreeSpecies.WENGE, GENUS_MILLETTIA, SPECIES_WENGE, true, new Color(0xada157), ForestryWoodType.WENGE) + arboriculture.registerSpecies(ForestryTreeSpecies.WENGE, GENUS_MILLETTIA, SPECIES_WENGE, true, TextColor.fromRgb(0xada157), ForestryWoodType.WENGE) .setTreeFeature(FeatureWenge::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.WENGE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.WENGE).block().getStateDefinition().getPossibleStates()) @@ -493,12 +492,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_2); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.COCOBOLO, ForestryTreeSpecies.BALSA, 10); + mutations.add(ForestryTreeSpecies.COCOBOLO, ForestryTreeSpecies.BALSA, 0.10f); }) .setRarity(0.0005F); // Baobab - arboriculture.registerSpecies(ForestryTreeSpecies.BAOBAB, GENUS_ADANSONIA, SPECIES_BAOBAB, true, new Color(0xfeff8f), ForestryWoodType.BAOBAB) + arboriculture.registerSpecies(ForestryTreeSpecies.BAOBAB, GENUS_ADANSONIA, SPECIES_BAOBAB, true, TextColor.fromRgb(0xfeff8f), ForestryWoodType.BAOBAB) .setTreeFeature(FeatureBaobab::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.BAOBAB)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.BAOBAB).block().getStateDefinition().getPossibleStates()) @@ -512,12 +511,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.GIRTH, ForestryAlleles.GIRTH_3); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.BALSA, ForestryTreeSpecies.WENGE, 10); + mutations.add(ForestryTreeSpecies.BALSA, ForestryTreeSpecies.WENGE, 0.10f); }) .setRarity(0.005f); // Mahoe - arboriculture.registerSpecies(ForestryTreeSpecies.MAHOE, GENUS_TALIPARITI, SPECIES_MAHOE, true, new Color(0xa0ba1b), ForestryWoodType.MAHOE) + arboriculture.registerSpecies(ForestryTreeSpecies.MAHOE, GENUS_TALIPARITI, SPECIES_MAHOE, true, TextColor.fromRgb(0xa0ba1b), ForestryWoodType.MAHOE) .setTreeFeature(FeatureMahoe::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.MAHOE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.MAHOE).block().getStateDefinition().getPossibleStates()) @@ -529,12 +528,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_SLOWEST); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.BALSA, ForestryTreeSpecies.DESERT_ACACIA, 5); + mutations.add(ForestryTreeSpecies.BALSA, ForestryTreeSpecies.DESERT_ACACIA, 0.05f); }) .setRarity(0.000005f); // Willow - arboriculture.registerSpecies(ForestryTreeSpecies.WILLOW, GENUS_SALIX, SPECIES_WILLOW, true, new Color(0xa3b8a5), ForestryWoodType.WILLOW) + arboriculture.registerSpecies(ForestryTreeSpecies.WILLOW, GENUS_SALIX, SPECIES_WILLOW, true, TextColor.fromRgb(0xa3b8a5), ForestryWoodType.WILLOW) .setTreeFeature(FeatureWillow::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.WILLOW)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.WILLOW).block().getStateDefinition().getPossibleStates()) @@ -546,20 +545,20 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_FASTER); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.OAK, ForestryTreeSpecies.BIRCH, 10) + mutations.add(ForestryTreeSpecies.OAK, ForestryTreeSpecies.BIRCH, 0.10f) .restrictTemperature(TemperatureType.WARM, TemperatureType.HOT) .restrictHumidity(HumidityType.DAMP); - mutations.add(ForestryTreeSpecies.OAK, ForestryTreeSpecies.LIME, 10) + mutations.add(ForestryTreeSpecies.OAK, ForestryTreeSpecies.LIME, 0.10f) .restrictTemperature(TemperatureType.WARM, TemperatureType.HOT) .restrictHumidity(HumidityType.DAMP); - mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.BIRCH, 10) + mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.BIRCH, 0.10f) .restrictTemperature(TemperatureType.WARM, TemperatureType.HOT) .restrictHumidity(HumidityType.DAMP); }) .setRarity(0.0025f); // Sipiri - arboriculture.registerSpecies(ForestryTreeSpecies.SIPIRI, GENUS_CHLOROCARDIUM, SPECIES_SIPIRI, true, new Color(0x678911), ForestryWoodType.GREENHEART) + arboriculture.registerSpecies(ForestryTreeSpecies.SIPIRI, GENUS_CHLOROCARDIUM, SPECIES_SIPIRI, true, TextColor.fromRgb(0x678911), ForestryWoodType.GREENHEART) .setTreeFeature(FeatureGreenheart::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.SIPIRI)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.SIPIRI).block().getStateDefinition().getPossibleStates()) @@ -572,14 +571,14 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_SLOW); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.KAPOK, ForestryTreeSpecies.MAHOGANY, 10) + mutations.add(ForestryTreeSpecies.KAPOK, ForestryTreeSpecies.MAHOGANY, 0.10f) .restrictTemperature(TemperatureType.WARM, TemperatureType.HOT) .restrictHumidity(HumidityType.DAMP); }) .setRarity(0.0025f); // Papaya - arboriculture.registerSpecies(ForestryTreeSpecies.PAPAYA, GENUS_CARICA, SPECIES_PAPAYA, true, new Color(0x6d9f58), ForestryWoodType.PAPAYA) + arboriculture.registerSpecies(ForestryTreeSpecies.PAPAYA, GENUS_CARICA, SPECIES_PAPAYA, true, TextColor.fromRgb(0x6d9f58), ForestryWoodType.PAPAYA) .setTreeFeature(FeaturePapaya::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.PAPAYA)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.PAPAYA).block().getStateDefinition().getPossibleStates()) @@ -593,12 +592,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_AVERAGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.JUNGLE, ForestryTreeSpecies.HILL_CHERRY, 5); + mutations.add(ForestryTreeSpecies.JUNGLE, ForestryTreeSpecies.HILL_CHERRY, 0.05f); }) .setRarity(0.005f); // Date - arboriculture.registerSpecies(ForestryTreeSpecies.DATE, GENUS_PHOENIX, SPECIES_DATE, true, new Color(0xcbcd79), ForestryWoodType.PALM) + arboriculture.registerSpecies(ForestryTreeSpecies.DATE, GENUS_PHOENIX, SPECIES_DATE, true, TextColor.fromRgb(0xcbcd79), ForestryWoodType.PALM) .setTreeFeature(FeatureDate::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.DATE)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.DATE).block().getStateDefinition().getPossibleStates()) @@ -613,12 +612,12 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.HEIGHT, ForestryAlleles.HEIGHT_AVERAGE); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.JUNGLE, ForestryTreeSpecies.PAPAYA, 5); + mutations.add(ForestryTreeSpecies.JUNGLE, ForestryTreeSpecies.PAPAYA, 0.05f); }) .setRarity(0.005f); // Poplar - arboriculture.registerSpecies(ForestryTreeSpecies.POPLAR, GENUS_POPULUS, SPECIES_POPLAR, true, new Color(0xa3b8a5), ForestryWoodType.POPLAR) + arboriculture.registerSpecies(ForestryTreeSpecies.POPLAR, GENUS_POPULUS, SPECIES_POPLAR, true, TextColor.fromRgb(0xa3b8a5), ForestryWoodType.POPLAR) .setTreeFeature(FeaturePoplar::new) .setDecorativeLeaves(ArboricultureBlocks.LEAVES_DECORATIVE.stack(ForestryLeafType.POPLAR)) .addVanillaStates(ArboricultureBlocks.LEAVES_DEFAULT.get(ForestryLeafType.POPLAR).block().getStateDefinition().getPossibleStates()) @@ -629,9 +628,9 @@ public static void register(IArboricultureRegistration arboriculture) { genome.set(TreeChromosomes.MATURATION, ForestryAlleles.MATURATION_SLOWER); }) .addMutations(mutations -> { - mutations.add(ForestryTreeSpecies.BIRCH, ForestryTreeSpecies.WILLOW, 5); - mutations.add(ForestryTreeSpecies.OAK, ForestryTreeSpecies.WILLOW, 5); - mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.WILLOW, 5); + mutations.add(ForestryTreeSpecies.BIRCH, ForestryTreeSpecies.WILLOW, 0.05f); + mutations.add(ForestryTreeSpecies.OAK, ForestryTreeSpecies.WILLOW, 0.05f); + mutations.add(ForestryTreeSpecies.LIME, ForestryTreeSpecies.WILLOW, 0.05f); }); } } diff --git a/src/main/java/forestry/plugin/client/DefaultForestryClientRegistration.java b/src/main/java/forestry/plugin/client/DefaultForestryClientRegistration.java index 284f3623b2..088d7c24f6 100644 --- a/src/main/java/forestry/plugin/client/DefaultForestryClientRegistration.java +++ b/src/main/java/forestry/plugin/client/DefaultForestryClientRegistration.java @@ -2,7 +2,7 @@ import forestry.api.ForestryConstants; import forestry.api.apiculture.ForestryBeeSpecies; -import forestry.api.apiculture.genetics.BeeLifeStage; +import forestry.api.apiculture.bee.BeeLifeStage; import forestry.api.arboriculture.ForestryTreeSpecies; import forestry.api.client.arboriculture.ForestryLeafSprites; import forestry.api.client.plugin.IClientRegistration; @@ -32,13 +32,13 @@ private static void registerApiculture(IClientRegistration client) { private static void registerArboriculture(IClientRegistration client) { // Vanilla sapling models - registerSapling(client, "minecraft", ForestryTreeSpecies.OAK); - registerSapling(client, "minecraft", ForestryTreeSpecies.DARK_OAK); - registerSapling(client, "minecraft", ForestryTreeSpecies.BIRCH); - registerSapling(client, "minecraft", ForestryTreeSpecies.ACACIA_VANILLA); - registerSapling(client, "minecraft", ForestryTreeSpecies.SPRUCE); - registerSapling(client, "minecraft", ForestryTreeSpecies.JUNGLE); - registerSapling(client, "minecraft", ForestryTreeSpecies.CHERRY_VANILLA); + registerSapling(client, ForestryTreeSpecies.OAK); + registerSapling(client, ForestryTreeSpecies.DARK_OAK); + registerSapling(client, ForestryTreeSpecies.BIRCH); + registerSapling(client, ForestryTreeSpecies.ACACIA_VANILLA); + registerSapling(client, ForestryTreeSpecies.SPRUCE); + registerSapling(client, ForestryTreeSpecies.JUNGLE); + registerSapling(client, ForestryTreeSpecies.CHERRY_VANILLA); // Vanilla leaf sprites client.setLeafSprite(ForestryTreeSpecies.OAK, ForestryLeafSprites.OAK); @@ -88,11 +88,11 @@ private static void registerArboriculture(IClientRegistration client) { client.setLeafTint(ForestryTreeSpecies.CHERRY_VANILLA, FixedLeafTint.NONE); } - private static void registerSapling(IClientRegistration registration, String modId, ResourceLocation speciesId) { + private static void registerSapling(IClientRegistration registration, ResourceLocation speciesId) { // remove the "tree/" prefix and add "_sapling" String path = speciesId.getPath().substring(5) + "_sapling"; - ResourceLocation blockModel = new ResourceLocation(modId, "block/" + path); - ResourceLocation itemModel = new ResourceLocation(modId, "item/" + path); + ResourceLocation blockModel = ResourceLocation.withDefaultNamespace("block/" + path); + ResourceLocation itemModel = ResourceLocation.withDefaultNamespace("item/" + path); registration.setSaplingModel(speciesId, blockModel, itemModel); } diff --git a/src/main/java/forestry/plugin/client/package-info.java b/src/main/java/forestry/plugin/client/package-info.java index 3cf6683b3e..d1c2370d98 100644 --- a/src/main/java/forestry/plugin/client/package-info.java +++ b/src/main/java/forestry/plugin/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.plugin.client; diff --git a/src/main/java/forestry/plugin/package-info.java b/src/main/java/forestry/plugin/package-info.java index b6bb61835b..5352e1e76f 100644 --- a/src/main/java/forestry/plugin/package-info.java +++ b/src/main/java/forestry/plugin/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.plugin; diff --git a/src/main/java/forestry/sorting/FilterLogic.java b/src/main/java/forestry/sorting/FilterLogic.java index e4eafaaa59..189a4085ac 100644 --- a/src/main/java/forestry/sorting/FilterLogic.java +++ b/src/main/java/forestry/sorting/FilterLogic.java @@ -4,22 +4,23 @@ import forestry.api.core.ILocationProvider; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpecies; -import forestry.api.genetics.alleles.IAlleleManager; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.genetics.filter.FilterData; import forestry.api.genetics.filter.IFilterLogic; import forestry.api.genetics.filter.IFilterRuleType; -import forestry.core.utils.NetworkUtil; +import forestry.api.modules.IForestryPacketServer; import forestry.core.utils.SpeciesUtil; import forestry.sorting.network.packets.PacketFilterChangeGenome; import forestry.sorting.network.packets.PacketFilterChangeRule; import forestry.sorting.network.packets.PacketGuiFilterUpdate; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; import javax.annotation.Nullable; @@ -44,7 +45,7 @@ public INetworkHandler getNetworkHandler() { } @Override - public CompoundTag write(CompoundTag data) { + public CompoundTag write(CompoundTag data, HolderLookup.Provider registries) { for (int i = 0; i < this.filterRules.length; i++) { data.putString("TypeFilter" + i, this.filterRules[i].getId()); } @@ -67,7 +68,7 @@ public CompoundTag write(CompoundTag data) { } @Override - public void read(CompoundTag data) { + public void read(CompoundTag data, HolderLookup.Provider registries) { for (int i = 0; i < this.filterRules.length; i++) { this.filterRules[i] = IForestryApi.INSTANCE.getFilterManager().getRuleOrDefault(data.getString("TypeFilter" + i)); } @@ -76,10 +77,10 @@ public void read(CompoundTag data) { for (int j = 0; j < 3; j++) { AlleleFilter filter = new AlleleFilter(); if (data.contains("GenomeFilterS" + i + "-" + j + "-" + 0)) { - filter.activeSpecies = SpeciesUtil.getAnySpecies(new ResourceLocation(data.getString("GenomeFilterS" + i + "-" + j + "-" + 0))); + filter.activeSpecies = SpeciesUtil.getAnySpecies(ResourceLocation.parse(data.getString("GenomeFilterS" + i + "-" + j + "-" + 0))); } if (data.contains("GenomeFilterS" + i + "-" + j + "-" + 1)) { - filter.inactiveSpecies = SpeciesUtil.getAnySpecies(new ResourceLocation(data.getString("GenomeFilterS" + i + "-" + j + "-" + 1))); + filter.inactiveSpecies = SpeciesUtil.getAnySpecies(ResourceLocation.parse(data.getString("GenomeFilterS" + i + "-" + j + "-" + 1))); } this.genomeFilter[i][j] = filter; } @@ -94,8 +95,8 @@ public void writeGuiData(FriendlyByteBuf buffer) { @Override public void readGuiData(FriendlyByteBuf buffer) { - this.filterRules = readFilterRules(buffer); - this.genomeFilter = readGenomeFilters(buffer); + this.filterRules = readFilterRules(buffer); + this.genomeFilter = readGenomeFilters(buffer); } public static void writeFilterRules(FriendlyByteBuf buffer, IFilterRuleType[] filterRules) { @@ -139,8 +140,7 @@ public static IFilterRuleType[] readFilterRules(FriendlyByteBuf buffer) { } public static AlleleFilter[][] readGenomeFilters(FriendlyByteBuf buffer) { - AlleleFilter[][] genomeFilters = new AlleleFilter[6][32023]; - IAlleleManager alleles = IForestryApi.INSTANCE.getAlleleManager(); + AlleleFilter[][] genomeFilters = new AlleleFilter[6][3]; for (int i = 0; i < 6; i++) { for (int j = 0; j < 3; j++) { @@ -210,7 +210,7 @@ public IFilterRuleType getRule(Direction facing) { public boolean setRule(Direction facing, IFilterRuleType rule) { if (this.filterRules[facing.ordinal()] != rule) { - this.filterRules[facing.ordinal()] = rule; + this.filterRules[facing.ordinal()] = rule; return true; } return false; @@ -248,12 +248,14 @@ public boolean setGenomeFilter(Direction facing, int index, boolean active, @Nul @Override public void sendToServer(Direction facing, int index, boolean active, @Nullable ISpecies allele) { - NetworkUtil.sendToServer(new PacketFilterChangeGenome(this.locatable.getCoordinates(), facing, (short) index, active, allele)); + IForestryPacketServer packet = new PacketFilterChangeGenome(this.locatable.getBlockPos(), facing, (short) index, active, allele); + PacketDistributor.sendToServer(packet); } @Override public void sendToServer(Direction facing, IFilterRuleType rule) { - NetworkUtil.sendToServer(new PacketFilterChangeRule(this.locatable.getCoordinates(), facing, rule)); + IForestryPacketServer packet = new PacketFilterChangeRule(this.locatable.getBlockPos(), facing, rule); + PacketDistributor.sendToServer(packet); } public PacketGuiFilterUpdate createGuiUpdatePacket(BlockPos pos) { diff --git a/src/main/java/forestry/sorting/ModuleSorting.java b/src/main/java/forestry/sorting/ModuleSorting.java index d2ea51c01c..828ab905b5 100644 --- a/src/main/java/forestry/sorting/ModuleSorting.java +++ b/src/main/java/forestry/sorting/ModuleSorting.java @@ -4,7 +4,6 @@ import forestry.api.genetics.filter.IFilterLogic; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.api.modules.IPacketRegistry; import forestry.core.network.PacketIdClient; import forestry.core.network.PacketIdServer; import forestry.modules.BlankForestryModule; @@ -15,6 +14,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.function.Consumer; @@ -31,11 +31,11 @@ public void registerEvents(IEventBus modBus) { } @Override - public void registerPackets(IPacketRegistry registry) { - registry.serverbound(PacketIdServer.FILTER_CHANGE_RULE, PacketFilterChangeRule.class, PacketFilterChangeRule::decode, PacketFilterChangeRule::handle); - registry.serverbound(PacketIdServer.FILTER_CHANGE_GENOME, PacketFilterChangeGenome.class, PacketFilterChangeGenome::decode, PacketFilterChangeGenome::handle); + public void registerPackets(PayloadRegistrar registrar) { + registrar.serverbound(PacketIdServer.FILTER_CHANGE_RULE, PacketFilterChangeRule.class, PacketFilterChangeRule::decode, PacketFilterChangeRule::handle); + registrar.serverbound(PacketIdServer.FILTER_CHANGE_GENOME, PacketFilterChangeGenome.class, PacketFilterChangeGenome::decode, PacketFilterChangeGenome::handle); - registry.clientbound(PacketIdClient.GUI_UPDATE_FILTER, PacketGuiFilterUpdate.class, PacketGuiFilterUpdate::decode, PacketGuiFilterUpdate::handle); + registrar.clientbound(PacketIdClient.GUI_UPDATE_FILTER, PacketGuiFilterUpdate.class, PacketGuiFilterUpdate::decode, PacketGuiFilterUpdate::handle); } public static void registerCapabilities(RegisterCapabilitiesEvent consumer) { diff --git a/src/main/java/forestry/sorting/blocks/BlockGeneticFilter.java b/src/main/java/forestry/sorting/blocks/BlockGeneticFilter.java index 83d574f564..2f656015e1 100644 --- a/src/main/java/forestry/sorting/blocks/BlockGeneticFilter.java +++ b/src/main/java/forestry/sorting/blocks/BlockGeneticFilter.java @@ -5,8 +5,6 @@ import forestry.sorting.tiles.TileGeneticFilter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; @@ -19,9 +17,6 @@ import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkHooks; - -import javax.annotation.Nullable; public class BlockGeneticFilter extends BlockForestry implements EntityBlock { public static final BooleanProperty NORTH = BooleanProperty.create("north"); @@ -42,10 +37,9 @@ public class BlockGeneticFilter extends BlockForestry implements EntityBlock { public BlockGeneticFilter() { super(Block.Properties.of() - .strength(0.25f, 3.0f) - .dynamicShape() - .noOcclusion(), - false + .strength(0.25f, 3.0f) + .dynamicShape() + .noOcclusion() ); this.registerDefaultState(this.getStateDefinition().any() .setValue(NORTH, false) @@ -70,17 +64,17 @@ public BlockState updateShape(BlockState state, Direction direction, BlockState } @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult rayTraceResult) { - TileGeneticFilter tile = TileUtil.getTile(worldIn, pos, TileGeneticFilter.class); - if (tile != null) { - if (TileUtil.isUsableByPlayer(playerIn, tile)) { - if (!worldIn.isClientSide) { - ServerPlayer sPlayer = (ServerPlayer) playerIn; - NetworkHooks.openScreen(sPlayer, tile, pos); - } + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + if (level.getBlockEntity(pos) instanceof TileGeneticFilter filter) { + if (!level.isClientSide) { + player.openMenu(filter, pos); + + return InteractionResult.CONSUME; + } else { return InteractionResult.SUCCESS; } } + return InteractionResult.PASS; } @@ -90,7 +84,6 @@ protected void createBlockStateDefinition(StateDefinition.Builder GENETIC_FILTER = REGISTRY.menuType(ContainerGeneticFilter::fromNetwork, "genetic_filter"); + public static final FeatureMenuType GENETIC_FILTER = REGISTRY.menuType(GeneticFilterMenu::fromNetwork, "genetic_filter"); } diff --git a/src/main/java/forestry/sorting/features/package-info.java b/src/main/java/forestry/sorting/features/package-info.java index 42d971b0a9..e28e17f6c1 100644 --- a/src/main/java/forestry/sorting/features/package-info.java +++ b/src/main/java/forestry/sorting/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting.features; diff --git a/src/main/java/forestry/sorting/gui/ContainerGeneticFilter.java b/src/main/java/forestry/sorting/gui/GeneticFilterMenu.java similarity index 78% rename from src/main/java/forestry/sorting/gui/ContainerGeneticFilter.java rename to src/main/java/forestry/sorting/gui/GeneticFilterMenu.java index 9d3529e0c2..fd913419e4 100644 --- a/src/main/java/forestry/sorting/gui/ContainerGeneticFilter.java +++ b/src/main/java/forestry/sorting/gui/GeneticFilterMenu.java @@ -1,6 +1,6 @@ package forestry.sorting.gui; -import forestry.core.gui.ContainerTile; +import forestry.core.gui.TileMenu; import forestry.core.tiles.TileUtil; import forestry.sorting.features.SortingMenuTypes; import forestry.sorting.network.packets.PacketGuiFilterUpdate; @@ -8,15 +8,15 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; -public class ContainerGeneticFilter extends ContainerTile { +public class GeneticFilterMenu extends TileMenu { private boolean guiNeedsUpdate = true; - public static ContainerGeneticFilter fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { + public static GeneticFilterMenu fromNetwork(int windowId, Inventory inv, FriendlyByteBuf data) { TileGeneticFilter tile = TileUtil.getTile(inv.player.level(), data.readBlockPos(), TileGeneticFilter.class); - return new ContainerGeneticFilter(windowId, inv, tile); + return new GeneticFilterMenu(windowId, inv, tile); } - public ContainerGeneticFilter(int windowId, Inventory playerInventory, TileGeneticFilter tile) { + public GeneticFilterMenu(int windowId, Inventory playerInventory, TileGeneticFilter tile) { super(windowId, SortingMenuTypes.GENETIC_FILTER.menuType(), tile, playerInventory.player); addInventory(playerInventory, 26, 140); } @@ -52,7 +52,7 @@ public void broadcastChanges() { } } - public boolean hasSameTile(ContainerGeneticFilter openContainer) { + public boolean hasSameTile(GeneticFilterMenu openContainer) { return this.tile == openContainer.tile; } } diff --git a/src/main/java/forestry/sorting/gui/GuiGeneticFilter.java b/src/main/java/forestry/sorting/gui/GuiGeneticFilter.java index 3cc471fdaa..2d673d59e1 100644 --- a/src/main/java/forestry/sorting/gui/GuiGeneticFilter.java +++ b/src/main/java/forestry/sorting/gui/GuiGeneticFilter.java @@ -21,14 +21,14 @@ import javax.annotation.Nullable; -public class GuiGeneticFilter extends GuiForestryTitled { +public class GuiGeneticFilter extends GuiForestryTitled { private final TileGeneticFilter tile; private final WidgetScrollBar scrollBar; public final SelectionWidget selection; @Nullable private EditBox searchField; - public GuiGeneticFilter(ContainerGeneticFilter container, Inventory inventory, Component title) { + public GuiGeneticFilter(GeneticFilterMenu container, Inventory inventory, Component title) { super(Constants.TEXTURE_PATH_GUI + "/filter.png", container, inventory, title); this.imageHeight = 222; this.imageWidth = 212; @@ -47,7 +47,7 @@ public GuiGeneticFilter(ContainerGeneticFilter container, Inventory inventory, C } } - this.scrollBar = new WidgetScrollBar(this.widgetManager, 157 + 36, 150, 12, 64, new Drawable(new ResourceLocation(Constants.TEXTURE_PATH_GUI + "/container/creative_inventory/tabs.png"), 232, 0, 12, 15)); + this.scrollBar = new WidgetScrollBar(this.widgetManager, 157 + 36, 150, 12, 64, new Drawable(ResourceLocation.withDefaultNamespace(Constants.TEXTURE_PATH_GUI + "/container/creative_inventory/tabs.png"), 232, 0, 12, 15)); this.widgetManager.add(this.selection = new SelectionWidget(this.widgetManager, 0, 134, this.scrollBar, this)); this.widgetManager.add(this.scrollBar); this.scrollBar.setVisible(false); diff --git a/src/main/java/forestry/sorting/gui/package-info.java b/src/main/java/forestry/sorting/gui/package-info.java index 96b4f241d5..143d614299 100644 --- a/src/main/java/forestry/sorting/gui/package-info.java +++ b/src/main/java/forestry/sorting/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting.gui; diff --git a/src/main/java/forestry/sorting/gui/widgets/SpeciesWidget.java b/src/main/java/forestry/sorting/gui/widgets/SpeciesWidget.java index ed856d6ca3..dd145f3017 100644 --- a/src/main/java/forestry/sorting/gui/widgets/SpeciesWidget.java +++ b/src/main/java/forestry/sorting/gui/widgets/SpeciesWidget.java @@ -23,6 +23,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ResolvableProfile; import javax.annotation.Nullable; import java.util.IdentityHashMap; @@ -45,7 +46,7 @@ public SpeciesWidget(WidgetManager manager, int xPos, int yPos, Direction facing ImmutableSet.Builder> entries = ImmutableSet.builder(); for (ISpeciesType type : IForestryApi.INSTANCE.getGeneticManager().getSpeciesTypes()) { - IBreedingTracker tracker = type.getBreedingTracker(manager.minecraft.level, manager.minecraft.player.getGameProfile()); + IBreedingTracker tracker = type.getBreedingTracker(manager.minecraft.level, new ResolvableProfile(manager.minecraft.player.getGameProfile())); for (ResourceLocation id : tracker.getDiscoveredSpecies()) { ISpecies species = type.getSpeciesSafe(id); diff --git a/src/main/java/forestry/sorting/gui/widgets/package-info.java b/src/main/java/forestry/sorting/gui/widgets/package-info.java index 5e67247bca..6f9412a041 100644 --- a/src/main/java/forestry/sorting/gui/widgets/package-info.java +++ b/src/main/java/forestry/sorting/gui/widgets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting.gui.widgets; diff --git a/src/main/java/forestry/sorting/inventory/package-info.java b/src/main/java/forestry/sorting/inventory/package-info.java index ab61feda35..6c9b7f8947 100644 --- a/src/main/java/forestry/sorting/inventory/package-info.java +++ b/src/main/java/forestry/sorting/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting.inventory; diff --git a/src/main/java/forestry/sorting/network/packets/PacketFilterChangeGenome.java b/src/main/java/forestry/sorting/network/packets/PacketFilterChangeGenome.java index 3c100a55b8..a89640d7fa 100644 --- a/src/main/java/forestry/sorting/network/packets/PacketFilterChangeGenome.java +++ b/src/main/java/forestry/sorting/network/packets/PacketFilterChangeGenome.java @@ -1,50 +1,53 @@ package forestry.sorting.network.packets; -import forestry.api.ForestryCapabilities; import forestry.api.genetics.ISpecies; import forestry.api.modules.IForestryPacketServer; import forestry.core.network.PacketIdServer; -import forestry.core.tiles.TileUtil; import forestry.core.utils.NetworkUtil; import forestry.core.utils.SpeciesUtil; +import forestry.sorting.FilterLogic; +import forestry.sorting.tiles.TileGeneticFilter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.neoforged.neoforge.network.handling.IPayloadContext; import javax.annotation.Nullable; public record PacketFilterChangeGenome(BlockPos pos, Direction facing, short index, boolean active, @Nullable ISpecies species) implements IForestryPacketServer { - public static void handle(PacketFilterChangeGenome msg, ServerPlayer player) { - TileUtil.getInterface(player.level(), msg.pos(), ForestryCapabilities.FILTER_LOGIC, null).ifPresent(logic -> { + public static void handle(PacketFilterChangeGenome msg, IPayloadContext ctx) { + Player player = ctx.player(); + if (player.level().getBlockEntity(msg.pos()) instanceof TileGeneticFilter filter) { + FilterLogic logic = filter.getLogic(); + if (logic.setGenomeFilter(msg.facing(), msg.index(), msg.active(), msg.species())) { - logic.getNetworkHandler().sendToPlayers(logic, player.serverLevel(), player); + logic.getNetworkHandler().sendToPlayers(logic, (ServerLevel) player.level(), player); } - }); + } } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writeDirection(buffer, this.facing); - buffer.writeShort(this.index); - buffer.writeBoolean(this.active); - if (this.species != null) { + public static void encode(RegistryFriendlyByteBuf buffer, PacketFilterChangeGenome msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writeDirection(buffer, msg.facing); + buffer.writeShort(msg.index); + buffer.writeBoolean(msg.active); + if (msg.species != null) { buffer.writeBoolean(true); - buffer.writeResourceLocation(this.species.id()); + buffer.writeResourceLocation(msg.species.id()); } else { buffer.writeBoolean(false); } } @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.FILTER_CHANGE_GENOME; } - public static PacketFilterChangeGenome decode(FriendlyByteBuf buffer) { + public static PacketFilterChangeGenome decode(RegistryFriendlyByteBuf buffer) { BlockPos pos = buffer.readBlockPos(); Direction facing = NetworkUtil.readDirection(buffer); short index = buffer.readShort(); diff --git a/src/main/java/forestry/sorting/network/packets/PacketFilterChangeRule.java b/src/main/java/forestry/sorting/network/packets/PacketFilterChangeRule.java index 929214e548..64922c6dd3 100644 --- a/src/main/java/forestry/sorting/network/packets/PacketFilterChangeRule.java +++ b/src/main/java/forestry/sorting/network/packets/PacketFilterChangeRule.java @@ -1,42 +1,45 @@ package forestry.sorting.network.packets; -import forestry.api.ForestryCapabilities; import forestry.api.IForestryApi; import forestry.api.genetics.filter.IFilterRuleType; import forestry.api.modules.IForestryPacketServer; import forestry.core.network.PacketIdServer; -import forestry.core.tiles.TileUtil; +import forestry.sorting.FilterLogic; +import forestry.sorting.tiles.TileGeneticFilter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.neoforged.neoforge.network.handling.IPayloadContext; import java.util.Objects; public record PacketFilterChangeRule(BlockPos pos, Direction facing, IFilterRuleType rule) implements IForestryPacketServer { @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.FILTER_CHANGE_RULE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - buffer.writeShort(this.facing.get3DDataValue()); - buffer.writeShort(IForestryApi.INSTANCE.getFilterManager().getId(this.rule)); + public static void encode(RegistryFriendlyByteBuf buffer, PacketFilterChangeRule msg) { + buffer.writeBlockPos(msg.pos); + buffer.writeShort(msg.facing.get3DDataValue()); + buffer.writeShort(IForestryApi.INSTANCE.getFilterManager().getId(msg.rule)); } - public static PacketFilterChangeRule decode(FriendlyByteBuf buffer) { + public static PacketFilterChangeRule decode(RegistryFriendlyByteBuf buffer) { return new PacketFilterChangeRule(buffer.readBlockPos(), Direction.VALUES[buffer.readShort()], Objects.requireNonNull(IForestryApi.INSTANCE.getFilterManager().getRule(buffer.readShort()))); } - public static void handle(PacketFilterChangeRule msg, ServerPlayer player) { - TileUtil.getInterface(player.level(), msg.pos(), ForestryCapabilities.FILTER_LOGIC, null).ifPresent(logic -> { - if (logic.setRule(msg.facing(), msg.rule())) { - logic.getNetworkHandler().sendToPlayers(logic, player.serverLevel(), player); + public static void handle(PacketFilterChangeRule msg, IPayloadContext ctx) { + Player player = ctx.player(); + if (player.level().getBlockEntity(msg.pos()) instanceof TileGeneticFilter filter) { + FilterLogic logic = filter.getLogic(); + + if (logic.setRule(msg.facing, msg.rule)) { + logic.getNetworkHandler().sendToPlayers(logic, (ServerLevel) player.level(), player); } - }); + } } } diff --git a/src/main/java/forestry/sorting/network/packets/PacketGuiFilterUpdate.java b/src/main/java/forestry/sorting/network/packets/PacketGuiFilterUpdate.java index a2a5fc60f1..91b1312265 100644 --- a/src/main/java/forestry/sorting/network/packets/PacketGuiFilterUpdate.java +++ b/src/main/java/forestry/sorting/network/packets/PacketGuiFilterUpdate.java @@ -1,40 +1,34 @@ package forestry.sorting.network.packets; -import forestry.api.ForestryCapabilities; import forestry.api.genetics.filter.IFilterRuleType; import forestry.api.modules.IForestryPacketClient; import forestry.core.network.PacketIdClient; -import forestry.core.tiles.TileUtil; import forestry.sorting.AlleleFilter; import forestry.sorting.FilterLogic; +import forestry.sorting.tiles.TileGeneticFilter; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketGuiFilterUpdate(BlockPos pos, IFilterRuleType[] filterRules, AlleleFilter[][] genomeFilter) implements IForestryPacketClient { - @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.GUI_UPDATE_FILTER; } - @Override - public void write(FriendlyByteBuf buffer) { + public void write(RegistryFriendlyByteBuf buffer) { buffer.writeBlockPos(this.pos); FilterLogic.writeFilterRules(buffer, this.filterRules); FilterLogic.writeGenomeFilters(buffer, this.genomeFilter); } - public static PacketGuiFilterUpdate decode(FriendlyByteBuf buffer) { + public static PacketGuiFilterUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketGuiFilterUpdate(buffer.readBlockPos(), FilterLogic.readFilterRules(buffer), FilterLogic.readGenomeFilters(buffer)); } - public static void handle(PacketGuiFilterUpdate msg, Player player) { - TileUtil.getInterface(player.level(), msg.pos(), ForestryCapabilities.FILTER_LOGIC, null).ifPresent(l -> { - if (l instanceof FilterLogic logic) { - logic.readGuiUpdatePacket(msg); - } - }); + public static void handle(PacketGuiFilterUpdate msg, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(msg.pos) instanceof TileGeneticFilter filter) { + filter.getLogic().readGuiUpdatePacket(msg); + } } } diff --git a/src/main/java/forestry/sorting/network/packets/package-info.java b/src/main/java/forestry/sorting/network/packets/package-info.java index 6b45e5f1cc..dbc1a046de 100644 --- a/src/main/java/forestry/sorting/network/packets/package-info.java +++ b/src/main/java/forestry/sorting/network/packets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting.network.packets; diff --git a/src/main/java/forestry/sorting/package-info.java b/src/main/java/forestry/sorting/package-info.java index a4f9ed5b99..5f26c08430 100644 --- a/src/main/java/forestry/sorting/package-info.java +++ b/src/main/java/forestry/sorting/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting; diff --git a/src/main/java/forestry/sorting/tiles/TileGeneticFilter.java b/src/main/java/forestry/sorting/tiles/TileGeneticFilter.java index 4143b3cd17..ca93439676 100644 --- a/src/main/java/forestry/sorting/tiles/TileGeneticFilter.java +++ b/src/main/java/forestry/sorting/tiles/TileGeneticFilter.java @@ -1,6 +1,5 @@ package forestry.sorting.tiles; -import forestry.api.ForestryCapabilities; import forestry.api.genetics.capability.IIndividualHandlerItem; import forestry.api.genetics.filter.FilterData; import forestry.core.inventory.AdjacentInventoryCache; @@ -11,12 +10,12 @@ import forestry.core.utils.ItemStackUtil; import forestry.sorting.FilterLogic; import forestry.sorting.features.SortingTiles; -import forestry.sorting.gui.ContainerGeneticFilter; -import forestry.sorting.inventory.ItemHandlerFilter; +import forestry.sorting.gui.GeneticFilterMenu; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -25,15 +24,9 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemHandlerHelper; - -import javax.annotation.Nullable; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.ItemHandlerHelper; + import java.util.ArrayList; import java.util.List; @@ -51,35 +44,34 @@ public TileGeneticFilter(BlockPos pos, BlockState state) { } @Override - public void saveAdditional(CompoundTag data) { - super.saveAdditional(data); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - data.put("Logic", this.logic.write(new CompoundTag())); + nbt.put("Logic", this.logic.write(new CompoundTag(), registries)); } @Override - public void load(CompoundTag data) { - super.load(data); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - this.logic.read(data.getCompound("Logic")); + this.logic.read(nbt.getCompound("Logic"), registries); } @Override - public void writeGuiData(FriendlyByteBuf data) { - this.logic.writeGuiData(data); + public void writeGuiData(RegistryFriendlyByteBuf buffer) { + this.logic.writeGuiData(buffer); } - @OnlyIn(Dist.CLIENT) @Override - public void readGuiData(FriendlyByteBuf data) { - this.logic.readGuiData(data); + public void readGuiData(RegistryFriendlyByteBuf buffer) { + this.logic.readGuiData(buffer); } private void sendToPlayers(ServerLevel server, Player filterChanger) { for (Player player : server.players()) { - if (player != filterChanger && player.containerMenu instanceof ContainerGeneticFilter) { - if (((ContainerGeneticFilter) filterChanger.containerMenu).hasSameTile((ContainerGeneticFilter) player.containerMenu)) { - ((ContainerGeneticFilter) player.containerMenu).setGuiNeedsUpdate(true); + if (player != filterChanger && player.containerMenu instanceof GeneticFilterMenu) { + if (((GeneticFilterMenu) filterChanger.containerMenu).hasSameTile((GeneticFilterMenu) player.containerMenu)) { + ((GeneticFilterMenu) player.containerMenu).setGuiNeedsUpdate(true); } } } @@ -113,21 +105,21 @@ public boolean isConnected(Direction facing) { return TileUtil.getInventoryFromTile(tileEntity, facing.getOpposite()) != null; } - private ItemStack transferItem(ItemStack itemStack, Direction facing) { + private ItemStack transferItem(ItemStack stack, Direction facing) { IItemHandler itemHandler = this.inventoryCache.getAdjacentInventory(facing); if (itemHandler == null) { return ItemStack.EMPTY; } - ItemStack transferredStack = ItemHandlerHelper.insertItemStacked(itemHandler, itemStack.copy(), true); - if (transferredStack.getCount() == itemStack.getCount()) { + ItemStack transferredStack = ItemHandlerHelper.insertItemStacked(itemHandler, stack.copy(), true); + if (transferredStack.getCount() == stack.getCount()) { return ItemStack.EMPTY; } - transferredStack = ItemHandlerHelper.insertItemStacked(itemHandler, itemStack.copy(), false); + transferredStack = ItemHandlerHelper.insertItemStacked(itemHandler, stack.copy(), false); if (transferredStack.isEmpty()) { - return itemStack; + return stack; } - ItemStack copy = itemStack.copy(); - copy.setCount(itemStack.getCount() - transferredStack.getCount()); + ItemStack copy = stack.copy(); + copy.setCount(stack.getCount() - transferredStack.getCount()); return copy; } @@ -153,27 +145,16 @@ public List getValidDirections(ItemStack stack, Direction from) { return validFacings; } - private boolean isValidFacing(Direction facing, ItemStack itemStack, FilterData filterData) { - return this.inventoryCache.getAdjacentInventory(facing) != null && this.logic.isValid(facing, itemStack, filterData); + private boolean isValidFacing(Direction facing, ItemStack stack, FilterData filterData) { + return this.inventoryCache.getAdjacentInventory(facing) != null && this.logic.isValid(facing, stack, filterData); } public FilterLogic getLogic() { return this.logic; } - @Nullable @Override public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { - return new ContainerGeneticFilter(windowId, player.getInventory(), this); - } - - @Override - public LazyOptional getCapability(Capability capability, @Nullable Direction facing) { - if (capability == ForgeCapabilities.ITEM_HANDLER && facing != null) { - return LazyOptional.of(() -> new ItemHandlerFilter(this, facing)).cast(); - } else if (capability == ForestryCapabilities.FILTER_LOGIC) { - return LazyOptional.of(() -> this.logic).cast(); - } - return super.getCapability(capability, facing); + return new GeneticFilterMenu(windowId, player.getInventory(), this); } } diff --git a/src/main/java/forestry/sorting/tiles/package-info.java b/src/main/java/forestry/sorting/tiles/package-info.java index be3ae1dcfd..e66e3d29ec 100644 --- a/src/main/java/forestry/sorting/tiles/package-info.java +++ b/src/main/java/forestry/sorting/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.sorting.tiles; diff --git a/src/main/java/forestry/storage/BackpackDefinition.java b/src/main/java/forestry/storage/BackpackDefinition.java deleted file mode 100755 index c0548a36fd..0000000000 --- a/src/main/java/forestry/storage/BackpackDefinition.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage; - -import forestry.api.storage.IBackpackDefinition; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import java.util.function.Predicate; - -public class BackpackDefinition implements IBackpackDefinition { - private final int primaryColor; - private final int secondaryColor; - private final Predicate filter; - - public BackpackDefinition(int primaryColor, int secondaryColor, Predicate filter) { - this.primaryColor = primaryColor; - this.secondaryColor = secondaryColor; - this.filter = filter; - } - - @Override - public Predicate getFilter() { - return this.filter; - } - - @Override - public Component getName(ItemStack backpack) { - Item item = backpack.getItem(); - Component display = Component.translatable((item.getDescriptionId(backpack)).trim()); - - CompoundTag tagCompound = backpack.getTag(); - if (tagCompound != null && tagCompound.contains("display", 10)) { - CompoundTag nbt = tagCompound.getCompound("display"); - - if (nbt.contains("Name", 8)) { - display = Component.literal(nbt.getString("Name")); - } - } - - return display; - } - - @Override - public int getPrimaryColour() { - return this.primaryColor; - } - - @Override - public int getSecondaryColour() { - return this.secondaryColor; - } -} diff --git a/src/main/java/forestry/storage/BackpackInterface.java b/src/main/java/forestry/storage/BackpackInterface.java deleted file mode 100644 index 7a4a2e725c..0000000000 --- a/src/main/java/forestry/storage/BackpackInterface.java +++ /dev/null @@ -1,39 +0,0 @@ -package forestry.storage; - -import com.google.common.base.Preconditions; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; -import forestry.api.storage.IBackpackInterface; -import forestry.storage.items.ItemBackpack; -import forestry.storage.items.ItemBackpackNaturalist; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import java.util.function.Predicate; - -// todo this code is stupid and bloated. next time it breaks, simplify it and remove the silly API for it -public class BackpackInterface implements IBackpackInterface { - @Override - public Item createBackpack(IBackpackDefinition definition, EnumBackpackType type) { - Preconditions.checkNotNull(definition, "definition must not be null"); - Preconditions.checkNotNull(type, "type must not be null"); - Preconditions.checkArgument(type != EnumBackpackType.NATURALIST, "type must not be NATURALIST. Use createNaturalistBackpack instead."); - - return new ItemBackpack(definition, type); - } - - @Override - public Item createNaturalistBackpack(IBackpackDefinition definition, ResourceLocation speciesTypeId, CreativeModeTab tab) { - Preconditions.checkNotNull(definition, "definition must not be null"); - Preconditions.checkNotNull(speciesTypeId, "rootUid must not be null"); - - return new ItemBackpackNaturalist(speciesTypeId, definition, tab); - } - - @Override - public Predicate createNaturalistBackpackFilter(ResourceLocation speciesRootUid) { - return new BackpackFilterNaturalist(speciesRootUid); - } -} diff --git a/src/main/java/forestry/storage/BackpackMode.java b/src/main/java/forestry/storage/BackpackMode.java index 37eb881a96..e3df493e20 100755 --- a/src/main/java/forestry/storage/BackpackMode.java +++ b/src/main/java/forestry/storage/BackpackMode.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.storage; import net.minecraft.util.StringRepresentable; diff --git a/src/main/java/forestry/storage/BackpackResupplyHandler.java b/src/main/java/forestry/storage/BackpackResupplyHandler.java index da5bdadd0c..1de88e0816 100644 --- a/src/main/java/forestry/storage/BackpackResupplyHandler.java +++ b/src/main/java/forestry/storage/BackpackResupplyHandler.java @@ -1,33 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.storage; -import forestry.api.storage.BackpackResupplyEvent; +import forestry.api.event.BackpackEvent; import forestry.core.inventory.ItemInventory; import forestry.storage.inventory.ItemInventoryBackpack; import forestry.storage.items.ItemBackpack; -import net.minecraft.core.NonNullList; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.InventoryMenu; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.Event; +import net.neoforged.neoforge.common.NeoForge; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class BackpackResupplyHandler { - private static NonNullList getBackpacks(Inventory playerInventory) { - NonNullList backpacks = NonNullList.create(); + private static ArrayList getBackpacks(Inventory playerInventory) { + ArrayList backpacks = new ArrayList<>(); for (ItemStack itemStack : playerInventory.items) { if (itemStack.getItem() instanceof ItemBackpack) { backpacks.add(itemStack); @@ -43,10 +32,10 @@ public static void resupply(Player player) { if (ItemBackpack.getMode(backpack) == BackpackMode.RESUPPLY) { // Load their inventory ItemBackpack backpackItem = (ItemBackpack) backpack.getItem(); - ItemInventory backpackInventory = new ItemInventoryBackpack(player, backpackItem.getBackpackSize(), backpack); + ItemInventory backpackInventory = new ItemInventoryBackpack(backpackItem.getBackpackSize(), backpack); - Event event = new BackpackResupplyEvent(player, backpackItem.getDefinition(), backpackInventory); - if (!MinecraftForge.EVENT_BUS.post(event)) { + BackpackEvent.Resupply event = new BackpackEvent.Resupply(player, backpackItem.getDefinition(), backpackInventory); + if (!NeoForge.EVENT_BUS.post(event).isCanceled()) { for (int i = 0; i < backpackInventory.getContainerSize(); i++) { ItemStack itemStack = backpackInventory.getItem(i); if (topOffPlayerInventory(player, itemStack)) { diff --git a/src/main/java/forestry/storage/ModuleStorage.java b/src/main/java/forestry/storage/ModuleStorage.java index 0ead86468c..7eba99fa8b 100644 --- a/src/main/java/forestry/storage/ModuleStorage.java +++ b/src/main/java/forestry/storage/ModuleStorage.java @@ -5,6 +5,7 @@ import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; +import forestry.api.storage.BackpackDefinition; import forestry.api.storage.IBackpackInterface; import forestry.core.ForestryColors; import forestry.core.config.ForestryConfig; @@ -12,21 +13,18 @@ import forestry.storage.client.StorageClientHandler; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.entity.player.ItemEntityPickupEvent; +import net.neoforged.neoforge.event.tick.LevelTickEvent; import java.util.function.Consumer; @ForestryModule public class ModuleStorage extends BlankForestryModule { - public static final IBackpackInterface BACKPACK_INTERFACE = new BackpackInterface(); - - public static final BackpackDefinition APIARIST = new BackpackDefinition(0xc4923d, ForestryColors.WHITE, BACKPACK_INTERFACE.createNaturalistBackpackFilter(ForestrySpeciesTypes.BEE)); - public static final BackpackDefinition ARBORIST = new BackpackDefinition(0x657e3a, ForestryColors.WHITE, BACKPACK_INTERFACE.createNaturalistBackpackFilter(ForestrySpeciesTypes.TREE)); - public static final BackpackDefinition LEPIDOPTERIST = new BackpackDefinition(0x995b31, ForestryColors.WHITE, BACKPACK_INTERFACE.createNaturalistBackpackFilter(ForestrySpeciesTypes.BUTTERFLY)); + public static final BackpackDefinition APIARIST = new BackpackDefinition(0xc4923d, ForestryColors.WHITE, new NaturalistBackpackFilter(ForestrySpeciesTypes.BEE)); + public static final BackpackDefinition ARBORIST = new BackpackDefinition(0x657e3a, ForestryColors.WHITE, new NaturalistBackpackFilter(ForestrySpeciesTypes.TREE)); + public static final BackpackDefinition LEPIDOPTERIST = new BackpackDefinition(0x995b31, ForestryColors.WHITE, new NaturalistBackpackFilter(ForestrySpeciesTypes.BUTTERFLY)); public static final BackpackDefinition MINER = new BackpackDefinition(0x36187d, ForestryColors.WHITE, new BackpackFilter(ForestryTags.Items.MINER_ALLOW, ForestryTags.Items.MINER_REJECT)); public static final BackpackDefinition DIGGER = new BackpackDefinition(0x363cc5, ForestryColors.WHITE, new BackpackFilter(ForestryTags.Items.DIGGER_ALLOW, ForestryTags.Items.DIGGER_REJECT)); public static final BackpackDefinition FORESTER = new BackpackDefinition(0x347427, ForestryColors.WHITE, new BackpackFilter(ForestryTags.Items.FORESTER_ALLOW, ForestryTags.Items.FORESTER_REJECT)); @@ -41,29 +39,28 @@ public ResourceLocation getId() { @Override public void registerEvents(IEventBus modBus) { - MinecraftForge.EVENT_BUS.addListener(ModuleStorage::onItemPickup); - MinecraftForge.EVENT_BUS.addListener(ModuleStorage::onLevelTick); + NeoForge.EVENT_BUS.addListener(ModuleStorage::onItemPickup); + NeoForge.EVENT_BUS.addListener(ModuleStorage::onLevelTick); } - private static void onLevelTick(TickEvent.LevelTickEvent event) { + private static void onLevelTick(LevelTickEvent.Post event) { // todo use register/unregister on the IEventBus if (ForestryConfig.SERVER.enableBackpackResupply.get()) { - if (event.phase == TickEvent.Phase.END) { - for (Player player : event.level.players()) { - BackpackResupplyHandler.resupply(player); - } + for (Player player : event.getLevel().players()) { + BackpackResupplyHandler.resupply(player); } } } - private static void onItemPickup(EntityItemPickupEvent event) { - if (event.isCanceled() || event.getResult() == Event.Result.ALLOW) { - return; - } - - if (PickupHandlerStorage.onItemPickup(event.getEntity(), event.getItem())) { - event.setResult(Event.Result.ALLOW); - } + // TODO TEST + private static void onItemPickup(ItemEntityPickupEvent.Pre event) { +// if (/* previous event consumed the item */) { +// return; +// } +// +// if (PickupHandlerStorage.onItemPickup(event.getEntity(), event.getItem())) { +// event.setCanPickup(/* item should be removed from world, but NOT added to inventory */); +// } } @Override diff --git a/src/main/java/forestry/storage/BackpackFilterNaturalist.java b/src/main/java/forestry/storage/NaturalistBackpackFilter.java similarity index 79% rename from src/main/java/forestry/storage/BackpackFilterNaturalist.java rename to src/main/java/forestry/storage/NaturalistBackpackFilter.java index ce6cb6087f..ef97895a19 100644 --- a/src/main/java/forestry/storage/BackpackFilterNaturalist.java +++ b/src/main/java/forestry/storage/NaturalistBackpackFilter.java @@ -6,10 +6,10 @@ import java.util.function.Predicate; -public class BackpackFilterNaturalist implements Predicate { +public class NaturalistBackpackFilter implements Predicate { private final ResourceLocation speciesRootUid; - public BackpackFilterNaturalist(ResourceLocation speciesType) { + public NaturalistBackpackFilter(ResourceLocation speciesType) { this.speciesRootUid = speciesType; } diff --git a/src/main/java/forestry/storage/PickupHandlerStorage.java b/src/main/java/forestry/storage/PickupHandlerStorage.java index 88e533c9b5..72ba2820e6 100755 --- a/src/main/java/forestry/storage/PickupHandlerStorage.java +++ b/src/main/java/forestry/storage/PickupHandlerStorage.java @@ -1,18 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.storage; -import forestry.api.storage.IBackpackDefinition; -import forestry.storage.gui.ContainerBackpack; -import forestry.storage.gui.ContainerNaturalistBackpack; +import forestry.api.storage.BackpackDefinition; +import forestry.storage.gui.BackpackMenu; +import forestry.storage.gui.NaturalistBackpackMenu; import forestry.storage.items.ItemBackpack; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; @@ -26,7 +16,7 @@ public static boolean onItemPickup(Player player, ItemEntity entityitem) { } // Do not pick up if a backpack is open - if (player.containerMenu instanceof ContainerBackpack || player.containerMenu instanceof ContainerNaturalistBackpack) { + if (player.containerMenu instanceof BackpackMenu || player.containerMenu instanceof NaturalistBackpackMenu) { return false; } @@ -42,8 +32,8 @@ public static boolean onItemPickup(Player player, ItemEntity entityitem) { continue; } - IBackpackDefinition backpackDefinition = backpack.getDefinition(); - if (backpackDefinition.getFilter().test(itemstack)) { + BackpackDefinition backpackDefinition = backpack.getDefinition(); + if (backpackDefinition.filter().test(itemstack)) { ItemBackpack.tryStowing(player, pack, itemstack); } } @@ -70,7 +60,7 @@ private static void topOffPlayerInventory(Player player, ItemStack itemstack) { continue; } - if (ItemStack.isSameItemSameTags(inventoryStack, itemstack)) { + if (ItemStack.isSameItemSameComponents(inventoryStack, itemstack)) { int space = inventoryStack.getMaxStackSize() - inventoryStack.getCount(); if (space > itemstack.getCount()) { diff --git a/src/main/java/forestry/storage/client/FilledCrateModel.java b/src/main/java/forestry/storage/client/FilledCrateModel.java index 8dce5c8f74..d83808f2a4 100644 --- a/src/main/java/forestry/storage/client/FilledCrateModel.java +++ b/src/main/java/forestry/storage/client/FilledCrateModel.java @@ -16,9 +16,9 @@ import net.minecraft.util.GsonHelper; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.geometry.IGeometryBakingContext; -import net.minecraftforge.client.model.geometry.IGeometryLoader; -import net.minecraftforge.client.model.geometry.IUnbakedGeometry; +import net.neoforged.neoforge.client.model.geometry.IGeometryBakingContext; +import net.neoforged.neoforge.client.model.geometry.IGeometryLoader; +import net.neoforged.neoforge.client.model.geometry.IUnbakedGeometry; import org.joml.Vector3f; import javax.annotation.Nullable; @@ -45,14 +45,14 @@ public FilledCrateModel(BlockModel contents) { @SuppressWarnings("DataFlowIssue") @Override - public BakedModel bake(IGeometryBakingContext context, ModelBaker bakery, Function spriteGetter, ModelState modelState, ItemOverrides overrides, ResourceLocation modelLocation) { + public BakedModel bake(IGeometryBakingContext context, ModelBaker bakery, Function spriteGetter, ModelState modelState, ItemOverrides overrides) { if (cachedBaseModel == null) { - cachedBaseModel = bakery.getModel(Loader.FILLED_CRATE_LOCATION).bake(bakery, spriteGetter, modelState, modelLocation); + cachedBaseModel = bakery.getModel(Loader.FILLED_CRATE_LOCATION).bake(bakery, spriteGetter, modelState); cachedTransforms = cachedBaseModel.getTransforms(); cachedQuads = cachedBaseModel.getQuads(null, null, RandomSource.create()); } - return new Baked(this.contents.bake(bakery, spriteGetter, modelState, modelLocation), cachedQuads, cachedTransforms); + return new Baked(this.contents.bake(bakery, spriteGetter, modelState), cachedQuads, cachedTransforms); } public static class Loader implements IGeometryLoader { diff --git a/src/main/java/forestry/storage/client/StorageClientHandler.java b/src/main/java/forestry/storage/client/StorageClientHandler.java index 52c19219c3..b547648bc1 100644 --- a/src/main/java/forestry/storage/client/StorageClientHandler.java +++ b/src/main/java/forestry/storage/client/StorageClientHandler.java @@ -7,23 +7,22 @@ import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; import forestry.storage.features.BackpackMenuTypes; -import forestry.storage.gui.ContainerNaturalistBackpack; +import forestry.storage.gui.NaturalistBackpackMenu; import forestry.storage.gui.GuiBackpack; import forestry.storage.items.ItemBackpack; -import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.renderer.item.ItemProperties; import net.minecraft.client.renderer.item.ItemPropertyFunction; import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.Holder; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.ModelEvent; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; public class StorageClientHandler implements IClientModuleHandler { - public static final ModelResourceLocation FILLED_CRATE_MODEL = new ModelResourceLocation(ForestryConstants.MOD_ID, "filled_crate", "inventory"); + public static final ModelResourceLocation FILLED_CRATE_MODEL = new ModelResourceLocation(ForestryConstants.forestry("filled_crate"), "inventory"); @Override public void registerEvents(IEventBus modBus) { @@ -38,9 +37,9 @@ public void registerEvents(IEventBus modBus) { @SuppressWarnings("deprecation") ItemPropertyFunction itemPropertyFunction = (stack, clientLevel, holder, idk) -> ItemBackpack.getMode(stack).ordinal(); - for (RegistryObject entry : registry.getRegistry(Registries.ITEM).getEntries()) { - if (entry.get() instanceof ItemBackpack) { - ItemProperties.register(entry.get(), new ResourceLocation("mode"), itemPropertyFunction); + for (Holder entry : registry.getRegistry(Registries.ITEM).getEntries()) { + if (entry.value() instanceof ItemBackpack backpack) { + ItemProperties.register(backpack, ResourceLocation.withDefaultNamespace("mode"), itemPropertyFunction); } } }); @@ -51,7 +50,7 @@ private static void registerAdditionalModels(ModelEvent.RegisterAdditional event } private static void registerModelLoaders(ModelEvent.RegisterGeometryLoaders event) { - event.register("filled_crate", new FilledCrateModel.Loader()); + event.register(ForestryConstants.forestry("filled_crate"), new FilledCrateModel.Loader()); } private static void onModelBake(ModelEvent.BakingCompleted event) { @@ -60,10 +59,8 @@ private static void onModelBake(ModelEvent.BakingCompleted event) { FilledCrateModel.cachedQuads = null; } - private static void onClientSetup(FMLClientSetupEvent event) { - event.enqueueWork(() -> { - MenuScreens.register(BackpackMenuTypes.BACKPACK.menuType(), GuiBackpack::new); - MenuScreens.register(BackpackMenuTypes.NATURALIST_BACKPACK.menuType(), GuiNaturalistInventory::new); - }); + private static void onClientSetup(RegisterMenuScreensEvent event) { + event.register(BackpackMenuTypes.BACKPACK.menuType(), GuiBackpack::new); + event.register(BackpackMenuTypes.NATURALIST_BACKPACK.menuType(), GuiNaturalistInventory::new); } } diff --git a/src/main/java/forestry/storage/client/package-info.java b/src/main/java/forestry/storage/client/package-info.java index 07bd2a0cd4..70e1f55c61 100644 --- a/src/main/java/forestry/storage/client/package-info.java +++ b/src/main/java/forestry/storage/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage.client; diff --git a/src/main/java/forestry/storage/compat/StorageJeiPlugin.java b/src/main/java/forestry/storage/compat/StorageJeiPlugin.java index 1ad3533261..059f041165 100644 --- a/src/main/java/forestry/storage/compat/StorageJeiPlugin.java +++ b/src/main/java/forestry/storage/compat/StorageJeiPlugin.java @@ -1,7 +1,7 @@ package forestry.storage.compat; import forestry.api.modules.ForestryModuleIds; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.storage.features.BackpackItems; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; diff --git a/src/main/java/forestry/storage/compat/package-info.java b/src/main/java/forestry/storage/compat/package-info.java index ee09370b00..bc6087b9e5 100644 --- a/src/main/java/forestry/storage/compat/package-info.java +++ b/src/main/java/forestry/storage/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage.compat; diff --git a/src/main/java/forestry/storage/features/BackpackItems.java b/src/main/java/forestry/storage/features/BackpackItems.java index 683aee632f..72ac5a194a 100644 --- a/src/main/java/forestry/storage/features/BackpackItems.java +++ b/src/main/java/forestry/storage/features/BackpackItems.java @@ -1,33 +1,34 @@ package forestry.storage.features; -import forestry.api.core.ItemGroups; import forestry.api.genetics.ForestrySpeciesTypes; import forestry.api.modules.ForestryModuleIds; -import forestry.api.storage.EnumBackpackType; +import forestry.storage.items.EnumBackpackType; import forestry.modules.features.FeatureItem; import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; import forestry.storage.ModuleStorage; +import forestry.storage.items.ItemBackpack; +import forestry.storage.items.ItemBackpackNaturalist; @FeatureProvider public class BackpackItems { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.STORAGE); - public static final FeatureItem APIARIST_BACKPACK = REGISTRY.naturalistBackpack(ModuleStorage.APIARIST, ForestrySpeciesTypes.BEE, ItemGroups.tabApiculture, "apiarist_bag"); - public static final FeatureItem ARBORIST_BACKPACK = REGISTRY.naturalistBackpack(ModuleStorage.ARBORIST, ForestrySpeciesTypes.TREE, ItemGroups.tabArboriculture, "arborist_bag"); - public static final FeatureItem LEPIDOPTERIST_BACKPACK = REGISTRY.naturalistBackpack(ModuleStorage.LEPIDOPTERIST, ForestrySpeciesTypes.BUTTERFLY, ItemGroups.tabLepidopterology, "lepidopterist_bag"); + public static final FeatureItem APIARIST_BACKPACK = REGISTRY.item(() -> new ItemBackpackNaturalist(ForestrySpeciesTypes.BEE, ModuleStorage.APIARIST), "apiarist_bag"); + public static final FeatureItem ARBORIST_BACKPACK = REGISTRY.item(() -> new ItemBackpackNaturalist(ForestrySpeciesTypes.TREE, ModuleStorage.ARBORIST), "arborist_bag"); + public static final FeatureItem LEPIDOPTERIST_BACKPACK = REGISTRY.item(() -> new ItemBackpackNaturalist(ForestrySpeciesTypes.BUTTERFLY, ModuleStorage.LEPIDOPTERIST), "lepidopterist_bag"); - public static final FeatureItem MINER_BACKPACK = REGISTRY.backpack(ModuleStorage.MINER, EnumBackpackType.NORMAL, "miner_bag"); - public static final FeatureItem MINER_BACKPACK_T_2 = REGISTRY.backpack(ModuleStorage.MINER, EnumBackpackType.WOVEN, "miner_bag_woven"); - public static final FeatureItem DIGGER_BACKPACK = REGISTRY.backpack(ModuleStorage.DIGGER, EnumBackpackType.NORMAL, "digger_bag"); - public static final FeatureItem DIGGER_BACKPACK_T_2 = REGISTRY.backpack(ModuleStorage.DIGGER, EnumBackpackType.WOVEN, "digger_bag_woven"); - public static final FeatureItem FORESTER_BACKPACK = REGISTRY.backpack(ModuleStorage.FORESTER, EnumBackpackType.NORMAL, "forester_bag"); - public static final FeatureItem FORESTER_BACKPACK_T_2 = REGISTRY.backpack(ModuleStorage.FORESTER, EnumBackpackType.WOVEN, "forester_bag_woven"); - public static final FeatureItem HUNTER_BACKPACK = REGISTRY.backpack(ModuleStorage.HUNTER, EnumBackpackType.NORMAL, "hunter_bag"); - public static final FeatureItem HUNTER_BACKPACK_T_2 = REGISTRY.backpack(ModuleStorage.HUNTER, EnumBackpackType.WOVEN, "hunter_bag_woven"); - public static final FeatureItem ADVENTURER_BACKPACK = REGISTRY.backpack(ModuleStorage.ADVENTURER, EnumBackpackType.NORMAL, "adventurer_bag"); - public static final FeatureItem ADVENTURER_BACKPACK_T_2 = REGISTRY.backpack(ModuleStorage.ADVENTURER, EnumBackpackType.WOVEN, "adventurer_bag_woven"); - public static final FeatureItem BUILDER_BACKPACK = REGISTRY.backpack(ModuleStorage.BUILDER, EnumBackpackType.NORMAL, "builder_bag"); - public static final FeatureItem BUILDER_BACKPACK_T_2 = REGISTRY.backpack(ModuleStorage.BUILDER, EnumBackpackType.WOVEN, "builder_bag_woven"); + public static final FeatureItem MINER_BACKPACK = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.MINER, EnumBackpackType.NORMAL), "miner_bag"); + public static final FeatureItem MINER_BACKPACK_T_2 = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.MINER, EnumBackpackType.WOVEN), "miner_bag_woven"); + public static final FeatureItem DIGGER_BACKPACK = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.DIGGER, EnumBackpackType.NORMAL), "digger_bag"); + public static final FeatureItem DIGGER_BACKPACK_T_2 = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.DIGGER, EnumBackpackType.WOVEN), "digger_bag_woven"); + public static final FeatureItem FORESTER_BACKPACK = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.FORESTER, EnumBackpackType.NORMAL), "forester_bag"); + public static final FeatureItem FORESTER_BACKPACK_T_2 = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.FORESTER, EnumBackpackType.WOVEN), "forester_bag_woven"); + public static final FeatureItem HUNTER_BACKPACK = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.HUNTER, EnumBackpackType.NORMAL), "hunter_bag"); + public static final FeatureItem HUNTER_BACKPACK_T_2 = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.HUNTER, EnumBackpackType.WOVEN), "hunter_bag_woven"); + public static final FeatureItem ADVENTURER_BACKPACK = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.ADVENTURER, EnumBackpackType.NORMAL), "adventurer_bag"); + public static final FeatureItem ADVENTURER_BACKPACK_T_2 = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.ADVENTURER, EnumBackpackType.WOVEN), "adventurer_bag_woven"); + public static final FeatureItem BUILDER_BACKPACK = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.BUILDER, EnumBackpackType.NORMAL), "builder_bag"); + public static final FeatureItem BUILDER_BACKPACK_T_2 = REGISTRY.item(() -> new ItemBackpack(ModuleStorage.BUILDER, EnumBackpackType.WOVEN), "builder_bag_woven"); } diff --git a/src/main/java/forestry/storage/features/BackpackMenuTypes.java b/src/main/java/forestry/storage/features/BackpackMenuTypes.java index 25fe614abf..104fec4467 100644 --- a/src/main/java/forestry/storage/features/BackpackMenuTypes.java +++ b/src/main/java/forestry/storage/features/BackpackMenuTypes.java @@ -5,13 +5,13 @@ import forestry.modules.features.FeatureProvider; import forestry.modules.features.IFeatureRegistry; import forestry.modules.features.ModFeatureRegistry; -import forestry.storage.gui.ContainerBackpack; -import forestry.storage.gui.ContainerNaturalistBackpack; +import forestry.storage.gui.BackpackMenu; +import forestry.storage.gui.NaturalistBackpackMenu; @FeatureProvider public class BackpackMenuTypes { private static final IFeatureRegistry REGISTRY = ModFeatureRegistry.get(ForestryModuleIds.STORAGE); - public static final FeatureMenuType BACKPACK = REGISTRY.menuType(ContainerBackpack::fromNetwork, "backpack"); - public static final FeatureMenuType NATURALIST_BACKPACK = REGISTRY.menuType(ContainerNaturalistBackpack::fromNetwork, "naturalist_backpack"); + public static final FeatureMenuType BACKPACK = REGISTRY.menuType(BackpackMenu::fromNetwork, "backpack"); + public static final FeatureMenuType NATURALIST_BACKPACK = REGISTRY.menuType(NaturalistBackpackMenu::fromNetwork, "naturalist_backpack"); } diff --git a/src/main/java/forestry/storage/features/CrateItems.java b/src/main/java/forestry/storage/features/CrateItems.java index f64b641b8b..c0c7ae6fb0 100644 --- a/src/main/java/forestry/storage/features/CrateItems.java +++ b/src/main/java/forestry/storage/features/CrateItems.java @@ -97,7 +97,7 @@ public class CrateItems { public static final FeatureItem CRATED_PROPOLIS = register(ApicultureItems.PROPOLIS.get(EnumPropolis.NORMAL), "crated_propolis"); public static final FeatureItem CRATED_HONEYDEW = register(ApicultureItems.HONEYDEW, "crated_honeydew"); public static final FeatureItem CRATED_ROYAL_JELLY = register(ApicultureItems.ROYAL_JELLY, "crated_royal_jelly"); - public static final FeatureItemGroup CRATED_BEE_COMBS = REGISTRY.itemGroup(comb -> new ItemCrated(() -> ApicultureItems.BEE_COMBS.get(comb).stack()), "crated_bee_comb", EnumHoneyComb.VALUES); + public static final FeatureItemGroup CRATED_BEE_COMBS = REGISTRY.itemGroup(comb -> new ItemCrated(() -> ApicultureItems.BEE_COMBS.get(comb).stack()), "crated_bee_comb", EnumHoneyComb.values()); static { CRATES.addAll(CRATED_BEE_COMBS.getFeatures()); diff --git a/src/main/java/forestry/storage/features/package-info.java b/src/main/java/forestry/storage/features/package-info.java index e41963c3f7..90570d469a 100644 --- a/src/main/java/forestry/storage/features/package-info.java +++ b/src/main/java/forestry/storage/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage.features; diff --git a/src/main/java/forestry/storage/gui/BackpackMenu.java b/src/main/java/forestry/storage/gui/BackpackMenu.java new file mode 100644 index 0000000000..13c90d79c9 --- /dev/null +++ b/src/main/java/forestry/storage/gui/BackpackMenu.java @@ -0,0 +1,43 @@ +package forestry.storage.gui; + +import forestry.core.gui.ItemInventoryMenu; +import forestry.core.gui.slots.SlotFilteredInventory; +import forestry.storage.features.BackpackMenuTypes; +import forestry.storage.inventory.ItemInventoryBackpack; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.world.entity.player.Inventory; + +public class BackpackMenu extends ItemInventoryMenu { + public record Size(int rows, int columns, int startX, int startY) { + public static final Size DEFAULT = new Size(3, 5, 44, 19); + public static final Size T2 = new Size(5, 9, 8, 8); + + public int getSize() { + return this.rows * this.columns; + } + } + + private final Size size; + + public static BackpackMenu fromNetwork(int containerId, Inventory inv, RegistryFriendlyByteBuf extraData) { + int slotIndex = extraData.readByte(); + Size size = extraData.readBoolean() ? Size.T2 : Size.DEFAULT; + return new BackpackMenu(containerId, inv, size, slotIndex); + } + + public BackpackMenu(int containerId, Inventory playerInv, Size size, int slotIndex) { + super(BackpackMenuTypes.BACKPACK.menuType(), containerId, new ItemInventoryBackpack(size.getSize(), playerInv.getItem(slotIndex)), playerInv, 8, 11 + size.startY + size.rows * 18); + this.size = size; + // Inventory + for (int j = 0; j < size.rows; j++) { + for (int k = 0; k < size.columns; k++) { + int slot = k + j * size.columns; + addSlot(new SlotFilteredInventory(this.inventory, slot, size.startX + k * 18, size.startY + j * 18)); + } + } + } + + public Size getSize() { + return this.size; + } +} diff --git a/src/main/java/forestry/storage/gui/ContainerBackpack.java b/src/main/java/forestry/storage/gui/ContainerBackpack.java deleted file mode 100755 index 86d5925b0a..0000000000 --- a/src/main/java/forestry/storage/gui/ContainerBackpack.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.gui; - -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.slots.SlotFilteredInventory; -import forestry.storage.features.BackpackMenuTypes; -import forestry.storage.inventory.ItemInventoryBackpack; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -public class ContainerBackpack extends ContainerItemInventory { - public enum Size { - DEFAULT(3, 5, 44, 19), - T2(5, 9, 8, 8); - - final int rows; - final int columns; - final int startX; - final int startY; - - Size(int rows, int columns, int startX, int startY) { - this.rows = rows; - this.columns = columns; - this.startX = startX; - this.startY = startY; - } - - public int getSize() { - return this.rows * this.columns; - } - } - - private final Size size; - - public static ContainerBackpack fromNetwork(int windowID, Inventory inv, FriendlyByteBuf extraData) { - Size size = extraData.readEnum(Size.class); - ItemStack parent = extraData.readItem(); - return new ContainerBackpack(windowID, inv.player, size, parent); - } - - public ContainerBackpack(int windowID, Player player, Size size, ItemStack parent) { - super(windowID, new ItemInventoryBackpack(player, size.getSize(), parent), player.getInventory(), 8, 11 + size.startY + size.rows * 18, BackpackMenuTypes.BACKPACK.menuType()); - this.size = size; - // Inventory - for (int j = 0; j < size.rows; j++) { - for (int k = 0; k < size.columns; k++) { - int slot = k + j * size.columns; - addSlot(new SlotFilteredInventory(this.inventory, slot, size.startX + k * 18, size.startY + j * 18)); - } - } - } - - public Size getSize() { - return this.size; - } -} diff --git a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java deleted file mode 100755 index a97c4b4238..0000000000 --- a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.storage.gui; - -import forestry.api.IForestryApi; -import forestry.api.genetics.ISpeciesType; -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.ContainerNaturalistInventory; -import forestry.core.gui.IGuiSelectable; -import forestry.core.gui.INaturalistMenu; -import forestry.storage.features.BackpackMenuTypes; -import forestry.storage.inventory.ItemInventoryBackpackPaged; -import forestry.storage.items.ItemBackpack; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -public class ContainerNaturalistBackpack extends ContainerItemInventory implements IGuiSelectable, INaturalistMenu { - private final int currentPage; - private final ISpeciesType speciesRoot; - - public ContainerNaturalistBackpack(int windowId, Inventory inv, ItemInventoryBackpackPaged inventory, int selectedPage, ResourceLocation rootUid) { - super(windowId, inventory, inv, 18, 120, BackpackMenuTypes.NATURALIST_BACKPACK.menuType()); - - ContainerNaturalistInventory.addInventory(this, inventory, selectedPage); - - this.currentPage = selectedPage; - this.speciesRoot = IForestryApi.INSTANCE.getGeneticManager().getSpeciesType(rootUid); - } - - public static ContainerNaturalistBackpack makeContainer(int windowId, Player player, ItemStack heldItem, int page, ResourceLocation typeId) { - ItemInventoryBackpackPaged inventory = new ItemInventoryBackpackPaged(player, ItemBackpack.SLOTS_BACKPACK_APIARIST, heldItem, typeId); - return new ContainerNaturalistBackpack(windowId, player.getInventory(), inventory, page, typeId); - } - - @Override - public void handleSelectionRequest(ServerPlayer player, int primary, int secondary) { - this.inventory.flipPage(player, (short) primary); - } - - @Override - public ISpeciesType getSpeciesType() { - return this.speciesRoot; - } - - @Override - public int getCurrentPage() { - return this.currentPage; - } - - public static ContainerNaturalistBackpack fromNetwork(int windowId, Inventory playerInventory, FriendlyByteBuf buffer) { - int page = buffer.readByte(); - ResourceLocation typeId = buffer.readResourceLocation(); - ItemStack parent = playerInventory.getSelected(); - - return makeContainer(windowId, playerInventory.player, parent, page, typeId); - } -} diff --git a/src/main/java/forestry/storage/gui/GuiBackpack.java b/src/main/java/forestry/storage/gui/GuiBackpack.java index 338b01e038..b7b4a07ca9 100755 --- a/src/main/java/forestry/storage/gui/GuiBackpack.java +++ b/src/main/java/forestry/storage/gui/GuiBackpack.java @@ -15,20 +15,20 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -public class GuiBackpack extends GuiForestry { - public GuiBackpack(ContainerBackpack container, Inventory inv, Component title) { +public class GuiBackpack extends GuiForestry { + public GuiBackpack(BackpackMenu container, Inventory inv, Component title) { super(getTextureString(container), container, inv, title); - ContainerBackpack.Size size = container.getSize(); + BackpackMenu.Size size = container.getSize(); - if (size == ContainerBackpack.Size.T2) { + if (size == BackpackMenu.Size.T2) { this.imageWidth = 176; this.imageHeight = 192; } } - private static String getTextureString(ContainerBackpack container) { - ContainerBackpack.Size size = container.getSize(); - if (size == ContainerBackpack.Size.T2) { + private static String getTextureString(BackpackMenu container) { + BackpackMenu.Size size = container.getSize(); + if (size == BackpackMenu.Size.T2) { return Constants.TEXTURE_PATH_GUI + "/backpack_t2.png"; } return Constants.TEXTURE_PATH_GUI + "/backpack.png"; diff --git a/src/main/java/forestry/storage/gui/NaturalistBackpackMenu.java b/src/main/java/forestry/storage/gui/NaturalistBackpackMenu.java new file mode 100644 index 0000000000..dfed3c410b --- /dev/null +++ b/src/main/java/forestry/storage/gui/NaturalistBackpackMenu.java @@ -0,0 +1,57 @@ +package forestry.storage.gui; + +import forestry.api.IForestryApi; +import forestry.api.genetics.ISpeciesType; +import forestry.core.gui.ItemInventoryMenu; +import forestry.core.gui.NaturalistInventoryMenu; +import forestry.core.gui.IGuiSelectable; +import forestry.core.gui.INaturalistMenu; +import forestry.storage.features.BackpackMenuTypes; +import forestry.storage.inventory.ItemInventoryBackpackPaged; +import forestry.storage.items.ItemBackpack; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; + +public class NaturalistBackpackMenu extends ItemInventoryMenu implements IGuiSelectable, INaturalistMenu { + private final int currentPage; + private final ISpeciesType speciesRoot; + + public NaturalistBackpackMenu(int windowId, Inventory inv, ItemInventoryBackpackPaged inventory, int selectedPage, ResourceLocation rootUid) { + super(BackpackMenuTypes.NATURALIST_BACKPACK.menuType(), windowId, inventory, inv, 18, 120); + + NaturalistInventoryMenu.addInventory(this, inventory, selectedPage); + + this.currentPage = selectedPage; + this.speciesRoot = IForestryApi.INSTANCE.getGeneticManager().getSpeciesType(rootUid); + } + + public static NaturalistBackpackMenu makeContainer(int windowId, Inventory playerInv, int slotIndex, int page, ResourceLocation typeId) { + ItemInventoryBackpackPaged inventory = new ItemInventoryBackpackPaged(ItemBackpack.SLOTS_BACKPACK_APIARIST, playerInv.getItem(slotIndex), typeId); + return new NaturalistBackpackMenu(windowId, playerInv, inventory, page, typeId); + } + + @Override + public void handleSelectionRequest(ServerPlayer player, int primary, int secondary) { + this.inventory.flipPage(player, (short) primary); + } + + @Override + public ISpeciesType getSpeciesType() { + return this.speciesRoot; + } + + @Override + public int getCurrentPage() { + return this.currentPage; + } + + public static NaturalistBackpackMenu fromNetwork(int windowId, Inventory playerInv, FriendlyByteBuf buffer) { + int slotIndex = buffer.readByte(); + int page = buffer.readByte(); + ResourceLocation typeId = buffer.readResourceLocation(); + + return makeContainer(windowId, playerInv, slotIndex, page, typeId); + } +} diff --git a/src/main/java/forestry/storage/gui/package-info.java b/src/main/java/forestry/storage/gui/package-info.java index e40d174792..c9e73a51dc 100644 --- a/src/main/java/forestry/storage/gui/package-info.java +++ b/src/main/java/forestry/storage/gui/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage.gui; diff --git a/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java b/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java index ceac7dae6c..63711c67f7 100644 --- a/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java +++ b/src/main/java/forestry/storage/inventory/ItemInventoryBackpack.java @@ -1,27 +1,24 @@ package forestry.storage.inventory; -import com.google.common.base.Preconditions; -import forestry.api.storage.IBackpackDefinition; +import forestry.api.storage.BackpackDefinition; import forestry.core.inventory.ItemInventory; import forestry.storage.items.ItemBackpack; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; public class ItemInventoryBackpack extends ItemInventory { - private final IBackpackDefinition backpackDefinition; + private final BackpackDefinition backpackDefinition; - public ItemInventoryBackpack(Player player, int size, ItemStack parent) { - super(player, size, parent); + public ItemInventoryBackpack(int size, ItemStack parent) { + super(size, parent); Item item = parent.getItem(); - Preconditions.checkArgument(item instanceof ItemBackpack, "Parent must be a backpack."); this.backpackDefinition = ((ItemBackpack) item).getDefinition(); } @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { - return this.backpackDefinition.getFilter().test(stack); + return this.backpackDefinition.filter().test(stack); } } diff --git a/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java b/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java index 20e5787651..8c7db2a5c4 100644 --- a/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java +++ b/src/main/java/forestry/storage/inventory/ItemInventoryBackpackPaged.java @@ -1,37 +1,25 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.storage.inventory; import forestry.core.gui.IPagedInventory; -import forestry.storage.gui.ContainerNaturalistBackpack; +import forestry.storage.gui.NaturalistBackpackMenu; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.SimpleMenuProvider; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkHooks; public class ItemInventoryBackpackPaged extends ItemInventoryBackpack implements IPagedInventory { private final ResourceLocation typeId; - public ItemInventoryBackpackPaged(Player player, int size, ItemStack itemstack, ResourceLocation typeId) { - super(player, size, itemstack); + public ItemInventoryBackpackPaged(int size, ItemStack itemstack, ResourceLocation typeId) { + super(size, itemstack); this.typeId = typeId; } @Override public void flipPage(ServerPlayer player, short page) { ItemStack backpack = getParent(); - SimpleMenuProvider provider = new SimpleMenuProvider((windowId, playerInv, p) -> ContainerNaturalistBackpack.makeContainer(windowId, p, backpack, page, this.typeId), backpack.getHoverName()); - NetworkHooks.openScreen(player, provider, buffer -> { + SimpleMenuProvider provider = new SimpleMenuProvider((windowId, playerInv, p) -> NaturalistBackpackMenu.makeContainer(windowId, playerInv, this.slotIndex, page, this.typeId), backpack.getHoverName()); + player.openMenu(provider, buffer -> { buffer.writeByte(page); buffer.writeResourceLocation(this.typeId); }); diff --git a/src/main/java/forestry/storage/inventory/package-info.java b/src/main/java/forestry/storage/inventory/package-info.java index 16613582d5..ec2acb6e03 100644 --- a/src/main/java/forestry/storage/inventory/package-info.java +++ b/src/main/java/forestry/storage/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage.inventory; diff --git a/src/main/java/forestry/api/storage/EnumBackpackType.java b/src/main/java/forestry/storage/items/EnumBackpackType.java similarity index 89% rename from src/main/java/forestry/api/storage/EnumBackpackType.java rename to src/main/java/forestry/storage/items/EnumBackpackType.java index a1ca1f46bd..7d82b76da9 100644 --- a/src/main/java/forestry/api/storage/EnumBackpackType.java +++ b/src/main/java/forestry/storage/items/EnumBackpackType.java @@ -1,4 +1,4 @@ -package forestry.api.storage; +package forestry.storage.items; import net.minecraft.util.StringRepresentable; diff --git a/src/main/java/forestry/storage/items/ItemBackpack.java b/src/main/java/forestry/storage/items/ItemBackpack.java index 3c44f6a765..c92eac178c 100755 --- a/src/main/java/forestry/storage/items/ItemBackpack.java +++ b/src/main/java/forestry/storage/items/ItemBackpack.java @@ -1,40 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.storage.items; -import com.google.common.base.Preconditions; -import forestry.api.storage.BackpackStowEvent; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; +import forestry.api.event.BackpackEvent; +import forestry.api.storage.BackpackDefinition; import forestry.core.config.ForestryConfig; import forestry.core.inventory.ItemHandlerInventoryManipulator; import forestry.core.inventory.ItemInventory; -import forestry.core.inventory.StandardStackFilters; import forestry.core.items.ItemWithGui; import forestry.core.items.definitions.IColoredItem; import forestry.core.tiles.TileUtil; -import forestry.core.utils.NetworkUtil; import forestry.storage.BackpackMode; -import forestry.storage.gui.ContainerBackpack; +import forestry.storage.gui.BackpackMenu; import forestry.storage.inventory.ItemInventoryBackpack; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.Item; @@ -43,10 +29,8 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.items.IItemHandler; import javax.annotation.Nullable; import java.util.List; @@ -55,32 +39,33 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { public static final int SLOTS_BACKPACK_DEFAULT = 15; public static final int SLOTS_BACKPACK_WOVEN = 45; public static final int SLOTS_BACKPACK_APIARIST = 125; - private final IBackpackDefinition definition; + private final BackpackDefinition definition; private final EnumBackpackType type; - public ItemBackpack(IBackpackDefinition definition, EnumBackpackType type) { + public ItemBackpack(BackpackDefinition definition, EnumBackpackType type) { super(new Item.Properties().stacksTo(1)); this.definition = definition; this.type = type; } - public IBackpackDefinition getDefinition() { + public BackpackDefinition getDefinition() { return this.definition; } @Override - protected void writeContainerData(ServerPlayer player, ItemStack stack, FriendlyByteBuf buffer) { - NetworkUtil.writeEnum(buffer, this.type == EnumBackpackType.WOVEN ? ContainerBackpack.Size.T2 : ContainerBackpack.Size.DEFAULT); - buffer.writeItem(stack); + protected void writeContainerData(RegistryFriendlyByteBuf buffer, Player player, ItemStack stack, int slotIndex) { + // isWoven + buffer.writeByte(slotIndex); + buffer.writeBoolean(this.type == EnumBackpackType.WOVEN); } @Override - public InteractionResultHolder use(Level worldIn, Player playerIn, InteractionHand handIn) { + public InteractionResultHolder use(Level level, Player playerIn, InteractionHand hand) { if (!playerIn.isShiftKeyDown()) { - return super.use(worldIn, playerIn, handIn); + return super.use(level, playerIn, hand); } else { - ItemStack heldItem = playerIn.getItemInHand(handIn); + ItemStack heldItem = playerIn.getItemInHand(hand); switchMode(heldItem); return InteractionResultHolder.success(heldItem); } @@ -101,7 +86,7 @@ public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) { // We only do this when shift is clicked if (player != null && player.isShiftKeyDown()) { ItemStack heldItem = player.getItemInHand(context.getHand()); - return evaluateTileHit(heldItem, player, context.getLevel(), context.getClickedPos(), context.getClickedFace()) ? InteractionResult.PASS : InteractionResult.FAIL; + return evaluateTileHit(heldItem, context.getLevel(), context.getClickedPos(), context.getClickedFace()) ? InteractionResult.PASS : InteractionResult.FAIL; } return super.onItemUseFirst(stack, context); } @@ -112,9 +97,9 @@ public static void tryStowing(Player player, ItemStack backpackStack, ItemStack } ItemBackpack backpack = (ItemBackpack) backpackStack.getItem(); - ItemInventory inventory = new ItemInventoryBackpack(player, backpack.getBackpackSize(), backpackStack); + ItemInventory inventory = new ItemInventoryBackpack(backpack.getBackpackSize(), backpackStack); - if (MinecraftForge.EVENT_BUS.post(new BackpackStowEvent(player, backpack.getDefinition(), inventory, stack))) { + if (NeoForge.EVENT_BUS.post(new BackpackEvent.Stow(player, backpack.getDefinition(), inventory, stack)).isCanceled()) { return; } if (stack.isEmpty()) { @@ -144,8 +129,7 @@ private static IItemHandler getInventoryHit(Level world, BlockPos pos, Direction return TileUtil.getInventoryFromTile(targeted, side); } - private boolean evaluateTileHit(ItemStack stack, Player player, Level world, BlockPos pos, Direction side) { - + private boolean evaluateTileHit(ItemStack stack, Level world, BlockPos pos, Direction side) { // Shift right-clicking on an inventory tile will attempt to transfer // items contained in the backpack IItemHandler inventory = getInventoryHit(world, pos, side); @@ -159,7 +143,7 @@ private boolean evaluateTileHit(ItemStack stack, Player player, Level world, Blo if (!world.isClientSide) { // Create our own backpack inventory - ItemInventoryBackpack backpackInventory = new ItemInventoryBackpack(player, getBackpackSize(), stack); + ItemInventoryBackpack backpackInventory = new ItemInventoryBackpack(getBackpackSize(), stack); BackpackMode mode = getMode(stack); if (mode == BackpackMode.RECEIVE) { @@ -177,12 +161,12 @@ private boolean evaluateTileHit(ItemStack stack, Player player, Level world, Blo private static void transferToChest(ItemInventoryBackpack backpackInventory, IItemHandler target) { ItemHandlerInventoryManipulator manipulator = new ItemHandlerInventoryManipulator(backpackInventory.getItemHandler()); - manipulator.transferStacks(target, StandardStackFilters.ALL); + manipulator.transferStacks(target, stack -> true); } private void receiveFromChest(ItemInventoryBackpack backpackInventory, IItemHandler target) { ItemHandlerInventoryManipulator manipulator = new ItemHandlerInventoryManipulator(target); - manipulator.transferStacks(backpackInventory.getItemHandler(), this.definition.getFilter()); + manipulator.transferStacks(backpackInventory.getItemHandler(), this.definition.filter()); } public int getBackpackSize() { @@ -190,13 +174,12 @@ public int getBackpackSize() { } @Override - @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack itemstack, @Nullable Level world, List list, TooltipFlag flag) { - super.appendHoverText(itemstack, world, list, flag); + public void appendHoverText(ItemStack stack, TooltipContext ctx, List list, TooltipFlag flag) { + super.appendHoverText(stack, ctx, list, flag); - int occupied = ItemInventory.getOccupiedSlotCount(itemstack); + int occupied = ItemInventory.getOccupiedSlotCount(stack); - BackpackMode mode = getMode(itemstack); + BackpackMode mode = getMode(stack); String infoKey = mode.getTranslationKey(); if (infoKey != null) { list.add(Component.translatable(infoKey).withStyle(ChatFormatting.GRAY)); @@ -205,16 +188,11 @@ public void appendHoverText(ItemStack itemstack, @Nullable Level world, List new ContainerBackpack(windowId, player, ContainerBackpack.Size.DEFAULT, heldItem); - case WOVEN -> new ContainerBackpack(windowId, player, ContainerBackpack.Size.T2, heldItem); + public AbstractContainerMenu createMenu(int containerId, Inventory playerInv, int slotIndex) { + return switch (this.type) { + case NORMAL -> new BackpackMenu(containerId, playerInv, BackpackMenu.Size.DEFAULT, slotIndex); + case WOVEN -> new BackpackMenu(containerId, playerInv, BackpackMenu.Size.T2, slotIndex); default -> null; }; } diff --git a/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java b/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java index 4cce55cbca..367f5f92fb 100644 --- a/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java +++ b/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java @@ -1,42 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.storage.items; -import forestry.api.storage.EnumBackpackType; -import forestry.api.storage.IBackpackDefinition; -import forestry.storage.gui.ContainerNaturalistBackpack; -import net.minecraft.network.FriendlyByteBuf; +import forestry.api.storage.BackpackDefinition; +import forestry.storage.gui.NaturalistBackpackMenu; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; public class ItemBackpackNaturalist extends ItemBackpack { public final ResourceLocation typeId; - public ItemBackpackNaturalist(ResourceLocation typeId, IBackpackDefinition definition, CreativeModeTab tab) { + public ItemBackpackNaturalist(ResourceLocation typeId, BackpackDefinition definition) { super(definition, EnumBackpackType.NATURALIST); this.typeId = typeId; } @Override - protected void writeContainerData(ServerPlayer player, ItemStack stack, FriendlyByteBuf buffer) { + protected void writeContainerData(RegistryFriendlyByteBuf buffer, Player player, ItemStack stack, int slotIndex) { + // Item slot index + buffer.writeByte(slotIndex); + // Page number buffer.writeByte(0); + // Species type buffer.writeResourceLocation(this.typeId); } @Override - public AbstractContainerMenu getContainer(int windowId, Player player, ItemStack heldItem) { - return ContainerNaturalistBackpack.makeContainer(windowId, player, heldItem, 0, this.typeId); + public AbstractContainerMenu createMenu(int containerId, Inventory playerInv, int slotIndex) { + return NaturalistBackpackMenu.makeContainer(containerId, playerInv, slotIndex, 0, this.typeId); } } diff --git a/src/main/java/forestry/storage/items/ItemCrated.java b/src/main/java/forestry/storage/items/ItemCrated.java index 70a88a0cc9..f6804a9f5b 100644 --- a/src/main/java/forestry/storage/items/ItemCrated.java +++ b/src/main/java/forestry/storage/items/ItemCrated.java @@ -21,8 +21,8 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import java.util.function.Supplier; diff --git a/src/main/java/forestry/storage/items/package-info.java b/src/main/java/forestry/storage/items/package-info.java index f67de17611..0d09e9e62f 100644 --- a/src/main/java/forestry/storage/items/package-info.java +++ b/src/main/java/forestry/storage/items/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage.items; diff --git a/src/main/java/forestry/storage/package-info.java b/src/main/java/forestry/storage/package-info.java index 8c596e5f22..cc24d113b0 100644 --- a/src/main/java/forestry/storage/package-info.java +++ b/src/main/java/forestry/storage/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.storage; diff --git a/src/main/java/forestry/worktable/ModuleWorktable.java b/src/main/java/forestry/worktable/ModuleWorktable.java index da3e81ae3b..a541a4c77d 100644 --- a/src/main/java/forestry/worktable/ModuleWorktable.java +++ b/src/main/java/forestry/worktable/ModuleWorktable.java @@ -3,7 +3,6 @@ import forestry.api.client.IClientModuleHandler; import forestry.api.modules.ForestryModule; import forestry.api.modules.ForestryModuleIds; -import forestry.api.modules.IPacketRegistry; import forestry.core.network.PacketIdClient; import forestry.core.network.PacketIdServer; import forestry.modules.BlankForestryModule; @@ -11,7 +10,9 @@ import forestry.worktable.network.packets.PacketWorktableMemoryUpdate; import forestry.worktable.network.packets.PacketWorktableRecipeRequest; import forestry.worktable.network.packets.PacketWorktableRecipeUpdate; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; import java.util.function.Consumer; @@ -23,11 +24,11 @@ public ResourceLocation getId() { } @Override - public void registerPackets(IPacketRegistry registry) { - registry.serverbound(PacketIdServer.WORKTABLE_RECIPE_REQUEST, PacketWorktableRecipeRequest.class, PacketWorktableRecipeRequest::decode, PacketWorktableRecipeRequest::handle); + public void registerPackets(PayloadRegistrar registrar) { + registrar.playToServer(PacketIdServer.WORKTABLE_RECIPE_REQUEST, StreamCodec.of(PacketWorktableRecipeRequest::encode, PacketWorktableRecipeRequest::decode), PacketWorktableRecipeRequest::handle); - registry.clientbound(PacketIdClient.WORKTABLE_MEMORY_UPDATE, PacketWorktableMemoryUpdate.class, PacketWorktableMemoryUpdate::decode, PacketWorktableMemoryUpdate::handle); - registry.clientbound(PacketIdClient.WORKTABLE_CRAFTING_UPDATE, PacketWorktableRecipeUpdate.class, PacketWorktableRecipeUpdate::decode, PacketWorktableRecipeUpdate::handle); + registrar.playToClient(PacketIdClient.WORKTABLE_MEMORY_UPDATE, StreamCodec.of(PacketWorktableMemoryUpdate::encode, PacketWorktableMemoryUpdate::decode), PacketWorktableMemoryUpdate::handle); + registrar.playToClient(PacketIdClient.WORKTABLE_CRAFTING_UPDATE, StreamCodec.of(PacketWorktableRecipeUpdate::encode, PacketWorktableRecipeUpdate::decode), PacketWorktableRecipeUpdate::handle); } @Override diff --git a/src/main/java/forestry/worktable/blocks/WorktableBlock.java b/src/main/java/forestry/worktable/blocks/WorktableBlock.java index 09b92f768b..69c0059057 100644 --- a/src/main/java/forestry/worktable/blocks/WorktableBlock.java +++ b/src/main/java/forestry/worktable/blocks/WorktableBlock.java @@ -2,11 +2,10 @@ import forestry.core.blocks.BlockBase; import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.SoundType; -import org.jetbrains.annotations.Nullable; import java.util.List; @@ -16,8 +15,8 @@ public WorktableBlock(WorktableBlockType blockType) { } @Override - public void appendHoverText(ItemStack stack, @Nullable BlockGetter level, List tooltip, TooltipFlag flag) { - if (stack.getTag() != null) { + public void appendHoverText(ItemStack stack, Item.TooltipContext context, List tooltip, TooltipFlag flag) { + if (!stack.getComponents().isEmpty()) { tooltip.add(Component.translatable("block.forestry.worktable_tooltip")); } } diff --git a/src/main/java/forestry/worktable/blocks/WorktableBlockType.java b/src/main/java/forestry/worktable/blocks/WorktableBlockType.java index 1ab2058341..89b9e0f867 100644 --- a/src/main/java/forestry/worktable/blocks/WorktableBlockType.java +++ b/src/main/java/forestry/worktable/blocks/WorktableBlockType.java @@ -22,7 +22,7 @@ public IMachineProperties getMachineProperties() { } @Override - public String getSerializedName() { - return this.machineProperties.getSerializedName(); + public String identifier() { + return this.machineProperties.identifier(); } } diff --git a/src/main/java/forestry/worktable/blocks/package-info.java b/src/main/java/forestry/worktable/blocks/package-info.java index 27b07f316e..33b603c489 100644 --- a/src/main/java/forestry/worktable/blocks/package-info.java +++ b/src/main/java/forestry/worktable/blocks/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.blocks; diff --git a/src/main/java/forestry/worktable/client/WorktableClientHandler.java b/src/main/java/forestry/worktable/client/WorktableClientHandler.java index 2e0f9b4b2d..d1685c7614 100644 --- a/src/main/java/forestry/worktable/client/WorktableClientHandler.java +++ b/src/main/java/forestry/worktable/client/WorktableClientHandler.java @@ -3,17 +3,16 @@ import forestry.api.client.IClientModuleHandler; import forestry.worktable.features.WorktableMenus; import forestry.worktable.screens.WorktableScreen; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; public class WorktableClientHandler implements IClientModuleHandler { @Override public void registerEvents(IEventBus modBus) { - modBus.addListener(WorktableClientHandler::onClientSetup); + modBus.addListener(WorktableClientHandler::registerMenuScreens); } - private static void onClientSetup(FMLClientSetupEvent event) { - event.enqueueWork(() -> MenuScreens.register(WorktableMenus.WORKTABLE.menuType(), WorktableScreen::new)); + private static void registerMenuScreens(RegisterMenuScreensEvent event) { + event.register(WorktableMenus.WORKTABLE.menuType(), WorktableScreen::new); } } diff --git a/src/main/java/forestry/worktable/client/package-info.java b/src/main/java/forestry/worktable/client/package-info.java index 9a0d7c8855..5cedd52856 100644 --- a/src/main/java/forestry/worktable/client/package-info.java +++ b/src/main/java/forestry/worktable/client/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.client; diff --git a/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java b/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java index 3f0c3d345b..772675b67c 100644 --- a/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java +++ b/src/main/java/forestry/worktable/compat/WorktableJeiPlugin.java @@ -1,7 +1,7 @@ package forestry.worktable.compat; import forestry.api.modules.ForestryModuleIds; -import forestry.core.utils.JeiUtil; +import forestry.compat.jei.JeiUtil; import forestry.worktable.features.WorktableBlocks; import forestry.worktable.screens.WorktableScreen; import mezz.jei.api.IModPlugin; diff --git a/src/main/java/forestry/worktable/compat/WorktableRecipeTransferHandler.java b/src/main/java/forestry/worktable/compat/WorktableRecipeTransferHandler.java index c384b1a0cc..46abe7fe0b 100644 --- a/src/main/java/forestry/worktable/compat/WorktableRecipeTransferHandler.java +++ b/src/main/java/forestry/worktable/compat/WorktableRecipeTransferHandler.java @@ -1,7 +1,7 @@ package forestry.worktable.compat; -import forestry.core.utils.JeiUtil; -import forestry.core.utils.RecipeUtils; +import forestry.compat.jei.JeiUtil; +import forestry.core.utils.RecipeUtil; import forestry.worktable.features.WorktableMenus; import forestry.worktable.recipes.MemorizedRecipe; import forestry.worktable.screens.WorktableMenu; @@ -17,12 +17,13 @@ import net.minecraft.world.inventory.TransientCraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; import javax.annotation.Nullable; import java.util.List; import java.util.Optional; -class WorktableRecipeTransferHandler implements IRecipeTransferHandler { +class WorktableRecipeTransferHandler implements IRecipeTransferHandler> { @Override public Class getContainerClass() { return WorktableMenu.class; @@ -34,13 +35,13 @@ public Optional> getMenuType() { } @Override - public RecipeType getRecipeType() { + public RecipeType> getRecipeType() { return RecipeTypes.CRAFTING; } @Nullable @Override - public IRecipeTransferError transferRecipe(WorktableMenu container, CraftingRecipe recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { + public IRecipeTransferError transferRecipe(WorktableMenu container, RecipeHolder recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { if (doTransfer) { CraftingContainer inventory = new TransientCraftingContainer(container, 3, 3); @@ -50,7 +51,7 @@ public IRecipeTransferError transferRecipe(WorktableMenu container, CraftingReci inventory.setItem(i, firstItemStack); } - List matchingRecipes = RecipeUtils.findMatchingRecipes(inventory, player.level()); + List> matchingRecipes = RecipeUtil.findMatchingRecipes(inventory.asCraftInput(), player.level()); if (!matchingRecipes.isEmpty()) { MemorizedRecipe memorizedRecipe = new MemorizedRecipe(inventory, matchingRecipes); container.sendWorktableRecipeRequest(memorizedRecipe); diff --git a/src/main/java/forestry/worktable/compat/package-info.java b/src/main/java/forestry/worktable/compat/package-info.java index 5de1ca7948..4a0eb5f105 100644 --- a/src/main/java/forestry/worktable/compat/package-info.java +++ b/src/main/java/forestry/worktable/compat/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.compat; diff --git a/src/main/java/forestry/worktable/features/package-info.java b/src/main/java/forestry/worktable/features/package-info.java index 2608f32e79..ad11bc0e8e 100644 --- a/src/main/java/forestry/worktable/features/package-info.java +++ b/src/main/java/forestry/worktable/features/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.features; diff --git a/src/main/java/forestry/worktable/inventory/package-info.java b/src/main/java/forestry/worktable/inventory/package-info.java index 413ef24af3..fc8c28aa6a 100644 --- a/src/main/java/forestry/worktable/inventory/package-info.java +++ b/src/main/java/forestry/worktable/inventory/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.inventory; diff --git a/src/main/java/forestry/worktable/network/package-info.java b/src/main/java/forestry/worktable/network/package-info.java deleted file mode 100644 index acdc846779..0000000000 --- a/src/main/java/forestry/worktable/network/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault -@net.minecraft.MethodsReturnNonnullByDefault -package forestry.worktable.network; diff --git a/src/main/java/forestry/worktable/network/packets/PacketWorktableMemoryUpdate.java b/src/main/java/forestry/worktable/network/packets/PacketWorktableMemoryUpdate.java index 88ee400083..0e8b8bd7a1 100644 --- a/src/main/java/forestry/worktable/network/packets/PacketWorktableMemoryUpdate.java +++ b/src/main/java/forestry/worktable/network/packets/PacketWorktableMemoryUpdate.java @@ -7,8 +7,9 @@ import forestry.worktable.tiles.WorktableTile; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.entity.player.Player; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketWorktableMemoryUpdate(BlockPos pos, RecipeMemory memory) implements IForestryPacketClient { public PacketWorktableMemoryUpdate(WorktableTile worktable) { @@ -16,22 +17,21 @@ public PacketWorktableMemoryUpdate(WorktableTile worktable) { } @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.WORKTABLE_MEMORY_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - this.memory.writeData(buffer); + public static void encode(RegistryFriendlyByteBuf buffer, PacketWorktableMemoryUpdate msg) { + buffer.writeBlockPos(msg.pos); + msg.memory.writeData(buffer); } - public static PacketWorktableMemoryUpdate decode(FriendlyByteBuf buffer) { + public static PacketWorktableMemoryUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketWorktableMemoryUpdate(buffer.readBlockPos(), new RecipeMemory(buffer)); } - public static void handle(PacketWorktableMemoryUpdate msg, Player player) { - WorktableTile tile = TileUtil.getTile(player.level(), msg.pos, WorktableTile.class); + public static void handle(PacketWorktableMemoryUpdate msg, IPayloadContext context) { + WorktableTile tile = TileUtil.getTile(context.player().level(), msg.pos, WorktableTile.class); if (tile != null) { tile.getMemory().copy(msg.memory); } diff --git a/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeRequest.java b/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeRequest.java index 3e7c36441d..732e3a056a 100644 --- a/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeRequest.java +++ b/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeRequest.java @@ -8,37 +8,40 @@ import forestry.worktable.screens.WorktableMenu; import forestry.worktable.tiles.WorktableTile; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; +import net.neoforged.neoforge.network.handling.IPayloadContext; public record PacketWorktableRecipeRequest(BlockPos pos, MemorizedRecipe recipe) implements IForestryPacketServer { @Override - public ResourceLocation id() { + public Type type() { return PacketIdServer.WORKTABLE_RECIPE_REQUEST; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - this.recipe.writeData(buffer); + public static void encode(RegistryFriendlyByteBuf buffer, PacketWorktableRecipeRequest msg) { + buffer.writeBlockPos(msg.pos); + msg.recipe.writeData(buffer); } - public static PacketWorktableRecipeRequest decode(FriendlyByteBuf buffer) { + public static PacketWorktableRecipeRequest decode(RegistryFriendlyByteBuf buffer) { return new PacketWorktableRecipeRequest(buffer.readBlockPos(), new MemorizedRecipe(buffer)); } - public static void handle(PacketWorktableRecipeRequest msg, ServerPlayer player) { + public static void handle(PacketWorktableRecipeRequest msg, IPayloadContext ctx) { BlockPos pos = msg.pos(); MemorizedRecipe recipe = msg.recipe(); - TileUtil.actOnTile(player.level(), pos, WorktableTile.class, worktable -> { + ServerPlayer player = (ServerPlayer) ctx.player(); + ServerLevel level = player.serverLevel(); + + TileUtil.actOnTile(level, pos, WorktableTile.class, worktable -> { worktable.setCurrentRecipe(recipe); if (player.containerMenu instanceof WorktableMenu containerWorktable) { containerWorktable.updateCraftMatrix(); } - NetworkUtil.sendNetworkPacket(new PacketWorktableRecipeUpdate(worktable), pos, player.level()); + NetworkUtil.sendToPlayersTrackingPos(new PacketWorktableRecipeUpdate(worktable), pos, level); }); } } diff --git a/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeUpdate.java b/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeUpdate.java index 3bd7526a12..fb9eebe448 100644 --- a/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeUpdate.java +++ b/src/main/java/forestry/worktable/network/packets/PacketWorktableRecipeUpdate.java @@ -7,9 +7,8 @@ import forestry.worktable.recipes.MemorizedRecipe; import forestry.worktable.tiles.WorktableTile; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; import javax.annotation.Nullable; @@ -20,21 +19,20 @@ public PacketWorktableRecipeUpdate(WorktableTile tile) { } @Override - public ResourceLocation id() { + public Type type() { return PacketIdClient.WORKTABLE_CRAFTING_UPDATE; } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(this.pos); - NetworkUtil.writeStreamable(buffer, this.recipe); + public static void encode(RegistryFriendlyByteBuf buffer, PacketWorktableRecipeUpdate msg) { + buffer.writeBlockPos(msg.pos); + NetworkUtil.writeStreamable(buffer, msg.recipe); } - public static PacketWorktableRecipeUpdate decode(FriendlyByteBuf buffer) { + public static PacketWorktableRecipeUpdate decode(RegistryFriendlyByteBuf buffer) { return new PacketWorktableRecipeUpdate(buffer.readBlockPos(), NetworkUtil.readStreamable(buffer, MemorizedRecipe::new)); } - public static void handle(PacketWorktableRecipeUpdate msg, Player player) { - TileUtil.actOnTile(player.level(), msg.pos, WorktableTile.class, tile -> tile.setCurrentRecipe(msg.recipe)); + public static void handle(PacketWorktableRecipeUpdate msg, IPayloadContext ctx) { + TileUtil.actOnTile(ctx.player().level(), msg.pos, WorktableTile.class, tile -> tile.setCurrentRecipe(msg.recipe)); } } diff --git a/src/main/java/forestry/worktable/network/packets/package-info.java b/src/main/java/forestry/worktable/network/packets/package-info.java index 76d4671a79..47ced69760 100644 --- a/src/main/java/forestry/worktable/network/packets/package-info.java +++ b/src/main/java/forestry/worktable/network/packets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.network.packets; diff --git a/src/main/java/forestry/worktable/package-info.java b/src/main/java/forestry/worktable/package-info.java index 0c22bd74be..3616366a23 100644 --- a/src/main/java/forestry/worktable/package-info.java +++ b/src/main/java/forestry/worktable/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable; diff --git a/src/main/java/forestry/worktable/recipes/MemorizedRecipe.java b/src/main/java/forestry/worktable/recipes/MemorizedRecipe.java index 36a345f3b9..cfcd7dcb34 100644 --- a/src/main/java/forestry/worktable/recipes/MemorizedRecipe.java +++ b/src/main/java/forestry/worktable/recipes/MemorizedRecipe.java @@ -5,19 +5,20 @@ import forestry.core.network.IStreamable; import forestry.core.utils.InventoryUtil; import forestry.core.utils.NetworkUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.worktable.inventory.WorktableCraftingContainer; +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.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.CraftingRecipe; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import javax.annotation.Nullable; @@ -26,25 +27,25 @@ public class MemorizedRecipe implements INbtWritable, INbtReadable, IStreamable { private WorktableCraftingContainer craftMatrix = new WorktableCraftingContainer(); - private List recipes = new ArrayList<>(); + private List> recipes = new ArrayList<>(); private final List recipeIds = new ArrayList<>(); private int selectedRecipe; private long lastUsed; private boolean locked; - public MemorizedRecipe(FriendlyByteBuf buffer) { + public MemorizedRecipe(RegistryFriendlyByteBuf buffer) { readData(buffer); } - public MemorizedRecipe(CompoundTag nbt) { - read(nbt); + public MemorizedRecipe(CompoundTag nbt, HolderLookup.Provider registries) { + read(nbt, registries); } - public MemorizedRecipe(CraftingContainer craftMatrix, List recipes) { + public MemorizedRecipe(CraftingContainer craftMatrix, List> recipes) { InventoryUtil.deepCopyInventoryContents(craftMatrix, this.craftMatrix); this.recipes = recipes; - for (CraftingRecipe recipe : recipes) { - this.recipeIds.add(recipe.getId()); + for (RecipeHolder recipe : recipes) { + this.recipeIds.add(recipe.id()); } } @@ -57,16 +58,16 @@ public void setCraftMatrix(WorktableCraftingContainer usedMatrix) { } public void incrementRecipe() { - this.selectedRecipe++; + this.selectedRecipe++; if (this.selectedRecipe >= this.recipes.size()) { - this.selectedRecipe = 0; + this.selectedRecipe = 0; } } public void decrementRecipe() { - this.selectedRecipe--; + this.selectedRecipe--; if (this.selectedRecipe < 0) { - this.selectedRecipe = this.recipes.size() - 1; + this.selectedRecipe = this.recipes.size() - 1; } } @@ -75,16 +76,16 @@ public boolean hasRecipeConflict() { } public void removeRecipeConflicts() { - CraftingRecipe recipe = getSelectedRecipe(); - this.recipes.clear(); - this.recipes.add(recipe); - this.selectedRecipe = 0; + RecipeHolder recipe = getSelectedRecipe(); + this.recipes.clear(); + this.recipes.add(recipe); + this.selectedRecipe = 0; } public ItemStack getOutputIcon(Level level) { - CraftingRecipe selectedRecipe = getSelectedRecipe(); + RecipeHolder selectedRecipe = getSelectedRecipe(); if (selectedRecipe != null) { - ItemStack recipeOutput = selectedRecipe.assemble(this.craftMatrix, level.registryAccess()); + ItemStack recipeOutput = selectedRecipe.value().assemble(this.craftMatrix.asCraftInput(), level.registryAccess()); if (!recipeOutput.isEmpty()) { return recipeOutput; } @@ -92,14 +93,20 @@ public ItemStack getOutputIcon(Level level) { return ItemStack.EMPTY; } - public ItemStack getCraftingResult(CraftingContainer inventory, Level level) { - CraftingRecipe selectedRecipe = getSelectedRecipe(); - if (selectedRecipe != null && selectedRecipe.matches(inventory, level)) { - ItemStack recipeOutput = selectedRecipe.assemble(inventory, level.registryAccess()); - if (!recipeOutput.isEmpty()) { - return recipeOutput; + public ItemStack getCraftingResult(CraftingInput input, Level level) { + RecipeHolder selectedRecipe = getSelectedRecipe(); + + if (selectedRecipe != null) { + CraftingRecipe recipe = selectedRecipe.value(); + + if (recipe.matches(input, level)) { + ItemStack recipeOutput = recipe.assemble(input, level.registryAccess()); + if (!recipeOutput.isEmpty()) { + return recipeOutput; + } } } + return ItemStack.EMPTY; } @@ -111,24 +118,24 @@ public boolean hasSelectedRecipe() { return hasRecipes() && this.selectedRecipe >= 0 && this.recipeIds.size() > this.selectedRecipe && this.recipeIds.get(this.selectedRecipe) != null; } - public List getRecipes() { + public List> getRecipes() { if (this.recipes.isEmpty() && !this.recipeIds.isEmpty()) { for (ResourceLocation key : this.recipeIds) { - Recipe recipe = RecipeUtils.getRecipe(RecipeType.CRAFTING, key); - if (recipe instanceof CraftingRecipe) { - this.recipes.add((CraftingRecipe) recipe); + RecipeHolder recipe = RecipeUtil.getRecipe(key); + if (recipe != null) { + this.recipes.add(recipe); } } if (this.selectedRecipe > this.recipes.size()) { - this.selectedRecipe = 0; + this.selectedRecipe = 0; } } return this.recipes; } @Nullable - public CraftingRecipe getSelectedRecipe() { - List recipes = getRecipes(); + public RecipeHolder getSelectedRecipe() { + List> recipes = getRecipes(); if (recipes.isEmpty()) { return null; } else { @@ -136,7 +143,7 @@ public CraftingRecipe getSelectedRecipe() { } } - public boolean hasRecipe(@Nullable CraftingRecipe recipe) { + public boolean hasRecipe(@Nullable RecipeHolder recipe) { return getRecipes().contains(recipe); } @@ -149,7 +156,7 @@ public long getLastUsed() { } public void toggleLock() { - this.locked = !this.locked; + this.locked = !this.locked; } public boolean isLocked() { @@ -157,30 +164,34 @@ public boolean isLocked() { } @Override - public final void read(CompoundTag compoundNBT) { - InventoryUtil.readFromNBT(this.craftMatrix, "inventory", compoundNBT); - this.lastUsed = compoundNBT.getLong("LastUsed"); - this.locked = compoundNBT.getBoolean("Locked"); + public void read(CompoundTag nbt, HolderLookup.Provider registries) { + InventoryUtil.readFromNBT(this.craftMatrix, "inventory", nbt); + this.lastUsed = nbt.getLong("LastUsed"); + this.locked = nbt.getBoolean("Locked"); - if (compoundNBT.contains("SelectedRecipe")) { - this.selectedRecipe = compoundNBT.getInt("SelectedRecipe"); + if (nbt.contains("SelectedRecipe")) { + this.selectedRecipe = nbt.getInt("SelectedRecipe"); } - this.recipes.clear(); - this.recipeIds.clear(); - ListTag recipesNbt = compoundNBT.getList("Recipes", Tag.TAG_STRING); + this.recipes.clear(); + this.recipeIds.clear(); + ListTag recipesNbt = nbt.getList("Recipes", Tag.TAG_STRING); for (int i = 0; i < recipesNbt.size(); i++) { String recipeKey = recipesNbt.getString(i); - this.recipeIds.add(new ResourceLocation(recipeKey)); + ResourceLocation recipeId = ResourceLocation.tryParse(recipeKey); + + if (recipeId != null) { + this.recipeIds.add(recipeId); + } } if (this.selectedRecipe > this.recipeIds.size()) { - this.selectedRecipe = 0; + this.selectedRecipe = 0; } } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { InventoryUtil.writeToNBT(this.craftMatrix, "inventory", compoundNBT); compoundNBT.putLong("LastUsed", this.lastUsed); compoundNBT.putBoolean("Locked", this.locked); @@ -196,29 +207,29 @@ public CompoundTag write(CompoundTag compoundNBT) { } @Override - public void writeData(FriendlyByteBuf data) { - NetworkUtil.writeInventory(data, this.craftMatrix); - data.writeBoolean(this.locked); - data.writeVarInt(this.selectedRecipe); + public void writeData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.writeInventory(buffer, this.craftMatrix); + buffer.writeBoolean(this.locked); + buffer.writeVarInt(this.selectedRecipe); - data.writeVarInt(this.recipeIds.size()); + buffer.writeVarInt(this.recipeIds.size()); for (ResourceLocation recipeName : this.recipeIds) { - data.writeResourceLocation(recipeName); + buffer.writeResourceLocation(recipeName); } } @Override - public void readData(FriendlyByteBuf data) { - NetworkUtil.readInventory(data, this.craftMatrix); - this.locked = data.readBoolean(); - this.selectedRecipe = data.readVarInt(); - - this.recipes.clear(); - this.recipeIds.clear(); - int recipeCount = data.readVarInt(); + public void readData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.readInventory(buffer, this.craftMatrix); + this.locked = buffer.readBoolean(); + this.selectedRecipe = buffer.readVarInt(); + + this.recipes.clear(); + this.recipeIds.clear(); + int recipeCount = buffer.readVarInt(); for (int i = 0; i < recipeCount; i++) { - ResourceLocation recipeId = data.readResourceLocation(); - this.recipeIds.add(recipeId); + ResourceLocation recipeId = buffer.readResourceLocation(); + this.recipeIds.add(recipeId); } } } diff --git a/src/main/java/forestry/worktable/recipes/RecipeMemory.java b/src/main/java/forestry/worktable/recipes/RecipeMemory.java index 97e81b1eb8..196547f4ff 100644 --- a/src/main/java/forestry/worktable/recipes/RecipeMemory.java +++ b/src/main/java/forestry/worktable/recipes/RecipeMemory.java @@ -3,12 +3,14 @@ import forestry.api.core.INbtWritable; import forestry.core.network.IStreamable; import forestry.core.utils.NetworkUtil; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import javax.annotation.Nullable; @@ -21,14 +23,14 @@ public class RecipeMemory implements INbtWritable, IStreamable { private final List memorizedRecipes = new ArrayList<>(CAPACITY); private long lastUpdate; - public RecipeMemory(FriendlyByteBuf buffer) { + public RecipeMemory(RegistryFriendlyByteBuf buffer) { readData(buffer); } public RecipeMemory() { } - public RecipeMemory(CompoundTag nbt) { + public RecipeMemory(CompoundTag nbt, HolderLookup.Provider registries) { if (!nbt.contains("RecipeMemory")) { return; } @@ -37,10 +39,10 @@ public RecipeMemory(CompoundTag nbt) { for (int j = 0; j < memoryNbt.size(); ++j) { CompoundTag recipeNbt = memoryNbt.getCompound(j); - MemorizedRecipe recipe = new MemorizedRecipe(recipeNbt); + MemorizedRecipe recipe = new MemorizedRecipe(recipeNbt, registries); if (recipe.hasSelectedRecipe()) { - this.memorizedRecipes.add(recipe); + this.memorizedRecipes.add(recipe); } } } @@ -50,12 +52,12 @@ public long getLastUpdate() { } public void memorizeRecipe(long worldTime, MemorizedRecipe recipe, Level world) { - CraftingRecipe selectedRecipe = recipe.getSelectedRecipe(); + RecipeHolder selectedRecipe = recipe.getSelectedRecipe(); if (selectedRecipe == null) { return; } - this.lastUpdate = worldTime; + this.lastUpdate = worldTime; recipe.updateLastUse(this.lastUpdate); if (recipe.hasRecipeConflict()) { @@ -71,12 +73,12 @@ public void memorizeRecipe(long worldTime, MemorizedRecipe recipe, Level world) // add a new recipe if (this.memorizedRecipes.size() < CAPACITY) { - this.memorizedRecipes.add(recipe); + this.memorizedRecipes.add(recipe); } else { MemorizedRecipe oldest = getOldestUnlockedRecipe(); if (oldest != null) { - this.memorizedRecipes.remove(oldest); - this.memorizedRecipes.add(recipe); + this.memorizedRecipes.remove(oldest); + this.memorizedRecipes.add(recipe); } } } @@ -86,7 +88,7 @@ private void updateExistingRecipe(MemorizedRecipe existingRecipe, MemorizedRecip updatedRecipe.toggleLock(); } int index = this.memorizedRecipes.indexOf(existingRecipe); - this.memorizedRecipes.set(index, updatedRecipe); + this.memorizedRecipes.set(index, updatedRecipe); } @Nullable @@ -127,14 +129,14 @@ public boolean isLocked(int recipeIndex) { } public void toggleLock(long worldTime, int recipeIndex) { - this.lastUpdate = worldTime; + this.lastUpdate = worldTime; if (this.memorizedRecipes.size() > recipeIndex) { - this.memorizedRecipes.get(recipeIndex).toggleLock(); + this.memorizedRecipes.get(recipeIndex).toggleLock(); } } @Nullable - private MemorizedRecipe getExistingMemorizedRecipe(@Nullable CraftingRecipe recipe) { + private MemorizedRecipe getExistingMemorizedRecipe(@Nullable RecipeHolder recipe) { if (recipe != null) { for (MemorizedRecipe memorizedRecipe : this.memorizedRecipes) { if (memorizedRecipe.hasRecipe(recipe)) { @@ -147,12 +149,12 @@ private MemorizedRecipe getExistingMemorizedRecipe(@Nullable CraftingRecipe reci } @Override - public CompoundTag write(CompoundTag compoundNBT) { + public CompoundTag write(CompoundTag compoundNBT, HolderLookup.Provider registries) { ListTag listNBT = new ListTag(); for (MemorizedRecipe recipe : this.memorizedRecipes) { if (recipe != null && recipe.hasSelectedRecipe()) { CompoundTag recipeNbt = new CompoundTag(); - recipe.write(recipeNbt); + recipe.write(recipeNbt, registries); listNBT.add(recipeNbt); } } @@ -161,13 +163,13 @@ public CompoundTag write(CompoundTag compoundNBT) { } @Override - public void writeData(FriendlyByteBuf data) { - NetworkUtil.writeStreamables(data, this.memorizedRecipes); + public void writeData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.writeStreamables(buffer, this.memorizedRecipes); } @Override - public void readData(FriendlyByteBuf data) { - NetworkUtil.readStreamables(data, this.memorizedRecipes, MemorizedRecipe::new); + public void readData(RegistryFriendlyByteBuf buffer) { + NetworkUtil.readStreamables(buffer, this.memorizedRecipes, MemorizedRecipe::new); } public void copy(RecipeMemory memory) { diff --git a/src/main/java/forestry/worktable/recipes/package-info.java b/src/main/java/forestry/worktable/recipes/package-info.java index 670abd911d..192bfe9e76 100644 --- a/src/main/java/forestry/worktable/recipes/package-info.java +++ b/src/main/java/forestry/worktable/recipes/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.recipes; diff --git a/src/main/java/forestry/worktable/screens/WorktableMenu.java b/src/main/java/forestry/worktable/screens/WorktableMenu.java index d69a932130..8b7d49693b 100644 --- a/src/main/java/forestry/worktable/screens/WorktableMenu.java +++ b/src/main/java/forestry/worktable/screens/WorktableMenu.java @@ -1,12 +1,12 @@ package forestry.worktable.screens; -import forestry.core.gui.ContainerTile; +import forestry.api.modules.IForestryPacketServer; +import forestry.core.gui.TileMenu; import forestry.core.gui.IContainerCrafting; import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotCraftMatrix; import forestry.core.gui.slots.WorktableSlot; import forestry.core.inventory.InventoryGhostCrafting; -import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.tiles.TileUtil; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.NetworkUtil; @@ -25,8 +25,9 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.PacketDistributor; -public class WorktableMenu extends ContainerTile implements IContainerCrafting, IGuiSelectable { +public class WorktableMenu extends TileMenu implements IContainerCrafting, IGuiSelectable { private final WorktableCraftingContainer craftMatrix = new WorktableCraftingContainer(this); private long lastMemoryUpdate; private boolean craftMatrixChanged = false; @@ -67,15 +68,15 @@ public WorktableMenu(int windowId, Inventory inv, WorktableTile tile) { @Override public void broadcastChanges() { if (this.craftMatrixChanged) { - this.craftMatrixChanged = false; - this.tile.setCurrentRecipe(this.craftMatrix); + this.craftMatrixChanged = false; + this.tile.setCurrentRecipe(this.craftMatrix); sendPacketToListeners(new PacketWorktableRecipeUpdate(this.tile)); } super.broadcastChanges(); if (this.lastMemoryUpdate != this.tile.getMemory().getLastUpdate()) { - this.lastMemoryUpdate = this.tile.getMemory().getLastUpdate(); + this.lastMemoryUpdate = this.tile.getMemory().getLastUpdate(); sendPacketToListeners(new PacketWorktableMemoryUpdate(this.tile)); } } @@ -97,7 +98,7 @@ public void onCraftMatrixChanged(Container iinventory, int slot) { ItemStack currentStack = this.craftMatrix.getItem(slot); if (!ItemStackUtil.isIdenticalItem(stack, currentStack)) { - this.craftMatrix.setItem(slot, stack.copy()); + this.craftMatrix.setItem(slot, stack.copy()); } } @@ -105,29 +106,25 @@ public void onCraftMatrixChanged(Container iinventory, int slot) { // Direct changes to the underlying inventory are not detected, only slot changes. @Override public void slotsChanged(Container container) { - this.craftMatrixChanged = true; + this.craftMatrixChanged = true; } /* Gui Selection Handling */ public static void clearRecipe() { - sendRecipeClick(-1, 0); - } - - public static void sendRecipeClick(int mouseButton, int recipeIndex) { - NetworkUtil.sendToServer(new PacketGuiSelectRequest(mouseButton, recipeIndex)); + NetworkUtil.sendRecipeClick(-1, 0); } @Override public void handleSelectionRequest(ServerPlayer player, int primary, int secondary) { switch (primary) { case -1: { // clicked clear button - this.tile.clearCraftMatrix(); + this.tile.clearCraftMatrix(); updateCraftMatrix(); sendPacketToListeners(new PacketWorktableRecipeUpdate(this.tile)); break; } case 0: { // clicked a memorized recipe - this.tile.chooseRecipeMemory(secondary); + this.tile.chooseRecipeMemory(secondary); updateCraftMatrix(); sendPacketToListeners(new PacketWorktableRecipeUpdate(this.tile)); break; @@ -139,12 +136,12 @@ public void handleSelectionRequest(ServerPlayer player, int primary, int seconda break; } case 100: { // clicked previous recipe conflict button - this.tile.choosePreviousConflictRecipe(); + this.tile.choosePreviousConflictRecipe(); sendPacketToListeners(new PacketWorktableRecipeUpdate(this.tile)); break; } case 101: { // clicked next recipe conflict button - this.tile.chooseNextConflictRecipe(); + this.tile.chooseNextConflictRecipe(); sendPacketToListeners(new PacketWorktableRecipeUpdate(this.tile)); break; } @@ -152,6 +149,7 @@ public void handleSelectionRequest(ServerPlayer player, int primary, int seconda } public void sendWorktableRecipeRequest(MemorizedRecipe recipe) { - NetworkUtil.sendToServer(new PacketWorktableRecipeRequest(this.tile.getBlockPos(), recipe)); - } + IForestryPacketServer packet = new PacketWorktableRecipeRequest(this.tile.getBlockPos(), recipe); + PacketDistributor.sendToServer(packet); + } } diff --git a/src/main/java/forestry/worktable/screens/WorktableScreen.java b/src/main/java/forestry/worktable/screens/WorktableScreen.java index beeb56b395..df8342aeda 100644 --- a/src/main/java/forestry/worktable/screens/WorktableScreen.java +++ b/src/main/java/forestry/worktable/screens/WorktableScreen.java @@ -1,11 +1,10 @@ package forestry.worktable.screens; +import forestry.api.modules.IForestryPacketServer; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; -import forestry.core.gui.buttons.GuiBetterButton; -import forestry.core.gui.buttons.StandardButtonTextureSets; +import forestry.core.gui.widgets.ArrowButton; import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.utils.NetworkUtil; import forestry.core.utils.SoundUtil; import forestry.worktable.recipes.RecipeMemory; import forestry.worktable.screens.widgets.ClearWorktable; @@ -13,6 +12,7 @@ import forestry.worktable.tiles.WorktableTile; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; +import net.neoforged.neoforge.network.PacketDistributor; public class WorktableScreen extends GuiForestryTitled { private static final int SPACING = 18; @@ -57,13 +57,15 @@ public void containerTick() { } private void addButtons() { - addRenderableWidget(new GuiBetterButton(this.leftPos + 76, this.topPos + 56, StandardButtonTextureSets.LEFT_BUTTON_SMALL, b -> { - NetworkUtil.sendToServer(new PacketGuiSelectRequest(100, 0)); - SoundUtil.playButtonClick(); + addRenderableWidget(new ArrowButton(this.leftPos + 76, this.topPos + 56, ArrowButton.Texture.LEFT_BUTTON_SMALL, b -> { + IForestryPacketServer packet = new PacketGuiSelectRequest(100, 0); + PacketDistributor.sendToServer(packet); + SoundUtil.playButtonClick(); })); - addRenderableWidget(new GuiBetterButton(this.leftPos + 85, this.topPos + 56, StandardButtonTextureSets.RIGHT_BUTTON_SMALL, b -> { - NetworkUtil.sendToServer(new PacketGuiSelectRequest(101, 0)); - SoundUtil.playButtonClick(); + addRenderableWidget(new ArrowButton(this.leftPos + 85, this.topPos + 56, ArrowButton.Texture.RIGHT_BUTTON_SMALL, b -> { + IForestryPacketServer packet = new PacketGuiSelectRequest(101, 0); + PacketDistributor.sendToServer(packet); + SoundUtil.playButtonClick(); })); } diff --git a/src/main/java/forestry/worktable/screens/package-info.java b/src/main/java/forestry/worktable/screens/package-info.java index 888a5ba2eb..5c5bb51672 100644 --- a/src/main/java/forestry/worktable/screens/package-info.java +++ b/src/main/java/forestry/worktable/screens/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.screens; diff --git a/src/main/java/forestry/worktable/screens/widgets/MemorizedRecipeSlot.java b/src/main/java/forestry/worktable/screens/widgets/MemorizedRecipeSlot.java index 8cc43db772..2b06d3b057 100644 --- a/src/main/java/forestry/worktable/screens/widgets/MemorizedRecipeSlot.java +++ b/src/main/java/forestry/worktable/screens/widgets/MemorizedRecipeSlot.java @@ -5,9 +5,9 @@ import forestry.api.client.IForestryClientApi; import forestry.core.gui.widgets.ItemStackWidgetBase; import forestry.core.gui.widgets.WidgetManager; +import forestry.core.utils.NetworkUtil; import forestry.core.utils.SoundUtil; import forestry.worktable.recipes.RecipeMemory; -import forestry.worktable.screens.WorktableMenu; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -46,7 +46,7 @@ public void draw(GuiGraphics graphics, int startX, int startY) { @Override public void handleMouseClick(double mouseX, double mouseY, int mouseButton) { if (!getItemStack().isEmpty()) { - WorktableMenu.sendRecipeClick(mouseButton, this.slotIndex); + NetworkUtil.sendRecipeClick(mouseButton, this.slotIndex); SoundUtil.playButtonClick(); } } diff --git a/src/main/java/forestry/worktable/screens/widgets/package-info.java b/src/main/java/forestry/worktable/screens/widgets/package-info.java index c74af476c3..73e295b26f 100644 --- a/src/main/java/forestry/worktable/screens/widgets/package-info.java +++ b/src/main/java/forestry/worktable/screens/widgets/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.screens.widgets; diff --git a/src/main/java/forestry/worktable/tiles/WorktableTile.java b/src/main/java/forestry/worktable/tiles/WorktableTile.java index 9c8e5644b1..5c3f6953f3 100644 --- a/src/main/java/forestry/worktable/tiles/WorktableTile.java +++ b/src/main/java/forestry/worktable/tiles/WorktableTile.java @@ -5,7 +5,7 @@ import forestry.core.tiles.TileBase; import forestry.core.utils.InventoryUtil; import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.RecipeUtils; +import forestry.core.utils.RecipeUtil; import forestry.worktable.features.WorktableTiles; import forestry.worktable.inventory.WorktableCraftingContainer; import forestry.worktable.inventory.WorktableInventory; @@ -13,9 +13,10 @@ import forestry.worktable.recipes.RecipeMemory; import forestry.worktable.screens.WorktableMenu; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.Container; import net.minecraft.world.SimpleContainer; import net.minecraft.world.entity.player.Inventory; @@ -24,10 +25,11 @@ import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.ForgeHooks; +import net.neoforged.neoforge.common.CommonHooks; import javax.annotation.Nullable; import java.util.List; @@ -47,31 +49,31 @@ public WorktableTile(BlockPos pos, BlockState state) { } @Override - public void saveAdditional(CompoundTag data) { - super.saveAdditional(data); + public void saveAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.saveAdditional(nbt, registries); - this.craftingDisplay.write(data); - this.memory.write(data); + this.craftingDisplay.write(nbt, registries); + this.memory.write(nbt, registries); } @Override - public void load(CompoundTag data) { - super.load(data); + public void loadAdditional(CompoundTag nbt, HolderLookup.Provider registries) { + super.loadAdditional(nbt, registries); - this.craftingDisplay.read(data); - this.memory = new RecipeMemory(data); + this.craftingDisplay.read(nbt, registries); + this.memory = new RecipeMemory(nbt, registries); } @Override - public void writeData(FriendlyByteBuf data) { - this.craftingDisplay.writeData(data); - this.memory.writeData(data); + public void writeData(RegistryFriendlyByteBuf buffer) { + this.craftingDisplay.writeData(buffer); + this.memory.writeData(buffer); } @Override - public void readData(FriendlyByteBuf data) { - this.craftingDisplay.readData(data); - this.memory.readData(data); + public void readData(RegistryFriendlyByteBuf buffer) { + this.craftingDisplay.readData(buffer); + this.memory.readData(buffer); } public boolean hasRecipeConflict() { @@ -93,7 +95,7 @@ public void choosePreviousConflictRecipe() { @Override public ItemStack getResult(CraftingContainer inventory, Level level) { if (this.currentRecipe != null) { - return this.currentRecipe.getCraftingResult(inventory, level); + return this.currentRecipe.getCraftingResult(inventory.asCraftInput(), level); } return ItemStack.EMPTY; } @@ -118,13 +120,13 @@ private boolean craftRecipe(boolean simulate) { return false; } - CraftingRecipe selectedRecipe = this.currentRecipe.getSelectedRecipe(); + RecipeHolder selectedRecipe = this.currentRecipe.getSelectedRecipe(); if (selectedRecipe == null) { return false; } NonNullList inventoryStacks = InventoryUtil.getStacks(this); - WorktableCraftingContainer usedMatrix = RecipeUtils.getUsedMatrix(this.currentRecipe.getCraftMatrix(), inventoryStacks, this.level, selectedRecipe); + WorktableCraftingContainer usedMatrix = RecipeUtil.getUsedMatrix(this.currentRecipe.getCraftMatrix(), inventoryStacks, this.level, selectedRecipe.value()); if (usedMatrix == null) { return false; } @@ -155,12 +157,12 @@ private boolean craftRecipe(boolean simulate) { @Override public void onCraftingComplete(Player player) { - CraftingRecipe selectedRecipe = this.currentRecipe.getSelectedRecipe(); + RecipeHolder selectedRecipe = this.currentRecipe.getSelectedRecipe(); - ForgeHooks.setCraftingPlayer(player); + CommonHooks.setCraftingPlayer(player); WorktableCraftingContainer craftMatrix = this.currentRecipe.getCraftMatrix(); - NonNullList remainingItems = selectedRecipe.getRemainingItems(craftMatrix.copy()); - ForgeHooks.setCraftingPlayer(null); + NonNullList remainingItems = selectedRecipe.value().getRemainingItems(craftMatrix.asCraftInput()); + CommonHooks.setCraftingPlayer(null); for (ItemStack remainingItem : remainingItems) { if (remainingItem != null && !remainingItem.isEmpty()) { @@ -203,7 +205,7 @@ public void clearCraftMatrix() { } public void setCurrentRecipe(CraftingContainer crafting) { - List recipes = RecipeUtils.getRecipes(RecipeType.CRAFTING, crafting, this.level); + List> recipes = RecipeUtil.getRecipes(RecipeType.CRAFTING, crafting.asCraftInput(), this.level); MemorizedRecipe recipe = recipes.isEmpty() ? null : new MemorizedRecipe(crafting, recipes); if (this.currentRecipe != null && recipe != null) { diff --git a/src/main/java/forestry/worktable/tiles/package-info.java b/src/main/java/forestry/worktable/tiles/package-info.java index 33f4ba105a..379de342f8 100644 --- a/src/main/java/forestry/worktable/tiles/package-info.java +++ b/src/main/java/forestry/worktable/tiles/package-info.java @@ -1,4 +1,4 @@ @javax.annotation.ParametersAreNonnullByDefault -@forestry.core.utils.FieldsAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault @net.minecraft.MethodsReturnNonnullByDefault package forestry.worktable.tiles; diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 6a8ab860d9..0d320ec1cc 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -1,46 +1,34 @@ -public net.minecraft.world.level.block.DispenserBlock f_52661_ # DISPENSE_BEHAVIOR_REGISTRY -public net.minecraft.world.level.block.LeavesBlock m_54435_(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState; #updateDistance -public net.minecraft.core.Direction f_122346_ # VALUES - -public net.minecraft.world.inventory.AbstractContainerMenu f_38848_ # listeners -public net.minecraft.world.item.crafting.RecipeManager m_44054_(Lnet/minecraft/world/item/crafting/RecipeType;)Ljava/util/Map; # getRecipes -public net.minecraft.world.entity.player.Inventory m_36014_(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemStack;)Z # canMergeStacks -public net.minecraft.nbt.ListTag f_128716_ # tagList - -public net.minecraft.world.entity.npc.VillagerTrades$EmeraldForItems - -public-f net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool f_210559_ # rawTemplates -public net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool f_210560_ # templates +# CoreClientHandler.RENDER_TYPE_LINES_XRAY (Spectacles block highlighting) +public net.minecraft.client.renderer.RenderStateShard RENDERTYPE_LINES_SHADER +public net.minecraft.client.renderer.RenderStateShard$LineStateShard +public net.minecraft.client.renderer.RenderStateShard VIEW_OFFSET_Z_LAYERING +public net.minecraft.client.renderer.RenderStateShard TRANSLUCENT_TRANSPARENCY +public net.minecraft.client.renderer.RenderStateShard OUTLINE_TARGET +public net.minecraft.client.renderer.RenderStateShard COLOR_WRITE +public net.minecraft.client.renderer.RenderStateShard NO_CULL +public net.minecraft.client.renderer.RenderStateShard NO_DEPTH_TEST -public net.minecraft.data.worldgen.placement.OrePlacements m_195343_(ILnet/minecraft/world/level/levelgen/placement/PlacementModifier;)Ljava/util/List; # commonOrePlacement +# Boat.checkFallDamage +public net.minecraft.world.entity.vehicle.Boat status +public net.minecraft.world.entity.vehicle.Boat lastYd -public net.minecraft.world.level.biome.Biome m_47505_(Lnet/minecraft/core/BlockPos;)F # getTemperature +# ModuleApiculture.modifySnifferLoot +public-f net.minecraft.world.level.storage.loot.LootPool entries -# Spectacles block highlighting -public net.minecraft.client.renderer.RenderStateShard f_173095_ # RENDERTYPE_LINES_SHADER -public net.minecraft.client.renderer.RenderStateShard$LineStateShard -public net.minecraft.client.renderer.RenderStateShard f_110119_ # VIEW_OFFSET_Z_LAYERING -public net.minecraft.client.renderer.RenderStateShard f_110139_ # TRANSLUCENT_TRANSPARENCY -public net.minecraft.client.renderer.RenderStateShard f_110129_ # ITEM_ENTITY_TARGET -public net.minecraft.client.renderer.RenderStateShard f_110124_ # OUTLINE_TARGET -public net.minecraft.client.renderer.RenderStateShard f_110115_ # COLOR_WRITE -public net.minecraft.client.renderer.RenderStateShard f_110110_ # NO_CULL -public net.minecraft.client.renderer.RenderStateShard f_110111_ # NO_DEPTH_TEST +# RefractoryWaxParticle#createParticle +public net.minecraft.client.particle.GlowParticle (Lnet/minecraft/client/multiplayer/ClientLevel;DDDDDDLnet/minecraft/client/particle/SpriteSet;)V -# Boat -public net.minecraft.world.entity.vehicle.Boat f_38279_ # status -public net.minecraft.world.entity.vehicle.Boat f_38281_ # lastYd +# RecipeUtils.getRecipe +public net.minecraft.world.item.crafting.RecipeManager byType(Lnet/minecraft/world/item/crafting/RecipeType;)Ljava/util/Collection; -# NonStackingBeeEffect -public net.minecraft.world.level.chunk.ChunkAccess f_187610_ # blockEntities +# BackpackResupplyHandler.topOffPlayerInventory +public net.minecraft.world.entity.player.Inventory hasRemainingSpaceForItem(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/item/ItemStack;)Z -# ModuleApiculture.modifySnifferLoot -public-f net.minecraft.world.level.storage.loot.LootPool f_79023_ # entries +# BlockExtendedLeaves.tick +public net.minecraft.world.level.block.LeavesBlock updateDistance(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;)Lnet/minecraft/world/level/block/state/BlockState; -# ModuleArboriculture.modifyLeafStateCaches -public net.minecraft.world.level.block.state.BlockBehaviour$BlockStateBase$Cache -public net.minecraft.world.level.block.state.BlockBehaviour$BlockStateBase f_60593_ # cache -public net.minecraft.world.level.block.state.BlockBehaviour$BlockStateBase$Cache f_60850_ # faceSturdy +# For using the cached array instead of cloning every time +public net.minecraft.core.Direction VALUES -# RefractoryWaxParticle#createParticle -public net.minecraft.client.particle.GlowParticle (Lnet/minecraft/client/multiplayer/ClientLevel;DDDDDDLnet/minecraft/client/particle/SpriteSet;)V # \ No newline at end of file +# ForestryFeaturesProvider.commonOrePlacement +public net.minecraft.data.worldgen.placement.OrePlacements commonOrePlacement(ILnet/minecraft/world/level/levelgen/placement/PlacementModifier;)Ljava/util/List; # commonOrePlacement diff --git a/src/main/templates/META-INF/mods.toml b/src/main/templates/META-INF/neoforge.mods.toml similarity index 100% rename from src/main/templates/META-INF/mods.toml rename to src/main/templates/META-INF/neoforge.mods.toml

type, StreamDecoder decoder, BiConsumer packetHandler); } diff --git a/src/main/java/forestry/api/modules/package-info.java b/src/main/java/forestry/api/modules/package-info.java index a276f84390..b62f1c6a5d 100644 --- a/src/main/java/forestry/api/modules/package-info.java +++ b/src/main/java/forestry/api/modules/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.modules; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/multiblock/IFarmComponent.java b/src/main/java/forestry/api/multiblock/IFarmComponent.java index fdf5b4ba02..f022ec7ff0 100644 --- a/src/main/java/forestry/api/multiblock/IFarmComponent.java +++ b/src/main/java/forestry/api/multiblock/IFarmComponent.java @@ -1,6 +1,13 @@ package forestry.api.multiblock; -import forestry.api.farming.IFarmListener; +import forestry.api.farming.ICrop; +import forestry.api.farming.IFarmLogic; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.item.ItemStack; + +import java.util.Collection; +import java.util.List; /** * Needs to be implemented by TileEntities that want to be part of a farm. @@ -8,7 +15,6 @@ * They are automatically detected and handled by the farm when they join its structure. */ public interface IFarmComponent extends IMultiblockComponent { - /** * @return the multiblock logic for this component */ @@ -16,18 +22,64 @@ public interface IFarmComponent extends IMultibl T getMultiblockLogic(); /** - * Implemented by farm parts to apply a farmListener to the completed structure. + * Implemented by farm parts to receive client/server ticks from the completed structure. */ - interface Listener extends IFarmComponent { - IFarmListener getFarmListener(); + interface Active extends IFarmComponent { + void updateServer(int tickCount); + + void updateClient(int tickCount); } /** - * Implemented by farm parts to receive ticks from the completed structure. + * Implemented by farm parts to apply a farmListener to the completed structure. */ - interface Active extends IFarmComponent { - void updateServer(int tickCount); + interface Listener extends IFarmComponent { + /** + * Called before a crop is harvested. + * + * @param crop ICrop about to be harvested. + * @return true to cancel further processing of this crop. + */ + default boolean beforeCropHarvest(ICrop crop) { + return false; + } - void updateClient(int tickCount); + /** + * Called after a crop has been harvested, but before harvested items are stowed in the farms inventory. + * + * @param harvested Collection of harvested stacks. May be manipulated. Ensure removal of stacks with 0 or less items! + * @param crop Harvested {@link ICrop} + */ + default void afterCropHarvest(List harvested, ICrop crop) { + } + + /** + * Called after the stack of collected items has been returned by the farm logic, but before it is added to the farm's pending queue. + * + * @param collected Collection of collected stacks. May be manipulated. Ensure removal of stacks with 0 or less items! + */ + default void hasCollected(List collected, IFarmLogic logic) { + } + + /** + * Called after farmland has successfully been cultivated by a farm logic. + */ + default void hasCultivated(IFarmLogic logic, BlockPos pos, Direction direction, int extent) { + } + + /** + * Called after the stack of harvested crops has been returned by the farm logic, but before it is added to the farm's pending queue. + */ + default void hasScheduledHarvest(Collection harvested, IFarmLogic logic, BlockPos pos, Direction direction, int extent) { + } + + /** + * Can be used to cancel farm task on a per side/{@link IFarmLogic} basis. + * + * @return true to skip any work action on the given logic and direction for this work cycle. + */ + default boolean cancelTask(IFarmLogic logic, Direction direction) { + return false; + } } } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockComponent.java b/src/main/java/forestry/api/multiblock/IMultiblockComponent.java index de68437120..140ebd6290 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockComponent.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockComponent.java @@ -1,8 +1,8 @@ package forestry.api.multiblock; -import com.mojang.authlib.GameProfile; import forestry.core.inventory.IInventoryAdapter; import net.minecraft.core.BlockPos; +import net.minecraft.world.item.component.ResolvableProfile; import javax.annotation.Nullable; @@ -16,13 +16,13 @@ public interface IMultiblockComponent { * * @return ChunkCoordinates set to the location of this tile entity in the world. */ - BlockPos getCoordinates(); + BlockPos getBlockPos(); /** * @return the gameProfile of the player who owns this single component (not the entire multiblock) */ @Nullable - GameProfile getOwner(); + ResolvableProfile getOwner(); /** * @return the multiblock logic for this part diff --git a/src/main/java/forestry/api/multiblock/IMultiblockLogic.java b/src/main/java/forestry/api/multiblock/IMultiblockLogic.java index 934c82ef04..157746b4b1 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockLogic.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockLogic.java @@ -1,6 +1,8 @@ package forestry.api.multiblock; +import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.Level; @@ -11,10 +13,9 @@ * IMultiblockComponent tile entities must wire up the methods in the "Updating and Synchronization" section. * As a starting point, you can use MultiblockTileEntityBase. */ -public interface IMultiblockLogic extends INbtWritable { - +public interface IMultiblockLogic extends INbtWritable, INbtReadable { /** - * @return True if this block is connected to a multiblock controller. False otherwise. + * @return {@code true} if this block is connected to a multiblock controller. False otherwise. */ boolean isConnected(); @@ -28,40 +29,41 @@ public interface IMultiblockLogic extends INbtWritable { /** * call on Tile.validate() **/ - void validate(Level world, IMultiblockComponent part); + void validate(Level level, IMultiblockComponent part); /** - * call on Tile.invalidate() + * call on Tile.setRemoved() **/ - void invalidate(Level world, IMultiblockComponent part); + void setRemoved(Level level, IMultiblockComponent part); /** * call on Tile.onChunkUnload() **/ - void onChunkUnload(Level world, IMultiblockComponent part); + void onChunkUnload(Level level, IMultiblockComponent part); /** * Writes data for client synchronization. * Use this in Tile.getDescriptionPacket() */ - void encodeDescriptionPacket(CompoundTag packetData); + void encodeUpdatePacket(CompoundTag nbt, HolderLookup.Provider registries); /** * Reads data for client synchronization. * Use this in Tile.onDataPacket() */ - void decodeDescriptionPacket(CompoundTag packetData); + void decodeUpdatePacket(CompoundTag nbt, HolderLookup.Provider registries); /** * Read the logic's data from file. * Use this in Tile.read() */ - void readFromNBT(CompoundTag CompoundNBT); + @Override + void read(CompoundTag nbt, HolderLookup.Provider registries); /** * Write the logic's data to file. * Use this in Tile.write() */ @Override - CompoundTag write(CompoundTag CompoundNBT); + CompoundTag write(CompoundTag nbt, HolderLookup.Provider registries); } diff --git a/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java b/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java index 52c3936167..e5bc519761 100644 --- a/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java +++ b/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java @@ -1,19 +1,17 @@ package forestry.api.multiblock; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; /** * Base logic class for Multiblock-connected tile entities. * Most multiblock components should derive from this. - * Supply it an IMultiblockLogic from MultiblockManager.logicFactory */ public abstract class MultiblockTileEntityBase extends BlockEntity implements IMultiblockComponent { private final T multiblockLogic; @@ -23,11 +21,6 @@ public MultiblockTileEntityBase(BlockEntityType tileEntityType, BlockPos pos, this.multiblockLogic = multiblockLogic; } - @Override - public BlockPos getCoordinates() { - return getBlockPos(); - } - @Override public T getMultiblockLogic() { return this.multiblockLogic; @@ -40,33 +33,33 @@ public T getMultiblockLogic() { public abstract void onMachineBroken(); @Override - public void load(CompoundTag data) { - super.load(data); - this.multiblockLogic.readFromNBT(data); + public void loadAdditional(CompoundTag data, HolderLookup.Provider registries) { + super.loadAdditional(data, registries); + this.multiblockLogic.read(data, registries); } @Override - public void saveAdditional(CompoundTag data) { - super.saveAdditional(data); - this.multiblockLogic.write(data); + public void saveAdditional(CompoundTag data, HolderLookup.Provider registries) { + super.saveAdditional(data, registries); + this.multiblockLogic.write(data, registries); } @Override public void setRemoved() { super.setRemoved(); - this.multiblockLogic.invalidate(this.level, this); + this.multiblockLogic.setRemoved(this.level, this); } @Override public void onChunkUnloaded() { super.onChunkUnloaded(); - this.multiblockLogic.onChunkUnload(this.level, this); + this.multiblockLogic.onChunkUnload(this.level, this); } @Override public void onLoad() { super.onLoad(); - this.multiblockLogic.validate(this.level, this); + this.multiblockLogic.validate(this.level, this); } /* Network Communication */ @@ -77,28 +70,25 @@ public ClientboundBlockEntityDataPacket getUpdatePacket() { } @Override - public CompoundTag getUpdateTag() { - CompoundTag updateTag = super.getUpdateTag(); - this.multiblockLogic.encodeDescriptionPacket(updateTag); - this.encodeDescriptionPacket(updateTag); + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { + CompoundTag updateTag = super.getUpdateTag(registries); + this.multiblockLogic.encodeUpdatePacket(updateTag, registries); + encodeDescriptionPacket(updateTag); return updateTag; } @Override - @OnlyIn(Dist.CLIENT) - public final void onDataPacket(Connection network, ClientboundBlockEntityDataPacket packet) { - super.onDataPacket(network, packet); + public final void onDataPacket(Connection network, ClientboundBlockEntityDataPacket packet, HolderLookup.Provider registries) { + super.onDataPacket(network, packet, registries); CompoundTag nbtData = packet.getTag(); - if (nbtData != null) { - this.multiblockLogic.decodeDescriptionPacket(nbtData); - this.decodeDescriptionPacket(nbtData); - } - } + this.multiblockLogic.decodeUpdatePacket(nbtData, registries); + this.decodeDescriptionPacket(nbtData); + } @Override - public void handleUpdateTag(CompoundTag tag) { - super.handleUpdateTag(tag); - this.multiblockLogic.decodeDescriptionPacket(tag); + public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider registries) { + super.handleUpdateTag(tag, registries); + this.multiblockLogic.decodeUpdatePacket(tag, registries); this.decodeDescriptionPacket(tag); } @@ -106,13 +96,11 @@ public void handleUpdateTag(CompoundTag tag) { * Used to write tileEntity-specific data to the descriptionPacket */ protected void encodeDescriptionPacket(CompoundTag packetData) { - } /** * Used to read tileEntity-specific data from the descriptionPacket (onDataPacket) */ protected void decodeDescriptionPacket(CompoundTag packetData) { - } } diff --git a/src/main/java/forestry/api/multiblock/package-info.java b/src/main/java/forestry/api/multiblock/package-info.java index bbc2486f75..3e6bc46ccb 100644 --- a/src/main/java/forestry/api/multiblock/package-info.java +++ b/src/main/java/forestry/api/multiblock/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.multiblock; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/package-info.java b/src/main/java/forestry/api/package-info.java index e417e677ff..832adc0ee2 100644 --- a/src/main/java/forestry/api/package-info.java +++ b/src/main/java/forestry/api/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/plugin/IApicultureRegistration.java b/src/main/java/forestry/api/plugin/IApicultureRegistration.java index 163f84c85d..468b148d74 100644 --- a/src/main/java/forestry/api/plugin/IApicultureRegistration.java +++ b/src/main/java/forestry/api/plugin/IApicultureRegistration.java @@ -1,8 +1,8 @@ package forestry.api.plugin; -import forestry.api.apiculture.IActivityType; -import forestry.api.apiculture.IFlowerType; -import forestry.api.apiculture.genetics.IBeeEffect; +import forestry.api.apiculture.bee.IActivityType; +import forestry.api.apiculture.bee.IFlowerType; +import forestry.api.apiculture.bee.IBeeEffect; import forestry.api.apiculture.hives.IHiveDefinition; import forestry.api.genetics.alleles.IAllele; import forestry.api.genetics.alleles.IChromosome; @@ -10,7 +10,6 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; -import java.awt.*; import java.util.Map; import java.util.function.Consumer; @@ -19,14 +18,6 @@ * Obtain an instance by overriding {@link IForestryPlugin#registerApiculture}. */ public interface IApicultureRegistration { - /** - * @deprecated Use variant that accepts TextColor - */ - @Deprecated(forRemoval = true) - default IBeeSpeciesBuilder registerSpecies(ResourceLocation id, String genus, String species, boolean dominant, Color outline) { - return registerSpecies(id, genus, species, dominant, TextColor.fromRgb(outline.getRGB())); - } - /** * Register a new bee species. * diff --git a/src/main/java/forestry/api/plugin/IArboricultureRegistration.java b/src/main/java/forestry/api/plugin/IArboricultureRegistration.java index 1e714d32f9..d94667a456 100644 --- a/src/main/java/forestry/api/plugin/IArboricultureRegistration.java +++ b/src/main/java/forestry/api/plugin/IArboricultureRegistration.java @@ -1,5 +1,6 @@ package forestry.api.plugin; +import forestry.api.arboriculture.ICharcoalPileWall; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.genetics.IFruit; import forestry.api.arboriculture.genetics.ITreeEffect; @@ -65,16 +66,10 @@ default ITreeSpeciesBuilder registerSpecies(ResourceLocation id, String genus, S * * @param state The state used to surround a pit of burning Log Pile blocks when making charcoal. * @param charcoal The amount of charcoal produced when using this block. - * @since 2.6.0 */ void registerCharcoalPitWall(BlockState state, int charcoal); - /** - * @since 2.6.0 - */ - default void registerCharcoalPitWall(Block block, int charcoal) { - for (BlockState state : block.getStateDefinition().getPossibleStates()) { - registerCharcoalPitWall(state, charcoal); - } - } + void registerCharcoalPitWall(Block block, int charcoal); + + void registerCharcoalPitWall(ICharcoalPileWall wall); } diff --git a/src/main/java/forestry/api/plugin/IBeeSpeciesBuilder.java b/src/main/java/forestry/api/plugin/IBeeSpeciesBuilder.java index 8fea7cc08c..1af321ad8a 100644 --- a/src/main/java/forestry/api/plugin/IBeeSpeciesBuilder.java +++ b/src/main/java/forestry/api/plugin/IBeeSpeciesBuilder.java @@ -1,8 +1,8 @@ package forestry.api.plugin; -import forestry.api.apiculture.IBeeJubilance; -import forestry.api.apiculture.genetics.IBeeSpecies; -import forestry.api.apiculture.genetics.IBeeSpeciesType; +import forestry.api.apiculture.bee.IBeeJubilance; +import forestry.api.apiculture.bee.IBeeSpecies; +import forestry.api.apiculture.bee.IBeeSpeciesType; import forestry.api.core.IProduct; import forestry.api.core.Product; import net.minecraft.network.chat.TextColor; diff --git a/src/main/java/forestry/api/plugin/IChromosomeBuilder.java b/src/main/java/forestry/api/plugin/IChromosomeBuilder.java index 028f2ce6be..28eab35b5a 100644 --- a/src/main/java/forestry/api/plugin/IChromosomeBuilder.java +++ b/src/main/java/forestry/api/plugin/IChromosomeBuilder.java @@ -13,7 +13,7 @@ public interface IChromosomeBuilder { /** * Add alleles as valid values for this chromosome. */ - IChromosomeBuilder addAlleles(List alleles); + IChromosomeBuilder addAlleles(List alleles); /** * Override the default value of this chromosome that was previously set in {@link IKaryotypeBuilder#set}. diff --git a/src/main/java/forestry/api/plugin/IGeneticRegistration.java b/src/main/java/forestry/api/plugin/IGeneticRegistration.java index 9d9f1c0e3e..cb14b3e708 100644 --- a/src/main/java/forestry/api/plugin/IGeneticRegistration.java +++ b/src/main/java/forestry/api/plugin/IGeneticRegistration.java @@ -1,5 +1,6 @@ package forestry.api.plugin; +import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.filter.IFilterRuleType; import net.minecraft.resources.ResourceLocation; @@ -32,15 +33,6 @@ public interface IGeneticRegistration { */ void defineTaxon(String parent, String name, Consumer action); - /** - * Register a new type of species. Can only be called from {@link IForestryPlugin#registerGenetics}. - * - * @param id The ID of the species. - * @param typeFactory The function to use to create the species type, given the completed karyotype. - * @return A builder that can be used to define properties of the species. - */ - ISpeciesTypeBuilder registerSpeciesType(ResourceLocation id, ISpeciesTypeFactory typeFactory); - /** * Modify an existing species, for example, adding an extra chromosome to bees, or adding additional permitted alleles to chromosomes. * Called after all species types are registered, but before the registry is finalized. diff --git a/src/main/java/forestry/api/plugin/IMutationsRegistration.java b/src/main/java/forestry/api/plugin/IMutationsRegistration.java index 015d4c359a..fe7a2234a7 100644 --- a/src/main/java/forestry/api/plugin/IMutationsRegistration.java +++ b/src/main/java/forestry/api/plugin/IMutationsRegistration.java @@ -19,16 +19,6 @@ public interface IMutationsRegistration { */ IMutationBuilder add(ResourceLocation firstParent, ResourceLocation secondParent, float chance); - /** - * Shortcut method for using legacy chance values. Chance must be between 0 and 100, inclusive. - * - * @deprecated Use the overload that takes a float instead. - */ - @Deprecated - default IMutationBuilder add(ResourceLocation firstParent, ResourceLocation secondParent, int chance) { - return add(firstParent, secondParent, chance / 100.0f); - } - /** * Retrieves an already existing mutation so that it can be further customized. * diff --git a/src/main/java/forestry/api/plugin/ISpeciesTypeFactory.java b/src/main/java/forestry/api/plugin/ISpeciesTypeFactory.java index 2c0d7f9e6b..931b4b1c03 100644 --- a/src/main/java/forestry/api/plugin/ISpeciesTypeFactory.java +++ b/src/main/java/forestry/api/plugin/ISpeciesTypeFactory.java @@ -3,6 +3,6 @@ import forestry.api.genetics.ISpeciesType; import forestry.api.genetics.alleles.IKaryotype; -public interface ISpeciesTypeFactory { - ISpeciesType create(IKaryotype karyotype, ISpeciesTypeBuilder builder); +public interface ISpeciesTypeFactory> { + T create(IKaryotype karyotype, ISpeciesTypeBuilder builder); } diff --git a/src/main/java/forestry/api/plugin/ITreeSpeciesBuilder.java b/src/main/java/forestry/api/plugin/ITreeSpeciesBuilder.java index 0faf5ab6cc..d3e05a721f 100644 --- a/src/main/java/forestry/api/plugin/ITreeSpeciesBuilder.java +++ b/src/main/java/forestry/api/plugin/ITreeSpeciesBuilder.java @@ -1,8 +1,7 @@ package forestry.api.plugin; -import forestry.api.arboriculture.ITreeGenData; import forestry.api.arboriculture.ITreeGenerator; -import forestry.api.arboriculture.ITreeSpecies; +import forestry.api.arboriculture.genetics.ITreeSpecies; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.genetics.ITreeSpeciesType; import net.minecraft.network.chat.TextColor; @@ -21,7 +20,7 @@ public interface ITreeSpeciesBuilder extends ISpeciesBuilder> factory); + ITreeSpeciesBuilder setTreeFeature(Function> factory); /** * Sets the tree generator instance used to generate trees when growing from a sapling or being placed in the world. diff --git a/src/main/java/forestry/api/plugin/package-info.java b/src/main/java/forestry/api/plugin/package-info.java index 1b04303d69..945e620ca1 100644 --- a/src/main/java/forestry/api/plugin/package-info.java +++ b/src/main/java/forestry/api/plugin/package-info.java @@ -1,10 +1,7 @@ /** * Contains classes related to registration of Forestry data by {@link forestry.api.plugin.IForestryPlugin} plugins. */ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.plugin; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/recipes/ICarpenterRecipe.java b/src/main/java/forestry/api/recipes/ICarpenterRecipe.java index b40b97c806..894b241494 100644 --- a/src/main/java/forestry/api/recipes/ICarpenterRecipe.java +++ b/src/main/java/forestry/api/recipes/ICarpenterRecipe.java @@ -5,7 +5,10 @@ import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; + +import java.util.Optional; public interface ICarpenterRecipe extends IForestryRecipe { /** @@ -27,7 +30,7 @@ public interface ICarpenterRecipe extends IForestryRecipe { /** * @return the fluid required for this recipe. return {@link FluidStack#EMPTY} if there is no required fluid. */ - FluidStack getInputFluid(); + Optional getInputFluid(); boolean matches(FluidStack fluid, ItemStack boxStack, Container craftingInventory, Level level); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorRecipe.java b/src/main/java/forestry/api/recipes/IFabricatorRecipe.java index 486714081f..c44e1611bb 100644 --- a/src/main/java/forestry/api/recipes/IFabricatorRecipe.java +++ b/src/main/java/forestry/api/recipes/IFabricatorRecipe.java @@ -2,16 +2,20 @@ import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; + +import java.util.Optional; public interface IFabricatorRecipe extends IForestryRecipe { /** * @return the molten liquid (and amount) required for this recipe. */ - FluidStack getResultFluid(); + Optional getRequiredFluid(); /** * @return the plan for this recipe (the item in the top right slot) @@ -21,7 +25,7 @@ public interface IFabricatorRecipe extends IForestryRecipe { /** * @return the crafting grid recipe. The crafting recipe's getRecipeOutput() is used as the IFabricatorRecipe's output. */ - ShapedRecipe getCraftingGridRecipe(); + CraftingRecipe getCraftingGridRecipe(); boolean matches(Level level, FluidStack liquid, ItemStack stack, Container inventory); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java b/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java deleted file mode 100644 index e88cd79d13..0000000000 --- a/src/main/java/forestry/api/recipes/IFabricatorSmeltingRecipe.java +++ /dev/null @@ -1,21 +0,0 @@ -package forestry.api.recipes; - -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.fluids.FluidStack; - -public interface IFabricatorSmeltingRecipe extends IForestryRecipe { - /** - * @return item to be melted down - */ - Ingredient getInput(); - - /** - * @return temperature at which the item melts. Glass is 1000, Sand is 3000. - */ - int getMeltingPoint(); - - /** - * @return resulting fluid - */ - FluidStack getResultFluid(); -} diff --git a/src/main/java/forestry/api/recipes/IFermenterRecipe.java b/src/main/java/forestry/api/recipes/IFermenterRecipe.java index 2e453ecc29..83aad399ad 100644 --- a/src/main/java/forestry/api/recipes/IFermenterRecipe.java +++ b/src/main/java/forestry/api/recipes/IFermenterRecipe.java @@ -3,7 +3,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.FluidIngredient; public interface IFermenterRecipe extends IForestryRecipe { /** @@ -12,9 +13,9 @@ public interface IFermenterRecipe extends IForestryRecipe { Ingredient getInputItem(); /** - * @return FluidStack representing the input fluid resource. + * @return Fluid representing the input fluid resource. */ - FluidStack getInputFluid(); + FluidIngredient getInputFluid(); /** * @return Value of the given resource, i.e. how much needs to be fermented for the output to be deposited into the product tank. @@ -30,7 +31,7 @@ public interface IFermenterRecipe extends IForestryRecipe { /** * @return Fluid representing output. Amount is determined by fermentationValue * modifier. */ - Fluid getOutput(); + Fluid getOutputFluid(); boolean matches(ItemStack inputItem, FluidStack inputFluid); } diff --git a/src/main/java/forestry/api/recipes/IForestryRecipe.java b/src/main/java/forestry/api/recipes/IForestryRecipe.java index 3e570add8f..e55b9404d2 100644 --- a/src/main/java/forestry/api/recipes/IForestryRecipe.java +++ b/src/main/java/forestry/api/recipes/IForestryRecipe.java @@ -1,27 +1,23 @@ package forestry.api.recipes; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.item.crafting.RecipeInput; import net.minecraft.world.level.Level; -public interface IForestryRecipe extends Recipe { - // +public interface IForestryRecipe extends Recipe { @Deprecated @Override - default boolean matches(Container inv, Level level) { + default boolean matches(RecipeInput inv, Level level) { return false; } @Deprecated @Override - default ItemStack assemble(Container inv, RegistryAccess lookup) { + default ItemStack assemble(RecipeInput inv, HolderLookup.Provider lookup) { return ItemStack.EMPTY; } @@ -33,7 +29,7 @@ default boolean canCraftInDimensions(int width, int height) { @Deprecated @Override - default NonNullList getRemainingItems(Container inv) { + default NonNullList getRemainingItems(RecipeInput inv) { return NonNullList.create(); } @@ -60,14 +56,4 @@ default String getGroup() { default ItemStack getToastSymbol() { return ItemStack.EMPTY; } - // - - @Override - ResourceLocation getId(); - - @Override - RecipeSerializer getSerializer(); - - @Override - RecipeType getType(); } diff --git a/src/main/java/forestry/api/recipes/IHygroregulatorRecipe.java b/src/main/java/forestry/api/recipes/IHygroregulatorRecipe.java index 3f8a4b04d8..51e1306921 100644 --- a/src/main/java/forestry/api/recipes/IHygroregulatorRecipe.java +++ b/src/main/java/forestry/api/recipes/IHygroregulatorRecipe.java @@ -1,12 +1,12 @@ package forestry.api.recipes; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; public interface IHygroregulatorRecipe extends IForestryRecipe { /** * @return FluidStack containing information on fluid and amount. */ - FluidStack getInputFluid(); + SizedFluidIngredient getInputFluid(); /** * @return How long the temperature change from this recipe will last before more fluid is consumed. diff --git a/src/main/java/forestry/api/recipes/ISqueezerContainerRecipe.java b/src/main/java/forestry/api/recipes/ISqueezerContainerRecipe.java index 102f040db8..7a3cf13a55 100644 --- a/src/main/java/forestry/api/recipes/ISqueezerContainerRecipe.java +++ b/src/main/java/forestry/api/recipes/ISqueezerContainerRecipe.java @@ -1,13 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ package forestry.api.recipes; import net.minecraft.world.item.ItemStack; diff --git a/src/main/java/forestry/api/recipes/ISqueezerRecipe.java b/src/main/java/forestry/api/recipes/ISqueezerRecipe.java index 4486c7a38e..7785c575b7 100644 --- a/src/main/java/forestry/api/recipes/ISqueezerRecipe.java +++ b/src/main/java/forestry/api/recipes/ISqueezerRecipe.java @@ -2,7 +2,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import java.util.List; diff --git a/src/main/java/forestry/api/recipes/IStillRecipe.java b/src/main/java/forestry/api/recipes/IStillRecipe.java index df37734305..e89c6ada60 100644 --- a/src/main/java/forestry/api/recipes/IStillRecipe.java +++ b/src/main/java/forestry/api/recipes/IStillRecipe.java @@ -1,6 +1,7 @@ package forestry.api.recipes; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient; public interface IStillRecipe extends IForestryRecipe { /** @@ -11,7 +12,7 @@ public interface IStillRecipe extends IForestryRecipe { /** * @return FluidStack representing the input liquid. */ - FluidStack getInput(); + SizedFluidIngredient getInput(); /** * @return FluidStack representing the output liquid. diff --git a/src/main/java/forestry/api/recipes/package-info.java b/src/main/java/forestry/api/recipes/package-info.java index 92a737c02c..bd782c5b4c 100644 --- a/src/main/java/forestry/api/recipes/package-info.java +++ b/src/main/java/forestry/api/recipes/package-info.java @@ -1,7 +1,4 @@ -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@javax.annotation.ParametersAreNonnullByDefault +@forestry.api.core.FieldsAreNonnullByDefault +@net.minecraft.MethodsReturnNonnullByDefault package forestry.api.recipes; - -import net.minecraft.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/forestry/api/storage/BackpackDefinition.java b/src/main/java/forestry/api/storage/BackpackDefinition.java new file mode 100644 index 0000000000..788a3f5713 --- /dev/null +++ b/src/main/java/forestry/api/storage/BackpackDefinition.java @@ -0,0 +1,18 @@ +package forestry.api.storage; + +import net.minecraft.world.item.ItemStack; + +import java.util.function.Predicate; + +/** + * Defines appearance and behavior of a backpack, for use in {@link forestry.storage.items.ItemBackpack} and its inheritors. + * + * @param primaryColor Primary color for the backpack icon, comprising the cloth part of the backpack. + * @param secondaryColor Secondary color for backpack icon, normally white. + * Can be used to tint the {@code layer1} texture if using a custom backpack model. + * @param filter Filters items that can be put into a backpack. + * @see forestry.storage.BackpackFilter + * @see forestry.storage.NaturalistBackpackFilter + */ +public record BackpackDefinition(int primaryColor, int secondaryColor, Predicate filter) { +} diff --git a/src/main/java/forestry/api/storage/BackpackEvent.java b/src/main/java/forestry/api/storage/BackpackEvent.java deleted file mode 100644 index d134803ed4..0000000000 --- a/src/main/java/forestry/api/storage/BackpackEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package forestry.api.storage; - -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; -import net.minecraftforge.eventbus.api.Event; - -public abstract class BackpackEvent extends Event { - - public final Player player; - public final IBackpackDefinition backpackDefinition; - public final Container backpackInventory; - - public BackpackEvent(Player player, IBackpackDefinition backpackDefinition, Container backpackInventory) { - this.player = player; - this.backpackDefinition = backpackDefinition; - this.backpackInventory = backpackInventory; - } -} diff --git a/src/main/java/forestry/api/storage/BackpackResupplyEvent.java b/src/main/java/forestry/api/storage/BackpackResupplyEvent.java deleted file mode 100644 index 5db1eaffe1..0000000000 --- a/src/main/java/forestry/api/storage/BackpackResupplyEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package forestry.api.storage; - -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; -import net.minecraftforge.eventbus.api.Cancelable; - -/** - * Use @SubscribeEvent on a method taking this event as an argument. Will fire whenever a backpack tries to resupply to a player inventory. Processing will stop - * if the event is canceled. - */ -@Cancelable -public class BackpackResupplyEvent extends BackpackEvent { - - public BackpackResupplyEvent(Player player, IBackpackDefinition backpackDefinition, Container backpackInventory) { - super(player, backpackDefinition, backpackInventory); - } - -} diff --git a/src/main/java/forestry/api/storage/BackpackStowEvent.java b/src/main/java/forestry/api/storage/BackpackStowEvent.java deleted file mode 100644 index 2ac7c0d4ed..0000000000 --- a/src/main/java/forestry/api/storage/BackpackStowEvent.java +++ /dev/null @@ -1,21 +0,0 @@ -package forestry.api.storage; - -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.eventbus.api.Cancelable; - -/** - * Use @SubscribeEvent on a method taking this event as an argument. Will fire whenever a backpack tries to store an item. Processing will stop if the stacksize - * of stackToStow drops to 0 or less or the event is canceled. - */ -@Cancelable -public class BackpackStowEvent extends BackpackEvent { - - public final ItemStack stackToStow; - - public BackpackStowEvent(Player player, IBackpackDefinition backpackDefinition, Container backpackInventory, ItemStack stackToStow) { - super(player, backpackDefinition, backpackInventory); - this.stackToStow = stackToStow; - } -} diff --git a/src/main/java/forestry/api/storage/IBackpackDefinition.java b/src/main/java/forestry/api/storage/IBackpackDefinition.java deleted file mode 100644 index c65eebc4af..0000000000 --- a/src/main/java/forestry/api/storage/IBackpackDefinition.java +++ /dev/null @@ -1,39 +0,0 @@ -package forestry.api.storage; - -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.ItemStack; - -import java.util.function.Predicate; - -/** - * To make your own backpack, create a backpack definition and register it with - * {@link IBackpackInterface#registerBackpackDefinition(String, IBackpackDefinition)}. - */ -public interface IBackpackDefinition { - /** - * @return Human-readable name of the backpack. - */ - Component getName(ItemStack backpack); - - /** - * @return Primary color for the backpack icon. - */ - int getPrimaryColour(); - - /** - * @return Secondary color for backpack icon, normally white. - */ - int getSecondaryColour(); - - /** - * Filters items that can be put into a backpack. - *