diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f8ff19e9..dd7dacdf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: uses: actions/setup-java@v3 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: 'gradle' - name: make gradle wrapper executable run: chmod +x ./gradlew diff --git a/.github/workflows/release.yml.disabled b/.github/workflows/release.yml.disabled new file mode 100644 index 00000000..baa54265 --- /dev/null +++ b/.github/workflows/release.yml.disabled @@ -0,0 +1,26 @@ +name: Release + +on: + push: + tags: + - 'v*' + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: checkout repository + uses: actions/checkout@v3 + - name: setup jdk + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: 21 + cache: 'gradle' + - name: make gradle wrapper executable + run: chmod +x ./gradlew + - name: publish + run: ./gradlew publishCurseForge publishModrinth publish + env: + CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }} + MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} diff --git a/.gitignore b/.gitignore index ff73fea0..4b1853a1 100755 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ bin *.launch .settings .metadata -.classpath +.cla* .project # idea @@ -16,11 +16,10 @@ out # gradle build .gradle +deploy.properties # other run logs libs - -# Files from Forge MDK -forge*changelog.txt +repo diff --git a/LICENSE b/LICENSE index 9a5f2f53..16e607db 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,6 @@ MIT License -Copyright (c) 2017 - Original Author is MrRiegel as seen here https://github.com/MrRiegel -- Secondary author Sam Bassett aka Lothrazar https://minecraft.curseforge.com/members/Lothrazar +Copyright (c) 2026 Lothrazar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/build.gradle b/build.gradle index b3d4f596..613c56af 100755 --- a/build.gradle +++ b/build.gradle @@ -1,257 +1,334 @@ -plugins { - id 'eclipse' - id 'idea' - id 'maven-publish' - id 'net.neoforged.gradle' version '[6.0.18,6.2)' -} - -version = "${mc_version}-${mod_version}" -group = mod_group_id - -base { - archivesName = "SimpleStorageNetwork" -} - -// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. -java.toolchain.languageVersion = JavaLanguageVersion.of(17) -import net.minecraftforge.gradle.common.tasks.SignJar -println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" -minecraft { - // The mappings can be changed at any time and must be in the following format. - // Channel: Version: - // official MCVersion Official field/method names from Mojang mapping files - // parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official - // - // You must be aware of the Mojang license when using the 'official' or 'parchment' mappings. - // See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md - // - // Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge - // Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started - // - // Use non-default mappings at your own risk. They may not always work. - // Simply re-run your setup task after changing the mappings to update your workspace. - mappings channel: mapping_channel, version: mapping_version - - // When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game. - // In most cases, it is not necessary to enable. - // enableEclipsePrepareRuns = true - // enableIdeaPrepareRuns = true - - // This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game. - // It is REQUIRED to be set to true for this template to function. - // See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html - copyIdeResources = true - - // When true, this property will add the folder name of all declared run configurations to generated IDE run configurations. - // The folder name can be set on a run configuration using the "folderName" property. - // By default, the folder name of a run configuration is the name of the Gradle project containing it. - // generateRunFolders = true - - // This property enables access transformers for use in development. - // They will be applied to the Minecraft artifact. - // The access transformer file can be anywhere in the project. - // However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge. - // This default location is a best practice to automatically put the file in the right place in the final jar. - // See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information. - // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') - - // Default run configurations. - // These can be tweaked, removed, or duplicated as needed. - runs { - // applies to all the run configs below - configureEach { - workingDirectory project.file('run') - - // Recommended logging data for a userdev environment - // The markers can be added/remove as needed separated by commas. - // "SCAN": For mods scan. - // "REGISTRIES": For firing of registry events. - // "REGISTRYDUMP": For getting the contents of all registries. - property 'forge.logging.markers', 'REGISTRIES' - - // Recommended logging level for the console - // You can set various levels here. - // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels - property 'forge.logging.console.level', 'debug' - - - mods { - "${mod_id}" { - source sourceSets.main - } - } - } - - client { - property 'mixin.env.remapRefMap', 'true' - property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg" - // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. - property 'forge.enabledGameTestNamespaces', mod_id - args '--username=ADev' - } - - server { - property 'mixin.env.remapRefMap', 'true' - property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg" - property 'forge.enabledGameTestNamespaces', mod_id - // args '--nogui' - } - - // This run config launches GameTestServer and runs all registered gametests, then exits. - // By default, the server will crash when no gametests are provided. - // The gametest system is also enabled by default for other run configs under the /test command. - gameTestServer { - property 'forge.enabledGameTestNamespaces', mod_id - } - - data { - // example of overriding the workingDirectory set in configureEach above - workingDirectory project.file('run-data') - - // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') - } - } -} - -// Include resources generated by data generators. -sourceSets.main.resources { srcDir 'src/generated/resources' } - -repositories { - - // flatDir { dir 'libs' } - maven { - // location of the maven that hosts JEI files - name = "Progwml6 maven" - url = 'https://dvs1.progwml6.com/files/maven/' - } - maven { - name = "curios" - url = 'https://maven.theillusivec4.top/' - } - maven { url = 'https://maven.blamejared.com' } - maven { - name = "TerraformersMC" - url = "https://maven.terraformersmc.com/" - } - maven { url = "https://modmaven.dev" } - maven { url = 'https://www.cursemaven.com' } -} - -dependencies { - -// implementation fg.deobf("blank:flib-1.20.1:${flib_version}") - implementation fg.deobf("curse.maven:flib-661261:${flib_file}") - // Specify the version of Minecraft to use. - // Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact. - // The "userdev" classifier will be requested and setup by ForgeGradle. - // If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"], - // then special handling is done to allow a setup of a vanilla dependency without the use of an external repository. - // minecraft "net.minecraftforge:forge:${mc_version}-${forge_version}" - minecraft "net.neoforged:forge:${mc_version}-${forge_version}" - - // Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings - // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime - compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}") - compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}") - runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}") - - compileOnly fg.deobf("dev.emi:emi-forge:${emi_version}+${mc_version}:api") - runtimeOnly fg.deobf("dev.emi:emi-forge:${emi_version}+${mc_version}") - - - runtimeOnly fg.deobf("top.theillusivec4.curios:curios-forge:${curios_version}+${mc_version}") - compileOnly fg.deobf("top.theillusivec4.curios:curios-forge:${curios_version}+${mc_version}:api") - - - - compileOnly fg.deobf("vazkii.patchouli:Patchouli:${mc_version}-${patchouli_version}-FORGE:api") - runtimeOnly fg.deobf("vazkii.patchouli:Patchouli:${mc_version}-${patchouli_version}-FORGE") - -//optional deps - - compileOnly fg.deobf("vazkii.botania:Botania:${mc_version}-443-FORGE:api") - runtimeOnly fg.deobf("vazkii.botania:Botania:${mc_version}-443-FORGE") - - implementation fg.deobf("curse.maven:cyclic-239286:5940363") - - // Example mod dependency using a mod jar from ./libs with a flat dir repository - // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar - // The group id is ignored when searching -- in this case, it is "blank" - // implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}") - - // For more info: - // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html - // http://www.gradle.org/docs/current/userguide/dependency_management.html -} - -// This block of code expands all declared replace properties in the specified resource targets. -// A missing property will result in an error. Properties are expanded using ${} Groovy notation. -// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments. -// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html -tasks.named('processResources', ProcessResources).configure { - var replaceProperties = [ - mc_version: mc_version, - mod_id: mod_id, - mod_version: mod_version - ] - inputs.properties replaceProperties - - filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { - expand replaceProperties + [project: project] - } -} - -// Example for how to get properties into the manifest for reading at runtime. -tasks.named('jar', Jar).configure { - manifest { - attributes([ - 'Specification-Title' : mod_id, - 'Specification-Vendor' : 'Lothrazar', - 'Specification-Version' : '1', // We are version 1 of ourselves - 'Implementation-Title' : project.name, - 'Implementation-Version' : project.jar.archiveVersion, - 'Implementation-Vendor' : 'Lothrazar', - 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") - ]) - } - - // This is the preferred method to reobfuscate your jar file - finalizedBy 'reobfJar' -} - - -// Example configuration to allow publishing using the maven-publish plugin -publishing { - publications { - register('mavenJava', MavenPublication) { - artifact jar - } - } - repositories { - maven { - url "file://${project.projectDir}/mcmodsrepo" - } - } -} - -task signJar(type: SignJar, dependsOn: jar) { - - // findProperty allows us to reference the property without it existing. - // Using project.propName would cause the script to fail validation if - // the property did not exist. - keyStore = project.findProperty('keyStore') - alias = project.findProperty('keyStoreAlias') - storePass = project.findProperty('keyStorePass') - keyPass = project.findProperty('keyStoreKeyPass') - inputFile = jar.archivePath - outputFile = jar.archivePath -} - -task cleanJar { - delete 'build/libs' -} - -tasks.withType(JavaCompile).configureEach { - options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation -} +import net.darkhax.curseforgegradle.TaskPublishCurseForge + +plugins { + id 'java-library' + id 'maven-publish' + id 'net.neoforged.moddev' version '2.0.141' + id 'idea' + id 'net.darkhax.curseforgegradle' version '1.1.25' + id 'com.modrinth.minotaur' version '2.8.7' apply false +} +def localProps = new Properties() +def localFile = file("mod.properties") +localFile.withInputStream { localProps.load(it) } +localProps.each { k, v -> project.ext.set(k, v) } + +if (project == rootProject) { +tasks.named('wrapper', Wrapper).configure { + // Define wrapper values here so as to not have to always do so when updating gradlew.properties. + // Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with + // documentation attached on cursor hover of gradle classes and methods. However, this comes with increased + // file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards. + // (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`) + distributionType = Wrapper.DistributionType.BIN +}} + +version = "${minecraft_version}-${mod_version}" +group = mod_group_id + +sourceSets.main.resources { + // Include resources generated by data generators. + srcDir('src/generated/resources') + + // Exclude common development only resources from finalized outputs + exclude("**/*.bbmodel") // BlockBench project files + exclude("src/generated/**/.cache") // datagen cache files +} + + + +repositories { +// mavenLocal() + flatDir { dir 'libs' } + + maven { + name = "curios" + url = 'https://maven.theillusivec4.top/' + } + maven { url = 'https://maven.blamejared.com' } + maven { url = 'https://www.cursemaven.com' } +} + +base { + archivesName = mod_id +} + +// Mojang ships Java 21 to end users in 1.21.1, so mods should target Java 21. +// for intellij make sure to set JVM Navigate to Build, Execution, Deployment > Build Tools > Gradle +java.toolchain.languageVersion = JavaLanguageVersion.of(21) +println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" + +neoForge { + // Specify the version of NeoForge to use. + version = project.neo_version + + + // This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game. + // It is REQUIRED to be set to true for the 1.21.1 template to function correctly. + // ideConfigGenerated = true + + // Other optional settings + // validateAccessTransformers = true + + parchment { + mappingsVersion = project.parchment_mappings_version + minecraftVersion = project.parchment_minecraft_version + } + accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg') + + // Default run configurations. + // These can be tweaked, removed, or duplicated as needed. + runs { + client { + client() + + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id + } + + server { + server() + programArgument '--nogui' + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + type = "gameTestServer" + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id + } + + data { + data() + + // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it + // gameDirectory = project.file('run-data') + + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() + } + + // applies to all the run configs above + configureEach { + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + systemProperty 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + logLevel = org.slf4j.event.Level.DEBUG + + } + } + + mods { + // define mod <-> source bindings + // these are used to tell the game which sources are for which mod + // multi mod projects should define one per mod + "${mod_id}" { + sourceSet(sourceSets.main) + } + } +} + +// Sets up a dependency configuration called 'localRuntime'. +// This configuration should be used instead of 'runtimeOnly' to declare +// a dependency that will be present for runtime testing but that is +// "optional", meaning it will not be pulled by dependents of this mod. +configurations { + runtimeClasspath.extendsFrom localRuntime +} + + +dependencies { + + // for other mods depending on THIS FLIB library, use either a local copy or a maven + // implementation "local.mods:flib:${minecraft_version}-${flib_version}" + implementation "curse.maven:flib-661261:${flib_file}" + + + //these mods have API jars for compile as well as the full mod for local + compileOnly "mezz.jei:jei-${minecraft_version}-neoforge-api:${jei_version}" + localRuntime "mezz.jei:jei-${minecraft_version}-neoforge:${jei_version}" + + compileOnly "top.theillusivec4.curios:curios-neoforge:${curios_version}+${minecraft_version}" + localRuntime "top.theillusivec4.curios:curios-neoforge:${curios_version}+${minecraft_version}" + + // no APIs + compileOnly "vazkii.patchouli:Patchouli:${minecraft_version}-${patchouli_version}-NEOFORGE" + + compileOnly "com.blamejared.crafttweaker:CraftTweaker-neoforge-${minecraft_version}:${crafttweaker_version}" + + + // Example mod dependency using a mod jar from ./libs with a flat dir repository + // This maps to ./libs/coolmod-${minecraft_version}-${coolmod_version}.jar + // The group id is ignored when searching -- in this case, it is "blank" + // implementation "blank:coolmod-${minecraft_version}:${coolmod_version}" + + // Example mod dependency using a file as dependency + // implementation files("libs/coolmod-${minecraft_version}-${coolmod_version}.jar") + + // Example project dependency using a sister or child project: + // implementation project(":myproject") + + // For more info: + // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html + // http://www.gradle.org/docs/current/userguide/dependency_management.html + + if (file('extra.gradle').exists()) { apply from: 'extra.gradle' } +} + +// This block of code expands all declared replace properties in the specified resource targets. +// A missing property will result in an error. Properties are expanded using ${} Groovy notation. +var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) { + var replaceProperties = [ + minecraft_version : minecraft_version, + neo_version : neo_version, + loader_version_range : loader_version_range, + flib_version : flib_version, + curse_slug : curse_slug, + mod_id : mod_id, + mod_name : mod_name, + mod_license : mod_license, + mod_version : mod_version, + mod_authors : mod_authors, + mod_description : mod_description + ] + inputs.properties replaceProperties + expand replaceProperties + from "src/main/templates" + into "build/generated/sources/modMetadata" +} + +// ??? +//sourceSets.main.resources.srcDir 'src/main/templates' + +// Include the output of "generateModMetadata" as an input directory for the build +// this works with both building through Gradle and the IDE. +sourceSets.main.resources.srcDir generateModMetadata +// To avoid having to run "generateModMetadata" manually, make it run on every project reload +neoForge.ideSyncTask generateModMetadata +// Ensure standard processResources doesn't try to double-process the same files + + +//processResources { +// //from("src/main/resources") +// // 1. Tell Gradle what to do if it finds a duplicate (usually take the first one) +// duplicatesStrategy = DuplicatesStrategy.INCLUDE +// +// // 2. Ensure we aren't accidentally pulling the raw templates folder +// // into the final build (the generateModMetadata task handles this instead) +// exclude 'templates' +//} + +// Example configuration to allow publishing using the maven-publish plugin +publishing { + publications { + register('mavenJava', MavenPublication) { + from components.java + } + } + repositories { + maven { + // url "file://${project.projectDir}/repo" + // url uri("${project.projectDir}/repo") + url = uri("${project.projectDir}/repo") + } + } +} + +apply from: 'gradle/deploy.gradle' + +// Capture ext properties set by deploy.gradle into local vars so they are +// accessible inside the task closure (where ext resolves to the task's ext). +def cfApiKey = ext.cfApiKey +def changelog = ext.changelog + +// --- CurseForge --- +// Defined here (not deploy.gradle) so TaskPublishCurseForge resolves against +// the plugins {} block classpath. +tasks.register('publishCurseForge', TaskPublishCurseForge) { + group = 'publishing' + description = 'Uploads the mod jar to CurseForge.' + dependsOn jar + + apiToken = cfApiKey + def mainFile = upload(curse_id, jar) + mainFile.displayName = "${mod_name} ${project.version}" + mainFile.releaseType = 'release' + mainFile.addGameVersion(minecraft_version) + mainFile.addGameVersion('NeoForge') + mainFile.addGameVersion('Java 21') + mainFile.changelog = changelog + mainFile.changelogType = 'markdown' + + doFirst { + def coreKey = project.findProperty('curseforge_core_api_key') ?: '' + def url = new URI("https://api.curseforge.com/v1/mods/${curse_id}/files").toURL() + def connection = url.openConnection() + connection.setRequestProperty('x-api-key', coreKey) + connection.setRequestProperty('Accept', 'application/json') + def response = new groovy.json.JsonSlurper().parse(connection.inputStream) + if (response.data.any { it.displayName?.contains(project.version as String) }) { + logger.warn("\n⚠️ CurseForge: version ${project.version} already exists for ${mod_name} — skipping upload.\n") + throw new StopExecutionException() + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} + +// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior. +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} + +tasks.register('syncExampleConfigs') { + group = 'documentation' + description = 'Copies generated example config files from run/config/ into examples/.' + + doLast { + def modId = project.mod_id + def srcDir = file('run/config') + def destDir = file('examples') + + if (!srcDir.exists()) { + logger.lifecycle("[${project.name}] run/config/ not found — nothing to sync.") + return + } + + def found = [ + "${modId}.json", + "${modId}.toml", + "${modId}-common.toml", + "${modId}-client.toml", + "${modId}-server.toml" + ].collect { new File(srcDir, it) }.findAll { it.exists() } + + if (found.isEmpty()) { + logger.lifecycle("[${project.name}] No matching config files in run/config/ for '${modId}'.") + return + } + + destDir.mkdirs() + found.each { src -> + java.nio.file.Files.copy( + src.toPath(), + new File(destDir, src.name).toPath(), + java.nio.file.StandardCopyOption.REPLACE_EXISTING + ) + logger.lifecycle("[${project.name}] Synced: ${src.name} → examples/") + } + } +} diff --git a/extra.gradle b/extra.gradle new file mode 100644 index 00000000..7a9b7886 --- /dev/null +++ b/extra.gradle @@ -0,0 +1,12 @@ +repositories { + maven { + name = "EMI" + url = "https://maven.terraformersmc.com/" + } +} + +dependencies { + + compileOnly "dev.emi:emi-neoforge:${emi_version}:api" + runtimeOnly "dev.emi:emi-neoforge:${emi_version}" +} diff --git a/gradle.properties b/gradle.properties index 84cc9a18..cba73616 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,37 +1,28 @@ # Sets default memory used for gradle commands. Can be overridden by user or command line properties. # This is required to provide enough memory for the Minecraft decompilation process. -org.gradle.jvmargs=-Xmx6G -org.gradle.daemon=false +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=true +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.configuration-cache=true +#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings +# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started +parchment_minecraft_version=1.21.1 +parchment_mappings_version=2024.11.17 -#use this if the gradle build has ' Could not find tools.jar. Please check that _____ contains a valid JDK installation ' -#org.gradle.java.home=C:\\Program Files\\Eclipse Adoptium\\jdk-8.0.322.6-hotspot +# your properties +# https://www.curseforge.com/minecraft/mc-mods/flib -# as needed run/server.properties : online-mode=false -# implementation fg.deobf("curse.maven:simple-storage-network-268495:3163007") +minecraft_version=1.21.1 +neo_version=21.1.229 +loader_version_range=[1,) -mod_id=storagenetwork -curse_id=268495 -mod_version=1.13.0 - -mc_version=1.20.1 - -# NEO -forge_version=47.1.104 - -mod_name=storagenetwork -mod_group_id=com.lothrazar.storagenetwork - -mapping_channel=official -mapping_version=1.20.1 - - -flib_version=0.0.14 -flib_file=5495793 -patchouli_version=84 -jei_version=15.3.0.4 -emi_version=1.0.21 -curios_version=5.7.2 +# flib_version=1.0.0 +patchouli_version=93 +jei_version=19.27.0.340 +curios_version=9.5.1 +crafttweaker_version=21.0.38 diff --git a/gradle/deploy.gradle b/gradle/deploy.gradle new file mode 100644 index 00000000..945c7ff1 --- /dev/null +++ b/gradle/deploy.gradle @@ -0,0 +1,135 @@ +// --------------------------------------------------------------------------- +// deployLocal — copies the built JAR to every folder listed in deploy.properties +// deploy.properties is gitignored; each developer maintains their own copy. +// +// Runs automatically after 'publish' via finalizedBy. +// Can also be run standalone with: gradlew deployLocal +// (depends only on 'jar' so it won't trigger a full publish cycle standalone) +// --------------------------------------------------------------------------- +def deployProps = new Properties() +def deployFile = rootProject.file('deploy.properties') +if (deployFile.exists()) { + deployFile.withInputStream { deployProps.load(it) } +} + +tasks.register('deployLocal') { + description = 'Copies build jar to all destinations in deploy.properties' + group = 'distribution' + dependsOn 'jar' + + def jarFile = layout.buildDirectory.file("libs/${base.archivesName.get()}-${version}.jar") + + def destinations = deployProps.getProperty('destinations', '') + .split(',') + .collect { it.trim() } + .findAll { it } + + onlyIf { !destinations.isEmpty() } + + // doLast avoids configuration cache errors from project.copy() references + doLast { + def source = jarFile.get().asFile + destinations.each { dest -> + def destDir = new File(dest) + destDir.mkdirs() + java.nio.file.Files.copy( + source.toPath(), + new File(destDir, source.name).toPath(), + java.nio.file.StandardCopyOption.REPLACE_EXISTING + ) + logger.lifecycle("Deployed ${source.name} -> ${dest}") + } + } +} + +tasks.named('publish') { + finalizedBy 'deployLocal' +} + +// --------------------------------------------------------------------------- +// publishCurseForge / publishModrinth / release / publishAll +// API keys are read from ~/.gradle/gradle.properties, deploy.properties, or env vars. +// +// ~/.gradle/gradle.properties (recommended): +// curseforge_api_key=... +// modrinth_token=... +// +// Run individually: +// gradlew publishCurseForge +// gradlew publishModrinth +// Run all at once: +// gradlew publishAll +// --------------------------------------------------------------------------- +apply plugin: 'com.modrinth.minotaur' + +def changelogText = (new groovy.json.JsonSlurper().parse(file('update.json'))[minecraft_version]?[mod_version] ?: '') as String +def mrToken = findProperty('modrinth_token') ?: deployProps.getProperty('modrinth_token', '') ?: System.getenv('MODRINTH_TOKEN') ?: '' + +// Exposed as ext so publishCurseForge in build.gradle can read them after apply from: +ext.cfApiKey = findProperty('curseforge_api_key') ?: deployProps.getProperty('curseforge_api_key', '') ?: System.getenv('CURSEFORGE_API_KEY') ?: '' +ext.changelog = changelogText + +// --- Modrinth --- +modrinth { + token = mrToken + projectId = modrinth_id + versionNumber = project.version + versionType = 'release' + uploadFile = jar + gameVersions = [minecraft_version] + loaders = ['neoforge'] + changelog = changelogText +} + +// important: unlike curseforge, modrinth has no problem with you making many copies of the same version +//so we have to hand roll up our own checke +tasks.named('modrinth').configure { + notCompatibleWithConfigurationCache('Minotaur is not configuration-cache compatible') + + doFirst { + if (!modrinth_id?.trim()) { + logger.warn(""" +================================================================================ + MODRINTH PROJECT NOT CONFIGURED — ${project.name} +================================================================================ + + 'modrinth_id' is empty. You must create the Modrinth project by hand first: + + 1. Go to https://modrinth.com/dashboard and create a new project + 2. Copy the project ID (shown on the project settings page) + 3. Open gradle.properties in this subproject + 4. Set: modrinth_id= + + This cannot be automated — Modrinth requires manual project creation. + +================================================================================ +""") + throw new StopExecutionException() + } + + def versions = new groovy.json.JsonSlurper() + .parse(new URI("https://api.modrinth.com/v2/project/${modrinth_id}/version").toURL()) + if (versions.any { it.version_number == project.version }) { + throw new GradleException("Modrinth version ${modrinth_id}-${project.version} already exists — bump mod_version before publishing.") + } + } +} + +tasks.register('publishModrinth') { + group = 'publishing' + description = 'Uploads the mod jar to Modrinth.' + dependsOn 'modrinth' +} + +// --- Combined tasks --- +tasks.register('release') { + group = 'publishing' + description = 'Publishes to CurseForge, Modrinth, and Maven.' + dependsOn 'publishCurseForge', 'publishModrinth', 'publish' +} + +//tasks.register('publishAll') { +// group = 'publishing' +// description = 'Uploads to CurseForge and Modrinth, and deploys locally.' +// dependsOn 'publishCurseForge', 'publishModrinth', 'deployLocal' +//} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 943f0cbf..1b33c55b 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37aef8d3..23449a2b 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 65dcd68d..23d15a93 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -83,10 +85,8 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +114,7 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar +CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. @@ -133,10 +133,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -144,7 +147,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +155,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -197,16 +200,20 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f..db3a6ac2 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,22 +59,22 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar +set CLASSPATH= @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell diff --git a/mod.properties b/mod.properties new file mode 100644 index 00000000..d0887de2 --- /dev/null +++ b/mod.properties @@ -0,0 +1,18 @@ + +flib_version=0.1.1 +flib_file=8022223 + +mod_id=storagenetwork +curse_id=268495 +mod_version=1.13.0 +mod_name=storagenetwork +mod_group_id=com.lothrazar.storagenetwork +curse_slug=simple-storage-network +modrinth_id=simple-storage-network +mod_license=SeeGithub +mod_authors=Lothrazar +mod_description=mod + + + +emi_version=1.1.23+1.21.1 diff --git a/settings.gradle b/settings.gradle index 24584e97..7a488e36 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,13 +1,9 @@ pluginManagement { repositories { gradlePluginPortal() - maven { - name = 'NeoForged' - url = 'https://maven.neoforged.net/releases' - } } } plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' -} \ No newline at end of file + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' +} diff --git a/src/main/java/com/lothrazar/storagenetwork/StorageNetworkMod.java b/src/main/java/com/lothrazar/storagenetwork/StorageNetworkMod.java index 434fcd03..2c7ad488 100644 --- a/src/main/java/com/lothrazar/storagenetwork/StorageNetworkMod.java +++ b/src/main/java/com/lothrazar/storagenetwork/StorageNetworkMod.java @@ -1,5 +1,7 @@ package com.lothrazar.storagenetwork; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.config.ModConfig; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.lothrazar.storagenetwork.block.cable.export.ScreenCableExportFilter; @@ -17,17 +19,17 @@ import com.lothrazar.storagenetwork.registry.PacketRegistry; import com.lothrazar.storagenetwork.registry.SsnEvents; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RegisterKeyMappingsEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.fml.loading.FMLPaths; +import com.lothrazar.storagenetwork.registry.SsnTab; +import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; +import net.neoforged.neoforge.common.NeoForge; @Mod(StorageNetworkMod.MODID) public class StorageNetworkMod { @@ -36,37 +38,47 @@ public class StorageNetworkMod { public static final Logger LOGGER = LogManager.getLogger(); public static ConfigRegistry CONFIG; - public StorageNetworkMod() { - FMLJavaModLoadingContext.get().getModEventBus().addListener(StorageNetworkMod::setup); - MinecraftForge.EVENT_BUS.register(new SsnRegistry.Tiles()); - MinecraftForge.EVENT_BUS.register(new SsnEvents()); - IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); - SsnRegistry.BLOCKS.register(bus); - SsnRegistry.ITEMS.register(bus); - SsnRegistry.TILES.register(bus); - SsnRegistry.CONTAINERS.register(bus); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setupClient); - FMLJavaModLoadingContext.get().getModEventBus().addListener(this::registerMapping); - }); + public StorageNetworkMod(IEventBus modEventBus, ModContainer modContainer) { + modContainer.registerConfig(ModConfig.Type.COMMON, ConfigRegistry.COMMON_CONFIG); + modEventBus.addListener(StorageNetworkMod::setup); + modEventBus.addListener(PacketRegistry::registerPayloads); + modEventBus.register(SsnTab.class); + modEventBus.register(StorageNetworkCapabilities.class); + NeoForge.EVENT_BUS.register(new SsnEvents()); + SsnRegistry.Blocks.init(); + SsnRegistry.BLOCKS.register(modEventBus); + SsnRegistry.Items.init(); + SsnRegistry.ITEMS.register(modEventBus); + SsnRegistry.Tiles.init(); + SsnRegistry.TILES.register(modEventBus); + SsnRegistry.Menus.init(); + SsnRegistry.CONTAINERS.register(modEventBus); + if (FMLEnvironment.dist == Dist.CLIENT) { + modEventBus.register(ClientEventRegistry.class); + modEventBus.addListener(this::setupClient); + modEventBus.addListener(this::registerScreens); + modEventBus.addListener(this::registerMapping); + } } private static void setup(FMLCommonSetupEvent event) { - PacketRegistry.init(); - CONFIG = new ConfigRegistry(FMLPaths.CONFIGDIR.get().resolve(MODID + ".toml")); + CONFIG = new ConfigRegistry(); } private void setupClient(final FMLClientSetupEvent event) { - MenuScreens.register(SsnRegistry.Menus.REQUEST.get(), ScreenNetworkTable::new); - MenuScreens.register(SsnRegistry.Menus.FILTER_KABEL.get(), ScreenCableFilter::new); - MenuScreens.register(SsnRegistry.Menus.IMPORT_FILTER_KABEL.get(), ScreenCableImportFilter::new); - MenuScreens.register(SsnRegistry.Menus.EXPORT_KABEL.get(), ScreenCableExportFilter::new); - MenuScreens.register(SsnRegistry.Menus.INVENTORY_REMOTE.get(), ScreenNetworkRemote::new); - MenuScreens.register(SsnRegistry.Menus.CRAFTING_REMOTE.get(), ScreenNetworkCraftingRemote::new); - MenuScreens.register(SsnRegistry.Menus.INVENTORY.get(), ScreenNetworkInventory::new); - MenuScreens.register(SsnRegistry.Menus.COLLECTOR.get(), ScreenCollectionFilter::new); - MenuScreens.register(SsnRegistry.Menus.REQUEST_EXPANDED.get(), ScreenNetworkInventoryExpanded::new); - MenuScreens.register(SsnRegistry.Menus.EXPANDED_REMOTE.get(), ScreenNetworkExpandedRemote::new); + } + + private void registerScreens(final RegisterMenuScreensEvent event) { + event.register(SsnRegistry.Menus.REQUEST.get(), ScreenNetworkTable::new); + event.register(SsnRegistry.Menus.FILTER_KABEL.get(), ScreenCableFilter::new); + event.register(SsnRegistry.Menus.IMPORT_FILTER_KABEL.get(), ScreenCableImportFilter::new); + event.register(SsnRegistry.Menus.EXPORT_KABEL.get(), ScreenCableExportFilter::new); + event.register(SsnRegistry.Menus.INVENTORY_REMOTE.get(), ScreenNetworkRemote::new); + event.register(SsnRegistry.Menus.CRAFTING_REMOTE.get(), ScreenNetworkCraftingRemote::new); + event.register(SsnRegistry.Menus.INVENTORY.get(), ScreenNetworkInventory::new); + event.register(SsnRegistry.Menus.COLLECTOR.get(), ScreenCollectionFilter::new); + event.register(SsnRegistry.Menus.REQUEST_EXPANDED.get(), ScreenNetworkInventoryExpanded::new); + event.register(SsnRegistry.Menus.EXPANDED_REMOTE.get(), ScreenNetworkExpandedRemote::new); } private void registerMapping(final RegisterKeyMappingsEvent event) { diff --git a/src/main/java/com/lothrazar/storagenetwork/api/DimPos.java b/src/main/java/com/lothrazar/storagenetwork/api/DimPos.java index 8eaf54d1..511d28d6 100644 --- a/src/main/java/com/lothrazar/storagenetwork/api/DimPos.java +++ b/src/main/java/com/lothrazar/storagenetwork/api/DimPos.java @@ -5,13 +5,14 @@ import com.lothrazar.storagenetwork.StorageNetworkMod; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; +import net.minecraft.core.component.DataComponents; +import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.component.CustomData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; @@ -19,17 +20,23 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.INBTSerializable; +import net.minecraft.core.Direction; +import net.neoforged.neoforge.capabilities.BlockCapability; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.common.util.INBTSerializable; +import net.neoforged.neoforge.items.IItemHandler; -public class DimPos implements INBTSerializable { +public class DimPos implements INBTSerializable { // NOPMD private String dimension; private BlockPos pos = new BlockPos(0, 0, 0); private Level world; public DimPos(CompoundTag tag) { - deserializeNBT(tag); + if (tag.contains(NBT_X)) { + pos = new BlockPos(tag.getInt(NBT_X), tag.getInt(NBT_Y), tag.getInt(NBT_Z)); + } + dimension = tag.getString(NBT_DIM); } public DimPos(Level world, BlockPos pos) { @@ -41,10 +48,11 @@ public DimPos(Level world, BlockPos pos) { } public static DimPos getPosStored(ItemStack itemStackIn) { - if (itemStackIn.getTag() == null || !itemStackIn.getTag().getBoolean(NBT_BOUND)) { + CustomData data = itemStackIn.get(DataComponents.CUSTOM_DATA); + if (data == null || !data.getUnsafe().getBoolean(NBT_BOUND)) { return null; } - return new DimPos(itemStackIn.getTag()); + return new DimPos(data.getUnsafe()); } public Level getWorld() { @@ -75,20 +83,23 @@ public static String dimensionToString(Level w) { public static final String NBT_BOUND = "bound"; public static void putPos(ItemStack stack, BlockPos pos, Level world) { - CompoundTag tag = stack.getOrCreateTag(); - tag.putInt(NBT_X, pos.getX()); - tag.putInt(NBT_Y, pos.getY()); - tag.putInt(NBT_Z, pos.getZ()); - tag.putString(NBT_DIM, DimPos.dimensionToString(world)); - tag.putBoolean(NBT_BOUND, true); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> { + tag.putInt(NBT_X, pos.getX()); + tag.putInt(NBT_Y, pos.getY()); + tag.putInt(NBT_Z, pos.getZ()); + tag.putString(NBT_DIM, DimPos.dimensionToString(world)); + tag.putBoolean(NBT_BOUND, true); + })); } public static String getDim(ItemStack stack) { - return stack.getOrCreateTag().getString(NBT_DIM); + CustomData data = stack.get(DataComponents.CUSTOM_DATA); + return data != null ? data.getUnsafe().getString(NBT_DIM) : ""; } public static void putDim(ItemStack stack, Level world) { - stack.getOrCreateTag().putString(NBT_DIM, DimPos.dimensionToString(world)); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> + tag.putString(NBT_DIM, DimPos.dimensionToString(world)))); } public static ServerLevel stringDimensionLookup(String s, MinecraftServer serv) { @@ -134,16 +145,20 @@ public V getTileEntity(Class tileEntityClassOrInterface, Level world) { return (V) tileEntity; } - public V getCapability(Capability capability, Direction side) { + public V getCapability(BlockCapability capability, Direction side) { Level world = getWorld(); if (world == null || getBlockPos() == null) { return null; } - BlockEntity tileEntity = world.getBlockEntity(getBlockPos()); - if (tileEntity == null) { + return world.getCapability(capability, getBlockPos(), side); + } + + public IItemHandler getItemHandler(Direction side) { + Level world = getWorld(); + if (world == null || getBlockPos() == null) { return null; } - return tileEntity.getCapability(capability, side).orElse(null); + return world.getCapability(Capabilities.ItemHandler.BLOCK, getBlockPos(), side); } @SuppressWarnings("deprecation") @@ -186,18 +201,23 @@ public String toString() { } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(net.minecraft.core.HolderLookup.Provider registries) { if (pos == null) { pos = new BlockPos(0, 0, 0); } - CompoundTag result = NbtUtils.writeBlockPos(pos); - result.putString(NBT_DIM, dimension); + CompoundTag result = new CompoundTag(); + result.putInt(NBT_X, pos.getX()); + result.putInt(NBT_Y, pos.getY()); + result.putInt(NBT_Z, pos.getZ()); + result.putString(NBT_DIM, dimension != null ? dimension : ""); return result; } @Override - public void deserializeNBT(CompoundTag nbt) { - pos = NbtUtils.readBlockPos(nbt); + public void deserializeNBT(net.minecraft.core.HolderLookup.Provider registries, CompoundTag nbt) { + if (nbt.contains(NBT_X)) { + pos = new BlockPos(nbt.getInt(NBT_X), nbt.getInt(NBT_Y), nbt.getInt(NBT_Z)); + } dimension = nbt.getString(NBT_DIM); } diff --git a/src/main/java/com/lothrazar/storagenetwork/api/IConnectableItemAutoIO.java b/src/main/java/com/lothrazar/storagenetwork/api/IConnectableItemAutoIO.java index f7ffaa44..84aa8acd 100644 --- a/src/main/java/com/lothrazar/storagenetwork/api/IConnectableItemAutoIO.java +++ b/src/main/java/com/lothrazar/storagenetwork/api/IConnectableItemAutoIO.java @@ -7,7 +7,7 @@ import com.lothrazar.storagenetwork.util.RequestBatch; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; /** * Only expose this capability if you want your cable/block to auto-export and import blocks controlled by the networks main. You could quite as well just expose {@link IConnectable} and do the diff --git a/src/main/java/com/lothrazar/storagenetwork/api/IGuiNetwork.java b/src/main/java/com/lothrazar/storagenetwork/api/IGuiNetwork.java index a96c6428..45eb64db 100644 --- a/src/main/java/com/lothrazar/storagenetwork/api/IGuiNetwork.java +++ b/src/main/java/com/lothrazar/storagenetwork/api/IGuiNetwork.java @@ -3,7 +3,7 @@ import java.util.List; import com.lothrazar.storagenetwork.gui.NetworkWidget; import com.lothrazar.storagenetwork.network.SettingsSyncMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; @@ -28,7 +28,7 @@ default BlockPos getPos() { } default void syncDataToServer() { - PacketRegistry.INSTANCE.sendToServer(new SettingsSyncMessage(getPos(), getDownwards(), getSort(), isJeiSearchSynced(), getAutoFocus())); + PacketDistributor.sendToServer(new SettingsSyncMessage(getPos(), getDownwards(), getSort(), isJeiSearchSynced(), getAutoFocus())); } void setSort(EnumSortType val); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/AbstractNetworkScreen.java b/src/main/java/com/lothrazar/storagenetwork/block/AbstractNetworkScreen.java index 6bad1a40..95028317 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/AbstractNetworkScreen.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/AbstractNetworkScreen.java @@ -81,12 +81,12 @@ this.width, getNetwork().scrollHeight, } @Override - public boolean mouseScrolled(double x, double y, double mouseButton) { - super.mouseScrolled(x, y, mouseButton); + public boolean mouseScrolled(double x, double y, double scrollX, double scrollY) { + super.mouseScrolled(x, y, scrollX, scrollY); //<0 going down // >0 going up - if (isScrollable(x, y) && mouseButton != 0) { - getNetwork().mouseScrolled(mouseButton); + if (isScrollable(x, y) && scrollY != 0) { + getNetwork().mouseScrolled(scrollY); } return true; } @@ -105,7 +105,7 @@ protected void blitSegment(GuiGraphics ms, TileableTexture tt, int xpos, int ypo @Override public void render(GuiGraphics ms, int mouseX, int mouseY, float partialTicks) { - this.renderBackground(ms); + this.renderBackground(ms, mouseX, mouseY, partialTicks); super.render(ms, mouseX, mouseY, partialTicks); this.renderTooltip(ms, mouseX, mouseY); getNetwork().searchBar.render(ms, mouseX, mouseY, partialTicks); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/EntityBlockConnectable.java b/src/main/java/com/lothrazar/storagenetwork/block/EntityBlockConnectable.java index 9cc8a7f6..32711e23 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/EntityBlockConnectable.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/EntityBlockConnectable.java @@ -2,7 +2,6 @@ import com.lothrazar.library.block.EntityBlockFlib; import com.lothrazar.storagenetwork.network.SortClientMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; @@ -16,8 +15,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.neoforge.network.PacketDistributor; public abstract class EntityBlockConnectable extends EntityBlockFlib { @@ -37,7 +35,7 @@ public RenderShape getRenderShape(BlockState bs) { } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player player, BlockHitResult result) { if (!world.isClientSide && hasGui) { if (world.getBlockEntity(pos) instanceof TileConnectable tile) { if (tile.getMain() == null || tile.getMain().getBlockPos() == null) { @@ -45,10 +43,10 @@ public InteractionResult use(BlockState state, Level world, BlockPos pos, Player } //sync ServerPlayer sp = (ServerPlayer) player; - PacketRegistry.INSTANCE.sendTo(new SortClientMessage(pos, tile.isDownwards(), tile.getSort()), sp.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(sp, new SortClientMessage(pos, tile.isDownwards(), tile.getSort())); //end sync if (tile instanceof MenuProvider) { - NetworkHooks.openScreen((ServerPlayer) player, (MenuProvider) tile, tile.getBlockPos()); + sp.openMenu((MenuProvider) tile, buf -> buf.writeBlockPos(tile.getBlockPos())); } else { throw new IllegalStateException("Our named container provider is missing!"); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/TileCableWithFacing.java b/src/main/java/com/lothrazar/storagenetwork/block/TileCableWithFacing.java index d6ec58fa..4440fdf2 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/TileCableWithFacing.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/TileCableWithFacing.java @@ -7,6 +7,7 @@ import com.lothrazar.storagenetwork.util.UtilConnections; 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.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -57,8 +58,8 @@ public TileMain getTileMain() { } @Override - public void load(CompoundTag compound) { - super.load(compound); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); if (compound.contains("direction")) { this.direction = Direction.values()[(compound.getInt("direction"))]; } @@ -68,8 +69,8 @@ public void load(CompoundTag compound) { } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); if (direction != null) { compound.putInt("direction", this.direction.ordinal()); } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/TileConnectable.java b/src/main/java/com/lothrazar/storagenetwork/block/TileConnectable.java index f61020b4..b7f849c5 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/TileConnectable.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/TileConnectable.java @@ -3,20 +3,18 @@ import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.api.DimPos; import com.lothrazar.storagenetwork.api.EnumSortType; +import com.lothrazar.storagenetwork.api.IConnectable; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.CapabilityConnectable; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +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.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; /** * Base class for Cable, Control, Request @@ -30,51 +28,53 @@ public TileConnectable(BlockEntityType tileEntityTypeIn, BlockPos pos, BlockS connectable = new CapabilityConnectable(); } + public IConnectable getConnectable() { + return connectable; + } + public EnumSortType getSort() { - return EnumSortType.NAME; //unused by some blocks + return EnumSortType.NAME; } public boolean isDownwards() { - return false; //unused by some blocks + return false; } @Override public void setChanged() { super.setChanged(); - // super.setPosition(posIn); - // StorageNetwork.log("TILE CONNECTABLE :: SET POS on the capability" + posIn + "?" + world); connectable.setPos(new DimPos(level, worldPosition)); } @Override - public void load(CompoundTag compound) { + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { if (compound.contains("connectable")) { - connectable.deserializeNBT(compound.getCompound("connectable")); + connectable.deserializeNBT(registries, compound.getCompound("connectable")); } - super.load(compound); + super.loadAdditional(compound, registries); } @Override - public void saveAdditional(CompoundTag compound) { - compound.put("connectable", connectable.serializeNBT()); - super.saveAdditional(compound); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + compound.put("connectable", connectable.serializeNBT(registries)); + super.saveAdditional(compound, registries); } @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { - return ClientboundBlockEntityDataPacket.create(this); //new ClientboundBlockEntityDataPacket(worldPosition, 0, syncData); + return ClientboundBlockEntityDataPacket.create(this); } @Override - public CompoundTag getUpdateTag() { + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { CompoundTag updateTag = new CompoundTag(); - this.saveAdditional(updateTag); + this.saveAdditional(updateTag, registries); return updateTag; } @Override - public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { - load(pkt.getTag()); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider registries) { + loadAdditional(pkt.getTag() == null ? new CompoundTag() : pkt.getTag(), registries); } @Override @@ -93,15 +93,6 @@ public void onChunkUnloaded() { } } - @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.CONNECTABLE_CAPABILITY) { - LazyOptional cap = LazyOptional.of(() -> connectable); - return cap.cast(); - } - return super.getCapability(capability, facing); - } - public DimPos getMain() { if (connectable == null) { return null; diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/BlockCable.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/BlockCable.java index 32d1129f..81452e3b 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/BlockCable.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/BlockCable.java @@ -37,8 +37,8 @@ import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.items.IItemHandler; public class BlockCable extends EntityBlockFlib implements SimpleWaterloggedBlock { @@ -67,7 +67,7 @@ public FluidState getFluidState(BlockState state) { @Deprecated @Override - public boolean isPathfindable(BlockState bs, BlockGetter bg, BlockPos pos, PathComputationType path) { + public boolean isPathfindable(BlockState bs, PathComputationType path) { return false; } @@ -75,23 +75,19 @@ public boolean isPathfindable(BlockState bs, BlockGetter bg, BlockPos pos, PathC @Override public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) { if (state.getBlock() != newState.getBlock()) { - BlockEntity tileentity = worldIn.getBlockEntity(pos); - if (tileentity != null) { - IItemHandler items = tileentity.getCapability(ForgeCapabilities.ITEM_HANDLER).orElse(null); - if (items != null) { - for (int i = 0; i < items.getSlots(); ++i) { - Containers.dropItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), items.getStackInSlot(i)); - } - worldIn.updateNeighbourForOutputSignal(pos, this); + IItemHandler items = worldIn.getCapability(Capabilities.ItemHandler.BLOCK, pos, null); + if (items != null) { + for (int i = 0; i < items.getSlots(); ++i) { + Containers.dropItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), items.getStackInSlot(i)); } - IConnectableItemAutoIO connectable = tileentity.getCapability(StorageNetworkCapabilities.CONNECTABLE_AUTO_IO).orElse(null); - if (connectable instanceof CapabilityConnectableAutoIO) { - CapabilityConnectableAutoIO filterCable = (CapabilityConnectableAutoIO) connectable; - for (int i = 0; i < filterCable.upgrades.getSlots(); ++i) { - Containers.dropItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), filterCable.upgrades.getStackInSlot(i)); - } - worldIn.updateNeighbourForOutputSignal(pos, this); + worldIn.updateNeighbourForOutputSignal(pos, this); + } + IConnectableItemAutoIO connectable = worldIn.getCapability(StorageNetworkCapabilities.CONNECTABLE_AUTO_IO, pos, null); + if (connectable instanceof CapabilityConnectableAutoIO filterCable) { + for (int i = 0; i < filterCable.upgrades.getSlots(); ++i) { + Containers.dropItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), filterCable.upgrades.getStackInSlot(i)); } + worldIn.updateNeighbourForOutputSignal(pos, this); } super.onRemove(state, worldIn, pos, newState, isMoving); } @@ -125,7 +121,7 @@ public static BlockState cleanBlockState(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { - if (ConfigRegistry.enableFacades.get()) { + if (ConfigRegistry.COMMON_CONFIG.isLoaded() && ConfigRegistry.enableFacades.get()) { TileCable tile = TileCable.getTileCable(worldIn, pos); if (tile != null && tile.getFacadeState() != null) { return tile.getFacadeState().getShape(worldIn, pos, context); @@ -190,8 +186,8 @@ public BlockState updateShape(BlockState stateIn, Direction facing, BlockState f StorageNetworkMod.log("new Inventory from updateShape " + facingState); return stateIn.setValue(property, EnumConnectType.INVENTORY); } - if (tileOffset != null) { - IConnectable cap = tileOffset.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY).orElse(null); + if (tileOffset != null && world instanceof Level levelInstance) { + IConnectable cap = levelInstance.getCapability(StorageNetworkCapabilities.CONNECTABLE, facingPos, null); if (cap != null) { StorageNetworkMod.log("Normal network item " + facingState); return stateIn.setValue(property, EnumConnectType.CABLE); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/CableFacadeRenderer.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/CableFacadeRenderer.java index 3d9ce8b6..1a6fbc56 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/CableFacadeRenderer.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/CableFacadeRenderer.java @@ -12,7 +12,7 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.resources.model.BakedModel; 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 CableFacadeRenderer implements BlockEntityRenderer { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/TileCable.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/TileCable.java index aef2a388..c0b41a89 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/TileCable.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/TileCable.java @@ -3,6 +3,7 @@ import com.lothrazar.storagenetwork.block.TileConnectable; import com.lothrazar.storagenetwork.registry.SsnRegistry; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; @@ -29,8 +30,8 @@ public TileCable(BlockPos pos, BlockState state) { } @Override - public void load(CompoundTag compound) { - super.load(compound); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); if (compound.contains(NBT_FACADE)) { setFacadeState(compound.getCompound(NBT_FACADE)); } @@ -40,14 +41,14 @@ public void load(CompoundTag compound) { } @Override - public void saveAdditional(CompoundTag compound) { + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { if (facadeState == null) { compound.remove(NBT_FACADE); } else { compound.put(NBT_FACADE, facadeState); } - super.saveAdditional(compound); + super.saveAdditional(compound, registries); } public static TileCable getTileCable(BlockGetter world, BlockPos pos) { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/BlockCableExport.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/BlockCableExport.java index 328a0d20..625e96a9 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/BlockCableExport.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/BlockCableExport.java @@ -14,7 +14,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkHooks; public class BlockCableExport extends BlockCable { @@ -33,13 +32,13 @@ public BlockEntityTicker getTicker(Level world, Block } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player playerIn, BlockHitResult result) { if (!world.isClientSide) { BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof MenuProvider) { ServerPlayer player = (ServerPlayer) playerIn; player.connection.send(tile.getUpdatePacket()); - NetworkHooks.openScreen(player, (MenuProvider) tile, tile.getBlockPos()); + player.openMenu((MenuProvider) tile, buf -> buf.writeBlockPos(tile.getBlockPos())); } else { throw new IllegalStateException("Our named container provider is missing!" + tile); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ContainerCableExportFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ContainerCableExportFilter.java index 0a8ee15b..db7044b3 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ContainerCableExportFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ContainerCableExportFilter.java @@ -10,7 +10,7 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.items.SlotItemHandler; +import net.neoforged.neoforge.items.SlotItemHandler; public class ContainerCableExportFilter extends ContainerCable { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ScreenCableExportFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ScreenCableExportFilter.java index 202f1f46..28e4f028 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ScreenCableExportFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/ScreenCableExportFilter.java @@ -14,7 +14,7 @@ import com.lothrazar.storagenetwork.gui.slot.ItemSlotNetwork; import com.lothrazar.storagenetwork.network.CableIOMessage; import com.lothrazar.storagenetwork.registry.ClientEventRegistry; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import com.lothrazar.storagenetwork.util.SsnConsts; import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.client.gui.GuiGraphics; @@ -30,7 +30,7 @@ public class ScreenCableExportFilter extends AbstractContainerScreen { return supplier.get(); }; - private final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/cable_filter.png"); + private final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/cable_filter.png"); ContainerCableExportFilter containerCableLink; private ButtonRequest btnRedstone; private ButtonRequest btnMinus; @@ -63,7 +63,7 @@ public void init() { this.isAllowlist = containerCableLink.cap.getFilter().isAllowList; btnRedstone = addRenderableWidget(new ButtonRequest(leftPos + 4, topPos + 4, "", (p) -> { this.syncData(0); - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.REDSTONE.ordinal())); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.REDSTONE.ordinal())); }, DEFAULT_NARRATION)); btnMinus = addRenderableWidget(new ButtonRequest(leftPos + 22, topPos + 4, "", (p) -> { this.syncData(-1); @@ -85,7 +85,7 @@ public void init() { // containerCableLink.cap.operationType = containerCableLink.cap.operationType.toggle(); OpCompareType old = OpCompareType.get(containerCableLink.cap.operationType); containerCableLink.cap.operationType = old.toggle().ordinal(); - PacketRegistry.INSTANCE.sendToServer( + PacketDistributor.sendToServer( new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP.ordinal(), containerCableLink.cap.operationType, false)); }, DEFAULT_NARRATION)); @@ -93,21 +93,21 @@ public void init() { } private void importFilterSlots() { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.IMPORT_FILTER.ordinal())); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.IMPORT_FILTER.ordinal())); } private void sendStackSlot(int value, ItemStack stack) { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); } private void syncData(int priority) { containerCableLink.cap.getFilter().isAllowList = this.isAllowlist; - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_DATA.ordinal(), priority, isAllowlist)); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_DATA.ordinal(), priority, isAllowlist)); } @Override public void render(GuiGraphics ms, int mouseX, int mouseY, float partialTicks) { - renderBackground(ms); + renderBackground(ms, mouseX, mouseY, partialTicks); super.render(ms, mouseX, mouseY, partialTicks); this.renderTooltip(ms, mouseX, mouseY); //true means we need redstone in order to work @@ -212,7 +212,7 @@ public void setFilterItems(List stacks) { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { ItemStack stackCarriedByMouse = minecraft.player.containerMenu.getCarried(); if (operationItemSlot.isMouseOverSlot((int) mouseX, (int) mouseY)) { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP_STACK.ordinal(), stackCarriedByMouse.copy())); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP_STACK.ordinal(), stackCarriedByMouse.copy())); return true; } for (int i = 0; i < this.itemSlotsGhost.size(); i++) { @@ -246,12 +246,12 @@ public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { - if (delta != 0) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + if (scrollY != 0) { for (int i = 0; i < this.itemSlotsGhost.size(); i++) { ItemSlotNetwork slot = itemSlotsGhost.get(i); if (slot.isMouseOverSlot((int) mouseX, (int) mouseY)) { - ItemStack changeme = ScreenCableImportFilter.scrollStack(delta, slot); + ItemStack changeme = ScreenCableImportFilter.scrollStack(scrollY, slot); if (changeme != null) { this.sendStackSlot(i, changeme); return true; @@ -259,7 +259,7 @@ public boolean mouseScrolled(double mouseX, double mouseY, double delta) { } } } - return super.mouseScrolled(mouseX, mouseY, delta); + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } @Override diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/TileCableExport.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/TileCableExport.java index 54d4f7f5..04a7cd1a 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/export/TileCableExport.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/export/TileCableExport.java @@ -1,12 +1,13 @@ package com.lothrazar.storagenetwork.block.cable.export; import com.lothrazar.storagenetwork.api.EnumStorageDirection; +import com.lothrazar.storagenetwork.api.IConnectableItemAutoIO; import com.lothrazar.storagenetwork.block.TileCableWithFacing; import com.lothrazar.storagenetwork.capability.CapabilityConnectableAutoIO; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; @@ -16,8 +17,6 @@ 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.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class TileCableExport extends TileCableWithFacing implements MenuProvider { @@ -29,6 +28,10 @@ public TileCableExport(BlockPos pos, BlockState state) { this.ioStorage.getFilter().isAllowList = true; } + public IConnectableItemAutoIO getIoStorage() { + return ioStorage; + } + @Override public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { return new ContainerCableExportFilter(i, level, worldPosition, playerInventory, playerEntity); @@ -46,27 +49,18 @@ public void setDirection(Direction direction) { } @Override - public void load(CompoundTag compound) { - super.load(compound); - this.ioStorage.deserializeNBT(compound.getCompound("ioStorage")); - ioStorage.upgrades.deserializeNBT(compound.getCompound("upgrades")); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); + this.ioStorage.deserializeNBT(registries, compound.getCompound("ioStorage")); + ioStorage.upgrades.deserializeNBT(registries, compound.getCompound("upgrades")); this.ioStorage.getFilter().isAllowList = true; } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - compound.put("ioStorage", this.ioStorage.serializeNBT()); - compound.put("upgrades", ioStorage.upgrades.serializeNBT()); - } - - @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.CONNECTABLE_AUTO_IO) { - LazyOptional cap = LazyOptional.of(() -> ioStorage); - return cap.cast(); - } - return super.getCapability(capability, facing); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); + compound.put("ioStorage", this.ioStorage.serializeNBT(registries)); + compound.put("upgrades", ioStorage.upgrades.serializeNBT(registries)); } public static void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableExport tile) {} diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/input/TileCableIO.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/input/TileCableIO.java index 4b1bd3d2..9dd90d00 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/input/TileCableIO.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/input/TileCableIO.java @@ -1,18 +1,17 @@ package com.lothrazar.storagenetwork.block.cable.input; import com.lothrazar.storagenetwork.api.EnumStorageDirection; +import com.lothrazar.storagenetwork.api.IConnectableItemAutoIO; import com.lothrazar.storagenetwork.block.TileCableWithFacing; import com.lothrazar.storagenetwork.capability.CapabilityConnectableAutoIO; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; 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.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class TileCableIO extends TileCableWithFacing { @@ -23,6 +22,10 @@ public TileCableIO(BlockPos pos, BlockState state) { this.ioStorage = new CapabilityConnectableAutoIO(this, EnumStorageDirection.IN); } + public IConnectableItemAutoIO getIoStorage() { + return ioStorage; + } + @Override public void setDirection(Direction direction) { super.setDirection(direction); @@ -30,24 +33,15 @@ public void setDirection(Direction direction) { } @Override - public void load(CompoundTag compound) { - super.load(compound); - this.ioStorage.deserializeNBT(compound.getCompound("ioStorage")); - } - - @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - compound.put("ioStorage", this.ioStorage.serializeNBT()); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); + this.ioStorage.deserializeNBT(registries, compound.getCompound("ioStorage")); } @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.CONNECTABLE_AUTO_IO) { - LazyOptional cap = LazyOptional.of(() -> ioStorage); - return cap.cast(); - } - return super.getCapability(capability, facing); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); + compound.put("ioStorage", this.ioStorage.serializeNBT(registries)); } public static void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableIO tile) {} diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/BlockCableImportFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/BlockCableImportFilter.java index 77c8d7b0..85c7b848 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/BlockCableImportFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/BlockCableImportFilter.java @@ -14,7 +14,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkHooks; public class BlockCableImportFilter extends BlockCable { @@ -33,13 +32,13 @@ public BlockEntityTicker getTicker(Level world, Block } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player playerIn, BlockHitResult result) { if (!world.isClientSide) { BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof MenuProvider) { ServerPlayer player = (ServerPlayer) playerIn; player.connection.send(tile.getUpdatePacket()); - NetworkHooks.openScreen(player, (MenuProvider) tile, tile.getBlockPos()); + player.openMenu((MenuProvider) tile, buf -> buf.writeBlockPos(tile.getBlockPos())); } else { throw new IllegalStateException("Our named container provider is missing!" + tile); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ContainerCableImportFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ContainerCableImportFilter.java index c48141d2..09055ed1 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ContainerCableImportFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ContainerCableImportFilter.java @@ -10,7 +10,7 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.items.SlotItemHandler; +import net.neoforged.neoforge.items.SlotItemHandler; public class ContainerCableImportFilter extends ContainerCable { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ScreenCableImportFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ScreenCableImportFilter.java index 069e7fa4..a026721a 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ScreenCableImportFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/ScreenCableImportFilter.java @@ -13,7 +13,7 @@ import com.lothrazar.storagenetwork.gui.slot.ItemSlotNetwork; import com.lothrazar.storagenetwork.network.CableIOMessage; import com.lothrazar.storagenetwork.registry.ClientEventRegistry; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import com.lothrazar.storagenetwork.util.SsnConsts; import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.client.gui.GuiGraphics; @@ -29,7 +29,7 @@ public class ScreenCableImportFilter extends AbstractContainerScreen { return supplier.get(); }; - private final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/cable_filter.png"); + private final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/cable_filter.png"); ContainerCableImportFilter containerCableLink; private ButtonRequest btnRedstone; private ButtonRequest btnMinus; @@ -63,7 +63,7 @@ public void init() { this.isAllowlist = containerCableLink.cap.getFilter().isAllowList; btnRedstone = addRenderableWidget(new ButtonRequest(leftPos + 4, topPos + 4, "", (p) -> { this.syncData(0); - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.REDSTONE.ordinal())); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.REDSTONE.ordinal())); }, DEFAULT_NARRATION)); btnMinus = addRenderableWidget(new ButtonRequest(leftPos + 22, topPos + 4, "", (p) -> { this.syncData(-1); @@ -78,7 +78,7 @@ public void init() { this.syncData(0); }, DEFAULT_NARRATION)); btnImport = addRenderableWidget(new ButtonRequest(leftPos + 80, topPos + 4, "", (p) -> { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.IMPORT_FILTER.ordinal())); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.IMPORT_FILTER.ordinal())); }, DEFAULT_NARRATION)); btnImport.setTextureId(TextureEnum.IMPORT); txtHeight = new TextboxInteger(this.font, leftPos + 48, topPos + 26, 36); @@ -89,7 +89,7 @@ public void init() { // containerCableLink.cap.operationType = containerCableLink.cap.operationType.toggle(); OpCompareType old = OpCompareType.get(containerCableLink.cap.operationType); containerCableLink.cap.operationType = old.toggle().ordinal(); - PacketRegistry.INSTANCE.sendToServer( + PacketDistributor.sendToServer( new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP.ordinal(), containerCableLink.cap.operationType, false)); }, DEFAULT_NARRATION)); @@ -112,17 +112,17 @@ public void renderLabels(GuiGraphics ms, int mouseX, int mouseY) { } private void sendStackSlot(int value, ItemStack stack) { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); } private void syncData(int priority) { containerCableLink.cap.getFilter().isAllowList = this.isAllowlist; - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_DATA.ordinal(), priority, isAllowlist)); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_DATA.ordinal(), priority, isAllowlist)); } @Override public void render(GuiGraphics ms, int mouseX, int mouseY, float partialTicks) { - renderBackground(ms); + renderBackground(ms, mouseX, mouseY, partialTicks); super.render(ms, mouseX, mouseY, partialTicks); this.renderTooltip(ms, mouseX, mouseY); if (containerCableLink == null || containerCableLink.cap == null) { @@ -217,12 +217,12 @@ public void setFilterItems(List stacks) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { - if (delta != 0) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + if (scrollY != 0) { for (int i = 0; i < this.itemSlotsGhost.size(); i++) { ItemSlotNetwork slot = itemSlotsGhost.get(i); if (slot.isMouseOverSlot((int) mouseX, (int) mouseY)) { - ItemStack changeme = ScreenCableImportFilter.scrollStack(delta, slot); + ItemStack changeme = ScreenCableImportFilter.scrollStack(scrollY, slot); if (changeme != null) { this.sendStackSlot(i, changeme); return true; @@ -230,7 +230,7 @@ public boolean mouseScrolled(double mouseX, double mouseY, double delta) { } } } - return super.mouseScrolled(mouseX, mouseY, delta); + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } /** @@ -254,7 +254,7 @@ public static ItemStack scrollStack(double delta, ItemSlotNetwork slot) { public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { ItemStack stackCarriedByMouse = minecraft.player.containerMenu.getCarried(); if (operationItemSlot.isMouseOverSlot((int) mouseX, (int) mouseY)) { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP_STACK.ordinal(), stackCarriedByMouse.copy())); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP_STACK.ordinal(), stackCarriedByMouse.copy())); return true; } for (int i = 0; i < this.itemSlotsGhost.size(); i++) { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/TileCableImportFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/TileCableImportFilter.java index acdc19f4..9b5a29c4 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/TileCableImportFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/inputfilter/TileCableImportFilter.java @@ -1,12 +1,13 @@ package com.lothrazar.storagenetwork.block.cable.inputfilter; import com.lothrazar.storagenetwork.api.EnumStorageDirection; +import com.lothrazar.storagenetwork.api.IConnectableItemAutoIO; import com.lothrazar.storagenetwork.block.TileCableWithFacing; import com.lothrazar.storagenetwork.capability.CapabilityConnectableAutoIO; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; @@ -16,8 +17,6 @@ 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.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class TileCableImportFilter extends TileCableWithFacing implements MenuProvider { @@ -28,6 +27,10 @@ public TileCableImportFilter(BlockPos pos, BlockState state) { this.ioStorage = new CapabilityConnectableAutoIO(this, EnumStorageDirection.IN); } + public IConnectableItemAutoIO getIoStorage() { + return ioStorage; + } + @Override public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { return new ContainerCableImportFilter(i, level, worldPosition, playerInventory, playerEntity); @@ -45,30 +48,17 @@ public void setDirection(Direction direction) { } @Override - public void load(CompoundTag compound) { - this.ioStorage.deserializeNBT(compound.getCompound("ioStorage")); - ioStorage.upgrades.deserializeNBT(compound.getCompound("upgrades")); - super.load(compound); - } - - @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - compound.put("ioStorage", this.ioStorage.serializeNBT()); - compound.put("upgrades", ioStorage.upgrades.serializeNBT()); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); + this.ioStorage.deserializeNBT(registries, compound.getCompound("ioStorage")); + ioStorage.upgrades.deserializeNBT(registries, compound.getCompound("upgrades")); } @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.CONNECTABLE_AUTO_IO) { - LazyOptional cap = LazyOptional.of(() -> ioStorage); - return cap.cast(); - } - // if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { - // LazyOptional cap = LazyOptional.of(() -> ioStorage.upgrades); - // return cap.cast(); - // } - return super.getCapability(capability, facing); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); + compound.put("ioStorage", this.ioStorage.serializeNBT(registries)); + compound.put("upgrades", ioStorage.upgrades.serializeNBT(registries)); } public static void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableImportFilter tile) {} diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/link/TileCableLink.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/link/TileCableLink.java index 7fbae4e3..69a1a7a7 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/link/TileCableLink.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/link/TileCableLink.java @@ -1,17 +1,16 @@ package com.lothrazar.storagenetwork.block.cable.link; +import com.lothrazar.storagenetwork.api.IConnectableLink; import com.lothrazar.storagenetwork.block.TileCableWithFacing; import com.lothrazar.storagenetwork.capability.CapabilityConnectableLink; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; 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.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class TileCableLink extends TileCableWithFacing { @@ -22,16 +21,20 @@ public TileCableLink(BlockPos pos, BlockState state) { this.itemStorage = new CapabilityConnectableLink(this); } + public IConnectableLink getItemStorage() { + return itemStorage; + } + @Override - public void load(CompoundTag compound) { - super.load(compound); - this.itemStorage.deserializeNBT(compound.getCompound("capability")); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); + this.itemStorage.deserializeNBT(registries, compound.getCompound("capability")); } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - compound.put("capability", itemStorage.serializeNBT()); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); + compound.put("capability", itemStorage.serializeNBT(registries)); } @Override @@ -40,15 +43,6 @@ public void setDirection(Direction direction) { this.itemStorage.setInventoryFace(direction); } - @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE_CAPABILITY) { - LazyOptional cap = LazyOptional.of(() -> itemStorage); - return cap.cast(); - } - return super.getCapability(capability, facing); - } - public static void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableLink tile) {} public static void serverTick(Level level, BlockPos blockPos, BlockState blockState, TileCableLink tile) { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/BlockCableFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/BlockCableFilter.java index 7b94a981..09d1cb4c 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/BlockCableFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/BlockCableFilter.java @@ -14,7 +14,6 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkHooks; public class BlockCableFilter extends BlockCable { @@ -33,13 +32,13 @@ public BlockEntityTicker getTicker(Level world, Block } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player playerIn, BlockHitResult result) { if (!world.isClientSide) { BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof MenuProvider) { ServerPlayer player = (ServerPlayer) playerIn; player.connection.send(tile.getUpdatePacket()); - NetworkHooks.openScreen(player, (MenuProvider) tile, tile.getBlockPos()); + player.openMenu((MenuProvider) tile, buf -> buf.writeBlockPos(tile.getBlockPos())); } else { throw new IllegalStateException("Our named container provider is missing!" + tile); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ContainerCableFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ContainerCableFilter.java index 405be6f8..d0bc83f5 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ContainerCableFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ContainerCableFilter.java @@ -4,7 +4,6 @@ import com.lothrazar.storagenetwork.block.cable.ContainerCable; import com.lothrazar.storagenetwork.capability.CapabilityConnectableLink; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -19,7 +18,7 @@ public class ContainerCableFilter extends ContainerCable { public ContainerCableFilter(int windowId, Level world, BlockPos pos, Inventory playerInv, Player player) { super(SsnRegistry.Menus.FILTER_KABEL.get(), windowId); tile = (TileCableFilter) world.getBlockEntity(pos); - IConnectableLink rawLink = tile.getCapability(StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE_CAPABILITY, null).orElse(null); + IConnectableLink rawLink = tile.getCapabilityLink(); if (!(rawLink instanceof CapabilityConnectableLink)) { return; } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ScreenCableFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ScreenCableFilter.java index b0a9b6c4..321fbd16 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ScreenCableFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/ScreenCableFilter.java @@ -11,7 +11,7 @@ import com.lothrazar.storagenetwork.gui.components.ButtonRequest.TextureEnum; import com.lothrazar.storagenetwork.gui.slot.ItemSlotNetwork; import com.lothrazar.storagenetwork.network.CableDataMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import com.lothrazar.storagenetwork.util.SsnConsts; import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.client.gui.GuiGraphics; @@ -27,7 +27,7 @@ public class ScreenCableFilter extends AbstractContainerScreen { return supplier.get(); }; - private final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/cable.png"); + private final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/cable.png"); ContainerCableFilter containerCableLink; private ButtonRequest btnRedstone; private ButtonRequest btnMinus; @@ -65,20 +65,20 @@ public void init() { } private void importFilterSlots() { - PacketRegistry.INSTANCE.sendToServer(new CableDataMessage(CableDataMessage.CableMessageType.IMPORT_FILTER.ordinal())); + PacketDistributor.sendToServer(new CableDataMessage(CableDataMessage.CableMessageType.IMPORT_FILTER.ordinal())); } private void sendStackSlot(int value, ItemStack stack) { - PacketRegistry.INSTANCE.sendToServer(new CableDataMessage(CableDataMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); + PacketDistributor.sendToServer(new CableDataMessage(CableDataMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); } private void syncData(int priority) { - PacketRegistry.INSTANCE.sendToServer(new CableDataMessage(CableDataMessage.CableMessageType.SYNC_DATA.ordinal(), priority, isAllowlist)); + PacketDistributor.sendToServer(new CableDataMessage(CableDataMessage.CableMessageType.SYNC_DATA.ordinal(), priority, isAllowlist)); } @Override public void render(GuiGraphics ms, int mouseX, int mouseY, float partialTicks) { - renderBackground(ms); + renderBackground(ms, mouseX, mouseY, partialTicks); super.render(ms, mouseX, mouseY, partialTicks); btnAllowIgn.setTextureId(this.isAllowlist ? TextureEnum.ALLOWLIST : TextureEnum.IGNORELIST); if (containerCableLink == null || containerCableLink.cap == null || containerCableLink.cap.connectable == null) { @@ -205,12 +205,12 @@ public boolean mouseClicked(double mouseX, double mouseY, int mouseButton) { } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { - if (delta != 0) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + if (scrollY != 0) { for (int i = 0; i < this.itemSlotsGhost.size(); i++) { ItemSlotNetwork slot = itemSlotsGhost.get(i); if (slot.isMouseOverSlot((int) mouseX, (int) mouseY)) { - ItemStack changeme = ScreenCableImportFilter.scrollStack(delta, slot); + ItemStack changeme = ScreenCableImportFilter.scrollStack(scrollY, slot); if (changeme != null) { this.sendStackSlot(i, changeme); return true; @@ -218,7 +218,7 @@ public boolean mouseScrolled(double mouseX, double mouseY, double delta) { } } } - return super.mouseScrolled(mouseX, mouseY, delta); + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); } @Override diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/TileCableFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/TileCableFilter.java index 82a4940c..db204b96 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/TileCableFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/linkfilter/TileCableFilter.java @@ -1,11 +1,12 @@ package com.lothrazar.storagenetwork.block.cable.linkfilter; +import com.lothrazar.storagenetwork.api.IConnectableLink; import com.lothrazar.storagenetwork.block.TileCableWithFacing; import com.lothrazar.storagenetwork.capability.CapabilityConnectableLink; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; @@ -15,8 +16,6 @@ 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.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class TileCableFilter extends TileCableWithFacing implements MenuProvider { @@ -27,6 +26,10 @@ public TileCableFilter(BlockPos pos, BlockState state) { this.capability = new CapabilityConnectableLink(this); } + public IConnectableLink getCapabilityLink() { + return capability; + } + @Override public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { return new ContainerCableFilter(i, level, worldPosition, playerInventory, playerEntity); @@ -37,18 +40,6 @@ public Component getDisplayName() { return Component.translatable("block.storagenetwork.filter_kabel"); } - @Override - public void load(CompoundTag compound) { - super.load(compound); - this.capability.deserializeNBT(compound.getCompound("capability")); - } - - @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - compound.put("capability", capability.serializeNBT()); - } - @Override public void setDirection(Direction direction) { super.setDirection(direction); @@ -56,12 +47,15 @@ public void setDirection(Direction direction) { } @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE_CAPABILITY) { - LazyOptional cap = LazyOptional.of(() -> this.capability); - return cap.cast(); - } - return super.getCapability(capability, facing); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); + this.capability.deserializeNBT(registries, compound.getCompound("capability")); + } + + @Override + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); + compound.put("capability", capability.serializeNBT(registries)); } public static void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableFilter tile) {} diff --git a/src/main/java/com/lothrazar/storagenetwork/block/cable/processing/TileCableProcess.java b/src/main/java/com/lothrazar/storagenetwork/block/cable/processing/TileCableProcess.java index b0665d20..71f1388e 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/cable/processing/TileCableProcess.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/cable/processing/TileCableProcess.java @@ -4,15 +4,13 @@ import com.lothrazar.storagenetwork.block.TileCableWithFacing; import com.lothrazar.storagenetwork.capability.CapabilityConnectableProcessing; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; 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.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class TileCableProcess extends TileCableWithFacing { @@ -24,17 +22,21 @@ public TileCableProcess(BlockPos pos, BlockState state) { this.itemStorage = new CapabilityConnectableProcessing(this); } + public IConnectableItemProcessing getItemStorage() { + return itemStorage; + } + @Override - public void load(CompoundTag compound) { - super.load(compound); - this.itemStorage.deserializeNBT(compound.getCompound("capability")); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); + this.itemStorage.deserializeNBT(registries, compound.getCompound("capability")); this.processModel.readFromNBT(compound); } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); - compound.put("capability", itemStorage.serializeNBT()); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); + compound.put("capability", itemStorage.serializeNBT(registries)); this.processModel.writeToNBT(compound); } @@ -44,15 +46,6 @@ public void setDirection(Direction direction) { this.itemStorage.setInventoryFace(direction); } - @Override - public LazyOptional getCapability(Capability capability, Direction facing) { - if (capability == StorageNetworkCapabilities.PROCESSING_CAPABILITY) { - LazyOptional cap = LazyOptional.of(() -> itemStorage); - return cap.cast(); - } - return super.getCapability(capability, facing); - } - public static void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableProcess tile) {} public static void serverTick(Level level, BlockPos blockPos, BlockState blockState, TileCableProcess tile) { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/collection/BlockCollection.java b/src/main/java/com/lothrazar/storagenetwork/block/collection/BlockCollection.java index b81f149c..1a956686 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/collection/BlockCollection.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/collection/BlockCollection.java @@ -14,7 +14,6 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkHooks; public class BlockCollection extends EntityBlockFlib { @@ -33,13 +32,13 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player playerIn, BlockHitResult result) { if (!world.isClientSide) { BlockEntity tile = world.getBlockEntity(pos); if (tile instanceof MenuProvider) { ServerPlayer player = (ServerPlayer) playerIn; player.connection.send(tile.getUpdatePacket()); - NetworkHooks.openScreen(player, (MenuProvider) tile, tile.getBlockPos()); + player.openMenu((MenuProvider) tile, buf -> buf.writeBlockPos(tile.getBlockPos())); } else { throw new IllegalStateException("Our named container provider is missing!" + tile); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/collection/CollectionItemStackHandler.java b/src/main/java/com/lothrazar/storagenetwork/block/collection/CollectionItemStackHandler.java index 03765c2e..03a825db 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/collection/CollectionItemStackHandler.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/collection/CollectionItemStackHandler.java @@ -6,9 +6,7 @@ import com.lothrazar.storagenetwork.block.TileConnectable; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.handler.FilterItemStackHandler; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; /** * @author ajsnarr98 Created MasterItemStackHandler * ItemStackHandler used for interfacing with TileMain like a chest. https://github.com/ajsnarr98/Storage-Network/tree/ajsnarr98-inventory @@ -46,7 +44,7 @@ public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { return stack; } validateSlotIndex(slot); - IConnectable cap = tile.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY).orElse(null); + IConnectable cap = tile.getConnectable(); // FilterItemStackHandler filter = cap.getFilter(); if (filter != null @@ -62,7 +60,7 @@ public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if (remaining > 0) { // if failed, refresh whole list update(); - return ItemHandlerHelper.copyStackWithSize(stack, remaining); + return stack.copyWithCount(remaining); } } catch (Exception e) { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/collection/ContainerCollectionFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/collection/ContainerCollectionFilter.java index 7f29aa77..2a244a73 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/collection/ContainerCollectionFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/collection/ContainerCollectionFilter.java @@ -1,10 +1,10 @@ package com.lothrazar.storagenetwork.block.collection; +import com.lothrazar.storagenetwork.api.IConnectable; import com.lothrazar.storagenetwork.block.cable.ContainerCable; import com.lothrazar.storagenetwork.capability.CapabilityConnectable; import com.lothrazar.storagenetwork.item.ItemUpgrade; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -20,9 +20,10 @@ public class ContainerCollectionFilter extends ContainerCable { public ContainerCollectionFilter(int windowId, Level world, BlockPos pos, Inventory playerInv, Player player) { super(SsnRegistry.Menus.COLLECTOR.get(), windowId); tile = (TileCollection) world.getBlockEntity(pos); - tile.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY).ifPresent(h -> { - this.cap = (CapabilityConnectable) h; - }); + IConnectable connectable = tile.getConnectable(); + if (connectable instanceof CapabilityConnectable pc) { + this.cap = pc; + } this.bindPlayerInvo(playerInv); } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/collection/ScreenCollectionFilter.java b/src/main/java/com/lothrazar/storagenetwork/block/collection/ScreenCollectionFilter.java index 0dcd824d..6d409a9b 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/collection/ScreenCollectionFilter.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/collection/ScreenCollectionFilter.java @@ -7,7 +7,7 @@ import com.lothrazar.storagenetwork.capability.handler.FilterItemStackHandler; import com.lothrazar.storagenetwork.gui.slot.ItemSlotNetwork; import com.lothrazar.storagenetwork.network.CableIOMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import com.lothrazar.storagenetwork.util.SsnConsts; import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.client.gui.GuiGraphics; @@ -19,7 +19,7 @@ public class ScreenCollectionFilter extends AbstractContainerScreen implements IGuiPrivate { - private final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/plain_filter.png"); + private final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/plain_filter.png"); ContainerCollectionFilter containerCableLink; private List itemSlotsGhost; @@ -44,12 +44,12 @@ public void init() { } private void sendStackSlot(int value, ItemStack stack) { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SAVE_FITLER.ordinal(), value, stack)); } @Override public void render(GuiGraphics ms, int mouseX, int mouseY, float partialTicks) { - renderBackground(ms); + renderBackground(ms, mouseX, mouseY, partialTicks); super.render(ms, mouseX, mouseY, partialTicks); this.renderTooltip(ms, mouseX, mouseY); } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/collection/TileCollection.java b/src/main/java/com/lothrazar/storagenetwork/block/collection/TileCollection.java index ded45004..fd154367 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/collection/TileCollection.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/collection/TileCollection.java @@ -1,13 +1,11 @@ package com.lothrazar.storagenetwork.block.collection; import com.lothrazar.storagenetwork.api.DimPos; -import com.lothrazar.storagenetwork.api.IConnectable; import com.lothrazar.storagenetwork.block.TileConnectable; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; @@ -15,10 +13,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; 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.common.util.NonNullSupplier; public class TileCollection extends TileConnectable implements MenuProvider { @@ -30,14 +24,23 @@ public TileCollection(BlockPos pos, BlockState state) { itemHandler.tile = this; } + public CollectionItemStackHandler getItemHandler() { + DimPos m = getMain(); + if (m != null) { + TileMain tileMain = m.getTileEntity(TileMain.class); + itemHandler.setMain(tileMain); + } + return itemHandler; + } + @Override - public void load(CompoundTag compound) { - super.load(compound); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); } @Override @@ -49,24 +52,4 @@ public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player public Component getDisplayName() { return Component.translatable("block.storagenetwork.collector"); } - - @SuppressWarnings("unchecked") - @Override - public LazyOptional getCapability(Capability cap, Direction side) { - if (cap == ForgeCapabilities.ITEM_HANDLER) { - IConnectable capabilityConnectable = super.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, side).orElse(null); - DimPos m = getMain(); - if (capabilityConnectable != null && m != null) { - TileMain tileMain = m.getTileEntity(TileMain.class); - itemHandler.setMain(tileMain); - } - return LazyOptional.of(new NonNullSupplier() { - - public @Override T get() { - return (T) itemHandler; - } - }); - } - return super.getCapability(cap, side); - } } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/exchange/BlockExchange.java b/src/main/java/com/lothrazar/storagenetwork/block/exchange/BlockExchange.java index fa7f6697..cb2b04da 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/exchange/BlockExchange.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/exchange/BlockExchange.java @@ -8,7 +8,6 @@ import net.minecraft.network.chat.Component; 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.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; @@ -30,8 +29,8 @@ public BlockEntityTicker getTicker(Level world, Block } @Override - public void appendHoverText(ItemStack stack, BlockGetter playerIn, List tooltip, TooltipFlag advanced) { - super.appendHoverText(stack, playerIn, tooltip, advanced); + public void appendHoverText(ItemStack stack, net.minecraft.world.item.Item.TooltipContext context, List tooltip, TooltipFlag advanced) { + super.appendHoverText(stack, context, tooltip, advanced); tooltip.add(Component.translatable("[WARNING: only use on small Storage Networks. A large AE2 network interfaced with a large Storage Network will cause lag] ").withStyle(ChatFormatting.DARK_GRAY)); } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/exchange/ExchangeItemStackHandler.java b/src/main/java/com/lothrazar/storagenetwork/block/exchange/ExchangeItemStackHandler.java index 41773b55..6a1ea6ef 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/exchange/ExchangeItemStackHandler.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/exchange/ExchangeItemStackHandler.java @@ -6,7 +6,6 @@ import com.lothrazar.storagenetwork.capability.handler.ItemStackMatcher; import com.lothrazar.storagenetwork.registry.ConfigRegistry; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; /** * @author ajsnarr98 Created MasterItemStackHandler @@ -80,7 +79,7 @@ public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if (remaining > 0) { // if failed, refresh whole list update(); - return ItemHandlerHelper.copyStackWithSize(stack, remaining); + return stack.copyWithCount(remaining); } } catch (Exception e) { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/exchange/TileExchange.java b/src/main/java/com/lothrazar/storagenetwork/block/exchange/TileExchange.java index 83e9ec14..0208a05c 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/exchange/TileExchange.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/exchange/TileExchange.java @@ -2,21 +2,15 @@ import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.api.DimPos; -import com.lothrazar.storagenetwork.api.IConnectable; import com.lothrazar.storagenetwork.block.TileConnectable; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.registry.SsnRegistry; -import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; 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.Level; import net.minecraft.world.level.block.entity.BlockEntity; 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.common.util.NonNullSupplier; public class TileExchange extends TileConnectable { @@ -27,43 +21,31 @@ public TileExchange(BlockPos pos, BlockState state) { itemHandler = new ExchangeItemStackHandler(); } - @Override - public void load(CompoundTag compound) { - super.load(compound); + public ExchangeItemStackHandler getItemHandler() { + try { + DimPos m = getMain(); + if (m != null && itemHandler != null && itemHandler.tileMain == null) { + TileMain tileMain = m.getTileEntity(TileMain.class); + if (tileMain != null) { + itemHandler.setMain(tileMain); + } + } + return itemHandler; + } + catch (Exception e) { + StorageNetworkMod.LOGGER.error("Exchange caught error from a mod", e); + return null; + } } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); } - @SuppressWarnings("unchecked") @Override - public LazyOptional getCapability(Capability cap, Direction side) { - if (cap == ForgeCapabilities.ITEM_HANDLER) { - try { - IConnectable capabilityConnectable = super.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, side).orElse(null); - DimPos m = getMain(); - if (capabilityConnectable != null && m != null - && itemHandler != null && - itemHandler.tileMain == null) { - TileMain tileMain = m.getTileEntity(TileMain.class); - if (tileMain != null) { - itemHandler.setMain(tileMain); - } - } - return LazyOptional.of(new NonNullSupplier() { - - public @Override T get() { - return (T) itemHandler; - } - }); - } - catch (Exception e) { - StorageNetworkMod.LOGGER.error("Exchange caught error from a mod", e); - } - } - return super.getCapability(cap, side); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); } private void tick() { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/expand/ScreenNetworkInventoryExpanded.java b/src/main/java/com/lothrazar/storagenetwork/block/expand/ScreenNetworkInventoryExpanded.java index 134964f2..cfe2ae8e 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/expand/ScreenNetworkInventoryExpanded.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/expand/ScreenNetworkInventoryExpanded.java @@ -8,7 +8,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class ScreenNetworkInventoryExpanded extends AbstractNetworkScreen { diff --git a/src/main/java/com/lothrazar/storagenetwork/block/inventory/ScreenNetworkInventory.java b/src/main/java/com/lothrazar/storagenetwork/block/inventory/ScreenNetworkInventory.java index 5d811ed3..baa045d8 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/inventory/ScreenNetworkInventory.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/inventory/ScreenNetworkInventory.java @@ -10,13 +10,13 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class ScreenNetworkInventory extends AbstractNetworkScreen { protected int HEIGHT = 256; public int WIDTH = 176; - private final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/inventory.png"); + private final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/inventory.png"); protected final NetworkWidget network; private TileInventory tile; diff --git a/src/main/java/com/lothrazar/storagenetwork/block/inventory/TileInventory.java b/src/main/java/com/lothrazar/storagenetwork/block/inventory/TileInventory.java index 976c162f..f16f94c4 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/inventory/TileInventory.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/inventory/TileInventory.java @@ -6,6 +6,7 @@ import com.lothrazar.storagenetwork.block.request.TileRequest; import com.lothrazar.storagenetwork.registry.SsnRegistry; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; @@ -42,8 +43,8 @@ public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player } @Override - public void load(CompoundTag compound) { - super.load(compound); + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.loadAdditional(compound, registries); autoFocus = compound.getBoolean("autoFocus"); setDownwards(compound.getBoolean("dir")); setSort(EnumSortType.values()[compound.getInt("sort")]); @@ -53,8 +54,8 @@ public void load(CompoundTag compound) { } @Override - public void saveAdditional(CompoundTag compound) { - super.saveAdditional(compound); + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { + super.saveAdditional(compound, registries); compound.putBoolean("dir", isDownwards()); compound.putInt("sort", getSort().ordinal()); compound.putBoolean("autoFocus", autoFocus); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/main/BlockMain.java b/src/main/java/com/lothrazar/storagenetwork/block/main/BlockMain.java index 02372b70..44ac9174 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/main/BlockMain.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/main/BlockMain.java @@ -41,8 +41,8 @@ public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, LivingEnt } @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, - Player playerIn, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level worldIn, BlockPos pos, + Player playerIn, BlockHitResult result) { if (worldIn.isClientSide) { return InteractionResult.SUCCESS; } @@ -51,7 +51,7 @@ public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, return InteractionResult.PASS; } // float hitX, float hitY, float hitZ; - if (hand == InteractionHand.MAIN_HAND && playerIn.getItemInHand(hand).isEmpty()) { + if (playerIn.getMainHandItem().isEmpty()) { displayConnections(playerIn, tileHere); return InteractionResult.SUCCESS; } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/main/NetworkModule.java b/src/main/java/com/lothrazar/storagenetwork/block/main/NetworkModule.java index 8f0b1b0a..46f51bea 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/main/NetworkModule.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/main/NetworkModule.java @@ -33,7 +33,6 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraftforge.items.ItemHandlerHelper; /** * Responsible for network connection list, cache, requests and single inserts. @@ -63,11 +62,7 @@ public Set getConnectables() { if (!pos.isLoaded()) { continue; } - BlockEntity tileEntity = pos.getTileEntity(BlockEntity.class); - if (tileEntity == null) { - continue; - } - IConnectable cap = tileEntity.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, null).orElse(null); + IConnectable cap = pos.getCapability(StorageNetworkCapabilities.CONNECTABLE, null); if (cap == null) { StorageNetworkMod.LOGGER.info("Somehow stored a dimpos that is not connectable... Skipping " + pos); continue; @@ -228,7 +223,7 @@ public int insertStack(ItemStack stack, boolean simulate) { String key = UtilInventory.getStackKey(stack); if (ch.hasCachedSlot(stack)) { DimPos cachedStoragePos = ch.getCachedSlot(stack); - IConnectableLink storage = cachedStoragePos.getCapability(StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE_CAPABILITY, null); + IConnectableLink storage = cachedStoragePos.getCapability(StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE, null); if (storage == null) { // The block at the cached position is not even an IConnectableLink anymore ch.remove(key); @@ -306,7 +301,7 @@ public ItemStack request(ItemStackMatcher matcher, int size, boolean simulate) { if (alreadyTransferred <= 0) { return ItemStack.EMPTY; } - return ItemHandlerHelper.copyStackWithSize(usedMatcher.getStack(), alreadyTransferred); + return usedMatcher.getStack().copyWithCount(alreadyTransferred); } public void executeRequestBatch(RequestBatch batch) { @@ -385,7 +380,7 @@ private void addConnectables(DimPos sourcePos, Set set, DimPos masterPos if (tileHere == null) { continue; } - IConnectable capabilityConnectable = tileHere.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, direction.getOpposite()).orElse(null); + IConnectable capabilityConnectable = lookPos.getCapability(StorageNetworkCapabilities.CONNECTABLE, direction.getOpposite()); if (capabilityConnectable == null) { continue; } @@ -434,11 +429,7 @@ private Set getConnectableStorage() { if (!dimpos.isLoaded()) { continue; } - BlockEntity tileEntity = dimpos.getTileEntity(BlockEntity.class); - if (tileEntity == null) { - continue; - } - IConnectableLink capConnect = tileEntity.getCapability(StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE_CAPABILITY, null).orElse(null); + IConnectableLink capConnect = dimpos.getCapability(StorageNetworkCapabilities.CONNECTABLE_ITEM_STORAGE, null); if (capConnect == null) { continue; } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/main/TileMain.java b/src/main/java/com/lothrazar/storagenetwork/block/main/TileMain.java index 0b6deb05..978014d9 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/main/TileMain.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/main/TileMain.java @@ -13,6 +13,7 @@ import com.lothrazar.storagenetwork.util.Request; import com.lothrazar.storagenetwork.util.RequestBatch; 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; @@ -36,22 +37,20 @@ public NetworkModule getNetwork() { } @Override - public CompoundTag getUpdateTag() { + public CompoundTag getUpdateTag(HolderLookup.Provider registries) { CompoundTag nbt = new CompoundTag(); - this.saveAdditional(nbt); + this.saveAdditional(nbt, registries); return nbt; } @Override public ClientboundBlockEntityDataPacket getUpdatePacket() { - saveWithFullMetadata(); return ClientboundBlockEntityDataPacket.create(this); } @Override - public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { - load(pkt.getTag() == null ? new CompoundTag() : pkt.getTag()); - super.onDataPacket(net, pkt); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider registries) { + loadAdditional(pkt.getTag() == null ? new CompoundTag() : pkt.getTag(), registries); } /** @@ -130,7 +129,7 @@ private void tick() { } //does it have processing capability? //in practice it will not have both, its either IO or processing - IConnectableItemProcessing processingCap = connectable.getPos().getCapability(StorageNetworkCapabilities.PROCESSING_CAPABILITY, null); + IConnectableItemProcessing processingCap = connectable.getPos().getCapability(StorageNetworkCapabilities.PROCESSING, null); if (processingCap != null && isRunnable(connectable)) { processingCap.execute(this); } diff --git a/src/main/java/com/lothrazar/storagenetwork/block/request/BlockRequest.java b/src/main/java/com/lothrazar/storagenetwork/block/request/BlockRequest.java index 7a1da6ee..ae42c6bf 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/request/BlockRequest.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/request/BlockRequest.java @@ -2,7 +2,6 @@ import com.lothrazar.library.block.EntityBlockFlib; import com.lothrazar.storagenetwork.network.SortClientMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.Container; @@ -18,8 +17,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.neoforge.network.PacketDistributor; public class BlockRequest extends EntityBlockFlib { @@ -51,7 +49,7 @@ public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState n } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult result) { + public InteractionResult useWithoutItem(BlockState state, Level world, BlockPos pos, Player player, BlockHitResult result) { if (!world.isClientSide) { TileRequest tile = (TileRequest) world.getBlockEntity(pos); if (tile.getMain() == null || tile.getMain().getBlockPos() == null) { @@ -59,10 +57,10 @@ public InteractionResult use(BlockState state, Level world, BlockPos pos, Player } //sync ServerPlayer sp = (ServerPlayer) player; - PacketRegistry.INSTANCE.sendTo(new SortClientMessage(pos, tile.isDownwards(), tile.getSort()), sp.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(sp, new SortClientMessage(pos, tile.isDownwards(), tile.getSort())); //end sync if (tile instanceof MenuProvider) { - NetworkHooks.openScreen((ServerPlayer) player, (MenuProvider) tile, tile.getBlockPos()); + sp.openMenu((MenuProvider) tile, buf -> buf.writeBlockPos(tile.getBlockPos())); } else { throw new IllegalStateException("Our named container provider is missing!"); diff --git a/src/main/java/com/lothrazar/storagenetwork/block/request/ScreenNetworkTable.java b/src/main/java/com/lothrazar/storagenetwork/block/request/ScreenNetworkTable.java index 59c48fa4..cd60656a 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/request/ScreenNetworkTable.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/request/ScreenNetworkTable.java @@ -10,13 +10,13 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class ScreenNetworkTable extends AbstractNetworkScreen { private static final int HEIGHT = 256; public static final int WIDTH = 176; - private final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/request.png"); + private final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/request.png"); private final NetworkWidget network; private TileRequest tile; diff --git a/src/main/java/com/lothrazar/storagenetwork/block/request/TileRequest.java b/src/main/java/com/lothrazar/storagenetwork/block/request/TileRequest.java index 17f47237..9e59d1af 100644 --- a/src/main/java/com/lothrazar/storagenetwork/block/request/TileRequest.java +++ b/src/main/java/com/lothrazar/storagenetwork/block/request/TileRequest.java @@ -6,6 +6,7 @@ import com.lothrazar.storagenetwork.block.TileConnectable; import com.lothrazar.storagenetwork.registry.SsnRegistry; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; @@ -29,7 +30,7 @@ public TileRequest(BlockPos pos, BlockState state) { } @Override - public void load(CompoundTag compound) { + protected void loadAdditional(CompoundTag compound, HolderLookup.Provider registries) { autoFocus = compound.getBoolean("autoFocus"); setDownwards(compound.getBoolean(NBT_DIR)); if (compound.contains(NBT_SORT)) { @@ -38,15 +39,16 @@ public void load(CompoundTag compound) { if (compound.contains(NBT_JEI)) { this.setJeiSearchSynced(compound.getBoolean(NBT_JEI)); } - super.load(compound); + super.loadAdditional(compound, registries); } @Override - public void saveAdditional(CompoundTag compound) { + protected void saveAdditional(CompoundTag compound, HolderLookup.Provider registries) { compound.putBoolean("autoFocus", autoFocus); compound.putBoolean(NBT_DIR, isDownwards()); compound.putInt(NBT_SORT, getSort().ordinal()); compound.putBoolean(NBT_JEI, this.isJeiSearchSynced()); + super.saveAdditional(compound, registries); } @Override diff --git a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectable.java b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectable.java index 4f348eec..1c2f93a7 100644 --- a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectable.java +++ b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectable.java @@ -1,8 +1,9 @@ package com.lothrazar.storagenetwork.capability; import com.lothrazar.storagenetwork.api.DimPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraftforge.common.util.INBTSerializable; +import net.neoforged.neoforge.common.util.INBTSerializable; public class CapabilityConnectable extends DefaultConnectable implements INBTSerializable { @@ -11,30 +12,30 @@ public CapabilityConnectable() { } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(HolderLookup.Provider registries) { CompoundTag result = new CompoundTag(); if (getMainPos() == null) { return result; } - result.put("master", getMainPos().serializeNBT()); + result.put("master", getMainPos().serializeNBT(registries)); if (getPos() != null) { - result.put("self", getPos().serializeNBT()); + result.put("self", getPos().serializeNBT(registries)); } - CompoundTag filters = this.filters.serializeNBT(); + CompoundTag filters = this.filters.serializeNBT(registries); result.put("filters", filters); result.putBoolean("needsRedstone", this.needsRedstone()); return result; } @Override - public void deserializeNBT(CompoundTag nbt) { + public void deserializeNBT(HolderLookup.Provider registries, CompoundTag nbt) { setMainPos(new DimPos(nbt.getCompound("master"))); if (nbt.contains("self")) { setPos(new DimPos(nbt.getCompound("self"))); } if (nbt.contains("filters")) { CompoundTag filters = nbt.getCompound("filters"); - this.filters.deserializeNBT(filters); + this.filters.deserializeNBT(registries, filters); } this.needsRedstone(nbt.getBoolean("needsRedstone")); } diff --git a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableAutoIO.java b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableAutoIO.java index 388cb528..e1c0ad83 100644 --- a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableAutoIO.java +++ b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableAutoIO.java @@ -21,13 +21,13 @@ import com.lothrazar.storagenetwork.util.RequestBatch; import com.lothrazar.storagenetwork.util.UtilInventory; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.INBTSerializable; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.common.util.INBTSerializable; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.ItemHandlerHelper; public class CapabilityConnectableAutoIO implements INBTSerializable, IConnectableItemAutoIO { @@ -84,7 +84,7 @@ public List getStoredStacks(boolean isFiltered) { } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return Collections.emptyList(); } @@ -114,7 +114,8 @@ public void setFilter(int value, ItemStack stack) { } public CapabilityConnectableAutoIO(BlockEntity tile, EnumStorageDirection direction) { - connectable = tile.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, null).orElse(null); + connectable = (tile instanceof com.lothrazar.storagenetwork.block.TileConnectable tc) + ? tc.getConnectable() : null; this.direction = direction; // Set some defaults if (direction == EnumStorageDirection.OUT) { @@ -130,17 +131,19 @@ public void setInventoryFace(Direction inventoryFace) { } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(HolderLookup.Provider registries) { CompoundTag result = new CompoundTag(); - result.put("upgrades", this.upgrades.serializeNBT()); - result.put("filters", this.filters.serializeNBT()); + result.put("upgrades", this.upgrades.serializeNBT(registries)); + result.put("filters", this.filters.serializeNBT(registries)); result.putInt("prio", priority); if (inventoryFace != null) { result.putString("inventoryFace", inventoryFace.toString()); } result.putBoolean("needsRedstone", this.needsRedstone()); CompoundTag operation = new CompoundTag(); - operation.put("stack", operationStack.serializeNBT()); + if (!operationStack.isEmpty()) { + operation.put("stack", (CompoundTag) operationStack.save(registries)); + } operation.putInt("operationType", operationType); operation.putInt("limit", operationLimit); result.put("operation", operation); @@ -148,14 +151,14 @@ public CompoundTag serializeNBT() { } @Override - public void deserializeNBT(CompoundTag nbt) { + public void deserializeNBT(HolderLookup.Provider registries, CompoundTag nbt) { CompoundTag upgrades = nbt.getCompound("upgrades"); if (upgrades != null) { - this.upgrades.deserializeNBT(upgrades); + this.upgrades.deserializeNBT(registries, upgrades); } CompoundTag filters = nbt.getCompound("filters"); if (filters != null) { - this.filters.deserializeNBT(filters); + this.filters.deserializeNBT(registries, filters); } priority = nbt.getInt("prio"); if (nbt.contains("inventoryFace")) { @@ -166,7 +169,7 @@ public void deserializeNBT(CompoundTag nbt) { this.operationLimit = operation.getInt("limit"); this.operationType = operation.getInt("operationType"); if (operation.contains("stack")) { - this.operationStack = ItemStack.of(operation.getCompound("stack")); + this.operationStack = ItemStack.parseOptional(registries, operation.getCompound("stack")); } else { this.operationStack = ItemStack.EMPTY; @@ -195,7 +198,7 @@ public ItemStack insertStack(ItemStack stack, boolean simulate) { } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return stack; } @@ -208,7 +211,7 @@ public List getStacksForFilter() { } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return Collections.emptyList(); } @@ -242,7 +245,7 @@ public IItemHandler getItemHandler() { return null; } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); - return inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + return inventoryPos.getItemHandler(inventoryFace.getOpposite()); } // @Deprecated // @Override @@ -260,7 +263,7 @@ public IItemHandler getItemHandler() { // } // DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // // Test whether the connected block has the IItemHandler capability - // IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + // IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); // if (itemHandler == null) { // return ItemStack.EMPTY; // } @@ -389,7 +392,7 @@ public RequestBatch runExport(TileMain main) { // STOCK upgrade means try { DimPos inventoryPos = connectable.getPos().offset(inventoryFace); - IItemHandler targetInventory = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler targetInventory = inventoryPos.getItemHandler(inventoryFace.getOpposite()); // request with false to see how many even exist in there. int stillNeeds = UtilInventory.containsAtLeastHowManyNeeded(targetInventory, matcher.getStack(), matcher.getStack().getCount()); @@ -434,7 +437,7 @@ public void runImport(TileMain main) { if (this.isStockMode()) { int filterSize = this.getFilters().getStackCount(stackCurrent); DimPos inventoryPos = connectable.getPos().offset(inventoryFace); - IItemHandler targetInventory = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler targetInventory = inventoryPos.getItemHandler(inventoryFace.getOpposite()); //request with false to see how many even exist in there. int chestHowMany = UtilInventory.countHowMany(targetInventory, stackCurrent); //so if chest=37 items of that kind diff --git a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableLink.java b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableLink.java index 0b7f49ca..95663e1a 100644 --- a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableLink.java +++ b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableLink.java @@ -14,13 +14,14 @@ import com.lothrazar.storagenetwork.util.Batch; import com.lothrazar.storagenetwork.util.StackProvider; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.INBTSerializable; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.common.util.INBTSerializable; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.ItemHandlerHelper; public class CapabilityConnectableLink implements IConnectableLink, INBTSerializable { @@ -39,7 +40,8 @@ public class CapabilityConnectableLink implements IConnectableLink, INBTSerializ } public CapabilityConnectableLink(BlockEntity tile) { - connectable = tile.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, null).orElse(null); + connectable = (tile instanceof com.lothrazar.storagenetwork.block.TileConnectable tc) + ? tc.getConnectable() : null; filters.setIsAllowlist(false); } @@ -70,7 +72,7 @@ public List getStoredStacks(boolean isFiltered) { } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return Collections.emptyList(); } @@ -105,7 +107,7 @@ public ItemStack insertStack(ItemStack stack, boolean simulate) { DimPos inventoryPos = connectable.getPos().offset(inventoryFace); try { // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return stack; } @@ -137,7 +139,7 @@ public ItemStack extractStack(IItemStackMatcher matcher, int size, boolean simul } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return ItemStack.EMPTY; } @@ -165,7 +167,7 @@ public ItemStack extractStack(IItemStackMatcher matcher, int size, boolean simul firstMatchedStack = stack.copy(); } else { - if (!ItemHandlerHelper.canItemStacksStack(firstMatchedStack, stack)) { + if (!ItemStack.isSameItemSameComponents(firstMatchedStack, stack)) { continue; } } @@ -195,7 +197,7 @@ public int getEmptySlots() { } DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, inventoryFace.getOpposite()); + IItemHandler itemHandler = inventoryPos.getItemHandler(inventoryFace.getOpposite()); if (itemHandler == null) { return 0; } @@ -225,7 +227,7 @@ public void setInventoryFace(Direction inventoryFace) { } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(HolderLookup.Provider registries) { CompoundTag result = new CompoundTag(); result.putInt("prio", priority); if (inventoryFace != null) { @@ -233,20 +235,22 @@ public CompoundTag serializeNBT() { } result.putString("way", filterDirection.toString()); CompoundTag operation = new CompoundTag(); - operation.put("stack", operationStack.serializeNBT()); + if (!operationStack.isEmpty()) { + operation.put("stack", (CompoundTag) operationStack.save(registries)); + } operation.putBoolean("mustBeSmaller", operationMustBeSmaller); operation.putInt("limit", operationLimit); result.put("operation", operation); - CompoundTag filters = this.filters.serializeNBT(); + CompoundTag filters = this.filters.serializeNBT(registries); result.put("filters", filters); return result; } @Override - public void deserializeNBT(CompoundTag nbt) { + public void deserializeNBT(HolderLookup.Provider registries, CompoundTag nbt) { priority = nbt.getInt("prio"); CompoundTag filters = nbt.getCompound("filters"); - this.filters.deserializeNBT(filters); + this.filters.deserializeNBT(registries, filters); if (nbt.contains("inventoryFace")) { inventoryFace = Direction.byName(nbt.getString("inventoryFace")); } @@ -262,7 +266,7 @@ public void deserializeNBT(CompoundTag nbt) { operationLimit = operation.getInt("limit"); operationMustBeSmaller = operation.getBoolean("mustBeSmaller"); if (operation.contains("stack")) { - operationStack = ItemStack.of(operation.getCompound("stack")); + operationStack = ItemStack.parseOptional(registries, operation.getCompound("stack")); } } } @@ -271,7 +275,7 @@ public void deserializeNBT(CompoundTag nbt) { public ItemStack extractFromSlot(int slot, int amount, boolean simulate) { DimPos inventoryPos = connectable.getPos().offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, + IItemHandler itemHandler = inventoryPos.getCapability(Capabilities.ItemHandler.BLOCK, inventoryFace.getOpposite()); if (itemHandler == null) { return ItemStack.EMPTY; @@ -295,7 +299,7 @@ public void addToStackProviderBatch(Batch availableItems) { } DimPos inventoryPos = connectablePos.offset(inventoryFace); // Test whether the connected block has the IItemHandler capability - IItemHandler itemHandler = inventoryPos.getCapability(ForgeCapabilities.ITEM_HANDLER, + IItemHandler itemHandler = inventoryPos.getCapability(Capabilities.ItemHandler.BLOCK, inventoryFace.getOpposite()); if (itemHandler == null) { return; diff --git a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableProcessing.java b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableProcessing.java index 4c3554f7..9911078b 100644 --- a/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableProcessing.java +++ b/src/main/java/com/lothrazar/storagenetwork/capability/CapabilityConnectableProcessing.java @@ -9,9 +9,10 @@ import com.lothrazar.storagenetwork.capability.handler.UpgradesItemStackHandler; import com.lothrazar.storagenetwork.registry.StorageNetworkCapabilities; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.util.INBTSerializable; +import net.neoforged.neoforge.common.util.INBTSerializable; public class CapabilityConnectableProcessing implements INBTSerializable, IConnectableItemProcessing { @@ -35,7 +36,8 @@ public IConnectableItemProcessing call() throws Exception { } public CapabilityConnectableProcessing(BlockEntity tile) { - connectable = tile.getCapability(StorageNetworkCapabilities.CONNECTABLE_CAPABILITY, null).orElse(null); + connectable = (tile instanceof com.lothrazar.storagenetwork.block.TileConnectable tc) + ? tc.getConnectable() : null; } public void setInventoryFace(Direction inventoryFace) { @@ -43,12 +45,12 @@ public void setInventoryFace(Direction inventoryFace) { } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(HolderLookup.Provider registries) { CompoundTag result = new CompoundTag(); result.putInt("prio", priority); - result.put("upgrades", this.upgrades.serializeNBT()); - result.put("filtersIn", this.filters.serializeNBT()); - result.put("filtersOut", this.filtersOut.serializeNBT()); + result.put("upgrades", this.upgrades.serializeNBT(registries)); + result.put("filtersIn", this.filters.serializeNBT(registries)); + result.put("filtersOut", this.filtersOut.serializeNBT(registries)); if (inventoryFace != null) { result.putString("inventoryFace", inventoryFace.toString()); } @@ -56,19 +58,19 @@ public CompoundTag serializeNBT() { } @Override - public void deserializeNBT(CompoundTag nbt) { + public void deserializeNBT(HolderLookup.Provider registries, CompoundTag nbt) { priority = nbt.getInt("prio"); CompoundTag upgrades = nbt.getCompound("upgrades"); if (upgrades != null) { - this.upgrades.deserializeNBT(upgrades); + this.upgrades.deserializeNBT(registries, upgrades); } CompoundTag filters = nbt.getCompound("filters"); if (filters != null) { - this.filters.deserializeNBT(filters); + this.filters.deserializeNBT(registries, filters); } CompoundTag filtersOut = nbt.getCompound("filtersOut"); if (filtersOut != null) { - this.filtersOut.deserializeNBT(filtersOut); + this.filtersOut.deserializeNBT(registries, filtersOut); } if (nbt.contains("inventoryFace")) { inventoryFace = Direction.byName(nbt.getString("inventoryFace")); diff --git a/src/main/java/com/lothrazar/storagenetwork/capability/handler/FilterItemStackHandler.java b/src/main/java/com/lothrazar/storagenetwork/capability/handler/FilterItemStackHandler.java index b67ad987..e8dd9d07 100644 --- a/src/main/java/com/lothrazar/storagenetwork/capability/handler/FilterItemStackHandler.java +++ b/src/main/java/com/lothrazar/storagenetwork/capability/handler/FilterItemStackHandler.java @@ -4,9 +4,9 @@ import java.util.stream.Collectors; import com.lothrazar.library.cap.ItemStackHandlerEx; import com.lothrazar.storagenetwork.api.IItemStackMatcher; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; public class FilterItemStackHandler extends ItemStackHandlerEx { @@ -84,8 +84,8 @@ public boolean allAreEmpty() { } @Override - public void deserializeNBT(CompoundTag nbt) { - super.deserializeNBT(nbt); + public void deserializeNBT(HolderLookup.Provider registries, CompoundTag nbt) { + super.deserializeNBT(registries, nbt); CompoundTag rulesTag = nbt.getCompound("rules"); tags = rulesTag.getBoolean("tags"); this.nbt = rulesTag.getBoolean("nbt"); @@ -93,8 +93,8 @@ public void deserializeNBT(CompoundTag nbt) { } @Override - public CompoundTag serializeNBT() { - CompoundTag result = super.serializeNBT(); + public CompoundTag serializeNBT(HolderLookup.Provider registries) { + CompoundTag result = super.serializeNBT(registries); CompoundTag rulesTag = new CompoundTag(); rulesTag.putBoolean("tags", tags); rulesTag.putBoolean("nbt", nbt); @@ -106,7 +106,7 @@ public CompoundTag serializeNBT() { public int getStackCount(ItemStack stackCurrent) { int s = 0; for (IItemStackMatcher m : getStackMatchers()) { - if (ItemHandlerHelper.canItemStacksStack(stackCurrent, m.getStack())) { + if (ItemStack.isSameItemSameComponents(stackCurrent, m.getStack())) { return s += m.getStack().getCount(); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/capability/handler/ItemStackMatcher.java b/src/main/java/com/lothrazar/storagenetwork/capability/handler/ItemStackMatcher.java index 2641b91c..de1c9dd8 100644 --- a/src/main/java/com/lothrazar/storagenetwork/capability/handler/ItemStackMatcher.java +++ b/src/main/java/com/lothrazar/storagenetwork/capability/handler/ItemStackMatcher.java @@ -1,6 +1,7 @@ package com.lothrazar.storagenetwork.capability.handler; import com.lothrazar.storagenetwork.api.IItemStackMatcher; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; @@ -22,20 +23,20 @@ public ItemStackMatcher(ItemStack stack, boolean ore, boolean nbt) { private ItemStackMatcher() {} - public void readFromNBT(CompoundTag compound) { + public void readFromNBT(HolderLookup.Provider registries, CompoundTag compound) { CompoundTag c = (CompoundTag) compound.get("stack"); - stack = ItemStack.of(c); + stack = c != null ? ItemStack.parseOptional(registries, c) : ItemStack.EMPTY; ore = compound.getBoolean("ore"); nbt = compound.getBoolean("nbt"); } - public CompoundTag writeToNBT(CompoundTag compound) { - CompoundTag c = new CompoundTag(); - stack.save(c); - compound.put("stack", c); + public CompoundTag writeToNBT(HolderLookup.Provider registries, CompoundTag compound) { + if (!stack.isEmpty()) { + compound.put("stack", stack.save(registries)); + } compound.putBoolean("ore", ore); compound.putBoolean("nbt", nbt); - return c; + return compound; } @Override @@ -68,9 +69,9 @@ public void setNbt(boolean nbt) { this.nbt = nbt; } - public static ItemStackMatcher loadFilterItemFromNBT(CompoundTag nbt) { + public static ItemStackMatcher loadFilterItemFromNBT(HolderLookup.Provider registries, CompoundTag nbt) { ItemStackMatcher fil = new ItemStackMatcher(); - fil.readFromNBT(nbt); + fil.readFromNBT(registries, nbt); return fil.getStack() != null && fil.getStack().getItem() != null ? fil : null; } @@ -79,7 +80,7 @@ public boolean match(ItemStack stackIn) { if (stackIn.isEmpty()) { return false; } - if (nbt && !ItemStack.isSameItemSameTags(stack, stackIn)) { + if (nbt && !ItemStack.isSameItemSameComponents(stack, stackIn)) { return false; } return stackIn.getItem() == stack.getItem(); diff --git a/src/main/java/com/lothrazar/storagenetwork/emi/EmiTransferHandler.java b/src/main/java/com/lothrazar/storagenetwork/emi/EmiTransferHandler.java index 725925aa..edc56903 100644 --- a/src/main/java/com/lothrazar/storagenetwork/emi/EmiTransferHandler.java +++ b/src/main/java/com/lothrazar/storagenetwork/emi/EmiTransferHandler.java @@ -8,7 +8,7 @@ import com.lothrazar.storagenetwork.gui.NetworkWidget; import com.lothrazar.storagenetwork.network.RecipeMessage; import com.lothrazar.storagenetwork.registry.ConfigRegistry; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import dev.emi.emi.api.recipe.EmiPlayerInventory; import dev.emi.emi.api.recipe.EmiRecipe; import dev.emi.emi.api.recipe.VanillaEmiRecipeCategories; @@ -18,8 +18,10 @@ import dev.emi.emi.api.stack.EmiStack; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; @@ -66,7 +68,7 @@ public boolean supportsRecipe(EmiRecipe recipe) { public boolean craft(EmiRecipe recipe, EmiCraftContext context) { AbstractContainerScreen screen = context.getScreen(); CompoundTag nbt = buildRecipe(recipe, screen); - PacketRegistry.INSTANCE.sendToServer(new RecipeMessage(nbt)); + PacketDistributor.sendToServer(new RecipeMessage(nbt)); Minecraft.getInstance().setScreen(screen); return true; } @@ -91,6 +93,7 @@ private CompoundTag buildRecipe(EmiRecipe recipe, AbstractContainerScreen scr if (possibleItems.isEmpty()) { continue; } + HolderLookup.Provider registries = Minecraft.getInstance().level.registryAccess(); ListTag invList = new ListTag(); for (int i = 0; i < possibleItems.size(); i++) { if (i >= ConfigRegistry.RECIPEMAXTAGS.get()) { @@ -98,8 +101,7 @@ private CompoundTag buildRecipe(EmiRecipe recipe, AbstractContainerScreen scr } ItemStack itemStack = possibleItems.get(i); if (!itemStack.isEmpty()) { - CompoundTag stackTag = new CompoundTag(); - itemStack.save(stackTag); + Tag stackTag = itemStack.save(registries); invList.add(stackTag); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/gui/ContainerNetwork.java b/src/main/java/com/lothrazar/storagenetwork/gui/ContainerNetwork.java index 39007af5..e97a0119 100644 --- a/src/main/java/com/lothrazar/storagenetwork/gui/ContainerNetwork.java +++ b/src/main/java/com/lothrazar/storagenetwork/gui/ContainerNetwork.java @@ -8,7 +8,7 @@ import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.handler.ItemStackMatcher; import com.lothrazar.storagenetwork.network.StackRefreshClientMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import com.lothrazar.storagenetwork.util.SsnConsts; import net.minecraft.core.NonNullList; import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; @@ -23,12 +23,13 @@ import net.minecraft.world.inventory.ResultSlot; import net.minecraft.world.inventory.Slot; 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.RecipeHolder; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; -import net.minecraftforge.network.NetworkDirection; +import net.neoforged.neoforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.items.wrapper.PlayerMainInvWrapper; public abstract class ContainerNetwork extends AbstractContainerMenu { @@ -127,10 +128,10 @@ public void slotsChanged(Container inventoryIn) { //it runs on server tho protected void findMatchingRecipeClient(Level world, CraftingContainer inventory, ResultContainer result) { - Optional optional = world.getRecipeManager().getRecipeFor(RecipeType.CRAFTING, inventory, world); + CraftingInput craftingInput = inventory.asCraftInput(); + Optional> optional = world.getRecipeManager().getRecipeFor(RecipeType.CRAFTING, craftingInput, world); if (optional.isPresent()) { - CraftingRecipe icraftingrecipe = optional.get(); - this.recipeCurrent = icraftingrecipe; + this.recipeCurrent = optional.get().value(); } } @@ -140,11 +141,13 @@ private void findMatchingRecipe(int containerId, Level world, Player player, Cra final int slotId = 0; ServerPlayer serverplayerentity = (ServerPlayer) player; ItemStack itemstack = ItemStack.EMPTY; - Optional optional = world.getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, inventory, world); + CraftingInput craftingInput = inventory.asCraftInput(); + Optional> optional = world.getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, craftingInput, world); if (optional.isPresent()) { - CraftingRecipe icraftingrecipe = optional.get(); - if (result.setRecipeUsed(world, serverplayerentity, icraftingrecipe)) { - itemstack = icraftingrecipe.assemble(inventory, world.registryAccess()); + RecipeHolder holder = optional.get(); + CraftingRecipe icraftingrecipe = holder.value(); + if (result.setRecipeUsed(world, serverplayerentity, holder)) { + itemstack = icraftingrecipe.assemble(craftingInput, world.registryAccess()); this.recipeCurrent = icraftingrecipe; } } @@ -171,14 +174,13 @@ public ItemStack quickMoveStack(Player playerIn, int slotIndex) { } else if (tileMain != null) { int rest = tileMain.insertStack(itemstack1, false); - ItemStack stack = rest == 0 ? ItemStack.EMPTY : ItemHandlerHelper.copyStackWithSize(itemstack1, rest); + ItemStack stack = rest == 0 ? ItemStack.EMPTY : itemstack1.copyWithCount(rest); slot.set(stack); broadcastChanges(); List list = tileMain.getNetwork().getSortedStacks(); if (playerIn instanceof ServerPlayer) { ServerPlayer sp = (ServerPlayer) playerIn; - PacketRegistry.INSTANCE.sendTo(new StackRefreshClientMessage(list, new ArrayList<>()), - sp.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(sp, new StackRefreshClientMessage(list, new ArrayList<>())); } if (stack.isEmpty()) { return ItemStack.EMPTY; @@ -224,7 +226,7 @@ protected void craftShift(Player player, TileMain tile) { for (int i = 0; i < matrix.getContainerSize(); i++) { recipeCopy.add(matrix.getItem(i).copy()); } - ItemStack res = recipeCurrent.assemble(matrix, level.registryAccess()); + ItemStack res = recipeCurrent.assemble(matrix.asCraftInput(), level.registryAccess()); if (res.isEmpty()) { StorageNetworkMod.LOGGER.error("err Recipe output is an empty stack " + recipeCurrent); return; @@ -232,14 +234,14 @@ protected void craftShift(Player player, TileMain tile) { int sizePerCraft = res.getCount(); //StorageNetwork.log("[craftShift] sizePerCraft = " + sizePerCraft + " for stack " + res); while (crafted + sizePerCraft <= res.getMaxStackSize()) { - res = recipeCurrent.assemble(matrix, level.registryAccess()); + res = recipeCurrent.assemble(matrix.asCraftInput(), level.registryAccess()); // StorageNetwork.log("[craftShift] crafted = " + crafted + " ; res.count() = " + res.getCount() + " MAX=" + res.getMaxStackSize()); if (!ItemHandlerHelper.insertItemStacked(new PlayerMainInvWrapper(playerInv), res, true).isEmpty()) { // StorageNetwork.log("[craftShift] cannot insert more, end"); break; } //stop if empty - if (recipeCurrent.matches(matrix, level) == false) { + if (recipeCurrent.matches(matrix.asCraftInput(), level) == false) { // StorageNetwork.log("[craftShift] recipe doesnt match i quit"); break; } @@ -248,7 +250,7 @@ protected void craftShift(Player player, TileMain tile) { if (!player.getInventory().add(res)) { player.drop(res, false); } - NonNullList remainder = recipeCurrent.getRemainingItems(this.matrix); + NonNullList remainder = recipeCurrent.getRemainingItems(this.matrix.asCraftInput()); for (int i = 0; i < remainder.size(); ++i) { ItemStack remainderCurrent = remainder.get(i); ItemStack slot = this.matrix.getItem(i); @@ -268,7 +270,7 @@ else if (!remainderCurrent.isEmpty()) { if (slot.isEmpty()) { this.matrix.setItem(i, remainderCurrent); } - else if (ItemStack.matches(slot, remainderCurrent) && ItemStack.isSameItemSameTags(slot, remainderCurrent)) { + else if (ItemStack.matches(slot, remainderCurrent) && ItemStack.isSameItemSameComponents(slot, remainderCurrent)) { remainderCurrent.grow(slot.getCount()); this.matrix.setItem(i, remainderCurrent); } diff --git a/src/main/java/com/lothrazar/storagenetwork/gui/NetworkWidget.java b/src/main/java/com/lothrazar/storagenetwork/gui/NetworkWidget.java index 8d28f271..70221dad 100644 --- a/src/main/java/com/lothrazar/storagenetwork/gui/NetworkWidget.java +++ b/src/main/java/com/lothrazar/storagenetwork/gui/NetworkWidget.java @@ -17,7 +17,7 @@ import com.lothrazar.storagenetwork.network.ClearRecipeMessage; import com.lothrazar.storagenetwork.network.InsertMessage; import com.lothrazar.storagenetwork.network.RequestMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import com.lothrazar.storagenetwork.util.SsnConsts; import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.client.Minecraft; @@ -32,7 +32,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class NetworkWidget { @@ -69,7 +69,7 @@ public NetworkWidget(IGuiNetwork gui, NetworkScreenSize size) { slots = Lists.newArrayList(); this.size = size; setScreenSize(); - PacketRegistry.INSTANCE.sendToServer(new RequestMessage()); + PacketDistributor.sendToServer(new RequestMessage()); lastClick = System.currentTimeMillis(); } @@ -163,8 +163,8 @@ public void init(Font font) { } clearGridBtn = new ButtonRequest( x, y, "", (p) -> { - PacketRegistry.INSTANCE.sendToServer(new ClearRecipeMessage()); - PacketRegistry.INSTANCE.sendToServer(new RequestMessage(0, ItemStack.EMPTY, false, false)); + PacketDistributor.sendToServer(new ClearRecipeMessage()); + PacketDistributor.sendToServer(new RequestMessage(0, ItemStack.EMPTY, false, false)); }, DEFAULT_NARRATION); clearGridBtn.setHeight(7); clearGridBtn.setWidth(7); @@ -218,7 +218,7 @@ private boolean doesStackMatchSearch(ItemStack stack) { else if (searchText.startsWith(EnumSearchPrefix.TOOLTIP.getPrefix())) { // search tooltips String tooltipString; Minecraft mc = Minecraft.getInstance(); - List tooltip = stack.getTooltipLines(mc.player, TooltipFlag.Default.NORMAL); + List tooltip = stack.getTooltipLines(net.minecraft.world.item.Item.TooltipContext.of(mc.level), mc.player, TooltipFlag.Default.NORMAL); List unformattedTooltip = tooltip.stream().map(Component::getString).collect(Collectors.toList()); tooltipString = Joiner.on(' ').join(unformattedTooltip).toLowerCase().trim(); return tooltipString.contains(searchText.toLowerCase().substring(1)); @@ -389,7 +389,7 @@ public void renderItemSlots(GuiGraphics ms, int mouseX, int mouseY, Font font) { public boolean charTyped(char typedChar, int keyCode) { if (searchBar.isFocused() && searchBar.charTyped(typedChar, keyCode)) { - PacketRegistry.INSTANCE.sendToServer(new RequestMessage(0, ItemStack.EMPTY, false, false)); + PacketDistributor.sendToServer(new RequestMessage(0, ItemStack.EMPTY, false, false)); syncTextToJei(); return true; } @@ -414,13 +414,13 @@ public void mouseClicked(double mouseX, double mouseY, int mouseButton) { && (mouseButton == UtilTileEntity.MOUSE_BTN_LEFT || mouseButton == UtilTileEntity.MOUSE_BTN_RIGHT) && stackCarriedByMouse.isEmpty()) { // Request an item (from the network) if we are in the upper section of the GUI - PacketRegistry.INSTANCE.sendToServer(new RequestMessage(mouseButton, this.stackUnderMouse.copy(), Screen.hasShiftDown(), + PacketDistributor.sendToServer(new RequestMessage(mouseButton, this.stackUnderMouse.copy(), Screen.hasShiftDown(), Screen.hasAltDown() || Screen.hasControlDown())); this.lastClick = System.currentTimeMillis(); } else if (!stackCarriedByMouse.isEmpty() && inField((int) mouseX, (int) mouseY)) { // Insert the item held by the mouse into the network - PacketRegistry.INSTANCE.sendToServer(new InsertMessage(0, mouseButton)); + PacketDistributor.sendToServer(new InsertMessage(0, mouseButton)); this.lastClick = System.currentTimeMillis(); } } @@ -485,13 +485,13 @@ public void render() { protected static final int W = 256; //i know they could all be in the same png file and i pull out sprites from it, but split images is easier to work with - public static final TileableTexture head = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_head.png"), W, 10); - public static final TileableTexture head_right = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_head_right.png"), W, 10); - public static final TileableTexture row = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_row.png"), W, SsnConsts.SQ); - public static final TileableTexture row_right = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_row_right.png"), W, SsnConsts.SQ); - public static final TileableTexture crafting = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_crafting.png"), W, 66); - public static final TileableTexture crafting_right = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_crafting_right.png"), W, 66); - public static final TileableTexture player = new TileableTexture(new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/expandable_player.png"), 176, 84); + public static final TileableTexture head = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_head.png"), W, 10); + public static final TileableTexture head_right = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_head_right.png"), W, 10); + public static final TileableTexture row = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_row.png"), W, SsnConsts.SQ); + public static final TileableTexture row_right = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_row_right.png"), W, SsnConsts.SQ); + public static final TileableTexture crafting = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_crafting.png"), W, 66); + public static final TileableTexture crafting_right = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_crafting_right.png"), W, 66); + public static final TileableTexture player = new TileableTexture(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/expandable_player.png"), 176, 84); protected void blitSegment(GuiGraphics ms, TileableTexture tt, int xpos, int ypos) { ms.blit(tt.texture(), xpos, ypos, 0, 0, tt.width(), tt.height()); diff --git a/src/main/java/com/lothrazar/storagenetwork/gui/components/ButtonRequest.java b/src/main/java/com/lothrazar/storagenetwork/gui/components/ButtonRequest.java index 9ddc01ba..1a09e1a7 100644 --- a/src/main/java/com/lothrazar/storagenetwork/gui/components/ButtonRequest.java +++ b/src/main/java/com/lothrazar/storagenetwork/gui/components/ButtonRequest.java @@ -108,12 +108,7 @@ public ResourceLocation getTexture() { public ButtonRequest(int xPos, int yPos, String displayString, OnPress handler, CreateNarration narration) { super(xPos, yPos, SIZE, SIZE, Component.translatable(displayString), handler, narration); - texture = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/cable.png"); - } - - @Override - public void render(GuiGraphics ms, int mx, int my, float pt) { - super.render(ms, mx, my, pt); + texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/cable.png"); } private int getTextureY() { diff --git a/src/main/java/com/lothrazar/storagenetwork/gui/components/TextboxInteger.java b/src/main/java/com/lothrazar/storagenetwork/gui/components/TextboxInteger.java index 61c076ad..77604533 100644 --- a/src/main/java/com/lothrazar/storagenetwork/gui/components/TextboxInteger.java +++ b/src/main/java/com/lothrazar/storagenetwork/gui/components/TextboxInteger.java @@ -2,7 +2,7 @@ //package com.lothrazar.cyclic.gui; import com.lothrazar.storagenetwork.network.CableIOMessage; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.neoforged.neoforge.network.PacketDistributor; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.components.EditBox; @@ -39,7 +39,7 @@ public boolean keyPressed(int key, int mx, int my) { } private void saveValue() { - PacketRegistry.INSTANCE.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP_TEXT.ordinal(), this.getCurrent(), false)); + PacketDistributor.sendToServer(new CableIOMessage(CableIOMessage.CableMessageType.SYNC_OP_TEXT.ordinal(), this.getCurrent(), false)); } @Override diff --git a/src/main/java/com/lothrazar/storagenetwork/gui/slot/ItemSlotNetwork.java b/src/main/java/com/lothrazar/storagenetwork/gui/slot/ItemSlotNetwork.java index 1ef05df0..0fcd4d56 100644 --- a/src/main/java/com/lothrazar/storagenetwork/gui/slot/ItemSlotNetwork.java +++ b/src/main/java/com/lothrazar/storagenetwork/gui/slot/ItemSlotNetwork.java @@ -53,17 +53,15 @@ public void drawSlot(GuiGraphics poseStack, Font font, int mx, int my) { amount = UtilInventory.formatLargeNumber(size); } final float scale = 0.85F; - PoseStack viewModelPose = RenderSystem.getModelViewStack(); - viewModelPose.pushPose(); - viewModelPose.translate(x + 3, y + 3, 0); - viewModelPose.scale(scale, scale, scale); - viewModelPose.translate(-1 * x, -1 * y, 0); - RenderSystem.applyModelViewMatrix(); + PoseStack pose = poseStack.pose(); + pose.pushPose(); + pose.translate(x + 3, y + 3, 0); + pose.scale(scale, scale, scale); + pose.translate(-1 * x, -1 * y, 0); if (isShowNumbers() && size > 1) { poseStack.renderItemDecorations(font, stack, x, y, amount); } - viewModelPose.popPose(); - RenderSystem.applyModelViewMatrix(); + pose.popPose(); if (isMouseOverSlot(mx, my)) { int j1 = x; int k1 = y; diff --git a/src/main/java/com/lothrazar/storagenetwork/item/ItemBuilder.java b/src/main/java/com/lothrazar/storagenetwork/item/ItemBuilder.java index 61ced6a1..ffd0f4aa 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/ItemBuilder.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/ItemBuilder.java @@ -10,6 +10,7 @@ import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; +import net.minecraft.core.component.DataComponents; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; @@ -21,15 +22,15 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; 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.event.entity.player.PlayerInteractEvent.LeftClickBlock; -import net.minecraftforge.eventbus.api.Event.Result; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.LeftClickBlock; public class ItemBuilder extends ItemFlib { @@ -41,14 +42,19 @@ public ItemBuilder(Properties properties) { public static void setBlockState(ItemStack wand, BlockState target) { CompoundTag encoded = NbtUtils.writeBlockState(target); - wand.getOrCreateTag().put(NBTBLOCKSTATE, encoded); + wand.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> tag.put(NBTBLOCKSTATE, encoded))); } public static BlockState getBlockState(Level level, ItemStack wand) { - if (!wand.getOrCreateTag().contains(NBTBLOCKSTATE)) { + CustomData customData = wand.get(DataComponents.CUSTOM_DATA); + if (customData == null) { return null; } - return NbtUtils.readBlockState(level.holderLookup(Registries.BLOCK), wand.getOrCreateTag().getCompound(NBTBLOCKSTATE)); + CompoundTag tag = customData.copyTag(); + if (!tag.contains(NBTBLOCKSTATE)) { + return null; + } + return NbtUtils.readBlockState(level.registryAccess().lookupOrThrow(Registries.BLOCK), tag.getCompound(NBTBLOCKSTATE)); } @SuppressWarnings("deprecation") @@ -61,9 +67,7 @@ public InteractionResult useOn(UseOnContext context) { BlockPos buildAt = pos.relative(context.getClickedFace()); if (world.getBlockEntity(pos) instanceof TileMain) { ItemStack stack = player.getItemInHand(hand); - CompoundTag tag = stack.getOrCreateTag(); DimPos.putPos(stack, pos, world); - stack.setTag(tag); UtilTileEntity.statusMessage(player, "item.remote.connected"); return InteractionResult.SUCCESS; } @@ -117,16 +121,19 @@ private boolean placeStateSafe(Level world, Player player, BlockPos placePos, Bl @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, net.minecraft.world.item.Item.TooltipContext context, List tooltip, TooltipFlag flagIn) { MutableComponent t = Component.translatable(getDescriptionId() + ".tooltip"); t.withStyle(ChatFormatting.GRAY); tooltip.add(t); - if (stack.hasTag()) { + if (stack.has(DataComponents.CUSTOM_DATA)) { DimPos dp = DimPos.getPosStored(stack); if (dp != null) { tooltip.add(dp.makeTooltip()); } // block state? - BlockState target = ItemBuilder.getBlockState(worldIn, stack); + BlockState target = null; + if (context.level() != null) { + target = ItemBuilder.getBlockState(context.level(), stack); + } if (target != null) { String block = target.getBlock().getDescriptionId(); t = Component.translatable(block); @@ -150,7 +157,7 @@ public static void onLeftClickBlock(LeftClickBlock event) { BlockState target = world.getBlockState(event.getPos()); ItemBuilder.setBlockState(held, target); UtilTileEntity.statusMessage(player, target); - event.setResult(Result.DENY); + event.setCanceled(true); } } } diff --git a/src/main/java/com/lothrazar/storagenetwork/item/ItemCollector.java b/src/main/java/com/lothrazar/storagenetwork/item/ItemCollector.java index 30077346..978642d8 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/ItemCollector.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/ItemCollector.java @@ -2,7 +2,9 @@ import java.util.List; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.component.CustomData; import org.apache.commons.lang3.tuple.Triple; import com.lothrazar.library.item.ItemFlib; import com.lothrazar.storagenetwork.StorageNetworkMod; @@ -26,9 +28,9 @@ 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.event.entity.player.EntityItemPickupEvent; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.event.entity.player.ItemEntityPickupEvent; public class ItemCollector extends ItemFlib { private static final String NBT_ENABLED = "Enabled"; @@ -45,16 +47,16 @@ protected ItemStack findAmmo(Player player, Item item) { public void toggleEnabled(ItemStack stack, Player player) { boolean newEnabled = !isEnabled(stack); - stack.getOrCreateTag().putBoolean(NBT_ENABLED, newEnabled); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> tag.putBoolean(NBT_ENABLED, newEnabled))); player.displayClientMessage(makeDisabledTooltip(newEnabled), true); } // not subscribe, called from SsnEvents.java - public void onEntityItemPickupEvent(EntityItemPickupEvent event) { - if (event.getEntity() instanceof Player && - event.getItem() != null && - !event.getItem().getItem().isEmpty()) { - Player player = event.getEntity(); + public void onEntityItemPickupEvent(ItemEntityPickupEvent.Pre event) { + if (event.getPlayer() instanceof Player && + event.getItemEntity() != null && + !event.getItemEntity().getItem().isEmpty()) { + Player player = event.getPlayer(); // find the collector that the player has with them (main hand, offhand, curios...) ItemStack collectorStack = this.findAmmo(player, this); @@ -67,7 +69,7 @@ public void onEntityItemPickupEvent(EntityItemPickupEvent event) { return; } - ItemStack item = event.getItem().getItem(); + ItemStack item = event.getItemEntity().getItem(); Level world = player.level(); DimPos dp = DimPos.getPosStored(collectorStack); if (dp != null && !world.isClientSide) { @@ -90,7 +92,8 @@ public void onEntityItemPickupEvent(EntityItemPickupEvent event) { } private static boolean isEnabled(ItemStack collectorStack) { - return collectorStack.getOrCreateTag().getBoolean(NBT_ENABLED); + CustomData customData = collectorStack.get(DataComponents.CUSTOM_DATA); + return customData != null && customData.copyTag().getBoolean(NBT_ENABLED); } @Override @@ -110,11 +113,11 @@ public InteractionResult useOn(UseOnContext context) { @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, net.minecraft.world.item.Item.TooltipContext context, List tooltip, TooltipFlag flagIn) { MutableComponent t = Component.translatable(getDescriptionId() + ".tooltip"); t.withStyle(ChatFormatting.GRAY); tooltip.add(t); - if (stack.hasTag()) { + if (stack.has(DataComponents.CUSTOM_DATA)) { DimPos dp = DimPos.getPosStored(stack); if (dp != null) { tooltip.add(dp.makeTooltip()); diff --git a/src/main/java/com/lothrazar/storagenetwork/item/ItemPicker.java b/src/main/java/com/lothrazar/storagenetwork/item/ItemPicker.java index 7406e23a..eefe8c5a 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/ItemPicker.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/ItemPicker.java @@ -15,14 +15,15 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; 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.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ItemPicker extends ItemFlib { @@ -82,11 +83,11 @@ public InteractionResult useOn(UseOnContext context) { @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, net.minecraft.world.item.Item.TooltipContext context, List tooltip, TooltipFlag flagIn) { MutableComponent t = Component.translatable(getDescriptionId() + ".tooltip"); t.withStyle(ChatFormatting.GRAY); tooltip.add(t); - if (stack.hasTag()) { + if (stack.has(DataComponents.CUSTOM_DATA)) { DimPos dp = DimPos.getPosStored(stack); if (dp != null) { tooltip.add(dp.makeTooltip()); diff --git a/src/main/java/com/lothrazar/storagenetwork/item/ItemUpgrade.java b/src/main/java/com/lothrazar/storagenetwork/item/ItemUpgrade.java index 7e25a078..b6c92fe1 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/ItemUpgrade.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/ItemUpgrade.java @@ -7,9 +7,8 @@ import net.minecraft.network.chat.MutableComponent; 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; public class ItemUpgrade extends ItemFlib { @@ -19,7 +18,7 @@ public ItemUpgrade(Properties properties) { @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, net.minecraft.world.item.Item.TooltipContext context, List tooltip, TooltipFlag flagIn) { MutableComponent t = Component.translatable(getDescriptionId() + ".tooltip"); t.withStyle(ChatFormatting.GRAY); tooltip.add(t); diff --git a/src/main/java/com/lothrazar/storagenetwork/item/remote/ItemRemote.java b/src/main/java/com/lothrazar/storagenetwork/item/remote/ItemRemote.java index e6baacc8..3ae9cec0 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/remote/ItemRemote.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/remote/ItemRemote.java @@ -11,6 +11,7 @@ import com.lothrazar.storagenetwork.util.UtilTileEntity; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; @@ -22,10 +23,11 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.context.UseOnContext; 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; public class ItemRemote extends ItemFlib implements MenuProvider { @@ -38,41 +40,39 @@ public ItemRemote(Properties properties) { super(properties.stacksTo(1)); } + private static CompoundTag readTag(ItemStack stack) { + CustomData customData = stack.get(DataComponents.CUSTOM_DATA); + return customData != null ? customData.copyTag() : new CompoundTag(); + } + public static boolean isJeiSearchSynced(ItemStack stack) { - CompoundTag tag = stack.getOrCreateTag(); - if (tag.contains(NBT_JEI)) { - return tag.getBoolean(NBT_JEI); - } - return false; + CompoundTag tag = readTag(stack); + return tag.contains(NBT_JEI) && tag.getBoolean(NBT_JEI); } public static void setJeiSearchSynced(ItemStack stack, boolean val) { - stack.getOrCreateTag().putBoolean(NBT_JEI, val); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> tag.putBoolean(NBT_JEI, val))); } public static boolean getDownwards(ItemStack stack) { - CompoundTag tag = stack.getOrCreateTag(); - if (tag.contains(NBT_DOWN)) { - return tag.getBoolean(NBT_DOWN); - } - return false; + CompoundTag tag = readTag(stack); + return tag.contains(NBT_DOWN) && tag.getBoolean(NBT_DOWN); } public static void setDownwards(ItemStack stack, boolean val) { - stack.getOrCreateTag().putBoolean(NBT_DOWN, val); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> tag.putBoolean(NBT_DOWN, val))); } public static EnumSortType getSort(ItemStack stack) { - CompoundTag tag = stack.getOrCreateTag(); + CompoundTag tag = readTag(stack); if (tag.contains(NBT_SORT)) { - int sort = tag.getInt(NBT_SORT); - return EnumSortType.values()[sort]; + return EnumSortType.values()[tag.getInt(NBT_SORT)]; } return EnumSortType.NAME; } public static void setSort(ItemStack stack, EnumSortType val) { - stack.getOrCreateTag().putInt(NBT_SORT, val.ordinal()); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> tag.putInt(NBT_SORT, val.ordinal()))); } @Override @@ -92,9 +92,9 @@ public InteractionResult useOn(UseOnContext context) { @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, net.minecraft.world.item.Item.TooltipContext context, List tooltip, TooltipFlag flagIn) { tooltip.add(Component.translatable(getDescriptionId() + ".tooltip").withStyle(ChatFormatting.GRAY)); - if (stack.hasTag()) { + if (stack.has(DataComponents.CUSTOM_DATA)) { DimPos dp = DimPos.getPosStored(stack); if (dp != null) { tooltip.add(dp.makeTooltip()); @@ -106,7 +106,6 @@ public void appendHoverText(ItemStack stack, Level worldIn, List tool public InteractionResultHolder use(Level world, Player player, InteractionHand hand) { ItemStack itemStackIn = player.getItemInHand(hand); if (UtilRemote.openRemote(world, player, itemStackIn, this)) { - // ok great return InteractionResultHolder.success(itemStackIn); } return super.use(world, player, hand); @@ -133,10 +132,10 @@ else if (crafting) { } public static void setAutoFocus(ItemStack stack, boolean autoFocus) { - stack.getOrCreateTag().putBoolean("autoFocus", autoFocus); + stack.update(DataComponents.CUSTOM_DATA, CustomData.EMPTY, data -> data.update(tag -> tag.putBoolean("autoFocus", autoFocus))); } public static boolean getAutoFocus(ItemStack stack) { - return stack.getOrCreateTag().getBoolean("autoFocus"); + return readTag(stack).getBoolean("autoFocus"); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkCraftingRemote.java b/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkCraftingRemote.java index d1a069e2..0d1afb79 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkCraftingRemote.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkCraftingRemote.java @@ -10,13 +10,13 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class ScreenNetworkCraftingRemote extends AbstractNetworkScreen { private static final int HEIGHT = 256; private static final int WIDTH = 176; - private static final ResourceLocation textureCraft = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/request.png"); + private static final ResourceLocation textureCraft = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/request.png"); private final NetworkWidget network; private final ItemStack remote; diff --git a/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkExpandedRemote.java b/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkExpandedRemote.java index a263bf58..16aade14 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkExpandedRemote.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkExpandedRemote.java @@ -8,7 +8,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class ScreenNetworkExpandedRemote extends AbstractNetworkScreen { diff --git a/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkRemote.java b/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkRemote.java index 0267fa15..7551b8ff 100644 --- a/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkRemote.java +++ b/src/main/java/com/lothrazar/storagenetwork/item/remote/ScreenNetworkRemote.java @@ -10,14 +10,13 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class ScreenNetworkRemote extends AbstractNetworkScreen { private static final int HEIGHT = 256; private static final int WIDTH = 176; - private static final ResourceLocation texture = new ResourceLocation(StorageNetworkMod.MODID, - "textures/gui/inventory.png"); + private static final ResourceLocation texture = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/inventory.png"); private final NetworkWidget network; private final ItemStack remote; diff --git a/src/main/java/com/lothrazar/storagenetwork/jei/JeiHooks.java b/src/main/java/com/lothrazar/storagenetwork/jei/JeiHooks.java index 622a1433..f5512cf8 100644 --- a/src/main/java/com/lothrazar/storagenetwork/jei/JeiHooks.java +++ b/src/main/java/com/lothrazar/storagenetwork/jei/JeiHooks.java @@ -9,7 +9,7 @@ import mezz.jei.api.runtime.IRecipesGui; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; public class JeiHooks { diff --git a/src/main/java/com/lothrazar/storagenetwork/jei/JeiPlugin.java b/src/main/java/com/lothrazar/storagenetwork/jei/JeiPlugin.java index d0c90f1c..247cbd1d 100644 --- a/src/main/java/com/lothrazar/storagenetwork/jei/JeiPlugin.java +++ b/src/main/java/com/lothrazar/storagenetwork/jei/JeiPlugin.java @@ -23,7 +23,7 @@ public class JeiPlugin implements IModPlugin { @Override public ResourceLocation getPluginUid() { - return new ResourceLocation(StorageNetworkMod.MODID, "jei"); + return ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "jei"); } @Override diff --git a/src/main/java/com/lothrazar/storagenetwork/jei/RequestRecipeTransferHandler.java b/src/main/java/com/lothrazar/storagenetwork/jei/RequestRecipeTransferHandler.java index a1a936de..49575ce7 100644 --- a/src/main/java/com/lothrazar/storagenetwork/jei/RequestRecipeTransferHandler.java +++ b/src/main/java/com/lothrazar/storagenetwork/jei/RequestRecipeTransferHandler.java @@ -4,7 +4,9 @@ import java.util.stream.Collectors; import com.lothrazar.storagenetwork.network.RecipeMessage; import com.lothrazar.storagenetwork.registry.ConfigRegistry; -import com.lothrazar.storagenetwork.registry.PacketRegistry; +import net.minecraft.client.Minecraft; +import net.minecraft.core.HolderLookup; +import net.neoforged.neoforge.network.PacketDistributor; import mezz.jei.api.constants.RecipeTypes; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.ingredient.IRecipeSlotView; @@ -19,27 +21,28 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; /** * https://github.com/mezz/JustEnoughItems/blob/1.19/Common/src/main/java/mezz/jei/common/transfer/BasicRecipeTransferHandler.java - * + * * NEW in mc1.19: abstract class to override in the Plugin during registration */ -public abstract class RequestRecipeTransferHandler implements IRecipeTransferHandler { +public abstract class RequestRecipeTransferHandler implements IRecipeTransferHandler> { @Override - public IRecipeTransferError transferRecipe(C c, CraftingRecipe recipe, IRecipeSlotsView recipeSlots, Player playerEntity, + public IRecipeTransferError transferRecipe(C c, RecipeHolder recipe, IRecipeSlotsView recipeSlots, Player playerEntity, boolean maxTransfer, boolean doTransfer) { if (doTransfer) { CompoundTag nbt = RequestRecipeTransferHandler.recipeToTag(c, recipeSlots); - PacketRegistry.INSTANCE.sendToServer(new RecipeMessage(nbt)); + PacketDistributor.sendToServer(new RecipeMessage(nbt)); } return null; } public static CompoundTag recipeToTag(AbstractContainerMenu container, IRecipeSlotsView recipeSlots) { CompoundTag nbt = new CompoundTag(); - + HolderLookup.Provider registries = Minecraft.getInstance().level.registryAccess(); List slotsViewList = recipeSlots.getSlotViews(); for (Slot slot : container.slots) { if (slot.container instanceof net.minecraft.world.inventory.CraftingContainer) { @@ -59,9 +62,7 @@ public static CompoundTag recipeToTag(AbstractContainerMenu container, IRecipeSl } ItemStack itemStack = possibleItems.get(i); if (!itemStack.isEmpty()) { - CompoundTag stackTag = new CompoundTag(); - itemStack.save(stackTag); - invList.add(stackTag); + invList.add(itemStack.save(registries)); } } nbt.put("s" + (slot.getSlotIndex()), invList); @@ -71,7 +72,7 @@ public static CompoundTag recipeToTag(AbstractContainerMenu container, IRecipeSl } @Override - public RecipeType getRecipeType() { + public RecipeType> getRecipeType() { return RecipeTypes.CRAFTING; } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/CableDataMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/CableDataMessage.java index fcf50b6c..ee231727 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/CableDataMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/CableDataMessage.java @@ -1,59 +1,85 @@ package com.lothrazar.storagenetwork.network; -import java.util.function.Supplier; import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.cable.linkfilter.ContainerCableFilter; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.CapabilityConnectableLink; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import com.lothrazar.storagenetwork.util.UtilTileEntity; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class CableDataMessage { +public class CableDataMessage implements CustomPacketPayload { + + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "cable_data")); + + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + CableDataMessage::write, + CableDataMessage::read + ); public enum CableMessageType { SYNC_DATA, IMPORT_FILTER, SAVE_FITLER; } - private boolean isAllowlist; + private final boolean isAllowlist; private final int id; - private int value = 0; - private ItemStack stack = ItemStack.EMPTY; + private final int value; + private ItemStack stack; public CableDataMessage(int id) { this.id = id; + this.value = 0; + this.isAllowlist = false; + this.stack = ItemStack.EMPTY; } public CableDataMessage(int id, int value, boolean is) { - this(id); + this.id = id; this.value = value; this.isAllowlist = is; + this.stack = ItemStack.EMPTY; } public CableDataMessage(int id, int value, ItemStack mystack) { - this(id); + this.id = id; this.value = value; - stack = mystack; + this.isAllowlist = false; + this.stack = mystack; } @Override public String toString() { - return "CableDataMessage{" + - "isAllowlist=" + isAllowlist + - ", id=" + id + - ", value=" + value + - ", stack=" + stack + - '}'; + return "CableDataMessage{isAllowlist=" + isAllowlist + ", id=" + id + ", value=" + value + ", stack=" + stack + '}'; + } + + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } + + private static void write(RegistryFriendlyByteBuf buf, CableDataMessage msg) { + buf.writeInt(msg.id); + buf.writeInt(msg.value); + buf.writeBoolean(msg.isAllowlist); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, msg.stack); } - public static void handle(CableDataMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); + private static CableDataMessage read(RegistryFriendlyByteBuf buf) { + CableDataMessage c = new CableDataMessage(buf.readInt(), buf.readInt(), buf.readBoolean()); + c.stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); + return c; + } + + public static void handle(CableDataMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); CapabilityConnectableLink link = null; ContainerCableFilter container = (ContainerCableFilter) player.containerMenu; if (container == null || container.cap == null) { @@ -67,11 +93,9 @@ public static void handle(CableDataMessage message, Supplier TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "cable_facade")); - private CableFacadeMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + CableFacadeMessage::write, + CableFacadeMessage::read + ); + + private final BlockPos pos; + private final boolean erase; + private final CompoundTag blockStateTag; public CableFacadeMessage(BlockPos pos, CompoundTag state) { this.pos = pos; @@ -27,41 +35,45 @@ public CableFacadeMessage(BlockPos pos, CompoundTag state) { public CableFacadeMessage(BlockPos pos, boolean eraseIn) { this.pos = pos; this.erase = eraseIn; - blockStateTag = new CompoundTag(); + this.blockStateTag = new CompoundTag(); + } + + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void handle(CableFacadeMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); + private static void write(RegistryFriendlyByteBuf buf, CableFacadeMessage msg) { + buf.writeBoolean(msg.erase); + buf.writeBlockPos(msg.pos); + buf.writeNbt(msg.blockStateTag); + } + + private static CableFacadeMessage read(RegistryFriendlyByteBuf buf) { + boolean erase = buf.readBoolean(); + BlockPos pos = buf.readBlockPos(); + CompoundTag tag = buf.readNbt(); + if (erase) { + return new CableFacadeMessage(pos, true); + } + return new CableFacadeMessage(pos, tag != null ? tag : new CompoundTag()); + } + + public static void handle(CableFacadeMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); ServerLevel serverWorld = (ServerLevel) player.level(); TileCable tile = TileCable.getTileCable(serverWorld, message.pos); if (tile != null) { if (message.erase) { - // StorageNetworkMod.log("Network Packet facade SAVE NULL EMPTY ERASE " + message.blockStateTag); tile.setFacadeState(null); } else { - // StorageNetworkMod.log("Network Packet facade SAVE " + message.blockStateTag); tile.setFacadeState(message.blockStateTag); } serverWorld.markAndNotifyBlock(message.pos, serverWorld.getChunkAt(message.pos), tile.getBlockState(), tile.getBlockState(), 3, 1); } }); - ctx.get().setPacketHandled(true); - } - - public static CableFacadeMessage decode(FriendlyByteBuf buf) { - CableFacadeMessage message = new CableFacadeMessage(); - message.erase = buf.readBoolean(); - message.pos = buf.readBlockPos(); - message.blockStateTag = buf.readNbt(); - return message; - } - - public static void encode(CableFacadeMessage msg, FriendlyByteBuf buf) { - buf.writeBoolean(msg.erase); - buf.writeBlockPos(msg.pos); - buf.writeNbt(msg.blockStateTag); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/CableIOMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/CableIOMessage.java index 1bcd725c..2d0d9e40 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/CableIOMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/CableIOMessage.java @@ -1,6 +1,5 @@ package com.lothrazar.storagenetwork.network; -import java.util.function.Supplier; import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.TileConnectable; import com.lothrazar.storagenetwork.block.cable.export.ContainerCableExportFilter; @@ -9,76 +8,95 @@ import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.CapabilityConnectable; import com.lothrazar.storagenetwork.capability.CapabilityConnectableAutoIO; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import com.lothrazar.storagenetwork.util.UtilTileEntity; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class CableIOMessage { +public class CableIOMessage implements CustomPacketPayload { + + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "cable_io")); + + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + CableIOMessage::write, + CableIOMessage::read + ); public enum CableMessageType { SYNC_DATA, IMPORT_FILTER, SAVE_FITLER, REDSTONE, SYNC_OP, SYNC_OP_TEXT, SYNC_OP_STACK; } - private boolean isAllowlist; + private final boolean isAllowlist; private final int id; - private int value = 0; - private ItemStack stack = ItemStack.EMPTY; + private final int value; + private ItemStack stack; public CableIOMessage(int id) { this.id = id; + this.value = 0; + this.isAllowlist = false; + this.stack = ItemStack.EMPTY; } public CableIOMessage(int id, int value, boolean isall) { - this(id); + this.id = id; this.value = value; this.isAllowlist = isall; + this.stack = ItemStack.EMPTY; } public CableIOMessage(int id, int value, ItemStack stackin) { - this(id); + this.id = id; this.value = value; - stack = stackin; + this.isAllowlist = false; + this.stack = stackin; } public CableIOMessage(int id, ItemStack s) { - this(id); + this.id = id; + this.value = 0; + this.isAllowlist = false; this.stack = s; } @Override public String toString() { - return "CableDataMessage{" + - "isAllowlist=" + isAllowlist + - ", id=" + id + - ", value=" + value + - ", stack=" + stack + - '}'; + return "CableDataMessage{isAllowlist=" + isAllowlist + ", id=" + id + ", value=" + value + ", stack=" + stack + '}'; + } + + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } + + private static void write(RegistryFriendlyByteBuf buf, CableIOMessage msg) { + buf.writeInt(msg.id); + buf.writeInt(msg.value); + buf.writeBoolean(msg.isAllowlist); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, msg.stack); } - /** - * TODO: mostly duplicate of CableDataMessage, needs merge or refactor - * - * @param message - * @param ctx - */ - public static void handle(CableIOMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - handleInternal(message, ctx); - }); - ctx.get().setPacketHandled(true); + private static CableIOMessage read(RegistryFriendlyByteBuf buf) { + CableIOMessage c = new CableIOMessage(buf.readInt(), buf.readInt(), buf.readBoolean()); + c.stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); + return c; } - private static void handleInternal(CableIOMessage message, Supplier ctx) { - ServerPlayer player = ctx.get().getSender(); + public static void handle(CableIOMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> handleInternal(message, ctx)); + } + + private static void handleInternal(CableIOMessage message, IPayloadContext ctx) { + ServerPlayer player = (ServerPlayer) ctx.player(); CapabilityConnectableAutoIO link = null; TileConnectable tile = null; CapabilityConnectable connectable = null; - //TODO: how to refactor if (player.containerMenu instanceof ContainerCableExportFilter) { ContainerCableExportFilter ctr = (ContainerCableExportFilter) player.containerMenu; link = ctr.cap; @@ -104,11 +122,9 @@ private static void handleInternal(CableIOMessage message, Supplier TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "cable_limit")); - private CableLimitMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + CableLimitMessage::write, + CableLimitMessage::read + ); + + private final int limit; + private final ItemStack stack; public CableLimitMessage(int limit, ItemStack stack) { - super(); this.limit = limit; this.stack = stack; } - public static void handle(CableLimitMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - // ServerPlayerEntity player = ctx.get().getSender(); - // if (player.openContainer instanceof ContainerCableIO) { - // ContainerCableIO con = (ContainerCableIO) player.openContainer; - // if (con == null || con.autoIO == null) { - // return; - // } - // con.autoIO.operationLimit = message.limit; - // con.autoIO.operationStack = message.stack; - // con.tile.markDirty(); - // } - }); - ctx.get().setPacketHandled(true); + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static CableLimitMessage decode(FriendlyByteBuf buf) { - CableLimitMessage message = new CableLimitMessage(); - message.limit = buf.readInt(); - message.stack = ItemStack.of(buf.readNbt()); - return message; + private static void write(RegistryFriendlyByteBuf buf, CableLimitMessage msg) { + buf.writeInt(msg.limit); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, msg.stack); } - public static void encode(CableLimitMessage msg, FriendlyByteBuf buf) { - buf.writeInt(msg.limit); - buf.writeNbt(msg.stack.serializeNBT()); + private static CableLimitMessage read(RegistryFriendlyByteBuf buf) { + int limit = buf.readInt(); + ItemStack stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); + return new CableLimitMessage(limit, stack); + } + + public static void handle(CableLimitMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + // handler body intentionally left empty (see original comments) + }); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/ClearRecipeMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/ClearRecipeMessage.java index 64471e5b..22fe9cd0 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/ClearRecipeMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/ClearRecipeMessage.java @@ -2,44 +2,38 @@ import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.gui.ContainerNetwork; -import com.lothrazar.storagenetwork.registry.PacketRegistry; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ClearRecipeMessage { +public class ClearRecipeMessage implements CustomPacketPayload { - public static void handle(ClearRecipeMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); - ClearRecipeMessage.clearContainerRecipe(player, true); - }); - ctx.get().setPacketHandled(true); - } + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "clear_recipe")); + + public static final StreamCodec STREAM_CODEC = + StreamCodec.unit(new ClearRecipeMessage()); - public static ClearRecipeMessage decode(FriendlyByteBuf buf) { - return new ClearRecipeMessage(); + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void encode(ClearRecipeMessage msg, FriendlyByteBuf buf) {} + public static void handle(ClearRecipeMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); + ClearRecipeMessage.clearContainerRecipe(player, true); + }); + } - /** - * Should be in a public util. - * - * Clears recipe and puts ingredients back in the network. If possible. - * - * May stop partway and leave items in if network is disconnected. - * - * @param player - * @param doRefresh - */ static void clearContainerRecipe(ServerPlayer player, boolean doRefresh) { if (player.containerMenu instanceof ContainerNetwork) { ContainerNetwork container = (ContainerNetwork) player.containerMenu; @@ -63,13 +57,12 @@ static void clearContainerRecipe(ServerPlayer player, boolean doRefresh) { craftMatrix.setItem(i, ItemStack.EMPTY); } else { - craftMatrix.setItem(i, ItemHandlerHelper.copyStackWithSize(stackInSlot, remainingAfter)); + craftMatrix.setItem(i, stackInSlot.copyWithCount(remainingAfter)); } } if (doRefresh) { List list = root.getNetwork().getStacks(); - PacketRegistry.INSTANCE.sendTo(new StackRefreshClientMessage(list, new ArrayList<>()), - player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(player, new StackRefreshClientMessage(list, new ArrayList<>())); container.broadcastChanges(); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/InsertMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/InsertMessage.java index f95a175a..7a5093f5 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/InsertMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/InsertMessage.java @@ -2,32 +2,54 @@ import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.gui.ContainerNetwork; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import com.lothrazar.storagenetwork.util.UtilTileEntity; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class InsertMessage { +public class InsertMessage implements CustomPacketPayload { - private int dim, mouseButton; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "insert")); + + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + InsertMessage::write, + InsertMessage::read + ); + + private final int dim; + private final int mouseButton; public InsertMessage(int dim, int buttonID) { this.dim = dim; this.mouseButton = buttonID; } - private InsertMessage() {} + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } + + private static void write(RegistryFriendlyByteBuf buf, InsertMessage msg) { + buf.writeInt(msg.dim); + buf.writeInt(msg.mouseButton); + } - public static void handle(InsertMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); + private static InsertMessage read(RegistryFriendlyByteBuf buf) { + return new InsertMessage(buf.readInt(), buf.readInt()); + } + + public static void handle(InsertMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); TileMain root = null; if (player.containerMenu instanceof ContainerNetwork) { root = ((ContainerNetwork) player.containerMenu).getTileMain(); @@ -38,7 +60,7 @@ public static void handle(InsertMessage message, Supplier if (message.mouseButton == UtilTileEntity.MOUSE_BTN_LEFT) { rest = root.insertStack(stack, false); if (rest != 0) { - send = ItemHandlerHelper.copyStackWithSize(stack, rest); + send = stack.copyWithCount(rest); } } else if (message.mouseButton == UtilTileEntity.MOUSE_BTN_RIGHT) { @@ -47,30 +69,14 @@ else if (message.mouseButton == UtilTileEntity.MOUSE_BTN_RIGHT) { stack.shrink(1); rest = root.insertStack(stack1, false) + stack.getCount(); if (rest != 0) { - send = ItemHandlerHelper.copyStackWithSize(stack, rest); + send = stack.copyWithCount(rest); } } player.containerMenu.setCarried(send); - // - PacketRegistry.INSTANCE.sendTo(new StackResponseClientMessage(send), - player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(player, new StackResponseClientMessage(send)); List list = root.getNetwork().getStacks(); - PacketRegistry.INSTANCE.sendTo(new StackRefreshClientMessage(list, new ArrayList<>()), - player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(player, new StackRefreshClientMessage(list, new ArrayList<>())); player.containerMenu.broadcastChanges(); }); - ctx.get().setPacketHandled(true); - } - - public static InsertMessage decode(FriendlyByteBuf buf) { - InsertMessage message = new InsertMessage(); - message.dim = buf.readInt(); - message.mouseButton = buf.readInt(); - return message; - } - - public static void encode(InsertMessage msg, FriendlyByteBuf buf) { - buf.writeInt(msg.dim); - buf.writeInt(msg.mouseButton); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/KeybindCollectorToggleMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/KeybindCollectorToggleMessage.java index 813d187a..131fcfba 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/KeybindCollectorToggleMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/KeybindCollectorToggleMessage.java @@ -1,27 +1,33 @@ package com.lothrazar.storagenetwork.network; -import com.lothrazar.storagenetwork.item.ItemCollector; +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.registry.SsnRegistry; import com.lothrazar.storagenetwork.util.UtilInventory; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; -import java.util.function.Supplier; +public class KeybindCollectorToggleMessage implements CustomPacketPayload { -public class KeybindCollectorToggleMessage { + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "keybind_collector_toggle")); - public KeybindCollectorToggleMessage() { + public static final StreamCodec STREAM_CODEC = + StreamCodec.unit(new KeybindCollectorToggleMessage()); + + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void handle(KeybindCollectorToggleMessage msg, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); + public static void handle(KeybindCollectorToggleMessage msg, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); if (player != null) { - - // added curios compatibility to toggle feature var searchResult = UtilInventory.getCurioRemote(player, SsnRegistry.Items.COLLECTOR_REMOTE.get()); ItemStack remoteFound = searchResult.getRight(); if (!remoteFound.isEmpty()) { @@ -29,14 +35,5 @@ public static void handle(KeybindCollectorToggleMessage msg, Supplier TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "keybind_curio")); - public static void handle(KeybindCurioMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); - ServerLevel serverWorld = (ServerLevel) player.level(); - UtilRemote.searchAndOpen(player, serverWorld); - }); - ctx.get().setPacketHandled(true); - } + public static final StreamCodec STREAM_CODEC = + StreamCodec.unit(new KeybindCurioMessage()); - public static KeybindCurioMessage decode(FriendlyByteBuf buf) { - KeybindCurioMessage message = new KeybindCurioMessage(); - return message; + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void encode(KeybindCurioMessage msg, FriendlyByteBuf buf) { - // buf.writeBoolean(msg.direction); + public static void handle(KeybindCurioMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); + ServerLevel serverWorld = (ServerLevel) player.level(); + UtilRemote.searchAndOpen(player, serverWorld); + }); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/RecipeMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/RecipeMessage.java index 29274e23..0593ccfb 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/RecipeMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/RecipeMessage.java @@ -4,65 +4,67 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Supplier; import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.handler.ItemStackMatcher; import com.lothrazar.storagenetwork.gui.ContainerNetwork; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import com.lothrazar.storagenetwork.util.UtilInventory; 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.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.items.wrapper.PlayerMainInvWrapper; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class RecipeMessage { +public class RecipeMessage implements CustomPacketPayload { - /** @formatter:off - * Sample data structure can have list of items for each slot (example: ore dictionary) - * { - * s0:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s1:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s2:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s3:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s4:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s5:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s6:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s7:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}], - * s8:[{id:"ic2:ingot",Count:1b,Damage:2s},{id:"immersiveengineering:metal",Count:1b,Damage:0s}] - * } - * @formatter:on - */ - private CompoundTag nbt; - private int index = 0; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "recipe")); - private RecipeMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + RecipeMessage::write, + RecipeMessage::read + ); + + private final CompoundTag nbt; + private final int index; public RecipeMessage(CompoundTag nbt) { this.nbt = nbt; + this.index = 0; + } + + private RecipeMessage(CompoundTag nbt, int index) { + this.nbt = nbt; + this.index = index; } - public static RecipeMessage decode(FriendlyByteBuf buf) { - RecipeMessage message = new RecipeMessage(); - message.index = buf.readInt(); - message.nbt = buf.readNbt(); - return message; + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void encode(RecipeMessage msg, FriendlyByteBuf buf) { + private static void write(RegistryFriendlyByteBuf buf, RecipeMessage msg) { buf.writeInt(msg.index); buf.writeNbt(msg.nbt); } - public static void handle(RecipeMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); + private static RecipeMessage read(RegistryFriendlyByteBuf buf) { + int index = buf.readInt(); + CompoundTag nbt = buf.readNbt(); + return new RecipeMessage(nbt != null ? nbt : new CompoundTag(), index); + } + + public static void handle(RecipeMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); if (player.containerMenu instanceof ContainerNetwork == false) { return; } @@ -76,20 +78,13 @@ public static void handle(RecipeMessage message, Supplier CraftingContainer craftMatrix = ctr.getCraftMatrix(); for (int slot = 0; slot < 9; slot++) { Map map = new HashMap<>(); - //if its a string, then ore dict is allowed - /********* - * parse nbt of the slot, whether its ore dict, itemstack, ore empty - **********/ - boolean isOreDict; - isOreDict = false; + boolean isOreDict = false; ListTag invList = message.nbt.getList("s" + slot, Tag.TAG_COMPOUND); for (int i = 0; i < invList.size(); i++) { CompoundTag stackTag = invList.getCompound(i); - ItemStack s = ItemStack.of(stackTag); + ItemStack s = ItemStack.parseOptional(player.registryAccess(), stackTag); map.put(i, s); } - /********* end parse nbt of this current slot ******/ - /********** now start trying to fill in recipe **/ for (int i = 0; i < map.size(); i++) { ItemStack stackCurrent = map.get(i); if (stackCurrent == null || stackCurrent.isEmpty()) { @@ -99,29 +94,21 @@ public static void handle(RecipeMessage message, Supplier itemStackMatcher.setNbt(true); itemStackMatcher.setOre(isOreDict); ItemStack ex = UtilInventory.extractItem(new PlayerMainInvWrapper(player.getInventory()), itemStackMatcher, 1, true); - /*********** First try and use the players inventory **/ if (ex != null && !ex.isEmpty() && craftMatrix.getItem(slot).isEmpty()) { UtilInventory.extractItem(new PlayerMainInvWrapper(player.getInventory()), itemStackMatcher, 1, false); - //make sure to add the real item after the nonsimulated withdrawl is complete https://github.com/PrinceOfAmber/Storage-Network/issues/16 craftMatrix.setItem(slot, ex); break; } - /********* now find it from the network ***/ stackCurrent = main.request(!stackCurrent.isEmpty() ? itemStackMatcher : null, 1, false); if (!stackCurrent.isEmpty() && craftMatrix.getItem(slot).isEmpty()) { craftMatrix.setItem(slot, stackCurrent); break; } } - /************** finished recipe population **/ - // } - //now make sure client sync happens. ctr.slotChanged(); List list = main.getNetwork().getStacks(); - PacketRegistry.INSTANCE.sendTo(new StackRefreshClientMessage(list, new ArrayList<>()), - player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); - } //end run + PacketDistributor.sendToPlayer(player, new StackRefreshClientMessage(list, new ArrayList<>())); + } }); - ctx.get().setPacketHandled(true); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/RefreshFilterClientMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/RefreshFilterClientMessage.java index d62e3d33..ba30d542 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/RefreshFilterClientMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/RefreshFilterClientMessage.java @@ -2,37 +2,61 @@ import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.cable.export.ScreenCableExportFilter; import com.lothrazar.storagenetwork.block.cable.inputfilter.ScreenCableImportFilter; import com.lothrazar.storagenetwork.block.cable.linkfilter.ScreenCableFilter; import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; -/** - * Refresh the current screen with large data set of stacks. - *

- * Used by Containers displaying network inventory as well as most other packets that perform small actions - */ @SuppressWarnings("resource") -public class RefreshFilterClientMessage { +public class RefreshFilterClientMessage implements CustomPacketPayload { - private int size; - private List stacks; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "refresh_filter_client")); - private RefreshFilterClientMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + RefreshFilterClientMessage::write, + RefreshFilterClientMessage::read + ); + + private final List stacks; public RefreshFilterClientMessage(List stacks) { - super(); this.stacks = stacks; - size = stacks.size(); } - public static void handle(RefreshFilterClientMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - //TODO: optimize with base class or interface + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } + + private static void write(RegistryFriendlyByteBuf buf, RefreshFilterClientMessage msg) { + buf.writeInt(msg.stacks.size()); + for (ItemStack stack : msg.stacks) { + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, stack); + buf.writeInt(stack.getCount()); + } + } + + private static RefreshFilterClientMessage read(RegistryFriendlyByteBuf buf) { + int size = buf.readInt(); + List stacks = new ArrayList<>(); + for (int i = 0; i < size; i++) { + ItemStack stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); + stack.setCount(buf.readInt()); + stacks.add(stack); + } + return new RefreshFilterClientMessage(stacks); + } + + public static void handle(RefreshFilterClientMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { if (Minecraft.getInstance().screen instanceof ScreenCableFilter) { ScreenCableFilter gui = (ScreenCableFilter) Minecraft.getInstance().screen; gui.setFilterItems(message.stacks); @@ -46,26 +70,5 @@ public static void handle(RefreshFilterClientMessage message, Supplier(); - for (int i = 0; i < message.size; i++) { - ItemStack stack = ItemStack.of(buf.readNbt()); - stack.setCount(buf.readInt()); - message.stacks.add(stack); - } - return message; - } - - public static void encode(RefreshFilterClientMessage msg, FriendlyByteBuf buf) { - buf.writeInt(msg.size); - for (ItemStack stack : msg.stacks) { - buf.writeNbt(stack.serializeNBT()); - buf.writeInt(stack.getCount()); - } } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/RequestMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/RequestMessage.java index 43960317..78668493 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/RequestMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/RequestMessage.java @@ -2,47 +2,79 @@ import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.block.main.TileMain; import com.lothrazar.storagenetwork.capability.handler.ItemStackMatcher; import com.lothrazar.storagenetwork.gui.ContainerNetwork; -import com.lothrazar.storagenetwork.registry.PacketRegistry; import com.lothrazar.storagenetwork.util.UtilTileEntity; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class RequestMessage { +public class RequestMessage implements CustomPacketPayload { - private int mouseButton = 0; - private ItemStack stack = ItemStack.EMPTY; - private boolean shift; - private boolean ctrl; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "request")); - @Override - public String toString() { - return "RequestMessage [mouseButton=" + mouseButton + ", shift=" + shift + ", ctrl=" + ctrl + ", stack=" + stack.toString() + "]"; - } + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + RequestMessage::write, + RequestMessage::read + ); - public RequestMessage() {} + private final int mouseButton; + private final ItemStack stack; + private final boolean shift; + private final boolean ctrl; + + public RequestMessage() { + this(0, ItemStack.EMPTY, false, false); + } public RequestMessage(int id, ItemStack stackIn, boolean shift, boolean ctrl) { - mouseButton = id; - this.stack = stackIn.copy(); - if (this.stack.getCount() > 64) { - this.stack.setCount(64); //important or it will be killed by a filter + this.mouseButton = id; + ItemStack s = stackIn.copy(); + if (s.getCount() > 64) { + s.setCount(64); } + this.stack = s; this.shift = shift; this.ctrl = ctrl; } - public static void handle(RequestMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } + + @Override + public String toString() { + return "RequestMessage [mouseButton=" + mouseButton + ", shift=" + shift + ", ctrl=" + ctrl + ", stack=" + stack.toString() + "]"; + } + + private static void write(RegistryFriendlyByteBuf buf, RequestMessage msg) { + buf.writeInt(msg.mouseButton); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, msg.stack); + buf.writeBoolean(msg.shift); + buf.writeBoolean(msg.ctrl); + } + + private static RequestMessage read(RegistryFriendlyByteBuf buf) { + int mouseButton = buf.readInt(); + ItemStack stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); + boolean shift = buf.readBoolean(); + boolean ctrl = buf.readBoolean(); + return new RequestMessage(mouseButton, stack, shift, ctrl); + } + + public static void handle(RequestMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); TileMain root = null; ContainerNetwork ctr = null; if (player.containerMenu instanceof ContainerNetwork) { @@ -53,7 +85,6 @@ public static void handle(RequestMessage message, Supplier StorageNetworkMod.log("Bad container"); } if (root == null) { - //maybe the table broke after doing this, rare case StorageNetworkMod.log("Request message cancelled, null tile"); return; } @@ -72,51 +103,22 @@ else if (isRightClick) { sizeRequested = Math.min(message.stack.getMaxStackSize() / 2, in / 2); } sizeRequested = Math.max(sizeRequested, 1); - boolean ore = false; - boolean nbt = true; - //try NBT first - stack = root.request( - new ItemStackMatcher(message.stack, ore, nbt), - sizeRequested, false); + stack = root.request(new ItemStackMatcher(message.stack, false, true), sizeRequested, false); if (stack.isEmpty()) { - //try again with NBT as false, ONLY if true didnt work - nbt = false; - stack = root.request( - new ItemStackMatcher(message.stack, ore, nbt), - sizeRequested, false); + stack = root.request(new ItemStackMatcher(message.stack, false, false), sizeRequested, false); } if (!stack.isEmpty()) { if (message.shift) { ItemHandlerHelper.giveItemToPlayer(player, stack); } else { - //when player TAKES an item, go here player.containerMenu.setCarried(stack); - PacketRegistry.INSTANCE.sendTo(new StackResponseClientMessage(stack), - player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(player, new StackResponseClientMessage(stack)); } } List list = root.getNetwork().getSortedStacks(); - PacketRegistry.INSTANCE.sendTo(new StackRefreshClientMessage(list, new ArrayList<>()), - player.connection.connection, NetworkDirection.PLAY_TO_CLIENT); + PacketDistributor.sendToPlayer(player, new StackRefreshClientMessage(list, new ArrayList<>())); player.containerMenu.broadcastChanges(); }); - ctx.get().setPacketHandled(true); - } - - public static RequestMessage decode(FriendlyByteBuf buf) { - RequestMessage msg = new RequestMessage(); - msg.mouseButton = buf.readInt(); - msg.stack = ItemStack.of(buf.readNbt()); - msg.shift = buf.readBoolean(); - msg.ctrl = buf.readBoolean(); - return msg; - } - - public static void encode(RequestMessage msg, FriendlyByteBuf buf) { - buf.writeInt(msg.mouseButton); - buf.writeNbt(msg.stack.serializeNBT()); - buf.writeBoolean(msg.shift); - buf.writeBoolean(msg.ctrl); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/SettingsSyncMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/SettingsSyncMessage.java index 96e6018d..961d79da 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/SettingsSyncMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/SettingsSyncMessage.java @@ -1,28 +1,37 @@ package com.lothrazar.storagenetwork.network; -import java.util.function.Supplier; +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.api.EnumSortType; import com.lothrazar.storagenetwork.api.ITileNetworkSync; import com.lothrazar.storagenetwork.item.remote.ContainerNetworkCraftingRemote; import com.lothrazar.storagenetwork.item.remote.ContainerNetworkRemote; import com.lothrazar.storagenetwork.item.remote.ItemRemote; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SettingsSyncMessage { +public class SettingsSyncMessage implements CustomPacketPayload { - private BlockPos pos; - private boolean direction; - private EnumSortType sort; - private boolean targetTileEntity; - private boolean jeiSync; - private boolean autoFocus; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "settings_sync")); - private SettingsSyncMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + SettingsSyncMessage::write, + SettingsSyncMessage::read + ); + + private final BlockPos pos; + private final boolean direction; + private final EnumSortType sort; + private final boolean targetTileEntity; + private final boolean jeiSync; + private final boolean autoFocus; public SettingsSyncMessage(BlockPos pos, boolean direction, EnumSortType sort, boolean jeiSync, boolean autoFocus) { this.pos = pos; @@ -30,12 +39,42 @@ public SettingsSyncMessage(BlockPos pos, boolean direction, EnumSortType sort, b this.sort = sort; this.jeiSync = jeiSync; this.autoFocus = autoFocus; + this.targetTileEntity = (pos != null); + } + + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void handle(SettingsSyncMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - ServerPlayer player = ctx.get().getSender(); - //TODO: how to refactor this + private static void write(RegistryFriendlyByteBuf buf, SettingsSyncMessage msg) { + buf.writeBoolean(msg.direction); + buf.writeInt(msg.sort.ordinal()); + if (msg.pos != null) { + buf.writeBoolean(true); + buf.writeBlockPos(msg.pos); + } + else { + buf.writeBoolean(false); + buf.writeBlockPos(BlockPos.ZERO); + } + buf.writeBoolean(msg.jeiSync); + buf.writeBoolean(msg.autoFocus); + } + + private static SettingsSyncMessage read(RegistryFriendlyByteBuf buf) { + boolean direction = buf.readBoolean(); + EnumSortType sort = EnumSortType.values()[buf.readInt()]; + boolean hasPos = buf.readBoolean(); + BlockPos pos = buf.readBlockPos(); + boolean jeiSync = buf.readBoolean(); + boolean autoFocus = buf.readBoolean(); + return new SettingsSyncMessage(hasPos ? pos : null, direction, sort, jeiSync, autoFocus); + } + + public static void handle(SettingsSyncMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + ServerPlayer player = (ServerPlayer) ctx.player(); if (message.targetTileEntity) { BlockEntity tileEntity = player.level().getBlockEntity(message.pos); if (tileEntity instanceof ITileNetworkSync) { @@ -66,33 +105,5 @@ else if (player.containerMenu instanceof ContainerNetworkRemote rcc) { } } }); - ctx.get().setPacketHandled(true); - } - - public static SettingsSyncMessage decode(FriendlyByteBuf buf) { - SettingsSyncMessage message = new SettingsSyncMessage(); - message.direction = buf.readBoolean(); - int sort = buf.readInt(); - message.sort = EnumSortType.values()[sort]; - message.targetTileEntity = buf.readBoolean(); - message.pos = buf.readBlockPos(); - message.jeiSync = buf.readBoolean(); - message.autoFocus = buf.readBoolean(); - return message; - } - - public static void encode(SettingsSyncMessage msg, FriendlyByteBuf buf) { - buf.writeBoolean(msg.direction); - buf.writeInt(msg.sort.ordinal()); - if (msg.pos != null) { - buf.writeBoolean(true); - buf.writeBlockPos(msg.pos); - } - else { // to avoid null values // inconsistent buffer size - buf.writeBoolean(false); - buf.writeBlockPos(BlockPos.ZERO); - } - buf.writeBoolean(msg.jeiSync); - buf.writeBoolean(msg.autoFocus); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/SortClientMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/SortClientMessage.java index dc8207fc..3f3c9ecc 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/SortClientMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/SortClientMessage.java @@ -1,31 +1,57 @@ package com.lothrazar.storagenetwork.network; -import java.util.function.Supplier; +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.api.EnumSortType; import com.lothrazar.storagenetwork.api.ITileNetworkSync; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SortClientMessage { +public class SortClientMessage implements CustomPacketPayload { - //sync sort data TO client gui FROM server - private BlockPos pos; - private boolean direction; - private EnumSortType sort; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "sort_client")); - private SortClientMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + SortClientMessage::write, + SortClientMessage::read + ); + + private final BlockPos pos; + private final boolean direction; + private final EnumSortType sort; public SortClientMessage(BlockPos pos, boolean direction, EnumSortType sort) { - this.pos = pos; + this.pos = pos != null ? pos : BlockPos.ZERO; this.direction = direction; this.sort = sort; } - public static void handle(SortClientMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { + @Override + public CustomPacketPayload.Type type() { + return TYPE; + } + + private static void write(RegistryFriendlyByteBuf buf, SortClientMessage msg) { + buf.writeBoolean(msg.direction); + buf.writeInt(msg.sort.ordinal()); + buf.writeBlockPos(msg.pos); + } + + private static SortClientMessage read(RegistryFriendlyByteBuf buf) { + boolean direction = buf.readBoolean(); + EnumSortType sort = EnumSortType.values()[buf.readInt()]; + BlockPos pos = buf.readBlockPos(); + return new SortClientMessage(pos, direction, sort); + } + + public static void handle(SortClientMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { Minecraft mc = Minecraft.getInstance(); BlockEntity tileEntity = mc.level.getBlockEntity(message.pos); if (tileEntity instanceof ITileNetworkSync) { @@ -35,26 +61,5 @@ public static void handle(SortClientMessage message, Supplier TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "stack_refresh_client")); + + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + StackRefreshClientMessage::write, + StackRefreshClientMessage::read + ); - private final int size; - private final int csize; private final List stacks; private final List craftableStacks; public StackRefreshClientMessage(List stacks, List craftableStacks) { - super(); this.stacks = stacks; this.craftableStacks = craftableStacks; - size = stacks.size(); - csize = craftableStacks.size(); } - public static void handle(StackRefreshClientMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - Minecraft mc = Minecraft.getInstance(); - if (mc.screen instanceof IGuiNetwork) { - IGuiNetwork gui = (IGuiNetwork) mc.screen; - gui.setStacks(message.stacks); - } - }); - ctx.get().setPacketHandled(true); + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static void encode(StackRefreshClientMessage msg, FriendlyByteBuf buf) { - buf.writeInt(msg.size); - buf.writeInt(msg.csize); + private static void write(RegistryFriendlyByteBuf buf, StackRefreshClientMessage msg) { + buf.writeInt(msg.stacks.size()); + buf.writeInt(msg.craftableStacks.size()); for (ItemStack stack : msg.stacks) { - buf.writeNbt(stack.serializeNBT()); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, stack); buf.writeInt(stack.getCount()); } for (ItemStack stack : msg.craftableStacks) { - buf.writeNbt(stack.serializeNBT()); + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, stack); buf.writeInt(stack.getCount()); } } - public static StackRefreshClientMessage decode(FriendlyByteBuf buf) { + private static StackRefreshClientMessage read(RegistryFriendlyByteBuf buf) { int size = buf.readInt(); int csize = buf.readInt(); - List stacks = Lists.newArrayList(); + List stacks = new ArrayList<>(); for (int i = 0; i < size; i++) { - CompoundTag stacktag = buf.readNbt(); - ItemStack stack = ItemStack.of(stacktag); + ItemStack stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); stack.setCount(buf.readInt()); stacks.add(stack); } - List craftableStacks = Lists.newArrayList(); + List craftableStacks = new ArrayList<>(); for (int i = 0; i < csize; i++) { - ItemStack stack = ItemStack.of(buf.readNbt()); + ItemStack stack = ItemStack.OPTIONAL_STREAM_CODEC.decode(buf); stack.setCount(buf.readInt()); craftableStacks.add(stack); } return new StackRefreshClientMessage(stacks, craftableStacks); } + + public static void handle(StackRefreshClientMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + Minecraft mc = Minecraft.getInstance(); + if (mc.screen instanceof IGuiNetwork) { + IGuiNetwork gui = (IGuiNetwork) mc.screen; + gui.setStacks(message.stacks); + } + }); + } } diff --git a/src/main/java/com/lothrazar/storagenetwork/network/StackResponseClientMessage.java b/src/main/java/com/lothrazar/storagenetwork/network/StackResponseClientMessage.java index 0bfd61bb..4005fa0e 100644 --- a/src/main/java/com/lothrazar/storagenetwork/network/StackResponseClientMessage.java +++ b/src/main/java/com/lothrazar/storagenetwork/network/StackResponseClientMessage.java @@ -1,40 +1,46 @@ package com.lothrazar.storagenetwork.network; -import java.util.function.Supplier; +import com.lothrazar.storagenetwork.StorageNetworkMod; import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; -/** - * Used by InsertMessage and RequestMessage as a response back to the client - * - * - */ -public class StackResponseClientMessage { +public class StackResponseClientMessage implements CustomPacketPayload { - private ItemStack stack; + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "stack_response_client")); - private StackResponseClientMessage() {} + public static final StreamCodec STREAM_CODEC = StreamCodec.of( + StackResponseClientMessage::write, + StackResponseClientMessage::read + ); - StackResponseClientMessage(ItemStack a) { - stack = a; + private final ItemStack stack; + + public StackResponseClientMessage(ItemStack stack) { + this.stack = stack; } - public static void handle(StackResponseClientMessage message, Supplier ctx) { - ctx.get().enqueueWork(() -> { - Minecraft.getInstance().player.containerMenu.setCarried(message.stack); // .setCarried(message.stack); - }); - ctx.get().setPacketHandled(true); + @Override + public CustomPacketPayload.Type type() { + return TYPE; } - public static StackResponseClientMessage decode(FriendlyByteBuf buf) { - StackResponseClientMessage message = new StackResponseClientMessage(); - message.stack = ItemStack.of(buf.readNbt()); - return message; + private static void write(RegistryFriendlyByteBuf buf, StackResponseClientMessage msg) { + ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, msg.stack); } - public static void encode(StackResponseClientMessage msg, FriendlyByteBuf buf) { - buf.writeNbt(msg.stack.serializeNBT()); + private static StackResponseClientMessage read(RegistryFriendlyByteBuf buf) { + return new StackResponseClientMessage(ItemStack.OPTIONAL_STREAM_CODEC.decode(buf)); + } + + public static void handle(StackResponseClientMessage message, IPayloadContext ctx) { + ctx.enqueueWork(() -> { + Minecraft.getInstance().player.containerMenu.setCarried(message.stack); + }); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/ClientEventRegistry.java b/src/main/java/com/lothrazar/storagenetwork/registry/ClientEventRegistry.java index e68f5aec..b58d2f04 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/ClientEventRegistry.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/ClientEventRegistry.java @@ -7,16 +7,13 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyMapping; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.client.settings.KeyConflictContext; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.client.event.EntityRenderersEvent; +import net.neoforged.neoforge.client.settings.KeyConflictContext; -@Mod.EventBusSubscriber(value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) public class ClientEventRegistry { - public static final ResourceLocation SLOT = new ResourceLocation(StorageNetworkMod.MODID, "textures/gui/slot.png"); + public static final ResourceLocation SLOT = ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "textures/gui/slot.png"); public static final KeyMapping INVENTORY_KEY = new KeyMapping("key.storagenetwork.remote", KeyConflictContext.UNIVERSAL, InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_I, "key.categories.inventory"); public static final KeyMapping COLLECTOR_TOGGLE_KEY = new KeyMapping("key.storagenetwork.collector_toggle", KeyConflictContext.UNIVERSAL, InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_DELETE, "key.categories.inventory"); diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/ConfigRegistry.java b/src/main/java/com/lothrazar/storagenetwork/registry/ConfigRegistry.java index 47c9b148..f3c1415d 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/ConfigRegistry.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/ConfigRegistry.java @@ -1,25 +1,22 @@ package com.lothrazar.storagenetwork.registry; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import com.electronwill.nightconfig.core.file.CommentedFileConfig; -import com.electronwill.nightconfig.core.io.WritingMode; import com.lothrazar.library.util.StringParseUtil; import com.lothrazar.storagenetwork.StorageNetworkMod; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; -import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; -import net.minecraftforge.common.ForgeConfigSpec.IntValue; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.ModConfigSpec; +import net.neoforged.neoforge.common.ModConfigSpec.BooleanValue; +import net.neoforged.neoforge.common.ModConfigSpec.ConfigValue; +import net.neoforged.neoforge.common.ModConfigSpec.IntValue; public class ConfigRegistry { - private static final ForgeConfigSpec.Builder COMMON_BUILDER = new ForgeConfigSpec.Builder(); - private static ForgeConfigSpec COMMON_CONFIG; + private static final ModConfigSpec.Builder COMMON_BUILDER = new ModConfigSpec.Builder(); + public static ModConfigSpec COMMON_CONFIG; private static BooleanValue LOGSPAM; private static IntValue REFRESHTICKS; public static IntValue EXCHANGEBUFFER; @@ -34,7 +31,7 @@ public class ConfigRegistry { } public static boolean isFacadeAllowed(ItemStack item) { - ResourceLocation itemId = ForgeRegistries.ITEMS.getKey(item.getItem()); + ResourceLocation itemId = BuiltInRegistries.ITEM.getKey(item.getItem()); if (StringParseUtil.isInList(CABLEIGNORELIST.get(), itemId)) { return false; } @@ -85,14 +82,7 @@ private static void initConfig() { COMMON_CONFIG = COMMON_BUILDER.build(); } - public ConfigRegistry(Path path) { - final CommentedFileConfig configData = CommentedFileConfig.builder(path) - .sync() - .autosave() - .writingMode(WritingMode.REPLACE) - .build(); - configData.load(); - COMMON_CONFIG.setConfig(configData); + public ConfigRegistry() { } public boolean logspam() { diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/PacketRegistry.java b/src/main/java/com/lothrazar/storagenetwork/registry/PacketRegistry.java index d113bc44..40677938 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/PacketRegistry.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/PacketRegistry.java @@ -2,39 +2,27 @@ import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.network.*; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.simple.SimpleChannel; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; public class PacketRegistry { - private static final String PROTOCOL_VERSION = Integer.toString(1); - //??https://wiki.mcjty.eu/modding/index.php?title=Tut14_Ep10 - public static final SimpleChannel INSTANCE = NetworkRegistry.ChannelBuilder - .named(new ResourceLocation(StorageNetworkMod.MODID, "main_channel")) - .clientAcceptedVersions(PROTOCOL_VERSION::equals) - .serverAcceptedVersions(PROTOCOL_VERSION::equals) - .networkProtocolVersion(() -> PROTOCOL_VERSION) - .simpleChannel(); - - public static void init() { - //https://gist.github.com/williewillus/353c872bcf1a6ace9921189f6100d09a - int id = 0; - INSTANCE.registerMessage(id++, CableDataMessage.class, CableDataMessage::encode, CableDataMessage::decode, CableDataMessage::handle); - INSTANCE.registerMessage(id++, CableIOMessage.class, CableIOMessage::encode, CableIOMessage::decode, CableIOMessage::handle); - INSTANCE.registerMessage(id++, StackRefreshClientMessage.class, StackRefreshClientMessage::encode, StackRefreshClientMessage::decode, StackRefreshClientMessage::handle); - INSTANCE.registerMessage(id++, InsertMessage.class, InsertMessage::encode, InsertMessage::decode, InsertMessage::handle); - INSTANCE.registerMessage(id++, RequestMessage.class, RequestMessage::encode, RequestMessage::decode, RequestMessage::handle); - INSTANCE.registerMessage(id++, ClearRecipeMessage.class, ClearRecipeMessage::encode, ClearRecipeMessage::decode, ClearRecipeMessage::handle); - INSTANCE.registerMessage(id++, SettingsSyncMessage.class, SettingsSyncMessage::encode, SettingsSyncMessage::decode, SettingsSyncMessage::handle); - INSTANCE.registerMessage(id++, RecipeMessage.class, RecipeMessage::encode, RecipeMessage::decode, RecipeMessage::handle); - id++; // INSTANCE.registerMessage(id++, CableFilterMessage.class, CableFilterMessage::encode, CableFilterMessage::decode, CableFilterMessage::handle); - INSTANCE.registerMessage(id++, CableLimitMessage.class, CableLimitMessage::encode, CableLimitMessage::decode, CableLimitMessage::handle); - INSTANCE.registerMessage(id++, StackResponseClientMessage.class, StackResponseClientMessage::encode, StackResponseClientMessage::decode, StackResponseClientMessage::handle); - INSTANCE.registerMessage(id++, RefreshFilterClientMessage.class, RefreshFilterClientMessage::encode, RefreshFilterClientMessage::decode, RefreshFilterClientMessage::handle); - INSTANCE.registerMessage(id++, SortClientMessage.class, SortClientMessage::encode, SortClientMessage::decode, SortClientMessage::handle); - INSTANCE.registerMessage(id++, KeybindCurioMessage.class, KeybindCurioMessage::encode, KeybindCurioMessage::decode, KeybindCurioMessage::handle); - INSTANCE.registerMessage(id++, KeybindCollectorToggleMessage.class, KeybindCollectorToggleMessage::encode, KeybindCollectorToggleMessage::decode, KeybindCollectorToggleMessage::handle); - INSTANCE.registerMessage(id++, CableFacadeMessage.class, CableFacadeMessage::encode, CableFacadeMessage::decode, CableFacadeMessage::handle); + public static void registerPayloads(RegisterPayloadHandlersEvent event) { + PayloadRegistrar reg = event.registrar(StorageNetworkMod.MODID); + reg.playToServer(CableDataMessage.TYPE, CableDataMessage.STREAM_CODEC, CableDataMessage::handle); + reg.playToServer(CableIOMessage.TYPE, CableIOMessage.STREAM_CODEC, CableIOMessage::handle); + reg.playToServer(InsertMessage.TYPE, InsertMessage.STREAM_CODEC, InsertMessage::handle); + reg.playToServer(RequestMessage.TYPE, RequestMessage.STREAM_CODEC, RequestMessage::handle); + reg.playToServer(ClearRecipeMessage.TYPE, ClearRecipeMessage.STREAM_CODEC, ClearRecipeMessage::handle); + reg.playToServer(SettingsSyncMessage.TYPE, SettingsSyncMessage.STREAM_CODEC, SettingsSyncMessage::handle); + reg.playToServer(RecipeMessage.TYPE, RecipeMessage.STREAM_CODEC, RecipeMessage::handle); + reg.playToServer(CableLimitMessage.TYPE, CableLimitMessage.STREAM_CODEC, CableLimitMessage::handle); + reg.playToServer(CableFacadeMessage.TYPE, CableFacadeMessage.STREAM_CODEC, CableFacadeMessage::handle); + reg.playToServer(KeybindCurioMessage.TYPE, KeybindCurioMessage.STREAM_CODEC, KeybindCurioMessage::handle); + reg.playToServer(KeybindCollectorToggleMessage.TYPE, KeybindCollectorToggleMessage.STREAM_CODEC, KeybindCollectorToggleMessage::handle); + reg.playToClient(StackRefreshClientMessage.TYPE, StackRefreshClientMessage.STREAM_CODEC, StackRefreshClientMessage::handle); + reg.playToClient(StackResponseClientMessage.TYPE, StackResponseClientMessage.STREAM_CODEC, StackResponseClientMessage::handle); + reg.playToClient(RefreshFilterClientMessage.TYPE, RefreshFilterClientMessage.STREAM_CODEC, RefreshFilterClientMessage::handle); + reg.playToClient(SortClientMessage.TYPE, SortClientMessage.STREAM_CODEC, SortClientMessage::handle); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/SsnEvents.java b/src/main/java/com/lothrazar/storagenetwork/registry/SsnEvents.java index e51d03f0..b6efbbcf 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/SsnEvents.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/SsnEvents.java @@ -6,6 +6,7 @@ import com.lothrazar.storagenetwork.network.CableFacadeMessage; import com.lothrazar.storagenetwork.network.KeybindCollectorToggleMessage; import com.lothrazar.storagenetwork.network.KeybindCurioMessage; +import net.neoforged.neoforge.network.PacketDistributor; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.world.entity.player.Player; @@ -16,15 +17,15 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import net.neoforged.neoforge.event.entity.player.ItemEntityPickupEvent; public class SsnEvents { @SubscribeEvent - public void onEntityItemPickupEvent(EntityItemPickupEvent event) { + public void onEntityItemPickupEvent(ItemEntityPickupEvent.Pre event) { SsnRegistry.Items.COLLECTOR_REMOTE.get().onEntityItemPickupEvent(event); } @@ -49,7 +50,7 @@ private void onHitFacadeHandler(PlayerInteractEvent.LeftClickBlock event) { TileCable cable = TileCable.getTileCable(level, event.getPos()); if (cable != null) { if (held.isEmpty()) { - PacketRegistry.INSTANCE.sendToServer(new CableFacadeMessage(event.getPos(), true)); + PacketDistributor.sendToServer(new CableFacadeMessage(event.getPos(), true)); } else { Block block = Block.byItem(held.getItem()); if (block == null || block == Blocks.AIR) { @@ -61,11 +62,11 @@ private void onHitFacadeHandler(PlayerInteractEvent.LeftClickBlock event) { } //pick the block, write to tags, and send to server boolean pickFluids = false; - BlockHitResult bhr = (BlockHitResult) player.pick(player.getBlockReach(), 1, pickFluids); + BlockHitResult bhr = (BlockHitResult) player.pick(player.blockInteractionRange(), 1, pickFluids); BlockPlaceContext context = new BlockPlaceContext(player, event.getHand(), held, bhr); BlockState facadeState = block.getStateForPlacement(context); CompoundTag tags = (facadeState == null) ? null : NbtUtils.writeBlockState(facadeState); - PacketRegistry.INSTANCE.sendToServer(new CableFacadeMessage(event.getPos(), tags)); + PacketDistributor.sendToServer(new CableFacadeMessage(event.getPos(), tags)); } } } @@ -73,11 +74,11 @@ private void onHitFacadeHandler(PlayerInteractEvent.LeftClickBlock event) { @SubscribeEvent public void onKeyInput(InputEvent.Key event) { if (ClientEventRegistry.INVENTORY_KEY.consumeClick()) { - PacketRegistry.INSTANCE.sendToServer(new KeybindCurioMessage()); + PacketDistributor.sendToServer(new KeybindCurioMessage()); } if (ClientEventRegistry.COLLECTOR_TOGGLE_KEY.consumeClick()) { - PacketRegistry.INSTANCE.sendToServer(new KeybindCollectorToggleMessage()); + PacketDistributor.sendToServer(new KeybindCollectorToggleMessage()); } } } diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/SsnRegistry.java b/src/main/java/com/lothrazar/storagenetwork/registry/SsnRegistry.java index 8701de38..37095837 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/SsnRegistry.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/SsnRegistry.java @@ -42,121 +42,126 @@ import com.lothrazar.storagenetwork.item.remote.ContainerNetworkExpandedRemote; import com.lothrazar.storagenetwork.item.remote.ContainerNetworkRemote; import com.lothrazar.storagenetwork.item.remote.ItemRemote; +import net.minecraft.core.registries.Registries; import net.minecraft.world.inventory.MenuType; 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.entity.BlockEntityType; -import net.minecraftforge.common.extensions.IForgeMenuType; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.common.extensions.IMenuTypeExtension; +import net.neoforged.neoforge.registries.DeferredBlock; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredItem; +import net.neoforged.neoforge.registries.DeferredRegister; public class SsnRegistry { - public static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, StorageNetworkMod.MODID); - public static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, StorageNetworkMod.MODID); - public static final DeferredRegister> TILES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, StorageNetworkMod.MODID); - public static final DeferredRegister> CONTAINERS = DeferredRegister.create(ForgeRegistries.MENU_TYPES, StorageNetworkMod.MODID); + public static final DeferredRegister.Blocks BLOCKS = DeferredRegister.createBlocks(StorageNetworkMod.MODID); + public static final DeferredRegister.Items ITEMS = DeferredRegister.createItems(StorageNetworkMod.MODID); + public static final DeferredRegister> TILES = DeferredRegister.create(Registries.BLOCK_ENTITY_TYPE, StorageNetworkMod.MODID); + public static final DeferredRegister> CONTAINERS = DeferredRegister.create(Registries.MENU, StorageNetworkMod.MODID); - @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public static class Blocks { - public static final RegistryObject REQUEST = BLOCKS.register("request", () -> new BlockRequest()); - public static final RegistryObject KABEL = BLOCKS.register("kabel", () -> new BlockCable()); - public static final RegistryObject MASTER = BLOCKS.register("master", () -> new BlockMain()); - public static final RegistryObject STORAGE_KABEL = BLOCKS.register("storage_kabel", () -> new BlockCableLink()); - public static final RegistryObject IMPORT_KABEL = BLOCKS.register("import_kabel", () -> new BlockCableIO()); - public static final RegistryObject IMPORT_FILTER_KABEL = BLOCKS.register("import_filter_kabel", () -> new BlockCableImportFilter()); - public static final RegistryObject FILTER_KABEL = BLOCKS.register("filter_kabel", () -> new BlockCableFilter()); - public static final RegistryObject EXPORT_KABEL = BLOCKS.register("export_kabel", () -> new BlockCableExport()); - public static final RegistryObject PROCESS_KABEL = BLOCKS.register("process_kabel", () -> new BlockCableProcess()); - public static final RegistryObject INVENTORY = BLOCKS.register("inventory", () -> new BlockInventory()); - public static final RegistryObject REQUEST_EXPANDED = BLOCKS.register("request_expanded", () -> new BlockInventoryExpanded()); - public static final RegistryObject EXCHANGE = BLOCKS.register("exchange", () -> new BlockExchange()); - public static final RegistryObject COLLECTOR = BLOCKS.register("collector", () -> new BlockCollection()); + public static void init() {} + + public static final DeferredBlock REQUEST = BLOCKS.register("request", () -> new BlockRequest()); + public static final DeferredBlock KABEL = BLOCKS.register("kabel", () -> new BlockCable()); + public static final DeferredBlock MASTER = BLOCKS.register("master", () -> new BlockMain()); + public static final DeferredBlock STORAGE_KABEL = BLOCKS.register("storage_kabel", () -> new BlockCableLink()); + public static final DeferredBlock IMPORT_KABEL = BLOCKS.register("import_kabel", () -> new BlockCableIO()); + public static final DeferredBlock IMPORT_FILTER_KABEL = BLOCKS.register("import_filter_kabel", () -> new BlockCableImportFilter()); + public static final DeferredBlock FILTER_KABEL = BLOCKS.register("filter_kabel", () -> new BlockCableFilter()); + public static final DeferredBlock EXPORT_KABEL = BLOCKS.register("export_kabel", () -> new BlockCableExport()); + public static final DeferredBlock PROCESS_KABEL = BLOCKS.register("process_kabel", () -> new BlockCableProcess()); + public static final DeferredBlock INVENTORY = BLOCKS.register("inventory", () -> new BlockInventory()); + public static final DeferredBlock REQUEST_EXPANDED = BLOCKS.register("request_expanded", () -> new BlockInventoryExpanded()); + public static final DeferredBlock EXCHANGE = BLOCKS.register("exchange", () -> new BlockExchange()); + public static final DeferredBlock COLLECTOR = BLOCKS.register("collector", () -> new BlockCollection()); } - @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public static class Items { - public static final RegistryObject REQUEST = ITEMS.register("request", () -> new BlockItem(Blocks.REQUEST.get(), new Item.Properties())); - public static final RegistryObject KABEL = ITEMS.register("kabel", () -> new BlockItem(Blocks.KABEL.get(), new Item.Properties())); - public static final RegistryObject INVENTORY = ITEMS.register("inventory", () -> new BlockItem(Blocks.INVENTORY.get(), new Item.Properties())); - public static final RegistryObject REQUEST_EXPANDED = ITEMS.register("request_expanded", () -> new BlockItem(Blocks.REQUEST_EXPANDED.get(), new Item.Properties())); - public static final RegistryObject MAS = ITEMS.register("master", () -> new BlockItem(Blocks.MASTER.get(), new Item.Properties())); - public static final RegistryObject SK = ITEMS.register("storage_kabel", () -> new BlockItem(Blocks.STORAGE_KABEL.get(), new Item.Properties())); - public static final RegistryObject IK = ITEMS.register("import_kabel", () -> new BlockItem(Blocks.IMPORT_KABEL.get(), new Item.Properties())); - public static final RegistryObject IFK = ITEMS.register("import_filter_kabel", () -> new BlockItem(Blocks.IMPORT_FILTER_KABEL.get(), new Item.Properties())); - public static final RegistryObject FK = ITEMS.register("filter_kabel", () -> new BlockItem(Blocks.FILTER_KABEL.get(), new Item.Properties())); - public static final RegistryObject EK = ITEMS.register("export_kabel", () -> new BlockItem(Blocks.EXPORT_KABEL.get(), new Item.Properties())); - // public static final RegistryObject PK = ITEMS.register("process_kabel", () -> new BlockItem(Blocks.PROCESS_KABEL.get(), new Item.Properties())); - public static final RegistryObject EXCHANGE = ITEMS.register("exchange", () -> new BlockItem(Blocks.EXCHANGE.get(), new Item.Properties())); - public static final RegistryObject COL = ITEMS.register("collector", () -> new BlockItem(Blocks.COLLECTOR.get(), new Item.Properties())); - public static final RegistryObject STACK_UPGRADE = ITEMS.register("stack_upgrade", () -> new ItemUpgrade(new Item.Properties())); - public static final RegistryObject SPEED_UPGRADE = ITEMS.register("speed_upgrade", () -> new ItemUpgrade(new Item.Properties())); - public static final RegistryObject SLOW_UPGRADE = ITEMS.register("slow_upgrade", () -> new ItemUpgrade(new Item.Properties())); - public static final RegistryObject STOCK_UPGRADE = ITEMS.register("stock_upgrade", () -> new ItemUpgrade(new Item.Properties())); - public static final RegistryObject OP_U = ITEMS.register("operation_upgrade", () -> new ItemUpgrade(new Item.Properties())); - public static final RegistryObject SINGLE_UPGRADE = ITEMS.register("single_upgrade", () -> new ItemUpgrade(new Item.Properties())); - public static final RegistryObject INVENTORY_REMOTE = ITEMS.register("inventory_remote", () -> new ItemRemote(new Item.Properties())); - public static final RegistryObject CRAFTING_REMOTE = ITEMS.register("crafting_remote", () -> new ItemRemote(new Item.Properties())); - public static final RegistryObject PICKER_REMOTE = ITEMS.register("picker_remote", () -> new ItemPicker(new Item.Properties())); - public static final RegistryObject COLLECTOR_REMOTE = ITEMS.register("collector_remote", () -> new ItemCollector(new Item.Properties())); - public static final RegistryObject BUILDER_REMOTE = ITEMS.register("builder_remote", () -> new ItemBuilder(new Item.Properties())); - public static final RegistryObject EXPANDED_REMOTE = ITEMS.register("expanded_remote", () -> new ItemRemote(new Item.Properties())); + public static void init() {} + + public static final DeferredItem REQUEST = ITEMS.register("request", () -> new BlockItem(Blocks.REQUEST.get(), new Item.Properties())); + public static final DeferredItem KABEL = ITEMS.register("kabel", () -> new BlockItem(Blocks.KABEL.get(), new Item.Properties())); + public static final DeferredItem INVENTORY = ITEMS.register("inventory", () -> new BlockItem(Blocks.INVENTORY.get(), new Item.Properties())); + public static final DeferredItem REQUEST_EXPANDED = ITEMS.register("request_expanded", () -> new BlockItem(Blocks.REQUEST_EXPANDED.get(), new Item.Properties())); + public static final DeferredItem MAS = ITEMS.register("master", () -> new BlockItem(Blocks.MASTER.get(), new Item.Properties())); + public static final DeferredItem SK = ITEMS.register("storage_kabel", () -> new BlockItem(Blocks.STORAGE_KABEL.get(), new Item.Properties())); + public static final DeferredItem IK = ITEMS.register("import_kabel", () -> new BlockItem(Blocks.IMPORT_KABEL.get(), new Item.Properties())); + public static final DeferredItem IFK = ITEMS.register("import_filter_kabel", () -> new BlockItem(Blocks.IMPORT_FILTER_KABEL.get(), new Item.Properties())); + public static final DeferredItem FK = ITEMS.register("filter_kabel", () -> new BlockItem(Blocks.FILTER_KABEL.get(), new Item.Properties())); + public static final DeferredItem EK = ITEMS.register("export_kabel", () -> new BlockItem(Blocks.EXPORT_KABEL.get(), new Item.Properties())); + // public static final DeferredItem PK = ITEMS.register("process_kabel", () -> new BlockItem(Blocks.PROCESS_KABEL.get(), new Item.Properties())); + public static final DeferredItem EXCHANGE = ITEMS.register("exchange", () -> new BlockItem(Blocks.EXCHANGE.get(), new Item.Properties())); + public static final DeferredItem COL = ITEMS.register("collector", () -> new BlockItem(Blocks.COLLECTOR.get(), new Item.Properties())); + public static final DeferredItem STACK_UPGRADE = ITEMS.register("stack_upgrade", () -> new ItemUpgrade(new Item.Properties())); + public static final DeferredItem SPEED_UPGRADE = ITEMS.register("speed_upgrade", () -> new ItemUpgrade(new Item.Properties())); + public static final DeferredItem SLOW_UPGRADE = ITEMS.register("slow_upgrade", () -> new ItemUpgrade(new Item.Properties())); + public static final DeferredItem STOCK_UPGRADE = ITEMS.register("stock_upgrade", () -> new ItemUpgrade(new Item.Properties())); + public static final DeferredItem OP_U = ITEMS.register("operation_upgrade", () -> new ItemUpgrade(new Item.Properties())); + public static final DeferredItem SINGLE_UPGRADE = ITEMS.register("single_upgrade", () -> new ItemUpgrade(new Item.Properties())); + public static final DeferredItem INVENTORY_REMOTE = ITEMS.register("inventory_remote", () -> new ItemRemote(new Item.Properties())); + public static final DeferredItem CRAFTING_REMOTE = ITEMS.register("crafting_remote", () -> new ItemRemote(new Item.Properties())); + public static final DeferredItem PICKER_REMOTE = ITEMS.register("picker_remote", () -> new ItemPicker(new Item.Properties())); + public static final DeferredItem COLLECTOR_REMOTE = ITEMS.register("collector_remote", () -> new ItemCollector(new Item.Properties())); + public static final DeferredItem BUILDER_REMOTE = ITEMS.register("builder_remote", () -> new ItemBuilder(new Item.Properties())); + public static final DeferredItem EXPANDED_REMOTE = ITEMS.register("expanded_remote", () -> new ItemRemote(new Item.Properties())); } - @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public static class Tiles { - public static final RegistryObject> MASTER = TILES.register("master", () -> BlockEntityType.Builder.of(TileMain::new, Blocks.MASTER.get()).build(null)); - public static final RegistryObject> INVENTORY = TILES.register("inventory", () -> BlockEntityType.Builder.of(TileInventory::new, Blocks.INVENTORY.get()).build(null)); - public static final RegistryObject> REQUEST_EXPANDED = TILES.register("request_expanded", () -> BlockEntityType.Builder.of(TileInventoryExpanded::new, Blocks.REQUEST_EXPANDED.get()).build(null)); - public static final RegistryObject> REQUEST = TILES.register("request", () -> BlockEntityType.Builder.of(TileRequest::new, Blocks.REQUEST.get()).build(null)); - public static final RegistryObject> KABEL = TILES.register("kabel", () -> BlockEntityType.Builder.of(TileCable::new, Blocks.KABEL.get()).build(null)); - public static final RegistryObject> STORAGE_KABEL = TILES.register("storage_kabel", () -> BlockEntityType.Builder.of(TileCableLink::new, Blocks.STORAGE_KABEL.get()).build(null)); - public static final RegistryObject> IMPORT_KABEL = TILES.register("import_kabel", () -> BlockEntityType.Builder.of(TileCableIO::new, Blocks.IMPORT_KABEL.get()).build(null)); - public static final RegistryObject> IMPORT_FILTER_KABEL = TILES.register("import_filter_kabel", () -> BlockEntityType.Builder.of(TileCableImportFilter::new, Blocks.IMPORT_FILTER_KABEL.get()).build(null)); - public static final RegistryObject> FILTER_KABEL = TILES.register("filter_kabel", () -> BlockEntityType.Builder.of(TileCableFilter::new, Blocks.FILTER_KABEL.get()).build(null)); - public static final RegistryObject> EXPORT_KABEL = TILES.register("export_kabel", () -> BlockEntityType.Builder.of(TileCableExport::new, Blocks.EXPORT_KABEL.get()).build(null)); - public static final RegistryObject> EXCHANGE = TILES.register("exchange", () -> BlockEntityType.Builder.of(TileExchange::new, Blocks.EXCHANGE.get()).build(null)); - public static final RegistryObject> COLLECTOR = TILES.register("collector", () -> BlockEntityType.Builder.of(TileCollection::new, Blocks.COLLECTOR.get()).build(null)); - public static final RegistryObject> PROCESS_KABEL = TILES.register("process_kabel", () -> BlockEntityType.Builder.of(TileCableProcess::new, Blocks.PROCESS_KABEL.get()).build(null)); + public static void init() {} + + public static final DeferredHolder, BlockEntityType> MASTER = TILES.register("master", () -> BlockEntityType.Builder.of(TileMain::new, Blocks.MASTER.get()).build(null)); + public static final DeferredHolder, BlockEntityType> INVENTORY = TILES.register("inventory", () -> BlockEntityType.Builder.of(TileInventory::new, Blocks.INVENTORY.get()).build(null)); + public static final DeferredHolder, BlockEntityType> REQUEST_EXPANDED = TILES.register("request_expanded", () -> BlockEntityType.Builder.of(TileInventoryExpanded::new, Blocks.REQUEST_EXPANDED.get()).build(null)); + public static final DeferredHolder, BlockEntityType> REQUEST = TILES.register("request", () -> BlockEntityType.Builder.of(TileRequest::new, Blocks.REQUEST.get()).build(null)); + public static final DeferredHolder, BlockEntityType> KABEL = TILES.register("kabel", () -> BlockEntityType.Builder.of(TileCable::new, Blocks.KABEL.get()).build(null)); + public static final DeferredHolder, BlockEntityType> STORAGE_KABEL = TILES.register("storage_kabel", () -> BlockEntityType.Builder.of(TileCableLink::new, Blocks.STORAGE_KABEL.get()).build(null)); + public static final DeferredHolder, BlockEntityType> IMPORT_KABEL = TILES.register("import_kabel", () -> BlockEntityType.Builder.of(TileCableIO::new, Blocks.IMPORT_KABEL.get()).build(null)); + public static final DeferredHolder, BlockEntityType> IMPORT_FILTER_KABEL = TILES.register("import_filter_kabel", () -> BlockEntityType.Builder.of(TileCableImportFilter::new, Blocks.IMPORT_FILTER_KABEL.get()).build(null)); + public static final DeferredHolder, BlockEntityType> FILTER_KABEL = TILES.register("filter_kabel", () -> BlockEntityType.Builder.of(TileCableFilter::new, Blocks.FILTER_KABEL.get()).build(null)); + public static final DeferredHolder, BlockEntityType> EXPORT_KABEL = TILES.register("export_kabel", () -> BlockEntityType.Builder.of(TileCableExport::new, Blocks.EXPORT_KABEL.get()).build(null)); + public static final DeferredHolder, BlockEntityType> EXCHANGE = TILES.register("exchange", () -> BlockEntityType.Builder.of(TileExchange::new, Blocks.EXCHANGE.get()).build(null)); + public static final DeferredHolder, BlockEntityType> COLLECTOR = TILES.register("collector", () -> BlockEntityType.Builder.of(TileCollection::new, Blocks.COLLECTOR.get()).build(null)); + public static final DeferredHolder, BlockEntityType> PROCESS_KABEL = TILES.register("process_kabel", () -> BlockEntityType.Builder.of(TileCableProcess::new, Blocks.PROCESS_KABEL.get()).build(null)); } - @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public static class Menus { - public static final RegistryObject> REQUEST = CONTAINERS.register("request", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static void init() {} + + public static final DeferredHolder, MenuType> REQUEST = CONTAINERS.register("request", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerNetworkCraftingTable(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> COLLECTOR = CONTAINERS.register("collector", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> COLLECTOR = CONTAINERS.register("collector", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerCollectionFilter(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> FILTER_KABEL = CONTAINERS.register("filter_kabel", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> FILTER_KABEL = CONTAINERS.register("filter_kabel", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerCableFilter(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> IMPORT_FILTER_KABEL = CONTAINERS.register("import_filter_kabel", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> IMPORT_FILTER_KABEL = CONTAINERS.register("import_filter_kabel", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerCableImportFilter(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> EXPORT_KABEL = CONTAINERS.register("export_kabel", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> EXPORT_KABEL = CONTAINERS.register("export_kabel", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerCableExportFilter(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> INVENTORY = CONTAINERS.register("inventory", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> INVENTORY = CONTAINERS.register("inventory", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerNetworkInventory(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> REQUEST_EXPANDED = CONTAINERS.register("request_expanded", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> REQUEST_EXPANDED = CONTAINERS.register("request_expanded", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerNetworkInventoryExpanded(windowId, inv.player.level(), data.readBlockPos(), inv, inv.player); })); - public static final RegistryObject> INVENTORY_REMOTE = CONTAINERS.register("inventory_remote", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> INVENTORY_REMOTE = CONTAINERS.register("inventory_remote", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerNetworkRemote(windowId, inv.player.getInventory()); })); - public static final RegistryObject> CRAFTING_REMOTE = CONTAINERS.register("crafting_remote", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> CRAFTING_REMOTE = CONTAINERS.register("crafting_remote", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerNetworkCraftingRemote(windowId, inv.player.getInventory()); })); - public static final RegistryObject> EXPANDED_REMOTE = CONTAINERS.register("expanded_remote", () -> IForgeMenuType.create((windowId, inv, data) -> { + public static final DeferredHolder, MenuType> EXPANDED_REMOTE = CONTAINERS.register("expanded_remote", () -> IMenuTypeExtension.create((windowId, inv, data) -> { return new ContainerNetworkExpandedRemote(windowId, inv.player.getInventory()); })); } diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/SsnTab.java b/src/main/java/com/lothrazar/storagenetwork/registry/SsnTab.java index 32256693..7f0ae217 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/SsnTab.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/SsnTab.java @@ -8,14 +8,13 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.RegisterEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; +import net.neoforged.neoforge.registries.RegisterEvent; -@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class SsnTab { - private static final ResourceKey TAB = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(StorageNetworkMod.MODID, "tab")); + private static final ResourceKey TAB = ResourceKey.create(Registries.CREATIVE_MODE_TAB, ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "tab")); @SubscribeEvent public static void onCreativeModeTabRegister(RegisterEvent event) { diff --git a/src/main/java/com/lothrazar/storagenetwork/registry/StorageNetworkCapabilities.java b/src/main/java/com/lothrazar/storagenetwork/registry/StorageNetworkCapabilities.java index acd3744e..48794bce 100644 --- a/src/main/java/com/lothrazar/storagenetwork/registry/StorageNetworkCapabilities.java +++ b/src/main/java/com/lothrazar/storagenetwork/registry/StorageNetworkCapabilities.java @@ -1,29 +1,75 @@ package com.lothrazar.storagenetwork.registry; + +import com.lothrazar.storagenetwork.StorageNetworkMod; import com.lothrazar.storagenetwork.api.IConnectable; import com.lothrazar.storagenetwork.api.IConnectableItemAutoIO; import com.lothrazar.storagenetwork.api.IConnectableItemProcessing; import com.lothrazar.storagenetwork.api.IConnectableLink; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityManager; -import net.minecraftforge.common.capabilities.CapabilityToken; -import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; - -@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) +import com.lothrazar.storagenetwork.block.cable.export.TileCableExport; +import com.lothrazar.storagenetwork.block.cable.input.TileCableIO; +import com.lothrazar.storagenetwork.block.cable.inputfilter.TileCableImportFilter; +import com.lothrazar.storagenetwork.block.cable.link.TileCableLink; +import com.lothrazar.storagenetwork.block.cable.linkfilter.TileCableFilter; +import com.lothrazar.storagenetwork.block.cable.processing.TileCableProcess; +import com.lothrazar.storagenetwork.block.cable.TileCable; +import com.lothrazar.storagenetwork.block.collection.TileCollection; +import com.lothrazar.storagenetwork.block.exchange.TileExchange; +import com.lothrazar.storagenetwork.block.expand.TileInventoryExpanded; +import com.lothrazar.storagenetwork.block.inventory.TileInventory; +import com.lothrazar.storagenetwork.block.main.TileMain; +import com.lothrazar.storagenetwork.block.request.TileRequest; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.capabilities.BlockCapability; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; + public class StorageNetworkCapabilities { - public static final Capability CONNECTABLE_CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {}); - public static final Capability CONNECTABLE_ITEM_STORAGE_CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {}); - public static final Capability CONNECTABLE_AUTO_IO = CapabilityManager.get(new CapabilityToken<>() {}); - public static final Capability PROCESSING_CAPABILITY = CapabilityManager.get(new CapabilityToken<>() {}); + public static final BlockCapability CONNECTABLE = + BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "connectable"), IConnectable.class); + + public static final BlockCapability CONNECTABLE_ITEM_STORAGE = + BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "connectable_item_storage"), IConnectableLink.class); + + public static final BlockCapability CONNECTABLE_AUTO_IO = + BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "connectable_auto_io"), IConnectableItemAutoIO.class); + + public static final BlockCapability PROCESSING = + BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(StorageNetworkMod.MODID, "connectable_processing"), IConnectableItemProcessing.class); @SubscribeEvent - public static void initCapabilities(RegisterCapabilitiesEvent event) { - event.register(IConnectable.class); - event.register(IConnectableLink.class); - event.register(IConnectableItemAutoIO.class); - event.register(IConnectableItemProcessing.class); + public static void registerCapabilities(RegisterCapabilitiesEvent event) { + // CONNECTABLE — all network tile entities provide this (master is the hub, not a node) + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.INVENTORY.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.REQUEST_EXPANDED.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.REQUEST.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.KABEL.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.STORAGE_KABEL.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.IMPORT_KABEL.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.IMPORT_FILTER_KABEL.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.FILTER_KABEL.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.EXPORT_KABEL.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.EXCHANGE.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.COLLECTOR.get(), (be, side) -> be.getConnectable()); + event.registerBlockEntity(CONNECTABLE, SsnRegistry.Tiles.PROCESS_KABEL.get(), (be, side) -> be.getConnectable()); + + // CONNECTABLE_ITEM_STORAGE — storage cable and filter cable + event.registerBlockEntity(CONNECTABLE_ITEM_STORAGE, SsnRegistry.Tiles.STORAGE_KABEL.get(), (be, side) -> be.getItemStorage()); + event.registerBlockEntity(CONNECTABLE_ITEM_STORAGE, SsnRegistry.Tiles.FILTER_KABEL.get(), (be, side) -> be.getCapabilityLink()); + + // CONNECTABLE_AUTO_IO — import and export cables + event.registerBlockEntity(CONNECTABLE_AUTO_IO, SsnRegistry.Tiles.IMPORT_KABEL.get(), (be, side) -> be.getIoStorage()); + event.registerBlockEntity(CONNECTABLE_AUTO_IO, SsnRegistry.Tiles.IMPORT_FILTER_KABEL.get(), (be, side) -> be.getIoStorage()); + event.registerBlockEntity(CONNECTABLE_AUTO_IO, SsnRegistry.Tiles.EXPORT_KABEL.get(), (be, side) -> be.getIoStorage()); + + // PROCESSING — processing cable + event.registerBlockEntity(PROCESSING, SsnRegistry.Tiles.PROCESS_KABEL.get(), (be, side) -> be.getItemStorage()); + + // ITEM_HANDLER — exchange and collector blocks proxy item access into the network + event.registerBlockEntity(Capabilities.ItemHandler.BLOCK, SsnRegistry.Tiles.EXCHANGE.get(), (be, side) -> be.getItemHandler()); + event.registerBlockEntity(Capabilities.ItemHandler.BLOCK, SsnRegistry.Tiles.COLLECTOR.get(), (be, side) -> be.getItemHandler()); } } diff --git a/src/main/java/com/lothrazar/storagenetwork/util/UtilConnections.java b/src/main/java/com/lothrazar/storagenetwork/util/UtilConnections.java index e08b3628..857e05c2 100644 --- a/src/main/java/com/lothrazar/storagenetwork/util/UtilConnections.java +++ b/src/main/java/com/lothrazar/storagenetwork/util/UtilConnections.java @@ -4,12 +4,13 @@ import com.lothrazar.storagenetwork.registry.SsnRegistry; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.core.registries.BuiltInRegistries; +import net.neoforged.neoforge.capabilities.Capabilities; public class UtilConnections { @@ -17,7 +18,7 @@ public static boolean isTargetAllowed(BlockState state) { if (state.getBlock() == Blocks.AIR) { return false; } - String blockId = ForgeRegistries.BLOCKS.getKey(state.getBlock()).toString(); + String blockId = BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString(); for (String s : StorageNetworkMod.CONFIG.ignorelist()) { if (blockId.equals(s)) { return false; @@ -49,10 +50,12 @@ public static boolean isInventory(Direction facing, LevelAccessor world, BlockPo return false; } BlockEntity neighbor = world.getBlockEntity(facingPos); - if (neighbor != null - && neighbor.getCapability(ForgeCapabilities.ITEM_HANDLER, facing.getOpposite()).orElse(null) != null) { - return true; + if (neighbor == null) { + return false; + } + if (world instanceof Level level) { + return level.getCapability(Capabilities.ItemHandler.BLOCK, facingPos, facing.getOpposite()) != null; } - return false; + return true; } } diff --git a/src/main/java/com/lothrazar/storagenetwork/util/UtilInventory.java b/src/main/java/com/lothrazar/storagenetwork/util/UtilInventory.java index bdeffddc..bf9e89bc 100644 --- a/src/main/java/com/lothrazar/storagenetwork/util/UtilInventory.java +++ b/src/main/java/com/lothrazar/storagenetwork/util/UtilInventory.java @@ -9,10 +9,9 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.core.registries.BuiltInRegistries; +import net.neoforged.fml.ModList; +import net.neoforged.neoforge.items.IItemHandler; import top.theillusivec4.curios.api.CuriosApi; import top.theillusivec4.curios.api.SlotResult; @@ -24,7 +23,7 @@ public static void nukeAndDrop(DimPos lookPos) { } public static String getStackKey(ItemStack stackInCopy) { - return ForgeRegistries.ITEMS.getKey(stackInCopy.getItem()).toString(); + return BuiltInRegistries.ITEM.getKey(stackInCopy.getItem()).toString(); } /** @@ -71,7 +70,7 @@ public static Triple getCurioRemote(Player player, I private static boolean isRemoteWithData(ItemStack stack, Item remote) { //if it has a tag, assume pos to network is valid - return stack.getItem() == remote && stack.hasTag(); + return stack.getItem() == remote && stack.has(net.minecraft.core.component.DataComponents.CUSTOM_DATA); } public static String formatLargeNumber(int size) { @@ -97,7 +96,7 @@ else if (size < Math.pow(10, 12)) { public static int countHowMany(IItemHandler inv, ItemStack stackIn) { int found = 0; for (int i = 0; i < inv.getSlots(); i++) { - if (ItemHandlerHelper.canItemStacksStack(inv.getStackInSlot(i), stackIn)) { + if (ItemStack.isSameItemSameComponents(inv.getStackInSlot(i), stackIn)) { found += inv.getStackInSlot(i).getCount(); } } @@ -107,7 +106,7 @@ public static int countHowMany(IItemHandler inv, ItemStack stackIn) { public static int containsAtLeastHowManyNeeded(IItemHandler inv, ItemStack stackIn, int minimumCount) { int found = 0; for (int i = 0; i < inv.getSlots(); i++) { - if (ItemHandlerHelper.canItemStacksStack(inv.getStackInSlot(i), stackIn)) { + if (ItemStack.isSameItemSameComponents(inv.getStackInSlot(i), stackIn)) { found += inv.getStackInSlot(i).getCount(); } } @@ -130,7 +129,7 @@ public static ItemStack extractItem(IItemHandler inv, ItemStackMatcher fil, int if (!ex.isEmpty()) { extracted++; if (extracted == num) { - return ItemHandlerHelper.copyStackWithSize(slot, num); + return slot.copyWithCount(num); } else { i--; diff --git a/src/main/java/com/lothrazar/storagenetwork/util/UtilRemote.java b/src/main/java/com/lothrazar/storagenetwork/util/UtilRemote.java index 7716e723..ae2d0914 100644 --- a/src/main/java/com/lothrazar/storagenetwork/util/UtilRemote.java +++ b/src/main/java/com/lothrazar/storagenetwork/util/UtilRemote.java @@ -15,7 +15,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.neoforge.network.PacketDistributor; public class UtilRemote { @@ -86,7 +86,7 @@ public static boolean openRemote(Level world, Player player, ItemStack itemStack } BlockEntity tile = serverTargetWorld.getBlockEntity(posTarget); if (tile instanceof TileMain) { - NetworkHooks.openScreen((ServerPlayer) player, theRemoteItem); + ((ServerPlayer) player).openMenu(theRemoteItem); return true; } else { diff --git a/src/main/java/com/lothrazar/storagenetwork/util/UtilTileEntity.java b/src/main/java/com/lothrazar/storagenetwork/util/UtilTileEntity.java index 8096ae6d..e5fda7c7 100644 --- a/src/main/java/com/lothrazar/storagenetwork/util/UtilTileEntity.java +++ b/src/main/java/com/lothrazar/storagenetwork/util/UtilTileEntity.java @@ -15,8 +15,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.core.registries.BuiltInRegistries; public class UtilTileEntity { @@ -28,7 +27,7 @@ public class UtilTileEntity { public static void addOrMergeIntoList(List list, ItemStack stackToAdd) { boolean added = false; for (ItemStack stack : list) { - if (ItemHandlerHelper.canItemStacksStack(stackToAdd, stack)) { + if (ItemStack.isSameItemSameComponents(stackToAdd, stack)) { stack.setCount(stack.getCount() + stackToAdd.getCount()); added = true; break; @@ -43,7 +42,7 @@ public static void playSoundFromServer(ServerPlayer entityIn, SoundEvent soundIn if (soundIn == null || entityIn == null) { return; } - entityIn.connection.send(new ClientboundSoundPacket(ForgeRegistries.SOUND_EVENTS.getHolder(soundIn).get(), SoundSource.PLAYERS, entityIn.xOld, entityIn.yOld, entityIn.zOld, volume, 1.0F, 0)); // pitch=1; seed=0 + entityIn.connection.send(new ClientboundSoundPacket(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(soundIn), SoundSource.PLAYERS, entityIn.xOld, entityIn.yOld, entityIn.zOld, volume, 1.0F, 0)); // pitch=1; seed=0 } public static void chatMessage(Player player, String message) { @@ -91,7 +90,7 @@ public static String getModNameForItem(Item theitem) { if (modNamesForIds.containsKey(theitem)) { return modNamesForIds.get(theitem); } - String modId = ForgeRegistries.ITEMS.getKey(theitem).getNamespace(); + String modId = BuiltInRegistries.ITEM.getKey(theitem).getNamespace(); String lowercaseModId = modId.toLowerCase(Locale.ENGLISH); modNamesForIds.put(theitem, lowercaseModId); return lowercaseModId; diff --git a/src/main/resources/data/curios/tags/items/charm.json b/src/main/resources/data/curios/tags/item/charm.json similarity index 88% rename from src/main/resources/data/curios/tags/items/charm.json rename to src/main/resources/data/curios/tags/item/charm.json index a49dbe37..2de6fd66 100644 --- a/src/main/resources/data/curios/tags/items/charm.json +++ b/src/main/resources/data/curios/tags/item/charm.json @@ -1,5 +1,5 @@ { - "replace": "false", + "replace": false, "values": [ "storagenetwork:expanded_remote", "storagenetwork:inventory_remote", diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/collector.json b/src/main/resources/data/storagenetwork/loot_table/blocks/collector.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/collector.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/collector.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/exchange.json b/src/main/resources/data/storagenetwork/loot_table/blocks/exchange.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/exchange.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/exchange.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/export_kabel.json b/src/main/resources/data/storagenetwork/loot_table/blocks/export_kabel.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/export_kabel.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/export_kabel.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/filter_kabel.json b/src/main/resources/data/storagenetwork/loot_table/blocks/filter_kabel.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/filter_kabel.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/filter_kabel.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/import_filter_kabel.json b/src/main/resources/data/storagenetwork/loot_table/blocks/import_filter_kabel.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/import_filter_kabel.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/import_filter_kabel.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/import_kabel.json b/src/main/resources/data/storagenetwork/loot_table/blocks/import_kabel.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/import_kabel.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/import_kabel.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/inventory.json b/src/main/resources/data/storagenetwork/loot_table/blocks/inventory.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/inventory.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/inventory.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/kabel.json b/src/main/resources/data/storagenetwork/loot_table/blocks/kabel.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/kabel.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/kabel.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/master.json b/src/main/resources/data/storagenetwork/loot_table/blocks/master.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/master.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/master.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/process_kabel.json.txt b/src/main/resources/data/storagenetwork/loot_table/blocks/process_kabel.json.txt similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/process_kabel.json.txt rename to src/main/resources/data/storagenetwork/loot_table/blocks/process_kabel.json.txt diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/request.json b/src/main/resources/data/storagenetwork/loot_table/blocks/request.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/request.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/request.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/request_expanded.json b/src/main/resources/data/storagenetwork/loot_table/blocks/request_expanded.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/request_expanded.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/request_expanded.json diff --git a/src/main/resources/data/storagenetwork/loot_tables/blocks/storage_kabel.json b/src/main/resources/data/storagenetwork/loot_table/blocks/storage_kabel.json similarity index 100% rename from src/main/resources/data/storagenetwork/loot_tables/blocks/storage_kabel.json rename to src/main/resources/data/storagenetwork/loot_table/blocks/storage_kabel.json diff --git a/src/main/resources/data/storagenetwork/recipe/builder_remote.json b/src/main/resources/data/storagenetwork/recipe/builder_remote.json new file mode 100644 index 00000000..4a8cb613 --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/builder_remote.json @@ -0,0 +1,19 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " i ", + "imi", + " i " + ], + "key": { + "i": { + "item": "storagenetwork:request" + }, + "m": { + "item": "storagenetwork:inventory_remote" + } + }, + "result": { + "id": "storagenetwork:builder_remote" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/collector.json b/src/main/resources/data/storagenetwork/recipe/collector.json similarity index 78% rename from src/main/resources/data/storagenetwork/recipes/collector.json rename to src/main/resources/data/storagenetwork/recipe/collector.json index 92d96391..b642c2ff 100644 --- a/src/main/resources/data/storagenetwork/recipes/collector.json +++ b/src/main/resources/data/storagenetwork/recipe/collector.json @@ -10,13 +10,13 @@ "item": "storagenetwork:speed_upgrade" }, "d": { - "tag": "forge:nuggets/iron" + "tag": "c:nuggets/iron" }, "c": { "item": "storagenetwork:inventory" } }, "result": { - "item": "storagenetwork:collector" + "id": "storagenetwork:collector" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/collector_remote.json b/src/main/resources/data/storagenetwork/recipe/collector_remote.json new file mode 100644 index 00000000..070f474b --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/collector_remote.json @@ -0,0 +1,19 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " i ", + "imi", + " i " + ], + "key": { + "i": { + "item": "storagenetwork:import_kabel" + }, + "m": { + "item": "storagenetwork:inventory_remote" + } + }, + "result": { + "id": "storagenetwork:collector_remote" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/crafting_remote.json b/src/main/resources/data/storagenetwork/recipe/crafting_remote.json new file mode 100644 index 00000000..e9d19fd5 --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/crafting_remote.json @@ -0,0 +1,25 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "pcp", + "imi", + "p p" + ], + "key": { + "c": { + "item": "minecraft:ender_chest" + }, + "i": { + "tag": "c:storage_blocks/gold" + }, + "m": { + "item": "storagenetwork:master" + }, + "p": { + "item": "minecraft:sea_lantern" + } + }, + "result": { + "id": "storagenetwork:crafting_remote" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/exchange.json b/src/main/resources/data/storagenetwork/recipe/exchange.json similarity index 78% rename from src/main/resources/data/storagenetwork/recipes/exchange.json rename to src/main/resources/data/storagenetwork/recipe/exchange.json index 3b9a86a6..53e7a272 100644 --- a/src/main/resources/data/storagenetwork/recipes/exchange.json +++ b/src/main/resources/data/storagenetwork/recipe/exchange.json @@ -10,13 +10,13 @@ "item": "storagenetwork:stack_upgrade" }, "d": { - "tag": "forge:nuggets/iron" + "tag": "c:nuggets/iron" }, "c": { "item": "storagenetwork:inventory" } }, "result": { - "item": "storagenetwork:exchange" + "id": "storagenetwork:exchange" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/expanded_remote.json b/src/main/resources/data/storagenetwork/recipe/expanded_remote.json similarity index 55% rename from src/main/resources/data/storagenetwork/recipes/expanded_remote.json rename to src/main/resources/data/storagenetwork/recipe/expanded_remote.json index a7446ecc..12bce39d 100644 --- a/src/main/resources/data/storagenetwork/recipes/expanded_remote.json +++ b/src/main/resources/data/storagenetwork/recipe/expanded_remote.json @@ -3,17 +3,17 @@ "pattern": [ " i ", "imi", - " i " + " i " ], "key": { - "i": { + "i": { "item": "storagenetwork:import_filter_kabel" - }, - "m": { - "item": "storagenetwork:request_expanded" - } + }, + "m": { + "item": "storagenetwork:request_expanded" + } }, "result": { - "item": "storagenetwork:expanded_remote" + "id": "storagenetwork:expanded_remote" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/export_kabel.json b/src/main/resources/data/storagenetwork/recipe/export_kabel.json similarity index 85% rename from src/main/resources/data/storagenetwork/recipes/export_kabel.json rename to src/main/resources/data/storagenetwork/recipe/export_kabel.json index f63197b4..a25c41be 100644 --- a/src/main/resources/data/storagenetwork/recipes/export_kabel.json +++ b/src/main/resources/data/storagenetwork/recipe/export_kabel.json @@ -14,7 +14,7 @@ } }, "result": { - "item": "storagenetwork:export_kabel", + "id": "storagenetwork:export_kabel", "count": 4 } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/filter_kabel.json b/src/main/resources/data/storagenetwork/recipe/filter_kabel.json similarity index 85% rename from src/main/resources/data/storagenetwork/recipes/filter_kabel.json rename to src/main/resources/data/storagenetwork/recipe/filter_kabel.json index af776b4e..b8876ccf 100644 --- a/src/main/resources/data/storagenetwork/recipes/filter_kabel.json +++ b/src/main/resources/data/storagenetwork/recipe/filter_kabel.json @@ -14,7 +14,7 @@ } }, "result": { - "item": "storagenetwork:filter_kabel", + "id": "storagenetwork:filter_kabel", "count": 4 } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/import_filter_kabel.json b/src/main/resources/data/storagenetwork/recipe/import_filter_kabel.json similarity index 83% rename from src/main/resources/data/storagenetwork/recipes/import_filter_kabel.json rename to src/main/resources/data/storagenetwork/recipe/import_filter_kabel.json index 8299bac0..d3a62a17 100644 --- a/src/main/resources/data/storagenetwork/recipes/import_filter_kabel.json +++ b/src/main/resources/data/storagenetwork/recipe/import_filter_kabel.json @@ -14,7 +14,7 @@ } }, "result": { - "item": "storagenetwork:import_filter_kabel", + "id": "storagenetwork:import_filter_kabel", "count": 4 } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/import_kabel.json b/src/main/resources/data/storagenetwork/recipe/import_kabel.json similarity index 85% rename from src/main/resources/data/storagenetwork/recipes/import_kabel.json rename to src/main/resources/data/storagenetwork/recipe/import_kabel.json index 6dba11c0..b7d81042 100644 --- a/src/main/resources/data/storagenetwork/recipes/import_kabel.json +++ b/src/main/resources/data/storagenetwork/recipe/import_kabel.json @@ -14,7 +14,7 @@ } }, "result": { - "item": "storagenetwork:import_kabel", + "id": "storagenetwork:import_kabel", "count": 4 } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/inventory.json b/src/main/resources/data/storagenetwork/recipe/inventory.json similarity index 77% rename from src/main/resources/data/storagenetwork/recipes/inventory.json rename to src/main/resources/data/storagenetwork/recipe/inventory.json index abc2ee76..25c261bd 100644 --- a/src/main/resources/data/storagenetwork/recipes/inventory.json +++ b/src/main/resources/data/storagenetwork/recipe/inventory.json @@ -10,13 +10,13 @@ "item": "storagenetwork:kabel" }, "d": { - "tag": "forge:nuggets/iron" + "tag": "c:nuggets/iron" }, "c": { "item": "minecraft:dropper" } }, "result": { - "item": "storagenetwork:inventory" + "id": "storagenetwork:inventory" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/inventory_remote.json b/src/main/resources/data/storagenetwork/recipe/inventory_remote.json new file mode 100644 index 00000000..c92dce50 --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/inventory_remote.json @@ -0,0 +1,25 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "pcp", + "imi", + "p p" + ], + "key": { + "c": { + "tag": "c:dusts/glowstone" + }, + "i": { + "tag": "c:ingots/gold" + }, + "m": { + "item": "storagenetwork:master" + }, + "p": { + "tag": "c:slimeballs" + } + }, + "result": { + "id": "storagenetwork:inventory_remote" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/kabel.json b/src/main/resources/data/storagenetwork/recipe/kabel.json similarity index 59% rename from src/main/resources/data/storagenetwork/recipes/kabel.json rename to src/main/resources/data/storagenetwork/recipe/kabel.json index e8d6e89b..0e699452 100644 --- a/src/main/resources/data/storagenetwork/recipes/kabel.json +++ b/src/main/resources/data/storagenetwork/recipe/kabel.json @@ -7,15 +7,14 @@ ], "key": { "s": { - "item": "minecraft:stone_slab", - "data": 0 + "item": "minecraft:stone_slab" }, "i": { - "tag": "forge:ingots/iron" + "tag": "c:ingots/iron" } }, "result": { - "item": "storagenetwork:kabel", + "id": "storagenetwork:kabel", "count": 8 } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/master.json b/src/main/resources/data/storagenetwork/recipe/master.json similarity index 78% rename from src/main/resources/data/storagenetwork/recipes/master.json rename to src/main/resources/data/storagenetwork/recipe/master.json index 889a5e3e..e9dc40c1 100644 --- a/src/main/resources/data/storagenetwork/recipes/master.json +++ b/src/main/resources/data/storagenetwork/recipe/master.json @@ -13,10 +13,10 @@ "item": "minecraft:quartz" }, "c": { - "tag": "forge:gems/diamond" + "tag": "c:gems/diamond" } }, "result": { - "item": "storagenetwork:master" + "id": "storagenetwork:master" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/network_book.json b/src/main/resources/data/storagenetwork/recipe/network_book.json new file mode 100644 index 00000000..e87f6369 --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/network_book.json @@ -0,0 +1,17 @@ +{ + "type": "minecraft:crafting_shapeless", + "neoforge:conditions": [ + {"type": "neoforge:mod_loaded", "modid": "patchouli"} + ], + "ingredients": [ + {"item": "storagenetwork:kabel"}, + {"item": "minecraft:book"} + ], + "result": { + "id": "patchouli:guide_book", + "count": 1, + "components": { + "patchouli:book": "storagenetwork:network_book" + } + } +} diff --git a/src/main/resources/data/storagenetwork/recipes/operation_upgrade.json b/src/main/resources/data/storagenetwork/recipe/operation_upgrade.json similarity index 52% rename from src/main/resources/data/storagenetwork/recipes/operation_upgrade.json rename to src/main/resources/data/storagenetwork/recipe/operation_upgrade.json index c0618902..53ef0cd1 100644 --- a/src/main/resources/data/storagenetwork/recipes/operation_upgrade.json +++ b/src/main/resources/data/storagenetwork/recipe/operation_upgrade.json @@ -1,23 +1,22 @@ { - "type": "minecraft:crafting_shaped", "pattern": [ " c ", "gig", - " c " + " c " ], "key": { "c": { - "tag": "forge:dusts/redstone" + "tag": "c:dusts/redstone" }, - "i": { - "item": "storagenetwork:kabel" - }, - "g": { + "i": { + "item": "storagenetwork:kabel" + }, + "g": { "item": "minecraft:comparator" - } + } }, "result": { - "item": "storagenetwork:operation_upgrade" + "id": "storagenetwork:operation_upgrade" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/picker_remote.json b/src/main/resources/data/storagenetwork/recipe/picker_remote.json new file mode 100644 index 00000000..2ad61cf0 --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/picker_remote.json @@ -0,0 +1,19 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " i ", + "imi", + " i " + ], + "key": { + "i": { + "item": "storagenetwork:kabel" + }, + "m": { + "item": "storagenetwork:inventory_remote" + } + }, + "result": { + "id": "storagenetwork:picker_remote" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/process_kabel.json.txt b/src/main/resources/data/storagenetwork/recipe/process_kabel.json.txt similarity index 100% rename from src/main/resources/data/storagenetwork/recipes/process_kabel.json.txt rename to src/main/resources/data/storagenetwork/recipe/process_kabel.json.txt diff --git a/src/main/resources/data/storagenetwork/recipes/request.json b/src/main/resources/data/storagenetwork/recipe/request.json similarity index 78% rename from src/main/resources/data/storagenetwork/recipes/request.json rename to src/main/resources/data/storagenetwork/recipe/request.json index c4b77672..74374b6c 100644 --- a/src/main/resources/data/storagenetwork/recipes/request.json +++ b/src/main/resources/data/storagenetwork/recipe/request.json @@ -10,13 +10,13 @@ "item": "minecraft:crafting_table" }, "d": { - "tag": "forge:ingots/gold" + "tag": "c:ingots/gold" }, "c": { "item": "storagenetwork:inventory" } }, "result": { - "item": "storagenetwork:request" + "id": "storagenetwork:request" } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/request_expanded.json b/src/main/resources/data/storagenetwork/recipe/request_expanded.json new file mode 100644 index 00000000..f0344e8c --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/request_expanded.json @@ -0,0 +1,28 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "csc", + "eme", + "cpc" + ], + "key": { + "e": { + "item": "minecraft:ender_eye" + }, + "c": { + "tag": "c:storage_blocks/copper" + }, + "m": { + "item": "storagenetwork:operation_upgrade" + }, + "s": { + "item": "storagenetwork:stack_upgrade" + }, + "p": { + "item": "storagenetwork:speed_upgrade" + } + }, + "result": { + "id": "storagenetwork:request_expanded" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/single_upgrade.json b/src/main/resources/data/storagenetwork/recipe/single_upgrade.json new file mode 100644 index 00000000..712087ed --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/single_upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " c ", + "gig", + " c " + ], + "key": { + "c": { + "tag": "c:dusts/redstone" + }, + "i": { + "item": "storagenetwork:kabel" + }, + "g": { + "item": "minecraft:coal" + } + }, + "result": { + "id": "storagenetwork:single_upgrade" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/slow_upgrade.json b/src/main/resources/data/storagenetwork/recipe/slow_upgrade.json new file mode 100644 index 00000000..1437cc1a --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/slow_upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " c ", + "gig", + " c " + ], + "key": { + "c": { + "tag": "c:dusts/redstone" + }, + "i": { + "item": "storagenetwork:kabel" + }, + "g": { + "item": "minecraft:copper_ingot" + } + }, + "result": { + "id": "storagenetwork:slow_upgrade" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/speed_upgrade.json b/src/main/resources/data/storagenetwork/recipe/speed_upgrade.json new file mode 100644 index 00000000..f6bb3225 --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/speed_upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " c ", + "gig", + " c " + ], + "key": { + "c": { + "tag": "c:dusts/redstone" + }, + "i": { + "item": "storagenetwork:kabel" + }, + "g": { + "item": "minecraft:gold_ingot" + } + }, + "result": { + "id": "storagenetwork:speed_upgrade" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/stack_upgrade.json b/src/main/resources/data/storagenetwork/recipe/stack_upgrade.json new file mode 100644 index 00000000..ac351bfa --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/stack_upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " c ", + "gig", + " c " + ], + "key": { + "c": { + "tag": "c:dusts/redstone" + }, + "i": { + "item": "storagenetwork:kabel" + }, + "g": { + "item": "minecraft:blaze_powder" + } + }, + "result": { + "id": "storagenetwork:stack_upgrade" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipe/stock_upgrade.json b/src/main/resources/data/storagenetwork/recipe/stock_upgrade.json new file mode 100644 index 00000000..882efeae --- /dev/null +++ b/src/main/resources/data/storagenetwork/recipe/stock_upgrade.json @@ -0,0 +1,22 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + " c ", + "gig", + " c " + ], + "key": { + "c": { + "tag": "c:dusts/redstone" + }, + "i": { + "item": "storagenetwork:kabel" + }, + "g": { + "item": "minecraft:chest" + } + }, + "result": { + "id": "storagenetwork:stock_upgrade" + } +} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/storage_kabel.json b/src/main/resources/data/storagenetwork/recipe/storage_kabel.json similarity index 73% rename from src/main/resources/data/storagenetwork/recipes/storage_kabel.json rename to src/main/resources/data/storagenetwork/recipe/storage_kabel.json index 4df25fc7..578af9a4 100644 --- a/src/main/resources/data/storagenetwork/recipes/storage_kabel.json +++ b/src/main/resources/data/storagenetwork/recipe/storage_kabel.json @@ -10,11 +10,11 @@ "item": "storagenetwork:kabel" }, "p": { - "tag": "forge:chests/wooden" + "tag": "c:chests/wooden" } }, "result": { - "item": "storagenetwork:storage_kabel", + "id": "storagenetwork:storage_kabel", "count": 4 } } \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/builder_remote.json b/src/main/resources/data/storagenetwork/recipes/builder_remote.json deleted file mode 100644 index 63f46e79..00000000 --- a/src/main/resources/data/storagenetwork/recipes/builder_remote.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " i ", - "imi", - " i " - ], - "key": { - "i": { - "item": "storagenetwork:request" - }, - "m": { - "item": "storagenetwork:inventory_remote" - } - }, - "result": { - "item": "storagenetwork:builder_remote" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/collector_remote.json b/src/main/resources/data/storagenetwork/recipes/collector_remote.json deleted file mode 100644 index c21af915..00000000 --- a/src/main/resources/data/storagenetwork/recipes/collector_remote.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " i ", - "imi", - " i " - ], - "key": { - "i": { - "item": "storagenetwork:import_kabel" - }, - "m": { - "item": "storagenetwork:inventory_remote" - } - }, - "result": { - "item": "storagenetwork:collector_remote" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/crafting_remote.json b/src/main/resources/data/storagenetwork/recipes/crafting_remote.json deleted file mode 100644 index b1f1e74c..00000000 --- a/src/main/resources/data/storagenetwork/recipes/crafting_remote.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - "pcp", - "imi", - "p p" - ], - "key": { - "c": { - "item": "minecraft:ender_chest" - }, - "i": { - "tag": "forge:storage_blocks/gold" - }, - "m": { - "item": "storagenetwork:master" - }, - "p": { - "item": "minecraft:sea_lantern" - } - }, - "result": { - "item": "storagenetwork:crafting_remote" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/inventory_remote.json b/src/main/resources/data/storagenetwork/recipes/inventory_remote.json deleted file mode 100644 index dd16c2e0..00000000 --- a/src/main/resources/data/storagenetwork/recipes/inventory_remote.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - "pcp", - "imi", - "p p" - ], - "key": { - "c": { - "tag": "forge:dusts/glowstone" - }, - "i": { - "tag": "forge:ingots/gold" - }, - "m": { - "item": "storagenetwork:master" - }, - "p": { - "tag": "forge:slimeballs" -} - }, - "result": { - "item": "storagenetwork:inventory_remote" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/network_book.json b/src/main/resources/data/storagenetwork/recipes/network_book.json deleted file mode 100644 index dda20b58..00000000 --- a/src/main/resources/data/storagenetwork/recipes/network_book.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "type": "crafting_shapeless", - "ingredients": [{ - "item": "storagenetwork:kabel", - "count": 1 - }, { - "item": "minecraft:book", - "count": 1 - }], - "result": { - "type": "forge:nbt", - "item": "patchouli:guide_book", - "count": 1, - "nbt": { - "patchouli:book": "storagenetwork:network_book" - } - }, - "conditions": [ - { - "values": [ - { - "modid": "patchouli", - "type": "forge:mod_loaded" - } - ], - "type": "forge:and" - } - ] -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/picker_remote.json b/src/main/resources/data/storagenetwork/recipes/picker_remote.json deleted file mode 100644 index bddf3f6d..00000000 --- a/src/main/resources/data/storagenetwork/recipes/picker_remote.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " i ", - "imi", - " i " - ], - "key": { - "i": { - "item": "storagenetwork:kabel" - }, - "m": { - "item": "storagenetwork:inventory_remote" - } - }, - "result": { - "item": "storagenetwork:picker_remote" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/request_expanded.json b/src/main/resources/data/storagenetwork/recipes/request_expanded.json deleted file mode 100644 index 45e10337..00000000 --- a/src/main/resources/data/storagenetwork/recipes/request_expanded.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "type": "minecraft:crafting_shaped", - "pattern": [ - "csc", - "eme", - "cpc" - ], - "key": { - "e": { - "item": "minecraft:ender_eye" - }, - "c": { - "tag": "forge:storage_blocks/copper" - }, - "m": { - "item": "storagenetwork:operation_upgrade" - }, - "s": { - "item": "storagenetwork:stack_upgrade" - }, - "p": { - "item": "storagenetwork:speed_upgrade" - } - }, - "result": { - "item": "storagenetwork:request_expanded" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/single_upgrade.json b/src/main/resources/data/storagenetwork/recipes/single_upgrade.json deleted file mode 100644 index 92456f8b..00000000 --- a/src/main/resources/data/storagenetwork/recipes/single_upgrade.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " c ", - "gig", - " c " - ], - "key": { - "c": { - "tag": "forge:dusts/redstone" - }, - "i": { - "item": "storagenetwork:kabel" - }, - "g": { - "item": "minecraft:coal" - } - }, - "result": { - "item": "storagenetwork:single_upgrade" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/slow_upgrade.json b/src/main/resources/data/storagenetwork/recipes/slow_upgrade.json deleted file mode 100644 index fca567ad..00000000 --- a/src/main/resources/data/storagenetwork/recipes/slow_upgrade.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " c ", - "gig", - " c " - ], - "key": { - "c": { - "tag": "forge:dusts/redstone" - }, - "i": { - "item": "storagenetwork:kabel" - }, - "g": { - "item": "minecraft:copper_ingot" - } - }, - "result": { - "item": "storagenetwork:slow_upgrade" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/speed_upgrade.json b/src/main/resources/data/storagenetwork/recipes/speed_upgrade.json deleted file mode 100644 index 305a222c..00000000 --- a/src/main/resources/data/storagenetwork/recipes/speed_upgrade.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " c ", - "gig", - " c " - ], - "key": { - "c": { - "tag": "forge:dusts/redstone" - }, - "i": { - "item": "storagenetwork:kabel" - }, - "g": { - "item": "minecraft:gold_ingot" - } - }, - "result": { - "item": "storagenetwork:speed_upgrade" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/stack_upgrade.json b/src/main/resources/data/storagenetwork/recipes/stack_upgrade.json deleted file mode 100644 index 94111aae..00000000 --- a/src/main/resources/data/storagenetwork/recipes/stack_upgrade.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " c ", - "gig", - " c " - ], - "key": { - "c": { - "tag": "forge:dusts/redstone" - }, - "i": { - "item": "storagenetwork:kabel" - }, - "g": { - "item": "minecraft:blaze_powder" - } - }, - "result": { - "item": "storagenetwork:stack_upgrade" - } -} \ No newline at end of file diff --git a/src/main/resources/data/storagenetwork/recipes/stock_upgrade.json b/src/main/resources/data/storagenetwork/recipes/stock_upgrade.json deleted file mode 100644 index be42fa91..00000000 --- a/src/main/resources/data/storagenetwork/recipes/stock_upgrade.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - - "type": "minecraft:crafting_shaped", - "pattern": [ - " c ", - "gig", - " c " - ], - "key": { - "c": { - "tag": "forge:dusts/redstone" - }, - "i": { - "item": "storagenetwork:kabel" - }, - "g": { - "item": "minecraft:chest" - } - }, - "result": { - "item": "storagenetwork:stock_upgrade" - } -} \ No newline at end of file diff --git a/src/main/resources/META-INF/mods.toml b/src/main/templates/META-INF/neoforge.mods.toml similarity index 55% rename from src/main/resources/META-INF/mods.toml rename to src/main/templates/META-INF/neoforge.mods.toml index 65bddd70..d111d3a7 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/templates/META-INF/neoforge.mods.toml @@ -1,63 +1,75 @@ -# This is an example mods.toml file. It contains the data relating to the loading mods. +# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods. # There are several mandatory fields (#mandatory), and many more that are optional (#optional). # The overall format is standard TOML format, v0.5.0. # Note that there are a couple of TOML lists in this file. # Find more information on toml format here: https://github.com/toml-lang/toml # The name of the mod loader type to load - for regular FML @Mod mods it should be javafml modLoader="javafml" #mandatory +license="${mod_license}" +# A version range to match for said mod loader - for regular FML @Mod it will be the FML version. This is currently 2. +loaderVersion="${loader_version_range}" #mandatory -license="MIT" - -# A version range to match for said mod loader - for regular FML @Mod it will be the forge version -loaderVersion="[46,)" #mandatory (26 is current forge version) # A URL to refer people to when problems occur with this mod -issueTrackerURL="https://github.com/Lothrazar/Storage-Network/issues" #optional +issueTrackerURL="https://github.com/Lothrazar/${mod_id}/issues" #optional # A list of mods - how many allowed here is determined by the individual mod loader [[mods]] #mandatory # The modid of the mod modId="${mod_id}" #mandatory - # The version number of the mod - there's a few well known ${} variables useable here or just hardcode it version="${mod_version}" #mandatory # A display name for the mod -displayName="Simple Storage Network" #mandatory + +displayName="${mod_name}" #mandatory # A URL to query for updates for this mod. See the JSON update specification -updateJSONURL="https://raw.githubusercontent.com/Lothrazar/Storage-Network/trunk/1.19/update.json" #optional -# A URL for the "homepage" for this mod, displayed in the mod UI -displayURL="https://minecraft.curseforge.com/projects/simple-storage-network" #optional +# updateJSONURL="https://raw.githubusercontent.com/Lothrazar/${mod_id}/trunk/${minecraft_version}/update.json" #optional +# A URL for the "homepage" for this mod, displayed in the mod UI # replace with your website +displayURL="https://www.curseforge.com/minecraft/mc-mods/${curse_slug}" + # A file name (in the root of the mod JAR) containing a logo for display logoFile="logoFile.png" #optional + # A text field displayed in the mod UI -credits="MrRiegel for the original mod" #optional -# A text field displayed in the mod UI -authors="Lothrazar, MrRiegel" #optional +authors="${mod_authors}" #optional # The description text for the mod (multi line!) (#mandatory) + description=''' -Storage Network to connect inventories to search and craft +${mod_description} ''' +# The [[mixins]] block allows you to declare your mixin config to FML so that it gets loaded. +#[[mixins]] +#config="${mod_id}.mixins.json" + +#[features.${mod_id}] +#openGLVersion="[3.2,)" + +# The [[accessTransformers]] block allows you to declare where your AT file is. +# If this block is omitted, a fallback attempt will be made to load an AT from META-INF/accesstransformer.cfg +[[accessTransformers]] + file="META-INF/accesstransformer.cfg" + # A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. -[[dependencies.storagenetwork]] #optional +[[dependencies.${mod_id}]] #optional # the modid of the dependency - modId="forge" #mandatory + modId="neoforge" #mandatory # Does this dependency have to exist - if not, ordering below must be specified - mandatory=true #mandatory + type="required" # was mandatory=true # The version range of the dependency - versionRange="[46,)" #mandatory + versionRange="[${neo_version},)" #mandatory # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory ordering="NONE" # Side this dependency is applied on - BOTH, CLIENT or SERVER side="BOTH" -# Here's another dependency -[[dependencies.storagenetwork]] +[[dependencies.${mod_id}]] modId="minecraft" - mandatory=true - versionRange="[${mc_version},)" + type="required" # was mandatory=true + versionRange="[${minecraft_version},)" ordering="NONE" side="BOTH" -[[dependencies.storagenetwork]] + +[[dependencies.${mod_id}]] modId="flib" - mandatory=true - versionRange="[0.0.14,)" + type="required" + versionRange="[${flib_version},)" ordering="NONE" - side="BOTH" \ No newline at end of file + side="BOTH" diff --git a/update.json b/update.json index 92f7f45b..7902ed82 100644 --- a/update.json +++ b/update.json @@ -1,20 +1,10 @@ { "homepage": "https://www.curseforge.com/minecraft/mc-mods/simple-storage-network", "promos": { - "1.20.1-latest": "1.13.0" + "1.21.1-latest": "1.13.0" }, - "1.20.1": { - "1.10.0":"Ported to 1.20.1, depends on flib-0.0.7+ . Fixed patchouli book. Port to new non-deprecated curios datapack tags. Includes pull requests merged into the 1.18 and 1.19 branches : Merge pull request #492 from IIpragmaII/trunk/1.18 @IIpragmaII @VasurTrekkson Improved performance for export node. fix priority german translation @lightlike . Fixed recipes not showing when pressing the JEI recipe key @Demerso. Create uk_ua.json @SKZGx " - ,"1.10.1":" Merge pull request #518 from ALFEECLARE: add ja_jp translation." - ,"1.11.0":" Fix the bug when using small window sizes where the top row of player inventory items getting inserted instead of picked up when using the remote when jei is installed. Merge pull request #536 from maxpowa : Add support for EMI mod; this also fixes crash #513. " - - ,"1.11.1":"The Storage Request Table 'storagenetwork:request' block no longer saves the contents of its crafting-grid; instead items are returned to the player on close, exactly matching vanilla crafting table behavior (this was changed to prevent potential exploits. If any items are left behind in the grid during world upgrade they will be returned and not lost. No changes were made to the remotes or to other blocks). Fixed a null pointer exception " - - ,"1.11.2":"Ported the Cable Facades feature (from Minecraft 1.12.2), so that you can shift-left-click with a block on a cable to hide it with a facade. Disable this feature or ignore certain blocks with the config file" - ,"1.11.3":"Fixed item tooltips not rendering in Storage Remote. Fixed visual rendering and text errors inside of import/export cables using the 'operation upgrade'" - ,"1.12.0":"Added a new Expanded Request Table and the Expanded Remote to support GUI Scale 2 or larger for players on large monitors/resolutions. Internal refactoring for Import and Export cable capabilities: item transactions are now executed inside the cable tile-entities instead of the main node tile-entity (meaning the main root node is doing less processing work, and also the network overall should have fewer wasted cycles). " - ,"1.12.1": "Fix JEI/EMI recipe autocomplete" - ,"1.13.0": "Improved look and feel of the plain Network Cable intersections. Merge pull request #593 from KishCom/trunk/1.20.1, Fix multiple export cables not working fixing #581\n Merge pull request #586 from ArtByteFilip/trunk/1.20.1 added the option to turn the network collector remote on and off " + "1.21.1": { + "1.13.0": "Improved look and feel of the plain Network Cable intersections. Merge pull request #593 from KishCom/trunk/1.20.1, Fix multiple export cables not working fixing #581\n Merge pull request #586 from ArtByteFilip/trunk/1.20.1 added the option to turn the network collector remote on and off " } }