diff --git a/.editorconfig b/.editorconfig index a18e8d5829..0614989b23 100644 --- a/.editorconfig +++ b/.editorconfig @@ -25,5 +25,5 @@ ij_java_blank_lines_before_method_body = 0 ij_java_else_on_new_line = false ij_java_class_count_to_use_import_on_demand = 999 ij_java_names_count_to_use_import_on_demand = 999 -ij_java_imports_layout = $*,|,java.**,|,javax.**,|,org.**,|,com.**,|,*,|,net.minecraftforge.** +ij_java_imports_layout = $*,|,java.**,|,javax.**,|,org.**,|,com.**,|,*,|,net.neoforged.** ij_java_insert_inner_class_imports = true \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000000..12c7b0873b --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,31 @@ +name: Build + +on: [ workflow_dispatch, push, pull_request ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Setup Java + run: echo "JAVA_HOME=$JAVA_HOME_17_X64" >> "$GITHUB_ENV" + + - name: NeoGradle Cache + uses: actions/cache@v4 + with: + path: "**/.gradle/repositories/" + key: "${{ runner.os }}-gradle-${{ hashFiles('**/libs.versions.*', '**/*.gradle*', '**/gradle-wrapper.properties') }}" + restore-keys: "${{ runner.os }}-gradle-" + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + with: + gradle-home-cache-cleanup: true + + - name: Validate Gradle Wrapper Integrity + uses: gradle/wrapper-validation-action@v2 + + - name: Build + run: ./gradlew build diff --git a/.github/workflows/gametest.yml b/.github/workflows/gametest.yml index 23bb055a98..4d65d58b00 100644 --- a/.github/workflows/gametest.yml +++ b/.github/workflows/gametest.yml @@ -1,23 +1,33 @@ -name: gametest +name: GameTests + on: [ workflow_dispatch ] jobs: - build: - runs-on: ubuntu-latest - steps: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v4 - - name: checkout repository - uses: actions/checkout@v3 + - name: Setup Java + run: echo "JAVA_HOME=$JAVA_HOME_17_X64" >> "$GITHUB_ENV" - - name: setup Java - uses: actions/setup-java@v3 - with: - distribution: temurin - java-version: 17 - cache: gradle + - name: NeoGradle Cache + uses: actions/cache@v4 + if: ${{ !endsWith(github.ref, '/dev') }} + with: + path: "**/.gradle/repositories/" + key: "${{ runner.os }}-gradle-${{ hashFiles('**/libs.versions.*', '**/*.gradle*', '**/gradle-wrapper.properties') }}" + restore-keys: "${{ runner.os }}-gradle-" - - name: make gradle wrapper executable - run: chmod +x ./gradlew + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + with: + gradle-home-cache-cleanup: true + cache-read-only: ${{ !endsWith(github.ref, '/dev') }} - - name: run gametests - run: ./gradlew prepareRunGameTestServer runGameTestServer --no-daemon + - name: Validate Gradle Wrapper Integrity + uses: gradle/wrapper-validation-action@v2 + + - name: Run GameTest Server + run: ./gradlew runGameTestServer diff --git a/.github/workflows/label-actions.yml b/.github/workflows/label-actions.yml index 1b59fae39c..76a959ab24 100644 --- a/.github/workflows/label-actions.yml +++ b/.github/workflows/label-actions.yml @@ -1,21 +1,21 @@ name: "Label Actions" on: - issues: - types: [labeled, unlabeled] - pull_request_target: - types: [labeled, unlabeled] + issues: + types: [ labeled, unlabeled ] + pull_request_target: + types: [ labeled, unlabeled ] permissions: - contents: read - issues: write - pull-requests: write - discussions: write + contents: read + issues: write + pull-requests: write + discussions: write jobs: - action: - runs-on: ubuntu-latest - steps: - - uses: dessant/label-actions@102faf474a544be75fbaf4df54e73d3c515a0e65 # Depend on an exact commit - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - config-path: '.github/config/label-actions.yml' + action: + runs-on: ubuntu-latest + steps: + - uses: dessant/label-actions@102faf474a544be75fbaf4df54e73d3c515a0e65 # Depend on an exact commit + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + config-path: '.github/config/label-actions.yml' diff --git a/.github/workflows/localization.yml b/.github/workflows/localization.yml index 01bed80205..b3605fd8a8 100644 --- a/.github/workflows/localization.yml +++ b/.github/workflows/localization.yml @@ -5,44 +5,44 @@ name: Crowdin Action # Controls when the action will run. on: workflow_dispatch - # Only run when started manually + # Only run when started manually - #: - # inputs: - # uploadTranslations: - # description: "Set to true to upload (changed) translations to Crowdin" - # type: boolean - # required: true - # default: false + #: + # inputs: + # uploadTranslations: + # description: "Set to true to upload (changed) translations to Crowdin" + # type: boolean + # required: true + # default: false - #schedule: - #- cron: '0 */6 * * *' # Every 6 hours - https://crontab.guru/#0_*/6_*_*_* +#schedule: +#- cron: '0 */6 * * *' # Every 6 hours - https://crontab.guru/#0_*/6_*_*_* jobs: - synchronize-with-crowdin: - runs-on: ubuntu-latest + synchronize-with-crowdin: + runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v2 + steps: + - name: Checkout + uses: actions/checkout@v2 - - name: crowdin action - uses: crowdin/github-action@1.4.9 - with: - # Upload sources to Crowdin - upload_sources: true - # Upload translations to Crowdin, only use true at initial run - upload_translations: false - # Make pull request of Crowdin translations - download_translations: true - # To download translations to the specified version branch - localization_branch_name: l10n_crowdin_translations - # Create pull request after pushing to branch - create_pull_request: true - pull_request_title: 'New Crowdin translations' - pull_request_body: 'New Crowdin pull request with translations' - pull_request_base_branch_name: 'mc1.20.1/dev' - env: - GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} - CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }} - CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }} + - name: crowdin action + uses: crowdin/github-action@1.4.9 + with: + # Upload sources to Crowdin + upload_sources: true + # Upload translations to Crowdin, only use true at initial run + upload_translations: false + # Make pull request of Crowdin translations + download_translations: true + # To download translations to the specified version branch + localization_branch_name: l10n_crowdin_translations + # Create pull request after pushing to branch + create_pull_request: true + pull_request_title: 'New Crowdin translations' + pull_request_body: 'New Crowdin pull request with translations' + pull_request_base_branch_name: 'mc1.20.1/dev' + env: + GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} + CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }} + CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }} diff --git a/build.gradle b/build.gradle index 89d9b78bb1..73f6a5d780 100644 --- a/build.gradle +++ b/build.gradle @@ -1,459 +1,230 @@ plugins { - id 'idea' + id 'java-library' id 'eclipse' + id 'idea' id 'maven-publish' - - id 'net.minecraftforge.gradle' version "${forgegradle_version}" - id 'org.spongepowered.mixin' version "${mixingradle_version}" - id 'org.parchmentmc.librarian.forgegradle' version "${librarian_version}" - - id 'com.matthewprenger.cursegradle' version "${cursegradle_version}" + id 'net.neoforged.moddev' version '2.0.9-beta' } -apply from: './gradle/java.gradle' +boolean dev = System.getenv('RELEASE') == null || System.getenv('RELEASE').equals('false'); +String buildNumber = System.getenv('BUILD_NUMBER') -jarJar.enable() +version = project.mod_version + (dev && buildNumber != null ? "-${buildNumber}" : '') +group = project.maven_group -boolean dev = System.getenv('RELEASE') == null || System.getenv('RELEASE').equals('false') -ext.buildNumber = System.getenv('BUILD_NUMBER') +repositories { + mavenLocal() +} base { - archivesName = "create-${artifact_minecraft_version}" - group = 'com.simibubi.create' - version = mod_version + (dev && buildNumber != null ? "-${buildNumber}" : '') + archivesName = "$mod_id-$minecraft_version" } -boolean inMultiModWorkspace = rootProject.hasProperty('multiModWorkspace.enabled') -boolean catnipInWorkspace = rootProject.hasProperty('multiModWorkspace.catnip') -boolean ponderInWorkspace = rootProject.hasProperty('multiModWorkspace.ponder') +java.toolchain.languageVersion = JavaLanguageVersion.of(21) -if (catnipInWorkspace) { - evaluationDependsOn(":catnip:Forge") -} +neoForge { + version = project.neo_version -if (ponderInWorkspace) { - evaluationDependsOn(":ponder:Forge") -} - -project.logger.lifecycle("MultiModWorkspace ${inMultiModWorkspace ? 'enabled' : 'disabled'} for project ${project.name}.") -project.logger.lifecycle("Dependencies included in Workspace: [Catnip: ${catnipInWorkspace}], [Ponder: ${ponderInWorkspace}]") - -mixin { - add sourceSets.main, 'create.refmap.json' - - config 'create.mixins.json' -} - -println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" - -mixin { - add sourceSets.main, 'create.refmap.json' - - debug.verbose = true - debug.export = true -} - -idea { - module { - downloadJavadoc = true - downloadSources = true - } -} - -minecraft { - - if (Boolean.parseBoolean(use_parchment)) { - mappings channel: 'parchment', version: "${parchment_version}-${minecraft_version}" - } else { - mappings channel: 'official', version: "${minecraft_version}" + parchment { + minecraftVersion = project.parchment_minecraft_version + mappingsVersion = project.parchment_version } - // This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game. - copyIdeResources = true - - if (file('src/main/resources/META-INF/accesstransformer.cfg').exists()) { - accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') - } + accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg') runs { - // applies to all the run configs below - configureEach { - if (inMultiModWorkspace) - ideaModule "createmod.Create.main" - else - ideaModule "Create.main" - - property 'forge.logging.markers', '' - property 'forge.logging.console.level', 'info' - jvmArgs '-XX:+IgnoreUnrecognizedVMOptions', '-XX:+AllowEnhancedClassRedefinition' - //jvmArgs("-XX:-OmitStackTraceInFastThrow") // uncomment when you get exceptions with null messages etc - //jvmArgs '-XX:+UnlockCommercialFeatures' // uncomment for profiling - - property 'mixin.debug.export', 'true' - property 'mixin.env.remapRefMap', 'true' - property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg" - - arg '-mixin.config=create.mixins.json' - arg '-mixin.config=catnip.mixins.json' - - mods { - create { - source sourceSets.main - } - - if (catnipInWorkspace) { - catnip { - source project(":catnip:Common").sourceSets.main - source project(":catnip:Forge").sourceSets.main - } - } - - if (ponderInWorkspace) { - ponder { - source project(":ponder:Common").sourceSets.main - source project(":ponder:Forge").sourceSets.main - } - } - } - } - client { - workingDirectory project.file('run') + client() + + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id } server { - workingDirectory project.file('run/server') + server() + + gameDirectory = project.file('run/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 { - workingDirectory project.file('run') - property 'forge.logging.markers', 'REGISTRIES,REGISTRYDUMP' - property 'forge.logging.console.level', 'debug' - args '--mod', 'create', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources') + 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() } - gameTestServer { - workingDirectory project.file('run/gametest') - // setForceExit false <- FIXME 1.20 + configureEach { + systemProperty 'forge.logging.markers', 'REGISTRIES' + + systemProperty 'mixin.debug.verbose', 'true' + systemProperty 'mixin.debug.export', 'true' + + // IThundxr ~ I use JBR for enhanced hotswap, this adds the required arg while not affecting other people + jvmArguments = ["-XX:+AllowEnhancedClassRedefinition", "-XX:+IgnoreUnrecognizedVMOptions"] + + logLevel = org.slf4j.event.Level.DEBUG + } + } + + mods { + "${mod_id}" { + sourceSet(sourceSets.main) } } } +configurations { + runtimeClasspath.extendsFrom localRuntime +} + repositories { - maven { - // location of the maven for Registrate and Flywheel - name = 'tterrag maven' - url = 'https://maven.tterrag.com' - } - maven { - // location of the maven that hosts JEI files since January 2023 - // location of the maven for Vazkii's mods - name = "Jared's maven" - url = "https://maven.blamejared.com/" - } - /*maven { - // location of a maven mirror for JEI files, as a fallback - name = "ModMaven" - url = "https://modmaven.dev" - }*/ - maven { - // location of the maven for Dynamic Trees - url = 'https://harleyoconnor.com/maven' - } - maven { - // location of the maven for Curios API - url = "https://maven.theillusivec4.top/" - } - maven { - // location of maven for CC: Tweaked - name = "squiddev" - url = "https://squiddev.cc/maven/" - } - maven { - name = "ftb" - url = "https://maven.saps.dev/releases" - } - maven { - name = "architectury" - url = "https://maven.architectury.dev/" - } - maven { - url = "https://jm.gserv.me/repository/maven-public/" + maven { url = "https://maven.createmod.net" } // Ponder, Catnip + maven { url = "https://maven.tterrag.com" } // Flywheel + maven { url = "https://maven.ithundxr.dev/snapshots" } // Registrate + maven { url = "https://maven.blamejared.com" } // JEI, Vazkii's Mods + maven { url = "https://harleyoconnor.com/maven" } // Dynamic Trees + maven { url = "https://maven.theillusivec4.top/" } // Curios API + maven { url = "https://maven.squiddev.cc/" } // CC: Tweaked + maven { url = "https://www.cursemaven.com" } + maven { url = "https://api.modrinth.com/maven" } + maven { url = "https://maven.saps.dev/releases" } // FTB Mods + maven { url = "https://maven.architectury.dev/" } // Arch API + maven { url = "https://jm.gserv.me/repository/maven-public/" // JourneyMap content { includeGroup "info.journeymap" includeGroup "mysticdrew" } } - - maven { - url = 'https://www.cursemaven.com' - content { - includeGroup "curse.maven" - } - } - maven { - // Location of the maven for Ponder, Catnip - name = 'createmod maven' - url 'https://maven.createmod.net' - } - maven { - name = "Modrinth" - url = "https://api.modrinth.com/maven" - content { - includeGroup "maven.modrinth" - } - } - maven { url = "https://raw.githubusercontent.com/Fuzss/modresources/main/maven/" } - // Mirror of maven.createmod.net if (System.getProperty("os.name").contains("Mac") && System.getenv("USER") == "ithundxr") { maven { url = "https://maven.ithundxr.dev/mirror" } } - mavenCentral() - mavenLocal() + // todo - temp + maven { url = "https://maven.ithundxr.dev/hidden" } // Flywheel 1.21 PR flatDir { - dirs 'libs' + dirs "libs" + } +} + +dependencies { + jarJar(implementation("com.tterrag.registrate:Registrate:${registrate_version}")) + + compileOnly("dev.engine_room.flywheel:flywheel-neoforge-api-${flywheel_minecraft_version}:${flywheel_version}") + jarJar(runtimeOnly("dev.engine_room.flywheel:flywheel-neoforge-${flywheel_minecraft_version}:${flywheel_version}")) + + jarJar(implementation("net.createmod.catnip:Catnip-NeoForge-${catnip_and_ponder_mc_ver}:${catnip_version}")) + jarJar(implementation("net.createmod.ponder:Ponder-NeoForge-${catnip_and_ponder_mc_ver}:${ponder_version}")) + + //compileOnly("mezz.jei:jei-${jei_minecraft_version}-common-api:${jei_version}") + //compileOnly("mezz.jei:jei-${jei_minecraft_version}-neoforge-api:${jei_version}") + implementation("mezz.jei:jei-${jei_minecraft_version}-neoforge:${jei_version}") + + compileOnly("top.theillusivec4.curios:curios-neoforge:${curios_version}+${curios_minecraft_version}:api") + // FIXME: Look into what to replace this with + //runtimeOnly("top.theillusivec4.curios:curios-neoforge:${curios_version}+${curios_minecraft_version}") + + if (cc_tweaked_enable.toBoolean()) { + compileOnly("cc.tweaked:cc-tweaked-${cc_tweaked_minecraft_version}-core-api:${cc_tweaked_version}") + compileOnly("cc.tweaked:cc-tweaked-${cc_tweaked_minecraft_version}-forge-api:${cc_tweaked_version}") + if (!cc_tweaked_disable_runtime.toBoolean()) + runtimeOnly("cc.tweaked:cc-tweaked-${cc_tweaked_minecraft_version}-forge:${cc_tweaked_version}") + } + + implementation("dev.architectury:architectury-neoforge:13.0.8") + implementation("dev.ftb.mods:ftb-chunks-neoforge:2101.1.1") + implementation("dev.ftb.mods:ftb-teams-neoforge:2101.1.0") + implementation("dev.ftb.mods:ftb-library-neoforge:2101.1.3") + + implementation("maven.modrinth:journeymap:1.21.1-6.0.0-beta.32+neoforge") + implementation("info.journeymap:journeymap-api-neoforge:2.0.0-1.21.1-SNAPSHOT") + + // implementation("curse.maven:druidcraft-340991:3101903") + // implementation("com.ferreusveritas.dynamictrees:DynamicTrees-1.16.5:0.10.0-Beta25") + // runtimeOnly("vazkii.arl:AutoRegLib:1.4-35.69") + // runtimeOnly("vazkii.quark:Quark:r2.0-212.984") + // runtimeOnly("slimeknights.mantle:Mantle:1.16.5-1.6.115") + // runtimeOnly("slimeknights.tconstruct:TConstruct:1.16.5-3.1.1.252") + // runtimeOnly("maven.modrinth:rubidium:0.5.3") + // implementation("com.railwayteam.railways:railways-1.18.2-1.1.1:all" { transitive = false }) + // runtimeOnly("maven.modrinth:aether:1.19.2-1.0.0-beta.1.1-forge") + // runtimeOnly("maven.modrinth:spark:1.10.38-forge") + // runtimeOnly("curse.maven:xycraft-653786:4788862") + // runtimeOnly("curse.maven:xycraft-world-653789:4788863") +} + +sourceSets.main.java { + if (!cc_tweaked_enable.toBoolean()) { + exclude "com/simibubi/create/compat/computercraft/implementation/**" } } sourceSets.main.resources { - srcDir 'src/generated/resources' - exclude '.cache/' + srcDir "src/generated/resources" + exclude ".cache/" } -dependencies { - minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" - - jarJar("com.tterrag.registrate:Registrate:${registrate_version}") { - jarJar.ranged(it, '[MC1.19.3-1.1.10,)') - } - jarJar("dev.engine_room.flywheel:flywheel-forge-${flywheel_minecraft_version}:${flywheel_version}") { - jarJar.ranged(it, '[1.0,2.0)') - } - - jarJar("net.createmod.catnip:Catnip-Forge-${minecraft_version}:${catnip_version}") { - jarJar.ranged(it, '[0.7.5,)') - } - jarJar("net.createmod.ponder:Ponder-Forge-${minecraft_version}:${ponder_version}") { - jarJar.ranged(it, '[0.7.5,)') - } - - implementation(jarJar("io.github.llamalad7:mixinextras-forge:${mixin_extras_version}")) { - jarJar.ranged(it, "[${mixin_extras_version},)") - } - - implementation fg.deobf("com.tterrag.registrate:Registrate:${registrate_version}") - - compileOnly fg.deobf("dev.engine_room.flywheel:flywheel-forge-api-${flywheel_minecraft_version}:${flywheel_version}") - runtimeOnly fg.deobf("dev.engine_room.flywheel:flywheel-forge-${flywheel_minecraft_version}:${flywheel_version}") - - if (catnipInWorkspace) { - implementation project(":catnip:Common") - implementation project(":catnip:Forge") - } else { - implementation fg.deobf("net.createmod.catnip:Catnip-Forge-${minecraft_version}:${catnip_version}") - } - - if (ponderInWorkspace) { - implementation project(":ponder:Common") - implementation project(":ponder:Forge") - } else { - implementation fg.deobf("net.createmod.ponder:Ponder-Forge-${minecraft_version}:${ponder_version}") - } - - compileOnly(annotationProcessor("io.github.llamalad7:mixinextras-common:${mixin_extras_version}")) - - // compileOnly fg.deobf("mezz.jei:jei-${jei_minecraft_version}-common-api:${jei_version}") - // compileOnly fg.deobf("mezz.jei:jei-${jei_minecraft_version}-forge-api:${jei_version}") - implementation fg.deobf("mezz.jei:jei-${jei_minecraft_version}-forge:${jei_version}") - - compileOnly fg.deobf("top.theillusivec4.curios:curios-forge:${curios_version}+${curios_minecraft_version}:api") - runtimeOnly fg.deobf("top.theillusivec4.curios:curios-forge:${curios_version}+${curios_minecraft_version}") - - if (cc_tweaked_enable.toBoolean()) { - compileOnly("cc.tweaked:cc-tweaked-${cc_tweaked_minecraft_version}-core-api:${cc_tweaked_version}") - compileOnly fg.deobf("cc.tweaked:cc-tweaked-${cc_tweaked_minecraft_version}-forge-api:${cc_tweaked_version}") - runtimeOnly fg.deobf("cc.tweaked:cc-tweaked-${cc_tweaked_minecraft_version}-forge:${cc_tweaked_version}") - } - - if (dynamic_trees_enable.toBoolean()) { - compileOnly fg.deobf("com.ferreusveritas.dynamictrees:DynamicTrees-${dynamic_trees_minecraft_version}:${dynamic_trees_version}") - } - - // implementation fg.deobf("curse.maven:ic2-classic-242942:5555152") - // implementation fg.deobf("curse.maven:druidcraft-340991:3101903") - // implementation fg.deobf("com.railwayteam.railways:railways-1.19.2-1.6.4:all") { transitive = false } - - implementation fg.deobf("dev.architectury:architectury-forge:9.1.12") - implementation fg.deobf("dev.ftb.mods:ftb-chunks-forge:2001.3.1") - implementation fg.deobf("dev.ftb.mods:ftb-teams-forge:2001.3.0") - implementation fg.deobf("dev.ftb.mods:ftb-library-forge:2001.2.4") - - implementation fg.deobf("curse.maven:journeymap-32274:5457831") - // implementation fg.deobf("ignored:journeymap-1.20.1-5.10.1-forge") - - // runtimeOnly fg.deobf("curse.maven:framedblocks-441647:5399211") - // runtimeOnly fg.deobf("curse.maven:galosphere-631098:4574834") - // runtimeOnly fg.deobf("curse.maven:elementary-ores-332609:4514276") 1.19.4 only - // runtimeOnly fg.deobf("curse.maven:flib-661261:4479544") - // runtimeOnly fg.deobf("curse.maven:infernal-expansion-395078:4002091") - // runtimeOnly fg.deobf("vazkii.autoreglib:AutoRegLib:1.8.2-58.126") - // runtimeOnly fg.deobf("curse.maven:quark-243121:4812006") - // runtimeOnly fg.deobf("curse.maven:mantle-74924:5339977") - // runtimeOnly fg.deobf("curse.maven:tinkers-construct-74072:5358052") - // runtimeOnly fg.deobf("maven.modrinth:rubidium:0.6.2c") - // runtimeOnly fg.deobf("maven.modrinth:aether:1.19.2-1.4.2-forge") - // runtimeOnly fg.deobf("maven.modrinth:spark:1.10.38-forge") - // runtimeOnly fg.deobf("curse.maven:forbidden-arcanus-309858:4852521") - // runtimeOnly fg.deobf("curse.maven:valhelsia-core-416935:4181245") - // runtimeOnly fg.deobf("curse.maven:modern-ui-352491:5229370") - // runtimeOnly fg.deobf("curse.maven:sophisticated-storage-619320:5194750") - // runtimeOnly fg.deobf("curse.maven:sophisticated-core-618298:5296313") - // runtimeOnly fg.deobf("curse.maven:functional-storage-556861:5499169") - // runtimeOnly fg.deobf("curse.maven:titanium-287342:5356458") - // runtimeOnly fg.deobf("curse.maven:storage-drawers-223852:3884263") - // runtimeOnly fg.deobf("curse.maven:ftb-chunks-forge-314906:5417874") - // runtimeOnly fg.deobf("curse.maven:architectury-api-419699:5137942") - // runtimeOnly fg.deobf("curse.maven:ftb-library-forge-404465:4661834") - // runtimeOnly fg.deobf("curse.maven:ftb-teams-forge-404468:4611938") - // runtimeOnly fg.deobf("curse.maven:citadel-331936:4556677") - // runtimeOnly fg.deobf("curse.maven:ice-and-fire-dragons-264231:5037952") - // runtimeOnly fg.deobf("curse.maven:exnihilosequentia-400012:4993344") - // runtimeOnly fg.deobf("curse.maven:upgrade-aquatic-326895:4777515") - // runtimeOnly fg.deobf("curse.maven:blueprint-382216:4749000") - // runtimeOnly fg.deobf("curse.maven:windsweptmod-636321:4817132") - // runtimeOnly fg.deobf("curse.maven:good-ending-690161:4363719") - - // https://discord.com/channels/313125603924639766/725850371834118214/910619168821354497 - // Prevent Mixin annotation processor from getting into IntelliJ's annotation processor settings - // This allows 'Settings > Build, Execution, and Deployment > Build Tools > Gradle > Build and run using' set to IntelliJ to work correctly - if (!Boolean.getBoolean('idea.sync.active')) { - annotationProcessor "org.spongepowered:mixin:${mixin_version}:processor" - } -} - -sourceSets.main.java { - if (!cc_tweaked_enable.toBoolean()) { - exclude 'com/simibubi/create/compat/computercraft/implementation/**' - } -} - -// Workaround for SpongePowered/MixinGradle#38 -afterEvaluate { - tasks.configureReobfTaskForReobfJar.mustRunAfter(tasks.compileJava) - tasks.configureReobfTaskForReobfJarJar.mustRunAfter(tasks.compileJava) -} - -processResources { - def buildProps = project.properties.clone() - - // Replaces FML's magic file.jarVersion string with the correct version at build time. - buildProps.put('file', [jarVersion: project.version]) - - filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { - expand buildProps - } -} - -compileJava { - options.compilerArgs = ['-Xdiags:verbose'] -} - -void addLicense(jarTask) { - jarTask.from('LICENSE') { +jar { + from('LICENSE') { rename { "${it}_${project.archivesBaseName}" } } } -tasks.jar { - archiveClassifier = 'slim' - finalizedBy('reobfJar') - addLicense it -} +tasks.withType(ProcessResources).configureEach { + var replaceProperties = [ + mod_version : mod_version, + mod_id : mod_id, + mod_name : mod_name, + mod_author : mod_author, + mod_description : mod_description, + mod_license : mod_license, + minecraft_version_range: minecraft_version_range, + neo_version_range : neo_version_range, + flywheel_version_range : flywheel_version_range, + ] + inputs.properties replaceProperties -tasks.jarJar { - finalizedBy('reobfJarJar') - addLicense it -} - -task jarJarRelease { - group = 'jarjar' - doLast { - tasks.jarJar { - archiveClassifier = '' - } + filesMatching(['META-INF/neoforge.mods.toml']) { + expand replaceProperties } - finalizedBy tasks.jarJar } -project.publishing { +java { + withSourcesJar() +} + +publishing { publications { - mavenJava(MavenPublication) { - artifactId base.archivesName.get() + register('mavenJava', MavenPublication) { from components.java - fg.component(it) - jarJar.component(it) } } - repositories { if (project.hasProperty('mavendir')) { - maven { url mavendir } + maven { url = mavendir } } } } -String getChangelogText() { - def changelogFile = file('changelog.txt') - String str = '' - int lineCount = 0 - boolean done = false - changelogFile.eachLine { - if (done || it == null) { - return - } - if (it.size() > 1) { - def temp = it - if (lineCount == 0) { - temp = "Create ${version}" - temp = "Create v${mod_version}  for Minecraft ${minecraft_version}
" - } else if (it.startsWith('-')) { - temp = "   $temp
" - temp = temp.replaceAll("(\\S+\\/\\S+)#([0-9]+)\\b", "\$0"); - temp = temp.replaceAll("#([0-9]+)\\b(?!<\\/a>)", "\$0"); - } else { - temp = "

$temp

" - } - str += temp - lineCount++ - } else { - str += "

Please submit any Issues you come across on the Issue Tracker.

" - done = true - } - } - return str +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' } -// changelog debugging -// new File("changelog.html").write getChangelogText() -// tasks.curseforge.enabled = !dev && project.hasProperty('simi_curseforge_key') -// curseforge { -// if (project.hasProperty('simi_curseforge_key')) { -// apiKey = project.simi_curseforge_key -// } -// -// project { -// id = project.projectId -// changelog = System.getenv('CHANGELOG') == null || System.getenv('CHANGELOG').equals('none') ? getChangelogText() : System.getenv('CHANGELOG') -// changelogType = 'html' -// releaseType = project.curse_type -// mainArtifact(shadowJar) { -// displayName = "Create - ${version}" -// } -// relations { -// optionalDependency 'jei' -// } -// } -// } +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/gradle.properties b/gradle.properties index 90f3b5e55e..19ccf99a1d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,55 +1,45 @@ -# 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 = -Xmx3G org.gradle.daemon = false +org.gradle.caching = true -# mod version info +# Mod Info mod_version = 0.5.2 -artifact_minecraft_version = 1.20.1 +maven_group = com.simibubi.create -minecraft_version = 1.20.1 -forge_version = 47.2.6 - -# build dependency versions -forgegradle_version = [6.0.16,6.2) -mixingradle_version = 0.7.+ -mixin_version = 0.8.5 -librarian_version = 1.+ -cursegradle_version = 1.4.0 -parchment_version = 2023.09.03 - -use_parchment = true - -# dependency versions -registrate_version = MC1.20-1.3.3 -flywheel_minecraft_version = 1.20.1 -flywheel_version = 1.0.0-beta-177 -jei_minecraft_version = 1.20.1 -jei_version = 15.10.0.39 -curios_minecraft_version = 1.20.1 -curios_version = 5.3.1 -catnip_version = 0.8.42 -ponder_version = 0.8.15 -mixin_extras_version = 0.4.1 - -cc_tweaked_enable = true -cc_tweaked_minecraft_version = 1.20.1 -cc_tweaked_version = 1.105.0 - -dynamic_trees_enable = true -dynamic_trees_minecraft_version = 1.20.1 -dynamic_trees_version = 1.3.0-BETA13 - -# mod options mod_id = create mod_name = Create mod_author = simibubi mod_description = Technology that empowers the player. mod_license = MIT -# curseforge information -projectId = 328085 -curse_type = beta +# Mod Dependencies +minecraft_version = 1.21.1 +minecraft_version_range=[1.21.1] -# github information -github_project = Creators-of-Create/Create +neo_version = 21.1.71 +neo_version_range=[21.1.71,) + +parchment_minecraft_version = 1.21.1 +parchment_version = 2024.11.17 + +# From maven.ithundxr.dev/snapshots +registrate_version = MC1.21-1.3.0+58 + +# From maven.ithundxr.dev/hidden +flywheel_minecraft_version = 1.21.1 +flywheel_version = 1.0.0-beta-fork.10 +flywheel_version_range = [1.0.0-alpha,2.0) + +# Optional Dependencies +jei_minecraft_version = 1.21 +jei_version = 19.5.0.33 +curios_minecraft_version = 1.21.1 +curios_version = 9.0.15 +catnip_version = 0.8.43 +ponder_version = 0.8.7 +catnip_and_ponder_mc_ver = 1.21.1 + +cc_tweaked_enable = true +cc_tweaked_disable_runtime = true +cc_tweaked_minecraft_version = 1.21.1 +cc_tweaked_version = 1.114.2 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index c1962a79e2..e6441136f3 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 309b4e18db..a4413138c9 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.4-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index aeb74cbb43..b740cf1339 100755 --- a/gradlew +++ b/gradlew @@ -55,7 +55,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,7 +83,8 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -130,10 +131,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -198,11 +202,11 @@ fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f13..25da30dbde 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/settings.gradle b/settings.gradle index 1a196a6fe8..6f7f994cff 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,16 +1,9 @@ pluginManagement { repositories { + mavenLocal() gradlePluginPortal() - mavenCentral() - jcenter() - maven { url = 'https://maven.minecraftforge.net/' } - maven { url = 'https://repo.spongepowered.org/repository/maven-public' } - maven { url = 'https://maven.parchmentmc.org' } + maven { url = 'https://maven.neoforged.net/releases' } } } -plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' -} - rootProject.name = 'Create' diff --git a/src/main/java/com/simibubi/create/AllAttachmentTypes.java b/src/main/java/com/simibubi/create/AllAttachmentTypes.java new file mode 100644 index 0000000000..6c358adc4b --- /dev/null +++ b/src/main/java/com/simibubi/create/AllAttachmentTypes.java @@ -0,0 +1,22 @@ +package com.simibubi.create; + +import java.util.function.Supplier; + +import com.simibubi.create.content.contraptions.minecart.capability.MinecartController; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.attachment.AttachmentType; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; + +public class AllAttachmentTypes { + private static final DeferredRegister> ATTACHMENT_TYPES = DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, Create.ID); + + public static final Supplier> MINECART_CONTROLLER = ATTACHMENT_TYPES.register( + "minecart_controller", () -> AttachmentType.builder(MinecartController::empty).serialize(MinecartController.SERIALIZER).build() + ); + + public static void register(IEventBus modEventBus) { + ATTACHMENT_TYPES.register(modEventBus); + } +} diff --git a/src/main/java/com/simibubi/create/AllBlockEntityTypes.java b/src/main/java/com/simibubi/create/AllBlockEntityTypes.java index 2bbcc0c19e..dab50e6d20 100644 --- a/src/main/java/com/simibubi/create/AllBlockEntityTypes.java +++ b/src/main/java/com/simibubi/create/AllBlockEntityTypes.java @@ -346,7 +346,7 @@ public class AllBlockEntityTypes { .validBlocks(AllBlocks.HAND_CRANK) .renderer(() -> HandCrankRenderer::new) .register(); - + public static final BlockEntityEntry VALVE_HANDLE = REGISTRATE .blockEntity("valve_handle", ValveHandleBlockEntity::new) .visual(() -> HandCrankVisual::new) @@ -795,7 +795,7 @@ public class AllBlockEntityTypes { .validBlocks(AllBlocks.ANALOG_LEVER) .renderer(() -> AnalogLeverRenderer::new) .register(); - + public static final BlockEntityEntry PLACARD = REGISTRATE .blockEntity("placard", PlacardBlockEntity::new) .validBlocks(AllBlocks.PLACARD) @@ -941,7 +941,7 @@ public class AllBlockEntityTypes { .validBlocksDeferred(TrackMaterial::allBlocks) .renderer(() -> TrackRenderer::new) .register(); - + public static final BlockEntityEntry FAKE_TRACK = REGISTRATE .blockEntity("fake_track", FakeTrackBlockEntity::new) .validBlocks(AllBlocks.FAKE_TRACK) @@ -990,7 +990,7 @@ public class AllBlockEntityTypes { .renderer(() -> TrackObserverRenderer::new) .validBlocks(AllBlocks.TRACK_OBSERVER) .register(); - + public static final BlockEntityEntry CLIPBOARD = REGISTRATE .blockEntity("clipboard", ClipboardBlockEntity::new) .validBlocks(AllBlocks.CLIPBOARD) diff --git a/src/main/java/com/simibubi/create/AllBlocks.java b/src/main/java/com/simibubi/create/AllBlocks.java index a528a6c3c2..f81bd15f31 100644 --- a/src/main/java/com/simibubi/create/AllBlocks.java +++ b/src/main/java/com/simibubi/create/AllBlocks.java @@ -282,10 +282,10 @@ import com.simibubi.create.foundation.data.ModelGen; import com.simibubi.create.foundation.data.SharedProperties; import com.simibubi.create.foundation.item.ItemDescription; import com.simibubi.create.foundation.item.UncontainableBlockItem; +import com.simibubi.create.foundation.mixin.accessor.BlockLootSubProviderAccessor; import com.simibubi.create.foundation.utility.ColorHandlers; import com.simibubi.create.foundation.utility.DyeHelper; import com.tterrag.registrate.providers.RegistrateRecipeProvider; -import com.tterrag.registrate.providers.loot.RegistrateBlockLootTables; import com.tterrag.registrate.util.DataIngredient; import com.tterrag.registrate.util.entry.BlockEntry; @@ -293,6 +293,7 @@ import net.createmod.catnip.utility.Couple; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.data.loot.BlockLootSubProvider; import net.minecraft.data.recipes.RecipeCategory; @@ -305,6 +306,7 @@ import net.minecraft.tags.ItemTags; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.Items; import net.minecraft.world.item.Rarity; +import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; @@ -321,17 +323,17 @@ import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.LootTable.Builder; import net.minecraft.world.level.storage.loot.entries.LootItem; import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount; +import net.minecraft.world.level.storage.loot.functions.CopyComponentsFunction; import net.minecraft.world.level.storage.loot.functions.CopyNameFunction; -import net.minecraft.world.level.storage.loot.functions.CopyNbtFunction; import net.minecraft.world.level.storage.loot.predicates.ExplosionCondition; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraft.world.level.storage.loot.providers.nbt.ContextNbtProvider; import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; -import net.minecraftforge.client.model.generators.ConfiguredModel; -import net.minecraftforge.client.model.generators.ModelFile; -import net.minecraftforge.common.Tags; -import net.minecraftforge.common.util.ForgeSoundType; +import net.neoforged.neoforge.client.model.generators.ConfiguredModel; +import net.neoforged.neoforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.common.util.DeferredSoundType; +@SuppressWarnings("removal") public class AllBlocks { static { @@ -354,8 +356,9 @@ public class AllBlocks { .setRolls(ConstantValue.exactly(1)) .add(LootItem.lootTableItem(AllBlocks.SCHEMATICANNON.get() .asItem()) - .apply(CopyNbtFunction.copyData(ContextNbtProvider.BLOCK_ENTITY) - .copy("Options", "BlockEntityTag.Options"))))); + // TODO 1.21: Make sure this works + .apply(CopyComponentsFunction.copyComponents(CopyComponentsFunction.Source.BLOCK_ENTITY) + .include(AllDataComponents.SCHEMATICANNON_OPTIONS.value()))))); }) .item() .transform(customItemModel()) @@ -1768,7 +1771,7 @@ public class AllBlocks { public static final BlockEntry ANDESITE_TUNNEL = REGISTRATE.block("andesite_tunnel", BeltTunnelBlock::new) .properties(p -> p.mapColor(MapColor.STONE)) - .transform(BuilderTransformers.beltTunnel("andesite", new ResourceLocation("block/polished_andesite"))) + .transform(BuilderTransformers.beltTunnel("andesite", ResourceLocation.withDefaultNamespace("block/polished_andesite"))) .onRegister(assignDataBehaviour(new AccumulatedItemCountDisplaySource(), "accumulate_items")) .onRegister(assignDataBehaviour(new ItemThroughputDisplaySource(), "item_throughput")) .register(); @@ -1996,7 +1999,7 @@ public class AllBlocks { .transform(BuilderTransformers.tableCloth("brass", SharedProperties::softMetal, false)) .properties(p -> p.mapColor(MapColor.TERRACOTTA_YELLOW) .requiresCorrectToolForDrops()) - .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.forgeItemTag("ingots/brass")), + .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.commonItemTag("ingots/brass")), RecipeCategory.DECORATIONS, c::get, 2)) .transform(pickaxeOnly()) .register(); @@ -2005,7 +2008,7 @@ public class AllBlocks { REGISTRATE.block("copper_table_cloth", p -> new TableClothBlock(p, "copper")) .transform(BuilderTransformers.tableCloth("copper", SharedProperties::copperMetal, false)) .properties(p -> p.requiresCorrectToolForDrops()) - .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.forgeItemTag("ingots/copper")), + .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.INGOTS_COPPER), RecipeCategory.DECORATIONS, c::get, 2)) .transform(pickaxeOnly()) .register(); @@ -2216,17 +2219,17 @@ public class AllBlocks { .forceSolidOn()) .addLayer(() -> RenderType::cutoutMipped) .loot((lt, block) -> { - Builder builder = LootTable.lootTable(); - LootItemCondition.Builder survivesExplosion = ExplosionCondition.survivesExplosion(); - lt.add(block, builder.withPool(LootPool.lootPool() - .when(survivesExplosion) - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(block) - .apply(CopyNameFunction.copyName(CopyNameFunction.NameSource.BLOCK_ENTITY)) - .apply(CopyNbtFunction.copyData(ContextNbtProvider.BLOCK_ENTITY) - .copy("UniqueId", "UniqueId")) - .apply(CopyNbtFunction.copyData(ContextNbtProvider.BLOCK_ENTITY) - .copy("Inventory", "Inventory"))))); + lt.add(block, LootTable.lootTable().withPool(LootPool.lootPool() + .when(ExplosionCondition.survivesExplosion()) + .setRolls(ConstantValue.exactly(1)) + .add(LootItem.lootTableItem(block) + .apply(CopyNameFunction.copyName(CopyNameFunction.NameSource.BLOCK_ENTITY)) + .apply(CopyComponentsFunction.copyComponents(CopyComponentsFunction.Source.BLOCK_ENTITY) + .include(AllDataComponents.TOOLBOX_UUID.value()) + .include(AllDataComponents.TOOLBOX_INVENTORY.value()) + ) + ) + )); }) .blockstate((c, p) -> { p.horizontalBlock(c.get(), p.models() @@ -2272,21 +2275,21 @@ public class AllBlocks { public static final BlockEntry BRASS_LADDER = REGISTRATE.block("brass_ladder", MetalLadderBlock::new) .transform(BuilderTransformers.ladder("brass", - () -> DataIngredient.tag(AllTags.forgeItemTag("ingots/brass")), MapColor.TERRACOTTA_YELLOW)) + () -> DataIngredient.tag(AllTags.commonItemTag("ingots/brass")), MapColor.TERRACOTTA_YELLOW)) .register(); public static final BlockEntry COPPER_LADDER = REGISTRATE.block("copper_ladder", MetalLadderBlock::new) .transform(BuilderTransformers.ladder("copper", - () -> DataIngredient.tag(AllTags.forgeItemTag("ingots/copper")), MapColor.COLOR_ORANGE)) + () -> DataIngredient.tag(Tags.Items.INGOTS_COPPER), MapColor.COLOR_ORANGE)) .register(); public static final BlockEntry ANDESITE_BARS = MetalBarsGen.createBars("andesite", true, () -> DataIngredient.items(AllItems.ANDESITE_ALLOY.get()), MapColor.STONE); public static final BlockEntry BRASS_BARS = MetalBarsGen.createBars("brass", true, - () -> DataIngredient.tag(AllTags.forgeItemTag("ingots/brass")), MapColor.TERRACOTTA_YELLOW); + () -> DataIngredient.tag(AllTags.commonItemTag("ingots/brass")), MapColor.TERRACOTTA_YELLOW); public static final BlockEntry COPPER_BARS = MetalBarsGen.createBars("copper", true, - () -> DataIngredient.tag(AllTags.forgeItemTag("ingots/copper")), MapColor.COLOR_ORANGE); + () -> DataIngredient.tag(Tags.Items.INGOTS_COPPER), MapColor.COLOR_ORANGE); public static final BlockEntry ANDESITE_SCAFFOLD = REGISTRATE .block("andesite_scaffolding", MetalScaffoldingBlock::new) @@ -2298,14 +2301,14 @@ public class AllBlocks { public static final BlockEntry BRASS_SCAFFOLD = REGISTRATE.block("brass_scaffolding", MetalScaffoldingBlock::new) .transform(BuilderTransformers.scaffold("brass", - () -> DataIngredient.tag(AllTags.forgeItemTag("ingots/brass")), MapColor.TERRACOTTA_YELLOW, + () -> DataIngredient.tag(AllTags.commonItemTag("ingots/brass")), MapColor.TERRACOTTA_YELLOW, AllSpriteShifts.BRASS_SCAFFOLD, AllSpriteShifts.BRASS_SCAFFOLD_INSIDE, AllSpriteShifts.BRASS_CASING)) .register(); public static final BlockEntry COPPER_SCAFFOLD = REGISTRATE.block("copper_scaffolding", MetalScaffoldingBlock::new) .transform(BuilderTransformers.scaffold("copper", - () -> DataIngredient.tag(AllTags.forgeItemTag("ingots/copper")), MapColor.COLOR_ORANGE, + () -> DataIngredient.tag(Tags.Items.INGOTS_COPPER), MapColor.COLOR_ORANGE, AllSpriteShifts.COPPER_SCAFFOLD, AllSpriteShifts.COPPER_SCAFFOLD_INSIDE, AllSpriteShifts.COPPER_CASING)) .register(); @@ -2349,7 +2352,7 @@ public class AllBlocks { .transform(BuilderTransformers.copycat()) .onRegister(CreateRegistrate.blockModel(() -> CopycatStepModel::new)) .item() - .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.forgeItemTag("ingots/zinc")), + .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.commonItemTag("ingots/zinc")), RecipeCategory.BUILDING_BLOCKS, c::get, 4)) .transform(customItemModel("copycat_base", "step")) .register(); @@ -2359,7 +2362,7 @@ public class AllBlocks { .transform(BuilderTransformers.copycat()) .onRegister(CreateRegistrate.blockModel(() -> CopycatPanelModel::new)) .item() - .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.forgeItemTag("ingots/zinc")), + .recipe((c, p) -> p.stonecutting(DataIngredient.tag(AllTags.commonItemTag("ingots/zinc")), RecipeCategory.BUILDING_BLOCKS, c::get, 4)) .transform(customItemModel("copycat_base", "panel")) .register(); @@ -2472,10 +2475,14 @@ public class AllBlocks { .requiresCorrectToolForDrops() .sound(SoundType.STONE)) .transform(pickaxeOnly()) - .loot((lt, b) -> lt.add(b, - RegistrateBlockLootTables.createSilkTouchDispatchTable(b, + .loot((lt, b) -> { + HolderLookup.RegistryLookup enchantmentRegistryLookup = ((BlockLootSubProviderAccessor) lt).create$getRegistries().lookupOrThrow(Registries.ENCHANTMENT); + + lt.add(b, + lt.createSilkTouchDispatchTable(b, lt.applyExplosionDecay(b, LootItem.lootTableItem(AllItems.RAW_ZINC.get()) - .apply(ApplyBonusCount.addOreBonusCount(Enchantments.BLOCK_FORTUNE)))))) + .apply(ApplyBonusCount.addOreBonusCount(enchantmentRegistryLookup.getOrThrow(Enchantments.FORTUNE)))))); + }) .tag(BlockTags.NEEDS_IRON_TOOL) .tag(Tags.Blocks.ORES) .transform(tagBlockAndItem("ores/zinc", "ores_in_ground/stone")) @@ -2489,10 +2496,15 @@ public class AllBlocks { .requiresCorrectToolForDrops() .sound(SoundType.DEEPSLATE)) .transform(pickaxeOnly()) - .loot((lt, b) -> lt.add(b, - RegistrateBlockLootTables.createSilkTouchDispatchTable(b, - lt.applyExplosionDecay(b, LootItem.lootTableItem(AllItems.RAW_ZINC.get()) - .apply(ApplyBonusCount.addOreBonusCount(Enchantments.BLOCK_FORTUNE)))))) + .loot((lt, b) -> { + HolderLookup.RegistryLookup enchantmentRegistryLookup = ((BlockLootSubProviderAccessor) lt).create$getRegistries().lookupOrThrow(Registries.ENCHANTMENT); + + + lt.add(b, + lt.createSilkTouchDispatchTable(b, + lt.applyExplosionDecay(b, LootItem.lootTableItem(AllItems.RAW_ZINC.get()) + .apply(ApplyBonusCount.addOreBonusCount(enchantmentRegistryLookup.getOrThrow(Enchantments.FORTUNE)))))); + }) .tag(BlockTags.NEEDS_IRON_TOOL) .tag(Tags.Blocks.ORES) .transform(tagBlockAndItem("ores/zinc", "ores_in_ground/deepslate")) @@ -2544,7 +2556,7 @@ public class AllBlocks { .transform(BuilderTransformers.palettesIronBlock()) .lang("Block of Industrial Iron") .register(); - + public static final BlockEntry WEATHERED_IRON_BLOCK = REGISTRATE.block("weathered_iron_block", Block::new) .transform(BuilderTransformers.palettesIronBlock()) .lang("Block of Weathered Iron") @@ -2574,9 +2586,9 @@ public class AllBlocks { .transform(axeOnly()) .blockstate(BlockStateGen.horizontalAxisBlockProvider(false)) .tag(Tags.Blocks.STORAGE_BLOCKS) - .tag(AllTags.forgeBlockTag("storage_blocks/cardboard")) + .tag(AllTags.commonBlockTag("storage_blocks/cardboard")) .item(CardboardBlockItem::new) - .tag(AllTags.forgeItemTag("storage_blocks/cardboard")) + .tag(AllTags.commonItemTag("storage_blocks/cardboard")) .tag(Tags.Items.STORAGE_BLOCKS) .build() .lang("Block of Cardboard") @@ -2606,7 +2618,7 @@ public class AllBlocks { REGISTRATE.block("experience_block", ExperienceBlock::new) .initialProperties(SharedProperties::softMetal) .properties(p -> p.mapColor(MapColor.PLANT) - .sound(new ForgeSoundType(1, .5f, () -> SoundEvents.AMETHYST_BLOCK_BREAK, + .sound(new DeferredSoundType(1, .5f, () -> SoundEvents.AMETHYST_BLOCK_BREAK, () -> SoundEvents.AMETHYST_BLOCK_STEP, () -> SoundEvents.AMETHYST_BLOCK_PLACE, () -> SoundEvents.AMETHYST_BLOCK_HIT, () -> SoundEvents.AMETHYST_BLOCK_FALL)) .requiresCorrectToolForDrops() @@ -2662,14 +2674,14 @@ public class AllBlocks { public static final CopperBlockSet COPPER_SHINGLES = new CopperBlockSet(REGISTRATE, "copper_shingles", "copper_roof_top", CopperBlockSet.DEFAULT_VARIANTS, (c, p) -> { - p.stonecutting(DataIngredient.tag(AllTags.forgeItemTag("ingots/copper")), RecipeCategory.BUILDING_BLOCKS, + p.stonecutting(DataIngredient.tag(Tags.Items.INGOTS_COPPER), RecipeCategory.BUILDING_BLOCKS, c::get, 2); }, (ws, block) -> connectedTextures(() -> new RoofBlockCTBehaviour(AllSpriteShifts.COPPER_SHINGLES.get(ws))) .accept(block)); public static final CopperBlockSet COPPER_TILES = new CopperBlockSet(REGISTRATE, "copper_tiles", "copper_roof_top", CopperBlockSet.DEFAULT_VARIANTS, (c, p) -> { - p.stonecutting(DataIngredient.tag(AllTags.forgeItemTag("ingots/copper")), RecipeCategory.BUILDING_BLOCKS, + p.stonecutting(DataIngredient.tag(Tags.Items.INGOTS_COPPER), RecipeCategory.BUILDING_BLOCKS, c::get, 2); }, (ws, block) -> connectedTextures(() -> new RoofBlockCTBehaviour(AllSpriteShifts.COPPER_TILES.get(ws))) .accept(block)); diff --git a/src/main/java/com/simibubi/create/AllCreativeModeTabs.java b/src/main/java/com/simibubi/create/AllCreativeModeTabs.java index aee0f12cdf..a1c50a90d5 100644 --- a/src/main/java/com/simibubi/create/AllCreativeModeTabs.java +++ b/src/main/java/com/simibubi/create/AllCreativeModeTabs.java @@ -29,6 +29,7 @@ import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.ReferenceArrayList; import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet; import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.lang.Components; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.entity.ItemRenderer; @@ -46,21 +47,17 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; -@EventBusSubscriber(bus = Bus.MOD) public class AllCreativeModeTabs { private static final DeferredRegister REGISTER = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, Create.ID); - public static final RegistryObject BASE_CREATIVE_TAB = REGISTER.register("base", + public static final DeferredHolder BASE_CREATIVE_TAB = REGISTER.register("base", () -> CreativeModeTab.builder() .title(Components.translatable("itemGroup.create.base")) .withTabsBefore(CreativeModeTabs.SPAWN_EGGS) @@ -68,7 +65,7 @@ public class AllCreativeModeTabs { .displayItems(new RegistrateDisplayItemsGenerator(true, AllCreativeModeTabs.BASE_CREATIVE_TAB)) .build()); - public static final RegistryObject PALETTES_CREATIVE_TAB = REGISTER.register("palettes", + public static final DeferredHolder PALETTES_CREATIVE_TAB = REGISTER.register("palettes", () -> CreativeModeTab.builder() .title(Components.translatable("itemGroup.create.palettes")) .withTabsBefore(BASE_CREATIVE_TAB.getKey()) @@ -85,14 +82,8 @@ public class AllCreativeModeTabs { static { MutableObject> isItem3d = new MutableObject<>(item -> false); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { - isItem3d.setValue(item -> { - ItemRenderer itemRenderer = Minecraft.getInstance() - .getItemRenderer(); - BakedModel model = itemRenderer.getModel(new ItemStack(item), null, null, 0); - return model.isGui3d(); - }); - }); + if (CatnipServices.PLATFORM.getEnv().isClient()) + isItem3d.setValue(makeClient3dItemPredicate()); IS_ITEM_3D_PREDICATE = isItem3d.getValue(); } @@ -107,9 +98,9 @@ public class AllCreativeModeTabs { } private final boolean addItems; - private final RegistryObject tabFilter; + private final DeferredHolder tabFilter; - public RegistrateDisplayItemsGenerator(boolean addItems, RegistryObject tabFilter) { + public RegistrateDisplayItemsGenerator(boolean addItems, DeferredHolder tabFilter) { this.addItems = addItems; this.tabFilter = tabFilter; } @@ -117,7 +108,7 @@ public class AllCreativeModeTabs { private static Predicate makeExclusionPredicate() { Set exclusions = new ReferenceOpenHashSet<>(); - List> simpleExclusions = List.of( + List> simpleExclusions = List.of( AllItems.INCOMPLETE_PRECISION_MECHANISM, AllItems.INCOMPLETE_REINFORCED_SHEET, AllItems.INCOMPLETE_TRACK, @@ -154,10 +145,10 @@ public class AllCreativeModeTabs { AllItems.CRUSHED_URANIUM, AllItems.CRUSHED_NICKEL ); - + exclusions.addAll(PackageStyles.RARE_BOXES); - for (ItemProviderEntry entry : simpleExclusions) { + for (ItemProviderEntry entry : simpleExclusions) { exclusions.add(entry.asItem()); } @@ -174,12 +165,12 @@ public class AllCreativeModeTabs { private static List makeOrderings() { List orderings = new ReferenceArrayList<>(); - Map, ItemProviderEntry> simpleBeforeOrderings = Map.of( + Map, ItemProviderEntry> simpleBeforeOrderings = Map.of( AllItems.EMPTY_BLAZE_BURNER, AllBlocks.BLAZE_BURNER, AllItems.SCHEDULE, AllBlocks.TRACK_STATION ); - Map, ItemProviderEntry> simpleAfterOrderings = Map.of( + Map, ItemProviderEntry> simpleAfterOrderings = Map.of( AllItems.VERTICAL_GEARBOX, AllBlocks.GEARBOX ); @@ -190,7 +181,7 @@ public class AllCreativeModeTabs { simpleAfterOrderings.forEach((entry, otherEntry) -> { orderings.add(ItemOrdering.after(entry.asItem(), otherEntry.asItem())); }); - + PackageStyles.STANDARD_BOXES.forEach(item -> { orderings.add(ItemOrdering.after(item, AllBlocks.PACKAGER.asItem())); }); @@ -201,15 +192,15 @@ public class AllCreativeModeTabs { private static Function makeStackFunc() { Map> factories = new Reference2ReferenceOpenHashMap<>(); - Map, Function> simpleFactories = Map.of( + Map, Function> simpleFactories = Map.of( AllItems.COPPER_BACKTANK, item -> { ItemStack stack = new ItemStack(item); - stack.getOrCreateTag().putInt("Air", BacktankUtil.maxAirWithoutEnchants()); + stack.set(AllDataComponents.BACKTANK_AIR, BacktankUtil.maxAirWithoutEnchants()); return stack; }, AllItems.NETHERITE_BACKTANK, item -> { ItemStack stack = new ItemStack(item); - stack.getOrCreateTag().putInt("Air", BacktankUtil.maxAirWithoutEnchants()); + stack.set(AllDataComponents.BACKTANK_AIR, BacktankUtil.maxAirWithoutEnchants()); return stack; } ); @@ -230,7 +221,7 @@ public class AllCreativeModeTabs { private static Function makeVisibilityFunc() { Map visibilities = new Reference2ObjectOpenHashMap<>(); - Map, TabVisibility> simpleVisibilities = Map.of( + Map, TabVisibility> simpleVisibilities = Map.of( AllItems.BLAZE_CAKE_BASE, TabVisibility.SEARCH_TAB_ONLY ); @@ -248,14 +239,14 @@ public class AllCreativeModeTabs { visibilities.put(entry.asItem(), TabVisibility.SEARCH_TAB_ONLY); } } - + for (BlockEntry entry : AllBlocks.TABLE_CLOTHS) { TableClothBlock block = entry.get(); if (block.getColor() != DyeColor.RED) { visibilities.put(entry.asItem(), TabVisibility.SEARCH_TAB_ONLY); } } - + for (BlockEntry entry : AllBlocks.PACKAGE_POSTBOXES) { PostboxBlock block = entry.get(); if (block.getColor() != DyeColor.WHITE) { @@ -301,7 +292,7 @@ public class AllCreativeModeTabs { private List collectBlocks(Predicate exclusionPredicate) { List items = new ReferenceArrayList<>(); - for (RegistryEntry entry : Create.REGISTRATE.getAll(Registries.BLOCK)) { + for (RegistryEntry entry : Create.REGISTRATE.getAll(Registries.BLOCK)) { if (!CreateRegistrate.isInCreativeTab(entry, tabFilter)) continue; Item item = entry.get() @@ -317,7 +308,7 @@ public class AllCreativeModeTabs { private List collectItems(Predicate exclusionPredicate) { List items = new ReferenceArrayList<>(); - for (RegistryEntry entry : Create.REGISTRATE.getAll(Registries.ITEM)) { + for (RegistryEntry entry : Create.REGISTRATE.getAll(Registries.ITEM)) { if (!CreateRegistrate.isInCreativeTab(entry, tabFilter)) continue; Item item = entry.get(); diff --git a/src/main/java/com/simibubi/create/AllDamageTypes.java b/src/main/java/com/simibubi/create/AllDamageTypes.java index eef7b55bc4..9700800b39 100644 --- a/src/main/java/com/simibubi/create/AllDamageTypes.java +++ b/src/main/java/com/simibubi/create/AllDamageTypes.java @@ -3,7 +3,7 @@ package com.simibubi.create; import com.simibubi.create.foundation.damageTypes.DamageTypeBuilder; import net.minecraft.core.registries.Registries; -import net.minecraft.data.worldgen.BootstapContext; +import net.minecraft.data.worldgen.BootstrapContext; import net.minecraft.resources.ResourceKey; import net.minecraft.world.damagesource.DamageEffects; import net.minecraft.world.damagesource.DamageScaling; @@ -25,7 +25,7 @@ public class AllDamageTypes { return ResourceKey.create(Registries.DAMAGE_TYPE, Create.asResource(name)); } - public static void bootstrap(BootstapContext ctx) { + public static void bootstrap(BootstrapContext ctx) { new DamageTypeBuilder(CRUSH).scaling(DamageScaling.ALWAYS).register(ctx); new DamageTypeBuilder(CUCKOO_SURPRISE).scaling(DamageScaling.ALWAYS).exhaustion(0.1f).register(ctx); new DamageTypeBuilder(FAN_FIRE).effects(DamageEffects.BURNING).register(ctx); diff --git a/src/main/java/com/simibubi/create/AllDataComponents.java b/src/main/java/com/simibubi/create/AllDataComponents.java new file mode 100644 index 0000000000..7da60ddd37 --- /dev/null +++ b/src/main/java/com/simibubi/create/AllDataComponents.java @@ -0,0 +1,342 @@ +package com.simibubi.create; + +import java.util.List; +import java.util.UUID; + +import com.mojang.serialization.Codec; +import com.simibubi.create.content.equipment.clipboard.ClipboardEntry; +import com.simibubi.create.content.equipment.clipboard.ClipboardOverrides.ClipboardType; +import com.simibubi.create.content.equipment.symmetryWand.mirror.SymmetryMirror; +import com.simibubi.create.content.equipment.zapper.PlacementPatterns; +import com.simibubi.create.content.equipment.zapper.terrainzapper.PlacementOptions; +import com.simibubi.create.content.equipment.zapper.terrainzapper.TerrainBrushes; +import com.simibubi.create.content.equipment.zapper.terrainzapper.TerrainTools; +import com.simibubi.create.content.fluids.potion.PotionFluid.BottleType; +import com.simibubi.create.content.logistics.box.PackageItem.PackageOrderData; +import com.simibubi.create.content.logistics.filter.AttributeFilterWhitelistMode; +import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute.ItemAttributeEntry; +import com.simibubi.create.content.logistics.redstoneRequester.AutoRequestData; +import com.simibubi.create.content.logistics.stockTicker.PackageOrder; +import com.simibubi.create.content.logistics.tableCloth.ShoppingListItem.ShoppingList; +import com.simibubi.create.content.processing.sequenced.SequencedAssemblyRecipe.SequencedAssembly; +import com.simibubi.create.content.redstone.displayLink.ClickToLinkBlockItem.ClickToLinkData; +import com.simibubi.create.content.schematics.cannon.SchematicannonBlockEntity.SchematicannonOptions; +import com.simibubi.create.content.trains.track.BezierTrackPointLocation; +import com.simibubi.create.content.trains.track.TrackPlacement.ConnectingFrom; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import net.minecraft.core.BlockPos; +import net.minecraft.core.UUIDUtil; +import net.minecraft.core.Vec3i; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.util.ExtraCodecs; +import net.minecraft.util.Unit; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemContainerContents; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Mirror; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; + +public class AllDataComponents { + private static final DeferredRegister.DataComponents DATA_COMPONENTS = DeferredRegister.createDataComponents(Registries.DATA_COMPONENT_TYPE, Create.ID); + + public static final DeferredHolder, DataComponentType> BACKTANK_AIR = DATA_COMPONENTS.registerComponentType( + "banktank_air", + builder -> builder.persistent(ExtraCodecs.NON_NEGATIVE_INT).networkSynchronized(ByteBufCodecs.VAR_INT) + ); + + public static final DeferredHolder, DataComponentType> BELT_FIRST_SHAFT = DATA_COMPONENTS.registerComponentType( + "belt_first_shaft", + builder -> builder.persistent(BlockPos.CODEC).networkSynchronized(BlockPos.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> INFERRED_FROM_RECIPE = DATA_COMPONENTS.registerComponentType( + "inferred_from_recipe", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> PLACEMENT_PATTERN = DATA_COMPONENTS.registerComponentType( + "placement_pattern", + builder -> builder.persistent(PlacementPatterns.CODEC).networkSynchronized(PlacementPatterns.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_BRUSH = DATA_COMPONENTS.registerComponentType( + "shaper_brush", + builder -> builder.persistent(TerrainBrushes.CODEC).networkSynchronized(TerrainBrushes.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_BRUSH_PARAMS = DATA_COMPONENTS.registerComponentType( + "shaper_brush_params", + builder -> builder.persistent(BlockPos.CODEC).networkSynchronized(BlockPos.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_PLACEMENT_OPTIONS = DATA_COMPONENTS.registerComponentType( + "shaper_placement_options", + builder -> builder.persistent(PlacementOptions.CODEC).networkSynchronized(PlacementOptions.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_TOOL = DATA_COMPONENTS.registerComponentType( + "shaper_tool", + builder -> builder.persistent(TerrainTools.CODEC).networkSynchronized(TerrainTools.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_BLOCK_USED = DATA_COMPONENTS.registerComponentType( + "shaper_block_used", + builder -> builder.persistent(BlockState.CODEC).networkSynchronized(ByteBufCodecs.idMapper(Block.BLOCK_STATE_REGISTRY)) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_SWAP = DATA_COMPONENTS.registerComponentType( + "shaper_swap", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> SHAPER_BLOCK_DATA = DATA_COMPONENTS.registerComponentType( + "shaper_block_data", + builder -> builder.persistent(CompoundTag.CODEC).networkSynchronized(ByteBufCodecs.COMPOUND_TAG) + ); + + public static final DeferredHolder, DataComponentType> FILTER_ITEMS = DATA_COMPONENTS.registerComponentType( + "filter_items", + builder -> builder.persistent(ItemContainerContents.CODEC).networkSynchronized(ItemContainerContents.STREAM_CODEC) + ); + + // These 2 are placed on items inside filters and not the filter itself + public static final DeferredHolder, DataComponentType> FILTER_ITEMS_RESPECT_NBT = DATA_COMPONENTS.registerComponentType( + "filter_items_respect_nbt", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> FILTER_ITEMS_BLACKLIST = DATA_COMPONENTS.registerComponentType( + "filter_items_blacklist", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> ATTRIBUTE_FILTER_WHITELIST_MODE = DATA_COMPONENTS.registerComponentType( + "attribute_filter_whitelist_mode", + builder -> builder.persistent(AttributeFilterWhitelistMode.CODEC).networkSynchronized(AttributeFilterWhitelistMode.STREAM_CODEC) + ); + + // TODO - Make a stream codec for this + public static final DeferredHolder, DataComponentType>> ATTRIBUTE_FILTER_MATCHED_ATTRIBUTES = DATA_COMPONENTS.registerComponentType( + "attribute_filter_matched_attributes", + builder -> builder.persistent(ItemAttributeEntry.CODEC.listOf()) + ); + + public static final DeferredHolder, DataComponentType> CLIPBOARD_TYPE = DATA_COMPONENTS.registerComponentType( + "clipboard_type", + builder -> builder.persistent(ClipboardType.CODEC).networkSynchronized(ClipboardType.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType>>> CLIPBOARD_PAGES = DATA_COMPONENTS.registerComponentType( + "clipboard_pages", + builder -> builder.persistent(ClipboardEntry.CODEC.listOf().listOf()).networkSynchronized(ClipboardEntry.STREAM_CODEC.apply(ByteBufCodecs.list()).apply(ByteBufCodecs.list())) + ); + + public static final DeferredHolder, DataComponentType> CLIPBOARD_READ_ONLY = DATA_COMPONENTS.registerComponentType( + "clipboard_read_only", + builder -> builder.persistent(Unit.CODEC).networkSynchronized(StreamCodec.unit(Unit.INSTANCE)) + ); + + public static final DeferredHolder, DataComponentType> CLIPBOARD_COPIED_VALUES = DATA_COMPONENTS.registerComponentType( + "clipboard_copied_values", + builder -> builder.persistent(CompoundTag.CODEC).networkSynchronized(ByteBufCodecs.COMPOUND_TAG) + ); + + public static final DeferredHolder, DataComponentType> CLIPBOARD_PREVIOUSLY_OPENED_PAGE = DATA_COMPONENTS.registerComponentType( + "clipboard_previously_opened_page", + builder -> builder.persistent(Codec.INT).networkSynchronized(ByteBufCodecs.INT) + ); + + public static final DeferredHolder, DataComponentType> TRACK_CONNECTING_FROM = DATA_COMPONENTS.registerComponentType( + "track_connecting_from", + builder -> builder.persistent(ConnectingFrom.CODEC).networkSynchronized(ConnectingFrom.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> TRACK_EXTENDED_CURVE = DATA_COMPONENTS.registerComponentType( + "track_extend_curve", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> TRACK_TARGETING_ITEM_SELECTED_POS = DATA_COMPONENTS.registerComponentType( + "track_targeting_item_selected_pos", + builder -> builder.persistent(BlockPos.CODEC).networkSynchronized(BlockPos.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> TRACK_TARGETING_ITEM_SELECTED_DIRECTION = DATA_COMPONENTS.registerComponentType( + "track_targeting_item_selected_direction", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> TRACK_TARGETING_ITEM_BEZIER = DATA_COMPONENTS.registerComponentType( + "track_targeting_item_bezier", + builder -> builder.persistent(BezierTrackPointLocation.CODEC).networkSynchronized(BezierTrackPointLocation.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_DEPLOYED = DATA_COMPONENTS.registerComponentType( + "schematic_deployed", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_OWNER = DATA_COMPONENTS.registerComponentType( + "schematic_owner", + builder -> builder.persistent(Codec.STRING).networkSynchronized(ByteBufCodecs.STRING_UTF8) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_FILE = DATA_COMPONENTS.registerComponentType( + "schematic_file", + builder -> builder.persistent(Codec.STRING).networkSynchronized(ByteBufCodecs.STRING_UTF8) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_ANCHOR = DATA_COMPONENTS.registerComponentType( + "schematic_anchor", + builder -> builder.persistent(BlockPos.CODEC).networkSynchronized(BlockPos.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_ROTATION = DATA_COMPONENTS.registerComponentType( + "schematic_rotation", + builder -> builder.persistent(Rotation.CODEC).networkSynchronized(CatnipStreamCodecs.ROTATION) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_MIRROR = DATA_COMPONENTS.registerComponentType( + "schematic_mirror", + builder -> builder.persistent(Mirror.CODEC).networkSynchronized(CatnipStreamCodecs.MIRROR) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_BOUNDS = DATA_COMPONENTS.registerComponentType( + "schematic_bounds", + builder -> builder.persistent(Vec3i.CODEC).networkSynchronized(CatnipStreamCodecs.VEC3I) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATIC_HASH = DATA_COMPONENTS.registerComponentType( + "schematic_hash", + builder -> builder.persistent(Codec.INT).networkSynchronized(ByteBufCodecs.INT) + ); + + public static final DeferredHolder, DataComponentType> CHROMATIC_COMPOUND_COLLECTING_LIGHT = DATA_COMPONENTS.registerComponentType( + "chromatic_compound_collecting_light", + builder -> builder.persistent(Codec.INT).networkSynchronized(ByteBufCodecs.INT) + ); + + public static final DeferredHolder, DataComponentType> SAND_PAPER_POLISHING = DATA_COMPONENTS.registerComponentType( + "sand_paper_polishing", + builder -> builder.persistent(ItemStack.CODEC).networkSynchronized(ItemStack.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SAND_PAPER_JEI = DATA_COMPONENTS.registerComponentType( + "sand_paper_jei", + builder -> builder.persistent(Unit.CODEC).networkSynchronized(StreamCodec.unit(Unit.INSTANCE)) + ); + + // Holds contraption data when a minecraft contraption is picked up + public static final DeferredHolder, DataComponentType> MINECRAFT_CONTRAPTION_DATA = DATA_COMPONENTS.registerComponentType( + "minecart_contraption_data", + builder -> builder.persistent(CompoundTag.CODEC).networkSynchronized(ByteBufCodecs.COMPOUND_TAG) + ); + + public static final DeferredHolder, DataComponentType> LINKED_CONTROLLER_ITEMS = DATA_COMPONENTS.registerComponentType( + "linked_controller_items", + builder -> builder.persistent(ItemContainerContents.CODEC).networkSynchronized(ItemContainerContents.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> TOOLBOX_INVENTORY = DATA_COMPONENTS.registerComponentType( + "toolbox_inventory", + builder -> builder.persistent(ItemContainerContents.CODEC).networkSynchronized(ItemContainerContents.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> TOOLBOX_UUID = DATA_COMPONENTS.registerComponentType( + "toolbox_uuid", + builder -> builder.persistent(UUIDUtil.CODEC).networkSynchronized(UUIDUtil.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SEQUENCED_ASSEMBLY = DATA_COMPONENTS.registerComponentType( + "sequenced_assembly", + builder -> builder.persistent(SequencedAssembly.CODEC).networkSynchronized(SequencedAssembly.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> TRAIN_SCHEDULE = DATA_COMPONENTS.registerComponentType( + "train_schedule", + builder -> builder.persistent(CompoundTag.CODEC).networkSynchronized(ByteBufCodecs.COMPOUND_TAG) + ); + + public static final DeferredHolder, DataComponentType> SYMMETRY_WAND = DATA_COMPONENTS.registerComponentType( + "symmetry_wand", + builder -> builder.persistent(SymmetryMirror.CODEC).networkSynchronized(SymmetryMirror.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SYMMETRY_WAND_ENABLE = DATA_COMPONENTS.registerComponentType( + "symmetry_wand_enable", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> SYMMETRY_WAND_SIMULATE = DATA_COMPONENTS.registerComponentType( + "symmetry_wand_simulate", + builder -> builder.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) + ); + + public static final DeferredHolder, DataComponentType> DISPLAY_LINK_SELECTED_POS = DATA_COMPONENTS.registerComponentType( + "display_link_selected_pos", + builder -> builder.persistent(BlockPos.CODEC).networkSynchronized(BlockPos.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> POTION_FLUID_BOTTLE_TYPE = DATA_COMPONENTS.registerComponentType( + "potion_fluid_bottle_type", + builder -> builder.persistent(BottleType.CODEC).networkSynchronized(BottleType.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SCHEMATICANNON_OPTIONS = DATA_COMPONENTS.registerComponentType( + "schematicannon_options", + builder -> builder.persistent(SchematicannonOptions.CODEC).networkSynchronized(SchematicannonOptions.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> AUTO_REQUEST_DATA = DATA_COMPONENTS.registerComponentType( + "auto_request_data", + builder -> builder.persistent(AutoRequestData.CODEC).networkSynchronized(AutoRequestData.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHOPPING_LIST = DATA_COMPONENTS.registerComponentType( + "shopping_list", + builder -> builder.persistent(ShoppingList.CODEC).networkSynchronized(ShoppingList.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> SHOPPING_LIST_ADDRESS = DATA_COMPONENTS.registerComponentType( + "shopping_list_address", + builder -> builder.persistent(Codec.STRING).networkSynchronized(ByteBufCodecs.STRING_UTF8) + ); + + public static final DeferredHolder, DataComponentType> PACKAGE_ADDRESS = DATA_COMPONENTS.registerComponentType( + "package_address", + builder -> builder.persistent(Codec.STRING).networkSynchronized(ByteBufCodecs.STRING_UTF8) + ); + + public static final DeferredHolder, DataComponentType> PACKAGE_CONTENTS = DATA_COMPONENTS.registerComponentType( + "package_contents", + builder -> builder.persistent(ItemContainerContents.CODEC).networkSynchronized(ItemContainerContents.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> PACKAGE_ORDER_DATA = DATA_COMPONENTS.registerComponentType( + "package_order_data", + builder -> builder.persistent(PackageOrderData.CODEC).networkSynchronized(PackageOrderData.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> PACKAGE_ORDER_CONTEXT = DATA_COMPONENTS.registerComponentType( + "package_order_context", + builder -> builder.persistent(PackageOrder.CODEC).networkSynchronized(PackageOrder.STREAM_CODEC) + ); + + public static final DeferredHolder, DataComponentType> CLICK_TO_LINK_DATA = DATA_COMPONENTS.registerComponentType( + "click_to_link_data", + builder -> builder.persistent(ClickToLinkData.CODEC).networkSynchronized(ClickToLinkData.STREAM_CODEC) + ); + + public static void register(IEventBus modEventBus) { + DATA_COMPONENTS.register(modEventBus); + } +} diff --git a/src/main/java/com/simibubi/create/AllEnchantments.java b/src/main/java/com/simibubi/create/AllEnchantments.java index 3f0a3f8636..8186244c3c 100644 --- a/src/main/java/com/simibubi/create/AllEnchantments.java +++ b/src/main/java/com/simibubi/create/AllEnchantments.java @@ -1,31 +1,76 @@ package com.simibubi.create; -import static com.simibubi.create.Create.REGISTRATE; +import com.simibubi.create.content.equipment.potatoCannon.PotatoProjectileTypeManager; -import com.simibubi.create.content.equipment.armor.CapacityEnchantment; -import com.simibubi.create.content.equipment.potatoCannon.PotatoRecoveryEnchantment; -import com.tterrag.registrate.util.entry.RegistryEntry; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.enchantment.Enchantment.Rarity; -import net.minecraft.world.item.enchantment.EnchantmentCategory; +import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.worldgen.BootstrapContext; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.EquipmentSlotGroup; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.EnchantmentEffectComponents; +import net.minecraft.world.item.enchantment.LevelBasedValue; +import net.minecraft.world.item.enchantment.effects.SetValue; +import net.minecraft.world.level.storage.loot.predicates.MatchTool; public class AllEnchantments { + public static final ResourceKey + POTATO_RECOVERY = key("potato_recovery"), + CAPACITY = key("capacity"); - public static final RegistryEntry POTATO_RECOVERY = REGISTRATE.object("potato_recovery") - .enchantment(EnchantmentCategory.BOW, PotatoRecoveryEnchantment::new) - .addSlots(EquipmentSlot.MAINHAND, EquipmentSlot.OFFHAND) - .lang("Potato Recovery") - .rarity(Rarity.UNCOMMON) - .register(); - - public static final RegistryEntry CAPACITY = REGISTRATE.object("capacity") - .enchantment(EnchantmentCategory.ARMOR_CHEST, CapacityEnchantment::new) - .addSlots(EquipmentSlot.CHEST) - .lang("Capacity") - .rarity(Rarity.COMMON) - .register(); + private static ResourceKey key(String name) { + return ResourceKey.create(Registries.ENCHANTMENT, Create.asResource(name)); + } - public static void register() {} + public static void bootstrap(BootstrapContext context) { + HolderGetter itemHolderGetter = context.lookup(Registries.ITEM); + + register( + context, + POTATO_RECOVERY, + Enchantment.enchantment( + Enchantment.definition( + HolderSet.direct(AllItems.POTATO_CANNON), + 10, + 3, + Enchantment.dynamicCost(15, 15), + Enchantment.dynamicCost(45, 15), + 1, + EquipmentSlotGroup.MAINHAND + ) + ).withEffect( + EnchantmentEffectComponents.AMMO_USE, + new SetValue(LevelBasedValue.perLevel(0.0F, 33.3333333333F)), + MatchTool.toolMatches( + ItemPredicate.Builder.item().of( + PotatoProjectileTypeManager.getItems().toArray(Item[]::new) + ) + ) + ) + ); + + register( + context, + CAPACITY, + Enchantment.enchantment( + Enchantment.definition( + itemHolderGetter.getOrThrow(AllTags.AllItemTags.PRESSURIZED_AIR_SOURCES.tag), + 10, + 3, + Enchantment.dynamicCost(15, 15), + Enchantment.dynamicCost(45, 15), + 1, + EquipmentSlotGroup.MAINHAND + ) + ) + ); + } + + private static void register(BootstrapContext context, ResourceKey key, Enchantment.Builder builder) { + context.register(key, builder.build(key.location())); + } } diff --git a/src/main/java/com/simibubi/create/AllEntityDataSerializers.java b/src/main/java/com/simibubi/create/AllEntityDataSerializers.java index ad3932e907..f5864fc08d 100644 --- a/src/main/java/com/simibubi/create/AllEntityDataSerializers.java +++ b/src/main/java/com/simibubi/create/AllEntityDataSerializers.java @@ -3,18 +3,17 @@ package com.simibubi.create; import com.simibubi.create.content.trains.entity.CarriageSyncDataSerializer; import net.minecraft.network.syncher.EntityDataSerializer; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; - +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; +import net.neoforged.neoforge.registries.NeoForgeRegistries; public class AllEntityDataSerializers { - private static final DeferredRegister> REGISTER = DeferredRegister.create(ForgeRegistries.Keys.ENTITY_DATA_SERIALIZERS, Create.ID); + private static final DeferredRegister> REGISTER = DeferredRegister.create(NeoForgeRegistries.Keys.ENTITY_DATA_SERIALIZERS, Create.ID); public static final CarriageSyncDataSerializer CARRIAGE_DATA = new CarriageSyncDataSerializer(); - public static final RegistryObject CARRIAGE_DATA_ENTRY = REGISTER.register("carriage_data", () -> CARRIAGE_DATA); + public static final DeferredHolder, CarriageSyncDataSerializer> CARRIAGE_DATA_ENTRY = REGISTER.register("carriage_data", () -> CARRIAGE_DATA); public static void register(IEventBus modEventBus) { REGISTER.register(modEventBus); diff --git a/src/main/java/com/simibubi/create/AllEntityTypes.java b/src/main/java/com/simibubi/create/AllEntityTypes.java index 30984943e8..c0ed5edef1 100644 --- a/src/main/java/com/simibubi/create/AllEntityTypes.java +++ b/src/main/java/com/simibubi/create/AllEntityTypes.java @@ -32,7 +32,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EntityType.EntityFactory; import net.minecraft.world.entity.MobCategory; -import net.minecraftforge.event.entity.EntityAttributeCreationEvent; +import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent; public class AllEntityTypes { @@ -69,7 +69,7 @@ public class AllEntityTypes { public static final EntityEntry SEAT = register("seat", SeatEntity::new, () -> SeatEntity.Render::new, MobCategory.MISC, 5, Integer.MAX_VALUE, false, true, SeatEntity::build).register(); - + public static final EntityEntry PACKAGE = register("package", PackageEntity::new, () -> PackageRenderer::new, MobCategory.MISC, 10, 3, true, false, PackageEntity::build).register(); @@ -99,7 +99,7 @@ public class AllEntityTypes { }) .renderer(renderer); } - + public static void registerEntityAttributes(EntityAttributeCreationEvent event) { event.put(PACKAGE.get(), PackageEntity.createPackageAttributes() .build()); diff --git a/src/main/java/com/simibubi/create/AllFluids.java b/src/main/java/com/simibubi/create/AllFluids.java index eea55ba3da..45c9c0571e 100644 --- a/src/main/java/com/simibubi/create/AllFluids.java +++ b/src/main/java/com/simibubi/create/AllFluids.java @@ -12,7 +12,6 @@ import org.joml.Vector3f; import com.mojang.blaze3d.shaders.FogShape; import com.mojang.blaze3d.systems.RenderSystem; -import com.simibubi.create.AllTags.AllFluidTags; import com.simibubi.create.content.decoration.palettes.AllPaletteStoneTypes; import com.simibubi.create.content.fluids.VirtualFluid; import com.simibubi.create.content.fluids.potion.PotionFluid; @@ -32,13 +31,14 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.fluids.FluidInteractionRegistry; -import net.minecraftforge.fluids.FluidInteractionRegistry.InteractionInformation; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; -import net.minecraftforge.fluids.ForgeFlowingFluid; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.common.NeoForgeMod; +import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.fluids.BaseFlowingFluid; +import net.neoforged.neoforge.fluids.FluidInteractionRegistry; +import net.neoforged.neoforge.fluids.FluidInteractionRegistry.InteractionInformation; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; public class AllFluids { static { @@ -52,10 +52,10 @@ public class AllFluids { public static final FluidEntry TEA = REGISTRATE.virtualFluid("tea") .lang("Builder's Tea") - .tag(AllTags.forgeFluidTag("tea")) + .tag(AllTags.commonFluidTag("teas")) .register(); - public static final FluidEntry HONEY = + public static final FluidEntry HONEY = REGISTRATE.standardFluid("honey", SolidRenderedPlaceableFluidType.create(0xEAAE2F, () -> 1f / 8f * AllConfigs.client().honeyTransparencyMultiplier.getF())) @@ -66,19 +66,19 @@ public class AllFluids { .tickRate(25) .slopeFindDistance(3) .explosionResistance(100f)) - .tag(AllFluidTags.HONEY.tag) - .source(ForgeFlowingFluid.Source::new) // TODO: remove when Registrate fixes FluidBuilder + .tag(Tags.Fluids.HONEY) + .source(BaseFlowingFluid.Source::new) // TODO: remove when Registrate fixes FluidBuilder .bucket() - .tag(AllTags.forgeItemTag("buckets/honey")) + .tag(AllTags.commonItemTag("buckets/honey")) .build() .register(); - public static final FluidEntry CHOCOLATE = + public static final FluidEntry CHOCOLATE = REGISTRATE.standardFluid("chocolate", SolidRenderedPlaceableFluidType.create(0x622020, () -> 1f / 32f * AllConfigs.client().chocolateTransparencyMultiplier.getF())) .lang("Chocolate") - .tag(AllTags.forgeFluidTag("chocolate")) + .tag(AllTags.commonFluidTag("chocolates")) .properties(b -> b.viscosity(1500) .density(1400)) .fluidProperties(p -> p.levelDecreasePerBlock(2) @@ -92,7 +92,7 @@ public class AllFluids { public static void register() {} public static void registerFluidInteractions() { - FluidInteractionRegistry.addInteraction(ForgeMod.LAVA_TYPE.get(), new InteractionInformation( + FluidInteractionRegistry.addInteraction(NeoForgeMod.LAVA_TYPE.value(), new InteractionInformation( HONEY.get().getFluidType(), fluidState -> { if (fluidState.isSource()) { @@ -105,7 +105,7 @@ public class AllFluids { } )); - FluidInteractionRegistry.addInteraction(ForgeMod.LAVA_TYPE.get(), new InteractionInformation( + FluidInteractionRegistry.addInteraction(NeoForgeMod.LAVA_TYPE.value(), new InteractionInformation( CHOCOLATE.get().getFluidType(), fluidState -> { if (fluidState.isSource()) { diff --git a/src/main/java/com/simibubi/create/AllInteractionBehaviours.java b/src/main/java/com/simibubi/create/AllInteractionBehaviours.java index 85eefbb530..e9012835dd 100644 --- a/src/main/java/com/simibubi/create/AllInteractionBehaviours.java +++ b/src/main/java/com/simibubi/create/AllInteractionBehaviours.java @@ -13,15 +13,15 @@ import com.simibubi.create.content.contraptions.behaviour.TrapdoorMovingInteract import com.simibubi.create.foundation.utility.AttachedRegistry; import com.tterrag.registrate.util.nullness.NonNullConsumer; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.registries.ForgeRegistries; public class AllInteractionBehaviours { - private static final AttachedRegistry BLOCK_BEHAVIOURS = new AttachedRegistry<>(ForgeRegistries.BLOCKS); + private static final AttachedRegistry BLOCK_BEHAVIOURS = new AttachedRegistry<>(BuiltInRegistries.BLOCK); private static final List GLOBAL_BEHAVIOURS = new ArrayList<>(); public static void registerBehaviour(ResourceLocation block, MovingInteractionBehaviour provider) { diff --git a/src/main/java/com/simibubi/create/AllItems.java b/src/main/java/com/simibubi/create/AllItems.java index 79cb68596e..4bc9a4e422 100644 --- a/src/main/java/com/simibubi/create/AllItems.java +++ b/src/main/java/com/simibubi/create/AllItems.java @@ -1,9 +1,9 @@ package com.simibubi.create; -import static com.simibubi.create.AllTags.forgeItemTag; import static com.simibubi.create.AllTags.AllItemTags.CREATE_INGOTS; import static com.simibubi.create.AllTags.AllItemTags.CRUSHED_RAW_MATERIALS; import static com.simibubi.create.AllTags.AllItemTags.PLATES; +import static com.simibubi.create.AllTags.commonItemTag; import static com.simibubi.create.Create.REGISTRATE; import static com.simibubi.create.foundation.data.recipe.CompatMetals.ALUMINUM; import static com.simibubi.create.foundation.data.recipe.CompatMetals.LEAD; @@ -26,7 +26,7 @@ import com.simibubi.create.content.equipment.armor.BacktankItem; import com.simibubi.create.content.equipment.armor.BacktankItem.BacktankBlockItem; import com.simibubi.create.content.equipment.armor.BaseArmorItem; import com.simibubi.create.content.equipment.armor.CardboardArmorItem; -import com.simibubi.create.content.equipment.armor.CardboardHelmetItem; +import com.simibubi.create.content.equipment.armor.CardboardArmorStealthOverlay; import com.simibubi.create.content.equipment.armor.DivingBootsItem; import com.simibubi.create.content.equipment.armor.DivingHelmetItem; import com.simibubi.create.content.equipment.armor.TrimmableArmorModelGenerator; @@ -37,6 +37,7 @@ import com.simibubi.create.content.equipment.goggles.GogglesModel; import com.simibubi.create.content.equipment.potatoCannon.PotatoCannonItem; import com.simibubi.create.content.equipment.sandPaper.SandPaperItem; import com.simibubi.create.content.equipment.symmetryWand.SymmetryWandItem; +import com.simibubi.create.content.equipment.tool.AllToolMaterials; import com.simibubi.create.content.equipment.tool.CardboardSwordItem; import com.simibubi.create.content.equipment.wrench.WrenchItem; import com.simibubi.create.content.equipment.zapper.terrainzapper.WorldshaperItem; @@ -78,7 +79,8 @@ import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterials; import net.minecraft.world.item.Item; import net.minecraft.world.item.Rarity; -import net.minecraftforge.common.Tags; +import net.minecraft.world.item.SwordItem; +import net.neoforged.neoforge.common.Tags; public class AllItems { @@ -86,18 +88,18 @@ public class AllItems { REGISTRATE.setCreativeTab(AllCreativeModeTabs.BASE_CREATIVE_TAB); } - public static final ItemEntry WHEAT_FLOUR = - taggedIngredient("wheat_flour", forgeItemTag("flour/wheat"), forgeItemTag("flour")), - DOUGH = taggedIngredient("dough", forgeItemTag("dough"), forgeItemTag("dough/wheat")), + public static final ItemEntry + WHEAT_FLOUR = taggedIngredient("wheat_flour", commonItemTag("flours/wheat"), commonItemTag("flours")), + DOUGH = taggedIngredient("dough", commonItemTag("doughs"), commonItemTag("doughs/wheat")), CINDER_FLOUR = ingredient("cinder_flour"), ROSE_QUARTZ = ingredient("rose_quartz"), POLISHED_ROSE_QUARTZ = ingredient("polished_rose_quartz"), POWDERED_OBSIDIAN = ingredient("powdered_obsidian"), - STURDY_SHEET = taggedIngredient("sturdy_sheet", forgeItemTag("plates/obsidian"), PLATES.tag), + STURDY_SHEET = taggedIngredient("sturdy_sheet", commonItemTag("plates/obsidian"), PLATES.tag), PROPELLER = ingredient("propeller"), WHISK = ingredient("whisk"), BRASS_HAND = ingredient("brass_hand"), CRAFTER_SLOT_COVER = ingredient("crafter_slot_cover"), ELECTRON_TUBE = ingredient("electron_tube"), TRANSMITTER = ingredient("transmitter"), PULP = ingredient("pulp"); public static final ItemEntry CARDBOARD = REGISTRATE.item("cardboard", CombustibleItem::new) - .tag(forgeItemTag("plates/cardboard")) + .tag(commonItemTag("plates/cardboard")) .onRegister(i -> i.setBurnTime(1000)) .register(); @@ -127,26 +129,26 @@ public class AllItems { public static final ItemEntry BAR_OF_CHOCOLATE = REGISTRATE.item("bar_of_chocolate", Item::new) .properties(p -> p.food(new FoodProperties.Builder().nutrition(6) - .saturationMod(0.3F) + .saturationModifier(0.3F) .build())) .lang("Bar of Chocolate") .register(); public static final ItemEntry SWEET_ROLL = REGISTRATE.item("sweet_roll", Item::new) .properties(p -> p.food(new FoodProperties.Builder().nutrition(6) - .saturationMod(0.8F) + .saturationModifier(0.8F) .build())) .register(); public static final ItemEntry CHOCOLATE_BERRIES = REGISTRATE.item("chocolate_glazed_berries", Item::new) .properties(p -> p.food(new FoodProperties.Builder().nutrition(7) - .saturationMod(0.8F) + .saturationModifier(0.8F) .build())) .register(); public static final ItemEntry HONEYED_APPLE = REGISTRATE.item("honeyed_apple", Item::new) .properties(p -> p.food(new FoodProperties.Builder().nutrition(8) - .saturationMod(0.8F) + .saturationModifier(0.8F) .build())) .register(); @@ -159,15 +161,16 @@ public class AllItems { public static final ItemEntry CARDBOARD_SWORD = REGISTRATE.item("cardboard_sword", CardboardSwordItem::new) .properties(p -> p.stacksTo(1)) + .properties(p -> p.attributes(SwordItem.createAttributes(AllToolMaterials.CARDBOARD, 3, 1))) .model(AssetLookup.itemModelWithPartials()) .register(); public static final ItemEntry RAW_ZINC = - taggedIngredient("raw_zinc", forgeItemTag("raw_materials/zinc"), forgeItemTag("raw_materials")); + taggedIngredient("raw_zinc", commonItemTag("raw_materials/zinc"), commonItemTag("raw_materials")); public static final ItemEntry ANDESITE_ALLOY = taggedIngredient("andesite_alloy", CREATE_INGOTS.tag), - ZINC_INGOT = taggedIngredient("zinc_ingot", forgeItemTag("ingots/zinc"), CREATE_INGOTS.tag), - BRASS_INGOT = taggedIngredient("brass_ingot", forgeItemTag("ingots/brass"), CREATE_INGOTS.tag); + ZINC_INGOT = taggedIngredient("zinc_ingot", commonItemTag("ingots/zinc"), CREATE_INGOTS.tag), + BRASS_INGOT = taggedIngredient("brass_ingot", commonItemTag("ingots/brass"), CREATE_INGOTS.tag); public static final ItemEntry CHROMATIC_COMPOUND = REGISTRATE.item("chromatic_compound", ChromaticCompoundItem::new) @@ -185,10 +188,10 @@ public class AllItems { .properties(p -> p.rarity(Rarity.UNCOMMON)) .register(); - public static final ItemEntry COPPER_NUGGET = - taggedIngredient("copper_nugget", forgeItemTag("nuggets/copper"), Tags.Items.NUGGETS), - ZINC_NUGGET = taggedIngredient("zinc_nugget", forgeItemTag("nuggets/zinc"), Tags.Items.NUGGETS), - BRASS_NUGGET = taggedIngredient("brass_nugget", forgeItemTag("nuggets/brass"), Tags.Items.NUGGETS); + public static final ItemEntry + COPPER_NUGGET = taggedIngredient("copper_nugget", commonItemTag("nuggets/copper"), Tags.Items.NUGGETS), + ZINC_NUGGET = taggedIngredient("zinc_nugget", commonItemTag("nuggets/zinc"), Tags.Items.NUGGETS), + BRASS_NUGGET = taggedIngredient("brass_nugget", commonItemTag("nuggets/brass"), Tags.Items.NUGGETS); public static final ItemEntry EXP_NUGGET = REGISTRATE.item("experience_nugget", ExperienceNuggetItem::new) @@ -197,11 +200,11 @@ public class AllItems { .lang("Nugget of Experience") .register(); - public static final ItemEntry COPPER_SHEET = - taggedIngredient("copper_sheet", forgeItemTag("plates/copper"), PLATES.tag), - BRASS_SHEET = taggedIngredient("brass_sheet", forgeItemTag("plates/brass"), PLATES.tag), - IRON_SHEET = taggedIngredient("iron_sheet", forgeItemTag("plates/iron"), PLATES.tag), - GOLDEN_SHEET = taggedIngredient("golden_sheet", forgeItemTag("plates/gold"), PLATES.tag, ItemTags.PIGLIN_LOVED), + public static final ItemEntry + COPPER_SHEET = taggedIngredient("copper_sheet", commonItemTag("plates/copper"), PLATES.tag), + BRASS_SHEET = taggedIngredient("brass_sheet", commonItemTag("plates/brass"), PLATES.tag), + IRON_SHEET = taggedIngredient("iron_sheet", commonItemTag("plates/iron"), PLATES.tag), + GOLDEN_SHEET = taggedIngredient("golden_sheet", commonItemTag("plates/gold"), PLATES.tag, ItemTags.PIGLIN_LOVED), CRUSHED_IRON = taggedIngredient("crushed_raw_iron", CRUSHED_RAW_MATERIALS.tag), CRUSHED_GOLD = taggedIngredient("crushed_raw_gold", CRUSHED_RAW_MATERIALS.tag, ItemTags.PIGLIN_LOVED), @@ -275,7 +278,7 @@ public class AllItems { COPPER_BACKTANK_PLACEABLE)) .model(AssetLookup.customGenericItemModel("_", "item")) .tag(AllItemTags.PRESSURIZED_AIR_SOURCES.tag) - .tag(forgeItemTag("armors/chestplates")) + .tag(ItemTags.CHEST_ARMOR) .register(), NETHERITE_BACKTANK = REGISTRATE @@ -285,7 +288,7 @@ public class AllItems { .model(AssetLookup.customGenericItemModel("_", "item")) .properties(p -> p.fireResistant()) .tag(AllItemTags.PRESSURIZED_AIR_SOURCES.tag) - .tag(forgeItemTag("armors/chestplates")) + .tag(ItemTags.CHEST_ARMOR) .register(); public static final ItemEntry @@ -294,14 +297,14 @@ public class AllItems { REGISTRATE .item("copper_diving_helmet", p -> new DivingHelmetItem(AllArmorMaterials.COPPER, p, Create.asResource("copper_diving"))) - .tag(forgeItemTag("armors/helmets")) + .tag(ItemTags.HEAD_ARMOR) .register(), NETHERITE_DIVING_HELMET = REGISTRATE .item("netherite_diving_helmet", p -> new DivingHelmetItem(ArmorMaterials.NETHERITE, p, Create.asResource("netherite_diving"))) .properties(p -> p.fireResistant()) - .tag(forgeItemTag("armors/helmets")) + .tag(ItemTags.HEAD_ARMOR) .register(); public static final ItemEntry @@ -310,40 +313,41 @@ public class AllItems { REGISTRATE .item("copper_diving_boots", p -> new DivingBootsItem(AllArmorMaterials.COPPER, p, Create.asResource("copper_diving"))) - .tag(forgeItemTag("armors/boots")) + .tag(ItemTags.FOOT_ARMOR) .register(), NETHERITE_DIVING_BOOTS = REGISTRATE .item("netherite_diving_boots", p -> new DivingBootsItem(ArmorMaterials.NETHERITE, p, Create.asResource("netherite_diving"))) .properties(p -> p.fireResistant()) - .tag(forgeItemTag("armors/boots")) + .tag(ItemTags.FOOT_ARMOR) .register(); public static final ItemEntry - CARDBOARD_HELMET = REGISTRATE.item("cardboard_helmet", p -> new CardboardHelmetItem(ArmorItem.Type.HELMET, p)) - .tag(forgeItemTag("armors/helmet"), ItemTags.TRIMMABLE_ARMOR) + CARDBOARD_HELMET = REGISTRATE.item("cardboard_helmet", p -> new CardboardArmorItem(ArmorItem.Type.HELMET, p)) + .tag(ItemTags.HEAD_ARMOR, ItemTags.TRIMMABLE_ARMOR) .onRegisterAfter(Registries.ITEM, v -> ItemDescription.useKey(v, "item.create.cardboard_armor")) .model(TrimmableArmorModelGenerator::generate) + .clientExtension(() -> () -> new CardboardArmorStealthOverlay()) .register(), CARDBOARD_CHESTPLATE = REGISTRATE.item("cardboard_chestplate", p -> new CardboardArmorItem(ArmorItem.Type.CHESTPLATE, p)) - .tag(forgeItemTag("armors/chestplate"), ItemTags.TRIMMABLE_ARMOR) + .tag(ItemTags.CHEST_ARMOR, ItemTags.TRIMMABLE_ARMOR) .onRegisterAfter(Registries.ITEM, v -> ItemDescription.useKey(v, "item.create.cardboard_armor")) .model(TrimmableArmorModelGenerator::generate) .register(), CARDBOARD_LEGGINGS = REGISTRATE.item("cardboard_leggings", p -> new CardboardArmorItem(ArmorItem.Type.LEGGINGS, p)) - .tag(forgeItemTag("armors/leggings"), ItemTags.TRIMMABLE_ARMOR) + .tag(ItemTags.LEG_ARMOR, ItemTags.TRIMMABLE_ARMOR) .onRegisterAfter(Registries.ITEM, v -> ItemDescription.useKey(v, "item.create.cardboard_armor")) .model(TrimmableArmorModelGenerator::generate) .register(), CARDBOARD_BOOTS = REGISTRATE.item("cardboard_boots", p -> new CardboardArmorItem(ArmorItem.Type.BOOTS, p)) - .tag(forgeItemTag("armors/boots"), ItemTags.TRIMMABLE_ARMOR) + .tag(ItemTags.FOOT_ARMOR, ItemTags.TRIMMABLE_ARMOR) .onRegisterAfter(Registries.ITEM, v -> ItemDescription.useKey(v, "item.create.cardboard_armor")) .model(TrimmableArmorModelGenerator::generate) .register(); @@ -386,6 +390,7 @@ public class AllItems { public static final ItemEntry POTATO_CANNON = REGISTRATE.item("potato_cannon", PotatoCannonItem::new) .model(AssetLookup.itemModelWithPartials()) + .tag(Tags.Items.ENCHANTABLES) .register(); public static final ItemEntry EXTENDO_GRIP = REGISTRATE.item("extendo_grip", ExtendoGripItem::new) @@ -490,7 +495,7 @@ public class AllItems { String metalName = metal.getName(); return REGISTRATE .item("crushed_raw_" + metalName, - props -> new TagDependentIngredientItem(props, AllTags.forgeItemTag("ores/" + metalName))) + props -> new TagDependentIngredientItem(props, AllTags.commonItemTag("ores/" + metalName))) .tag(CRUSHED_RAW_MATERIALS.tag) .register(); } diff --git a/src/main/java/com/simibubi/create/AllKeys.java b/src/main/java/com/simibubi/create/AllKeys.java index 0b1f1338be..afb3a083ba 100644 --- a/src/main/java/com/simibubi/create/AllKeys.java +++ b/src/main/java/com/simibubi/create/AllKeys.java @@ -1,5 +1,7 @@ package com.simibubi.create; +import net.neoforged.fml.common.EventBusSubscriber; + import org.lwjgl.glfw.GLFW; import com.mojang.blaze3d.platform.InputConstants; @@ -7,10 +9,9 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyMapping; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RegisterKeyMappingsEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent; @EventBusSubscriber(value = Dist.CLIENT, bus = EventBusSubscriber.Bus.MOD) public enum AllKeys { diff --git a/src/main/java/com/simibubi/create/AllMapDecorationTypes.java b/src/main/java/com/simibubi/create/AllMapDecorationTypes.java new file mode 100644 index 0000000000..24a934d774 --- /dev/null +++ b/src/main/java/com/simibubi/create/AllMapDecorationTypes.java @@ -0,0 +1,17 @@ +package com.simibubi.create; + +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.level.saveddata.maps.MapDecorationType; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredRegister; + +public class AllMapDecorationTypes { + private static final DeferredRegister DECORATION_TYPES = DeferredRegister.create(Registries.MAP_DECORATION_TYPE, Create.ID); + + public static final Holder STATION_MAP_DECORATION = DECORATION_TYPES.register("station", () -> new MapDecorationType(Create.asResource("station"), true, -1, false, true)); + + public static void register(IEventBus modEventBus) { + DECORATION_TYPES.register(modEventBus); + } +} diff --git a/src/main/java/com/simibubi/create/AllMovementBehaviours.java b/src/main/java/com/simibubi/create/AllMovementBehaviours.java index 6dde486402..737fb2d91a 100644 --- a/src/main/java/com/simibubi/create/AllMovementBehaviours.java +++ b/src/main/java/com/simibubi/create/AllMovementBehaviours.java @@ -13,14 +13,15 @@ import com.simibubi.create.content.contraptions.behaviour.dispenser.DropperMovem import com.simibubi.create.foundation.utility.AttachedRegistry; import com.tterrag.registrate.util.nullness.NonNullConsumer; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.registries.ForgeRegistries; public class AllMovementBehaviours { - private static final AttachedRegistry BLOCK_BEHAVIOURS = new AttachedRegistry<>(ForgeRegistries.BLOCKS); + private static final AttachedRegistry BLOCK_BEHAVIOURS = new AttachedRegistry<>(BuiltInRegistries.BLOCK); private static final List GLOBAL_BEHAVIOURS = new ArrayList<>(); public static void registerBehaviour(ResourceLocation block, MovementBehaviour behaviour) { diff --git a/src/main/java/com/simibubi/create/AllPackets.java b/src/main/java/com/simibubi/create/AllPackets.java index bf7ea041b5..9d98724fec 100644 --- a/src/main/java/com/simibubi/create/AllPackets.java +++ b/src/main/java/com/simibubi/create/AllPackets.java @@ -1,11 +1,6 @@ package com.simibubi.create; -import static net.minecraftforge.network.NetworkDirection.PLAY_TO_CLIENT; -import static net.minecraftforge.network.NetworkDirection.PLAY_TO_SERVER; - -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.function.Supplier; +import java.util.Locale; import com.simibubi.create.compat.computercraft.AttachedComputerPacket; import com.simibubi.create.compat.trainmap.TrainMapSyncPacket; @@ -91,7 +86,8 @@ import com.simibubi.create.content.schematics.packet.SchematicSyncPacket; import com.simibubi.create.content.schematics.packet.SchematicUploadPacket; import com.simibubi.create.content.trains.HonkPacket; import com.simibubi.create.content.trains.TrainHUDUpdatePacket; -import com.simibubi.create.content.trains.entity.TrainPacket; +import com.simibubi.create.content.trains.entity.AddTrainPacket; +import com.simibubi.create.content.trains.entity.RemoveTrainPacket; import com.simibubi.create.content.trains.entity.TrainPromptPacket; import com.simibubi.create.content.trains.entity.TrainRelocationPacket; import com.simibubi.create.content.trains.graph.TrackGraphRequestPacket; @@ -111,153 +107,137 @@ import com.simibubi.create.foundation.gui.menu.ClearMenuPacket; import com.simibubi.create.foundation.gui.menu.GhostItemSubmitPacket; import com.simibubi.create.foundation.networking.ISyncPersistentData; import com.simibubi.create.foundation.networking.LeftClickPacket; -import com.simibubi.create.foundation.networking.SimplePacketBase; import com.simibubi.create.foundation.utility.ServerSpeedProvider; import com.simibubi.create.infrastructure.command.HighlightPacket; import com.simibubi.create.infrastructure.command.SimpleCreateActions; import com.simibubi.create.infrastructure.debugInfo.ServerDebugInfoPacket; -import net.createmod.catnip.net.ClientboundSimpleActionPacket; -import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.Level; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.PacketDistributor; -import net.minecraftforge.network.PacketDistributor.TargetPoint; -import net.minecraftforge.network.simple.SimpleChannel; - -public enum AllPackets { +import net.createmod.catnip.net.base.BasePacketPayload; +import net.createmod.catnip.net.base.CatnipPacketRegistry; +import net.createmod.catnip.net.packets.ClientboundSimpleActionPacket; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +public enum AllPackets implements BasePacketPayload.PacketTypeProvider { // Client to Server - CONFIGURE_SCHEMATICANNON(ConfigureSchematicannonPacket.class, ConfigureSchematicannonPacket::new, PLAY_TO_SERVER), - CONFIGURE_STOCKSWITCH(ConfigureThresholdSwitchPacket.class, ConfigureThresholdSwitchPacket::new, PLAY_TO_SERVER), - CONFIGURE_SEQUENCER(ConfigureSequencedGearshiftPacket.class, ConfigureSequencedGearshiftPacket::new, - PLAY_TO_SERVER), - PLACE_SCHEMATIC(SchematicPlacePacket.class, SchematicPlacePacket::new, PLAY_TO_SERVER), - UPLOAD_SCHEMATIC(SchematicUploadPacket.class, SchematicUploadPacket::new, PLAY_TO_SERVER), - CLEAR_CONTAINER(ClearMenuPacket.class, ClearMenuPacket::new, PLAY_TO_SERVER), - CONFIGURE_FILTER(FilterScreenPacket.class, FilterScreenPacket::new, PLAY_TO_SERVER), - EXTENDO_INTERACT(ExtendoGripInteractionPacket.class, ExtendoGripInteractionPacket::new, PLAY_TO_SERVER), - CONTRAPTION_INTERACT(ContraptionInteractionPacket.class, ContraptionInteractionPacket::new, PLAY_TO_SERVER), - CLIENT_MOTION(ClientMotionPacket.class, ClientMotionPacket::new, PLAY_TO_SERVER), - PLACE_ARM(ArmPlacementPacket.class, ArmPlacementPacket::new, PLAY_TO_SERVER), - PLACE_PACKAGE_PORT(PackagePortPlacementPacket.class, PackagePortPlacementPacket::new, PLAY_TO_SERVER), - MINECART_COUPLING_CREATION(CouplingCreationPacket.class, CouplingCreationPacket::new, PLAY_TO_SERVER), - INSTANT_SCHEMATIC(InstantSchematicPacket.class, InstantSchematicPacket::new, PLAY_TO_SERVER), - SYNC_SCHEMATIC(SchematicSyncPacket.class, SchematicSyncPacket::new, PLAY_TO_SERVER), - LEFT_CLICK(LeftClickPacket.class, LeftClickPacket::new, PLAY_TO_SERVER), - PLACE_EJECTOR(EjectorPlacementPacket.class, EjectorPlacementPacket::new, PLAY_TO_SERVER), - TRIGGER_EJECTOR(EjectorTriggerPacket.class, EjectorTriggerPacket::new, PLAY_TO_SERVER), - EJECTOR_ELYTRA(EjectorElytraPacket.class, EjectorElytraPacket::new, PLAY_TO_SERVER), - LINKED_CONTROLLER_INPUT(LinkedControllerInputPacket.class, LinkedControllerInputPacket::new, PLAY_TO_SERVER), - LINKED_CONTROLLER_BIND(LinkedControllerBindPacket.class, LinkedControllerBindPacket::new, PLAY_TO_SERVER), - LINKED_CONTROLLER_USE_LECTERN(LinkedControllerStopLecternPacket.class, LinkedControllerStopLecternPacket::new, - PLAY_TO_SERVER), - SUBMIT_GHOST_ITEM(GhostItemSubmitPacket.class, GhostItemSubmitPacket::new, PLAY_TO_SERVER), - BLUEPRINT_COMPLETE_RECIPE(BlueprintAssignCompleteRecipePacket.class, BlueprintAssignCompleteRecipePacket::new, - PLAY_TO_SERVER), - CONFIGURE_SYMMETRY_WAND(ConfigureSymmetryWandPacket.class, ConfigureSymmetryWandPacket::new, PLAY_TO_SERVER), - CONFIGURE_WORLDSHAPER(ConfigureWorldshaperPacket.class, ConfigureWorldshaperPacket::new, PLAY_TO_SERVER), - TOOLBOX_EQUIP(ToolboxEquipPacket.class, ToolboxEquipPacket::new, PLAY_TO_SERVER), - TOOLBOX_DISPOSE_ALL(ToolboxDisposeAllPacket.class, ToolboxDisposeAllPacket::new, PLAY_TO_SERVER), - CONFIGURE_SCHEDULE(ScheduleEditPacket.class, ScheduleEditPacket::new, PLAY_TO_SERVER), - CONFIGURE_STATION(StationEditPacket.class, StationEditPacket::new, PLAY_TO_SERVER), - C_CONFIGURE_TRAIN(TrainEditPacket.class, TrainEditPacket::new, PLAY_TO_SERVER), - RELOCATE_TRAIN(TrainRelocationPacket.class, TrainRelocationPacket::new, PLAY_TO_SERVER), - CONTROLS_INPUT(ControlsInputPacket.class, ControlsInputPacket::new, PLAY_TO_SERVER), - CONFIGURE_DATA_GATHERER(DisplayLinkConfigurationPacket.class, DisplayLinkConfigurationPacket::new, PLAY_TO_SERVER), - DESTROY_CURVED_TRACK(CurvedTrackDestroyPacket.class, CurvedTrackDestroyPacket::new, PLAY_TO_SERVER), - SELECT_CURVED_TRACK(CurvedTrackSelectionPacket.class, CurvedTrackSelectionPacket::new, PLAY_TO_SERVER), - PLACE_CURVED_TRACK(PlaceExtendedCurvePacket.class, PlaceExtendedCurvePacket::new, PLAY_TO_SERVER), - GLUE_IN_AREA(SuperGlueSelectionPacket.class, SuperGlueSelectionPacket::new, PLAY_TO_SERVER), - GLUE_REMOVED(SuperGlueRemovalPacket.class, SuperGlueRemovalPacket::new, PLAY_TO_SERVER), - TRAIN_COLLISION(TrainCollisionPacket.class, TrainCollisionPacket::new, PLAY_TO_SERVER), - C_TRAIN_HUD(TrainHUDUpdatePacket.Serverbound.class, TrainHUDUpdatePacket.Serverbound::new, PLAY_TO_SERVER), - C_TRAIN_HONK(HonkPacket.Serverbound.class, HonkPacket.Serverbound::new, PLAY_TO_SERVER), - OBSERVER_STRESSOMETER(GaugeObservedPacket.class, GaugeObservedPacket::new, PLAY_TO_SERVER), - EJECTOR_AWARD(EjectorAwardPacket.class, EjectorAwardPacket::new, PLAY_TO_SERVER), - TRACK_GRAPH_REQUEST(TrackGraphRequestPacket.class, TrackGraphRequestPacket::new, PLAY_TO_SERVER), - CONFIGURE_ELEVATOR_CONTACT(ElevatorContactEditPacket.class, ElevatorContactEditPacket::new, PLAY_TO_SERVER), - REQUEST_FLOOR_LIST(ElevatorFloorListPacket.RequestFloorList.class, ElevatorFloorListPacket.RequestFloorList::new, - PLAY_TO_SERVER), - ELEVATOR_SET_FLOOR(ElevatorTargetFloorPacket.class, ElevatorTargetFloorPacket::new, PLAY_TO_SERVER), - VALUE_SETTINGS(ValueSettingsPacket.class, ValueSettingsPacket::new, PLAY_TO_SERVER), - CLIPBOARD_EDIT(ClipboardEditPacket.class, ClipboardEditPacket::new, PLAY_TO_SERVER), - CONTRAPTION_COLLIDER_LOCK_REQUEST(ContraptionColliderLockPacketRequest.class, - ContraptionColliderLockPacketRequest::new, PLAY_TO_SERVER), - RADIAL_WRENCH_MENU_SUBMIT(RadialWrenchMenuSubmitPacket.class, RadialWrenchMenuSubmitPacket::new, - PLAY_TO_SERVER), - LOGISTICS_STOCK_REQUEST(LogisticalStockRequestPacket.class, LogisticalStockRequestPacket::new, PLAY_TO_SERVER), - LOGISTICS_PACKAGE_REQUEST(PackageOrderRequestPacket.class, PackageOrderRequestPacket::new, PLAY_TO_SERVER), - CHAIN_CONVEYOR_CONNECT(ChainConveyorConnectionPacket.class, ChainConveyorConnectionPacket::new, PLAY_TO_SERVER), - CHAIN_CONVEYOR_RIDING(ServerboundChainConveyorRidingPacket.class, ServerboundChainConveyorRidingPacket::new, PLAY_TO_SERVER), - CHAIN_PACKAGE_INTERACTION(ChainPackageInteractionPacket.class, ChainPackageInteractionPacket::new, PLAY_TO_SERVER), - PACKAGE_PORT_CONFIGURATION(PackagePortConfigurationPacket.class, PackagePortConfigurationPacket::new, PLAY_TO_SERVER), - TRAIN_MAP_REQUEST(TrainMapSyncRequestPacket.class, TrainMapSyncRequestPacket::new, PLAY_TO_SERVER), - CONNECT_FACTORY_PANEL(FactoryPanelConnectionPacket.class, FactoryPanelConnectionPacket::new, PLAY_TO_SERVER), - CONFIGURE_FACTORY_PANEL(FactoryPanelConfigurationPacket.class, FactoryPanelConfigurationPacket::new, PLAY_TO_SERVER), - CONFIGURE_REDSTONE_REQUESTER(RedstoneRequesterConfigurationPacket.class, RedstoneRequesterConfigurationPacket::new, PLAY_TO_SERVER), - CONFIGURE_STOCK_KEEPER_CATEGORIES(StockKeeperCategoryEditPacket.class, StockKeeperCategoryEditPacket::new, PLAY_TO_SERVER), - REFUND_STOCK_KEEPER_CATEGORY(StockKeeperCategoryRefundPacket.class, StockKeeperCategoryRefundPacket::new, PLAY_TO_SERVER), - LOCK_STOCK_KEEPER(StockKeeperLockPacket.class, StockKeeperLockPacket::new, PLAY_TO_SERVER), - STOCK_KEEPER_HIDE_CATEGORY(StockKeeperCategoryHidingPacket.class, StockKeeperCategoryHidingPacket::new, PLAY_TO_SERVER), + CONFIGURE_SCHEMATICANNON(ConfigureSchematicannonPacket.class, ConfigureSchematicannonPacket.STREAM_CODEC), + CONFIGURE_STOCKSWITCH(ConfigureThresholdSwitchPacket.class, ConfigureThresholdSwitchPacket.STREAM_CODEC), + CONFIGURE_SEQUENCER(ConfigureSequencedGearshiftPacket.class, ConfigureSequencedGearshiftPacket.STREAM_CODEC), + PLACE_SCHEMATIC(SchematicPlacePacket.class, SchematicPlacePacket.STREAM_CODEC), + UPLOAD_SCHEMATIC(SchematicUploadPacket.class, SchematicUploadPacket.STREAM_CODEC), + CLEAR_CONTAINER(ClearMenuPacket.class, ClearMenuPacket.STREAM_CODEC), + CONFIGURE_FILTER(FilterScreenPacket.class, FilterScreenPacket.STREAM_CODEC), + EXTENDO_INTERACT(ExtendoGripInteractionPacket.class, ExtendoGripInteractionPacket.STREAM_CODEC), + CONTRAPTION_INTERACT(ContraptionInteractionPacket.class, ContraptionInteractionPacket.STREAM_CODEC), + CLIENT_MOTION(ClientMotionPacket.class, ClientMotionPacket.STREAM_CODEC), + PLACE_ARM(ArmPlacementPacket.class, ArmPlacementPacket.STREAM_CODEC), + PLACE_PACKAGE_PORT(PackagePortPlacementPacket.class, PackagePortPlacementPacket.STREAM_CODEC), + MINECART_COUPLING_CREATION(CouplingCreationPacket.class, CouplingCreationPacket.STREAM_CODEC), + INSTANT_SCHEMATIC(InstantSchematicPacket.class, InstantSchematicPacket.STREAM_CODEC), + SYNC_SCHEMATIC(SchematicSyncPacket.class, SchematicSyncPacket.STREAM_CODEC), + LEFT_CLICK(LeftClickPacket.class, LeftClickPacket.STREAM_CODEC), + PLACE_EJECTOR(EjectorPlacementPacket.class, EjectorPlacementPacket.STREAM_CODEC), + TRIGGER_EJECTOR(EjectorTriggerPacket.class, EjectorTriggerPacket.STREAM_CODEC), + EJECTOR_ELYTRA(EjectorElytraPacket.class, EjectorElytraPacket.STREAM_CODEC), + LINKED_CONTROLLER_INPUT(LinkedControllerInputPacket.class, LinkedControllerInputPacket.STREAM_CODEC), + LINKED_CONTROLLER_BIND(LinkedControllerBindPacket.class, LinkedControllerBindPacket.STREAM_CODEC), + LINKED_CONTROLLER_USE_LECTERN(LinkedControllerStopLecternPacket.class, LinkedControllerStopLecternPacket.STREAM_CODEC), + SUBMIT_GHOST_ITEM(GhostItemSubmitPacket.class, GhostItemSubmitPacket.STREAM_CODEC), + BLUEPRINT_COMPLETE_RECIPE(BlueprintAssignCompleteRecipePacket.class, BlueprintAssignCompleteRecipePacket.STREAM_CODEC), + CONFIGURE_SYMMETRY_WAND(ConfigureSymmetryWandPacket.class, ConfigureSymmetryWandPacket.STREAM_CODEC), + CONFIGURE_WORLDSHAPER(ConfigureWorldshaperPacket.class, ConfigureWorldshaperPacket.STREAM_CODEC), + TOOLBOX_EQUIP(ToolboxEquipPacket.class, ToolboxEquipPacket.STREAM_CODEC), + TOOLBOX_DISPOSE_ALL(ToolboxDisposeAllPacket.class, ToolboxDisposeAllPacket.STREAM_CODEC), + CONFIGURE_SCHEDULE(ScheduleEditPacket.class, ScheduleEditPacket.STREAM_CODEC), + CONFIGURE_STATION(StationEditPacket.class, StationEditPacket.STREAM_CODEC), + C_CONFIGURE_TRAIN(TrainEditPacket.Serverbound.class, TrainEditPacket.Serverbound.STREAM_CODEC), + RELOCATE_TRAIN(TrainRelocationPacket.class, TrainRelocationPacket.STREAM_CODEC), + CONTROLS_INPUT(ControlsInputPacket.class, ControlsInputPacket.STREAM_CODEC), + CONFIGURE_DATA_GATHERER(DisplayLinkConfigurationPacket.class, DisplayLinkConfigurationPacket.STREAM_CODEC), + DESTROY_CURVED_TRACK(CurvedTrackDestroyPacket.class, CurvedTrackDestroyPacket.STREAM_CODEC), + SELECT_CURVED_TRACK(CurvedTrackSelectionPacket.class, CurvedTrackSelectionPacket.STREAM_CODEC), + PLACE_CURVED_TRACK(PlaceExtendedCurvePacket.class, PlaceExtendedCurvePacket.STREAM_CODEC), + GLUE_IN_AREA(SuperGlueSelectionPacket.class, SuperGlueSelectionPacket.STREAM_CODEC), + GLUE_REMOVED(SuperGlueRemovalPacket.class, SuperGlueRemovalPacket.STREAM_CODEC), + TRAIN_COLLISION(TrainCollisionPacket.class, TrainCollisionPacket.STREAM_CODEC), + C_TRAIN_HUD(TrainHUDUpdatePacket.Serverbound.class, TrainHUDUpdatePacket.Serverbound.STREAM_CODEC), + C_TRAIN_HONK(HonkPacket.Serverbound.class, HonkPacket.Serverbound.STREAM_CODEC), + OBSERVER_STRESSOMETER(GaugeObservedPacket.class, GaugeObservedPacket.STREAM_CODEC), + EJECTOR_AWARD(EjectorAwardPacket.class, EjectorAwardPacket.STREAM_CODEC), + TRACK_GRAPH_REQUEST(TrackGraphRequestPacket.class, TrackGraphRequestPacket.STREAM_CODEC), + CONFIGURE_ELEVATOR_CONTACT(ElevatorContactEditPacket.class, ElevatorContactEditPacket.STREAM_CODEC), + REQUEST_FLOOR_LIST(ElevatorFloorListPacket.RequestFloorList.class, ElevatorFloorListPacket.RequestFloorList.STREAM_CODEC), + ELEVATOR_SET_FLOOR(ElevatorTargetFloorPacket.class, ElevatorTargetFloorPacket.STREAM_CODEC), + VALUE_SETTINGS(ValueSettingsPacket.class, ValueSettingsPacket.STREAM_CODEC), + CLIPBOARD_EDIT(ClipboardEditPacket.class, ClipboardEditPacket.STREAM_CODEC), + CONTRAPTION_COLLIDER_LOCK_REQUEST(ContraptionColliderLockPacketRequest.class, ContraptionColliderLockPacketRequest.STREAM_CODEC), + RADIAL_WRENCH_MENU_SUBMIT(RadialWrenchMenuSubmitPacket.class, RadialWrenchMenuSubmitPacket.STREAM_CODEC), + LOGISTICS_STOCK_REQUEST(LogisticalStockRequestPacket.class, LogisticalStockRequestPacket.STREAM_CODEC), + LOGISTICS_PACKAGE_REQUEST(PackageOrderRequestPacket.class, PackageOrderRequestPacket.STREAM_CODEC), + CHAIN_CONVEYOR_CONNECT(ChainConveyorConnectionPacket.class, ChainConveyorConnectionPacket.STREAM_CODEC), + CHAIN_CONVEYOR_RIDING(ServerboundChainConveyorRidingPacket.class, ServerboundChainConveyorRidingPacket.STREAM_CODEC), + CHAIN_PACKAGE_INTERACTION(ChainPackageInteractionPacket.class, ChainPackageInteractionPacket.STREAM_CODEC), + PACKAGE_PORT_CONFIGURATION(PackagePortConfigurationPacket.class, PackagePortConfigurationPacket.STREAM_CODEC), + TRAIN_MAP_REQUEST(TrainMapSyncRequestPacket.class, TrainMapSyncRequestPacket.STREAM_CODEC), + CONNECT_FACTORY_PANEL(FactoryPanelConnectionPacket.class, FactoryPanelConnectionPacket.STREAM_CODEC), + CONFIGURE_FACTORY_PANEL(FactoryPanelConfigurationPacket.class, FactoryPanelConfigurationPacket.STREAM_CODEC), + CONFIGURE_REDSTONE_REQUESTER(RedstoneRequesterConfigurationPacket.class, RedstoneRequesterConfigurationPacket.STREAM_CODEC), + CONFIGURE_STOCK_KEEPER_CATEGORIES(StockKeeperCategoryEditPacket.class, StockKeeperCategoryEditPacket.STREAM_CODEC), + REFUND_STOCK_KEEPER_CATEGORY(StockKeeperCategoryRefundPacket.class, StockKeeperCategoryRefundPacket.STREAM_CODEC), + LOCK_STOCK_KEEPER(StockKeeperLockPacket.class, StockKeeperLockPacket.STREAM_CODEC), + STOCK_KEEPER_HIDE_CATEGORY(StockKeeperCategoryHidingPacket.class, StockKeeperCategoryHidingPacket.STREAM_CODEC), // Server to Client - SYMMETRY_EFFECT(SymmetryEffectPacket.class, SymmetryEffectPacket::new, PLAY_TO_CLIENT), - SERVER_SPEED(ServerSpeedProvider.Packet.class, ServerSpeedProvider.Packet::new, PLAY_TO_CLIENT), - BEAM_EFFECT(ZapperBeamPacket.class, ZapperBeamPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_STALL(ContraptionStallPacket.class, ContraptionStallPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_DISASSEMBLE(ContraptionDisassemblyPacket.class, ContraptionDisassemblyPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_BLOCK_CHANGED(ContraptionBlockChangedPacket.class, ContraptionBlockChangedPacket::new, PLAY_TO_CLIENT), - GLUE_EFFECT(GlueEffectPacket.class, GlueEffectPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_SEAT_MAPPING(ContraptionSeatMappingPacket.class, ContraptionSeatMappingPacket::new, PLAY_TO_CLIENT), - LIMBSWING_UPDATE(LimbSwingUpdatePacket.class, LimbSwingUpdatePacket::new, PLAY_TO_CLIENT), - MINECART_CONTROLLER(MinecartControllerUpdatePacket.class, MinecartControllerUpdatePacket::new, PLAY_TO_CLIENT), - FLUID_SPLASH(FluidSplashPacket.class, FluidSplashPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_FLUID(ContraptionFluidPacket.class, ContraptionFluidPacket::new, PLAY_TO_CLIENT), - GANTRY_UPDATE(GantryContraptionUpdatePacket.class, GantryContraptionUpdatePacket::new, PLAY_TO_CLIENT), - BLOCK_HIGHLIGHT(HighlightPacket.class, HighlightPacket::new, PLAY_TO_CLIENT), - TUNNEL_FLAP(TunnelFlapPacket.class, TunnelFlapPacket::new, PLAY_TO_CLIENT), - FUNNEL_FLAP(FunnelFlapPacket.class, FunnelFlapPacket::new, PLAY_TO_CLIENT), - POTATO_CANNON(PotatoCannonPacket.class, PotatoCannonPacket::new, PLAY_TO_CLIENT), - SOUL_PULSE(SoulPulseEffectPacket.class, SoulPulseEffectPacket::new, PLAY_TO_CLIENT), - PERSISTENT_DATA(ISyncPersistentData.PersistentDataPacket.class, ISyncPersistentData.PersistentDataPacket::new, - PLAY_TO_CLIENT), - SYNC_POTATO_PROJECTILE_TYPES(PotatoProjectileTypeManager.SyncPacket.class, - PotatoProjectileTypeManager.SyncPacket::new, PLAY_TO_CLIENT), - SYNC_RAIL_GRAPH(TrackGraphSyncPacket.class, TrackGraphSyncPacket::new, PLAY_TO_CLIENT), - SYNC_EDGE_GROUP(SignalEdgeGroupPacket.class, SignalEdgeGroupPacket::new, PLAY_TO_CLIENT), - SYNC_TRAIN(TrainPacket.class, TrainPacket::new, PLAY_TO_CLIENT), - REMOVE_TE(RemoveBlockEntityPacket.class, RemoveBlockEntityPacket::new, PLAY_TO_CLIENT), - S_CONFIGURE_TRAIN(TrainEditReturnPacket.class, TrainEditReturnPacket::new, PLAY_TO_CLIENT), - CONTROLS_ABORT(ControlsStopControllingPacket.class, ControlsStopControllingPacket::new, PLAY_TO_CLIENT), - S_TRAIN_HUD(TrainHUDUpdatePacket.class, TrainHUDUpdatePacket::new, PLAY_TO_CLIENT), - S_TRAIN_HONK(HonkPacket.class, HonkPacket::new, PLAY_TO_CLIENT), - S_TRAIN_PROMPT(TrainPromptPacket.class, TrainPromptPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_RELOCATION(ContraptionRelocationPacket.class, ContraptionRelocationPacket::new, PLAY_TO_CLIENT), - TRACK_GRAPH_ROLL_CALL(TrackGraphRollCallPacket.class, TrackGraphRollCallPacket::new, PLAY_TO_CLIENT), - S_PLACE_EJECTOR(ArmPlacementPacket.ClientBoundRequest.class, ArmPlacementPacket.ClientBoundRequest::new, - PLAY_TO_CLIENT), - S_PLACE_ARM(EjectorPlacementPacket.ClientBoundRequest.class, EjectorPlacementPacket.ClientBoundRequest::new, - PLAY_TO_CLIENT), - S_PLACE_PACKAGE_PORT(PackagePortPlacementPacket.ClientBoundRequest.class, PackagePortPlacementPacket.ClientBoundRequest::new, - PLAY_TO_CLIENT), - UPDATE_ELEVATOR_FLOORS(ElevatorFloorListPacket.class, ElevatorFloorListPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_ACTOR_TOGGLE(ContraptionDisableActorPacket.class, ContraptionDisableActorPacket::new, PLAY_TO_CLIENT), - CONTRAPTION_COLLIDER_LOCK(ContraptionColliderLockPacket.class, ContraptionColliderLockPacket::new, PLAY_TO_CLIENT), - ATTACHED_COMPUTER(AttachedComputerPacket.class, AttachedComputerPacket::new, PLAY_TO_CLIENT), - SERVER_DEBUG_INFO(ServerDebugInfoPacket.class, ServerDebugInfoPacket::new, PLAY_TO_CLIENT), - PACKAGE_DESTROYED(PackageDestroyPacket.class, PackageDestroyPacket::new, PLAY_TO_CLIENT), - LOGISTICS_STOCK_RESPONSE(LogisticalStockResponsePacket.class, LogisticalStockResponsePacket::new, PLAY_TO_CLIENT), - FACTORY_PANEL_EFFECT(FactoryPanelEffectPacket.class, FactoryPanelEffectPacket::new, PLAY_TO_CLIENT), - PACKAGER_LINK_EFFECT(PackagerLinkEffectPacket.class, PackagerLinkEffectPacket::new, PLAY_TO_CLIENT), - REDSTONE_REQUESTER_EFFECT(RedstoneRequesterEffectPacket.class, RedstoneRequesterEffectPacket::new, PLAY_TO_CLIENT), - KNOCKBACK(KnockbackPacket.class, KnockbackPacket::new, PLAY_TO_CLIENT), - TRAIN_MAP_SYNC(TrainMapSyncPacket.class, TrainMapSyncPacket::new, PLAY_TO_CLIENT), - CLIENTBOUND_CHAIN_CONVEYOR(ClientboundChainConveyorRidingPacket.class, ClientboundChainConveyorRidingPacket::new, PLAY_TO_CLIENT); + SYMMETRY_EFFECT(SymmetryEffectPacket.class, SymmetryEffectPacket.STREAM_CODEC), + SERVER_SPEED(ServerSpeedProvider.Packet.class, ServerSpeedProvider.Packet.STREAM_CODEC), + BEAM_EFFECT(ZapperBeamPacket.class, ZapperBeamPacket.STREAM_CODEC), + CONTRAPTION_STALL(ContraptionStallPacket.class, ContraptionStallPacket.STREAM_CODEC), + CONTRAPTION_DISASSEMBLE(ContraptionDisassemblyPacket.class, ContraptionDisassemblyPacket.STREAM_CODEC), + CONTRAPTION_BLOCK_CHANGED(ContraptionBlockChangedPacket.class, ContraptionBlockChangedPacket.STREAM_CODEC), + GLUE_EFFECT(GlueEffectPacket.class, GlueEffectPacket.STREAM_CODEC), + CONTRAPTION_SEAT_MAPPING(ContraptionSeatMappingPacket.class, ContraptionSeatMappingPacket.STREAM_CODEC), + LIMBSWING_UPDATE(LimbSwingUpdatePacket.class, LimbSwingUpdatePacket.STREAM_CODEC), + MINECART_CONTROLLER(MinecartControllerUpdatePacket.class, MinecartControllerUpdatePacket.STREAM_CODEC), + FLUID_SPLASH(FluidSplashPacket.class, FluidSplashPacket.STREAM_CODEC), + CONTRAPTION_FLUID(ContraptionFluidPacket.class, ContraptionFluidPacket.STREAM_CODEC), + GANTRY_UPDATE(GantryContraptionUpdatePacket.class, GantryContraptionUpdatePacket.STREAM_CODEC), + BLOCK_HIGHLIGHT(HighlightPacket.class, HighlightPacket.STREAM_CODEC), + TUNNEL_FLAP(TunnelFlapPacket.class, TunnelFlapPacket.STREAM_CODEC), + FUNNEL_FLAP(FunnelFlapPacket.class, FunnelFlapPacket.STREAM_CODEC), + POTATO_CANNON(PotatoCannonPacket.class, PotatoCannonPacket.STREAM_CODEC), + SOUL_PULSE(SoulPulseEffectPacket.class, SoulPulseEffectPacket.STREAM_CODEC), + PERSISTENT_DATA(ISyncPersistentData.PersistentDataPacket.class, ISyncPersistentData.PersistentDataPacket.STREAM_CODEC), + SYNC_POTATO_PROJECTILE_TYPES(PotatoProjectileTypeManager.SyncPacket.class, PotatoProjectileTypeManager.SyncPacket.STREAM_CODEC), + SYNC_RAIL_GRAPH(TrackGraphSyncPacket.class, TrackGraphSyncPacket.STREAM_CODEC), + SYNC_EDGE_GROUP(SignalEdgeGroupPacket.class, SignalEdgeGroupPacket.STREAM_CODEC), + ADD_TRAIN(AddTrainPacket.class, AddTrainPacket.STREAM_CODEC), + REMOVE_TRAIN(RemoveTrainPacket.class, RemoveTrainPacket.STREAM_CODEC), + REMOVE_TE(RemoveBlockEntityPacket.class, RemoveBlockEntityPacket.STREAM_CODEC), + S_CONFIGURE_TRAIN(TrainEditReturnPacket.class, TrainEditReturnPacket.STREAM_CODEC), + CONTROLS_ABORT(ControlsStopControllingPacket.class, ControlsStopControllingPacket.STREAM_CODEC), + S_TRAIN_HUD(TrainHUDUpdatePacket.Clientbound.class, TrainHUDUpdatePacket.Clientbound.STREAM_CODEC), + S_TRAIN_HONK(HonkPacket.Clientbound.class, HonkPacket.Clientbound.STREAM_CODEC), + S_TRAIN_PROMPT(TrainPromptPacket.class, TrainPromptPacket.STREAM_CODEC), + CONTRAPTION_RELOCATION(ContraptionRelocationPacket.class, ContraptionRelocationPacket.STREAM_CODEC), + TRACK_GRAPH_ROLL_CALL(TrackGraphRollCallPacket.class, TrackGraphRollCallPacket.STREAM_CODEC), + S_PLACE_ARM(ArmPlacementPacket.ClientBoundRequest.class, ArmPlacementPacket.ClientBoundRequest.STREAM_CODEC), + S_PLACE_EJECTOR(EjectorPlacementPacket.ClientBoundRequest.class, EjectorPlacementPacket.ClientBoundRequest.STREAM_CODEC), + S_PLACE_PACKAGE_PORT(PackagePortPlacementPacket.ClientBoundRequest.class, PackagePortPlacementPacket.ClientBoundRequest.STREAM_CODEC), + UPDATE_ELEVATOR_FLOORS(ElevatorFloorListPacket.class, ElevatorFloorListPacket.STREAM_CODEC), + CONTRAPTION_ACTOR_TOGGLE(ContraptionDisableActorPacket.class, ContraptionDisableActorPacket.STREAM_CODEC), + CONTRAPTION_COLLIDER_LOCK(ContraptionColliderLockPacket.class, ContraptionColliderLockPacket.STREAM_CODEC), + ATTACHED_COMPUTER(AttachedComputerPacket.class, AttachedComputerPacket.STREAM_CODEC), + SERVER_DEBUG_INFO(ServerDebugInfoPacket.class, ServerDebugInfoPacket.STREAM_CODEC), + PACKAGE_DESTROYED(PackageDestroyPacket.class, PackageDestroyPacket.STREAM_CODEC), + LOGISTICS_STOCK_RESPONSE(LogisticalStockResponsePacket.class, LogisticalStockResponsePacket.STREAM_CODEC), + FACTORY_PANEL_EFFECT(FactoryPanelEffectPacket.class, FactoryPanelEffectPacket.STREAM_CODEC), + PACKAGER_LINK_EFFECT(PackagerLinkEffectPacket.class, PackagerLinkEffectPacket.STREAM_CODEC), + REDSTONE_REQUESTER_EFFECT(RedstoneRequesterEffectPacket.class, RedstoneRequesterEffectPacket.STREAM_CODEC), + KNOCKBACK(KnockbackPacket.class, KnockbackPacket.STREAM_CODEC), + TRAIN_MAP_SYNC(TrainMapSyncPacket.class, TrainMapSyncPacket.STREAM_CODEC), + CLIENTBOUND_CHAIN_CONVEYOR(ClientboundChainConveyorRidingPacket.class, ClientboundChainConveyorRidingPacket.STREAM_CODEC) + ; static { ClientboundSimpleActionPacket.addAction("rainbowDebug", () -> SimpleCreateActions::rainbowDebug); @@ -271,68 +251,27 @@ public enum AllPackets { ClientboundSimpleActionPacket.addAction("camAngleFunction", () -> SimpleCreateActions::camAngleFunction); } - public static final ResourceLocation CHANNEL_NAME = Create.asResource("main"); - public static final int NETWORK_VERSION = 3; - public static final String NETWORK_VERSION_STR = String.valueOf(NETWORK_VERSION); - private static SimpleChannel channel; + private final CatnipPacketRegistry.PacketType type; - private PacketType packetType; - - AllPackets(Class type, Function factory, - NetworkDirection direction) { - packetType = new PacketType<>(type, factory, direction); + AllPackets(Class clazz, StreamCodec codec) { + String name = this.name().toLowerCase(Locale.ROOT); + this.type = new CatnipPacketRegistry.PacketType<>( + new CustomPacketPayload.Type<>(Create.asResource(name)), + clazz, codec + ); } - public static void registerPackets() { - channel = NetworkRegistry.ChannelBuilder.named(CHANNEL_NAME) - .serverAcceptedVersions(NETWORK_VERSION_STR::equals) - .clientAcceptedVersions(NETWORK_VERSION_STR::equals) - .networkProtocolVersion(() -> NETWORK_VERSION_STR) - .simpleChannel(); - - for (AllPackets packet : values()) - packet.packetType.register(); + @Override + @SuppressWarnings("unchecked") + public CustomPacketPayload.Type getType() { + return (CustomPacketPayload.Type) this.type.type(); } - public static SimpleChannel getChannel() { - return channel; - } - - public static void sendToNear(Level world, BlockPos pos, int range, Object message) { - getChannel().send( - PacketDistributor.NEAR.with(TargetPoint.p(pos.getX(), pos.getY(), pos.getZ(), range, world.dimension())), - message); - } - - private static class PacketType { - private static int index = 0; - - private BiConsumer encoder; - private Function decoder; - private BiConsumer> handler; - private Class type; - private NetworkDirection direction; - - private PacketType(Class type, Function factory, NetworkDirection direction) { - encoder = T::write; - decoder = factory; - handler = (packet, contextSupplier) -> { - Context context = contextSupplier.get(); - if (packet.handle(context)) { - context.setPacketHandled(true); - } - }; - this.type = type; - this.direction = direction; - } - - private void register() { - getChannel().messageBuilder(type, index++, direction) - .encoder(encoder) - .decoder(decoder) - .consumerNetworkThread(handler) - .add(); + public static void register() { + CatnipPacketRegistry packetRegistry = new CatnipPacketRegistry(Create.ID, 1); + for (AllPackets packet : AllPackets.values()) { + packetRegistry.registerPacket(packet.type); } + packetRegistry.registerAllPackets(); } - } diff --git a/src/main/java/com/simibubi/create/AllParticleTypes.java b/src/main/java/com/simibubi/create/AllParticleTypes.java index 7cb2b0a653..0b90cfb1a0 100644 --- a/src/main/java/com/simibubi/create/AllParticleTypes.java +++ b/src/main/java/com/simibubi/create/AllParticleTypes.java @@ -15,16 +15,15 @@ import com.simibubi.create.foundation.particle.ICustomParticleData; import net.createmod.catnip.utility.lang.Lang; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.RegisterParticleProvidersEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.minecraft.core.registries.Registries; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RegisterParticleProvidersEvent; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; public enum AllParticleTypes { - ROTATION_INDICATOR(RotationIndicatorParticleData::new), AIR_FLOW(AirFlowParticleData::new), AIR(AirParticleData::new), @@ -64,11 +63,11 @@ public enum AllParticleTypes { } private static class ParticleEntry { - private static final DeferredRegister> REGISTER = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, Create.ID); + private static final DeferredRegister> REGISTER = DeferredRegister.create(Registries.PARTICLE_TYPE, Create.ID); private final String name; private final Supplier> typeFactory; - private final RegistryObject> object; + private final DeferredHolder, ParticleType> object; public ParticleEntry(String name, Supplier> typeFactory) { this.name = name; @@ -84,5 +83,4 @@ public enum AllParticleTypes { } } - } diff --git a/src/main/java/com/simibubi/create/AllRecipeTypes.java b/src/main/java/com/simibubi/create/AllRecipeTypes.java index 058cd6c84f..c77e57aa92 100644 --- a/src/main/java/com/simibubi/create/AllRecipeTypes.java +++ b/src/main/java/com/simibubi/create/AllRecipeTypes.java @@ -4,8 +4,11 @@ import java.util.Optional; import java.util.function.Predicate; import java.util.function.Supplier; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.simibubi.create.compat.jei.ConversionRecipe; import com.simibubi.create.content.equipment.sandPaper.SandPaperPolishingRecipe; import com.simibubi.create.content.equipment.toolbox.ToolboxDyeingRecipe; @@ -14,6 +17,7 @@ import com.simibubi.create.content.fluids.transfer.FillingRecipe; import com.simibubi.create.content.kinetics.crafter.MechanicalCraftingRecipe; import com.simibubi.create.content.kinetics.crusher.CrushingRecipe; import com.simibubi.create.content.kinetics.deployer.DeployerApplicationRecipe; +import com.simibubi.create.content.kinetics.deployer.ItemApplicationRecipe; import com.simibubi.create.content.kinetics.deployer.ManualApplicationRecipe; import com.simibubi.create.content.kinetics.fan.processing.HauntingRecipe; import com.simibubi.create.content.kinetics.fan.processing.SplashingRecipe; @@ -23,27 +27,30 @@ import com.simibubi.create.content.kinetics.mixer.MixingRecipe; import com.simibubi.create.content.kinetics.press.PressingRecipe; import com.simibubi.create.content.kinetics.saw.CuttingRecipe; import com.simibubi.create.content.processing.basin.BasinRecipe; +import com.simibubi.create.content.processing.recipe.ProcessingRecipe; import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeFactory; import com.simibubi.create.content.processing.recipe.ProcessingRecipeSerializer; import com.simibubi.create.content.processing.sequenced.SequencedAssemblyRecipeSerializer; import com.simibubi.create.foundation.recipe.IRecipeTypeInfo; import net.createmod.catnip.utility.lang.Lang; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; +import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeInput; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.item.crafting.ShapedRecipe; +import net.minecraft.world.item.crafting.ShapedRecipePattern; import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer; import net.minecraft.world.level.Level; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; -public enum AllRecipeTypes implements IRecipeTypeInfo { +public enum AllRecipeTypes implements IRecipeTypeInfo, StringRepresentable { CONVERSION(ConversionRecipe::new), CRUSHING(CrushingRecipe::new), @@ -66,19 +73,25 @@ public enum AllRecipeTypes implements IRecipeTypeInfo { TOOLBOX_DYEING(() -> new SimpleCraftingRecipeSerializer<>(ToolboxDyeingRecipe::new), () -> RecipeType.CRAFTING, false); - public static final Predicate> CAN_BE_AUTOMATED = r -> !r.getId() - .getPath() - .endsWith("_manual_only"); + public static final Predicate> CAN_BE_AUTOMATED = r -> !r.id() + .getPath() + .endsWith("_manual_only"); - private final ResourceLocation id; - private final RegistryObject> serializerObject; + public final ResourceLocation id; + public final Supplier> serializerSupplier; + private final DeferredHolder, RecipeSerializer> serializerObject; @Nullable - private final RegistryObject> typeObject; + private final DeferredHolder, RecipeType> typeObject; private final Supplier> type; + private boolean isProcessingRecipe; + + public static final Codec CODEC = StringRepresentable.fromEnum(AllRecipeTypes::values); + AllRecipeTypes(Supplier> serializerSupplier, Supplier> typeSupplier, boolean registerType) { String name = Lang.asId(name()); id = Create.asResource(name); + this.serializerSupplier = serializerSupplier; serializerObject = Registers.SERIALIZER_REGISTER.register(name, serializerSupplier); if (registerType) { typeObject = Registers.TYPE_REGISTER.register(name, typeSupplier); @@ -87,22 +100,26 @@ public enum AllRecipeTypes implements IRecipeTypeInfo { typeObject = null; type = typeSupplier; } + isProcessingRecipe = false; } AllRecipeTypes(Supplier> serializerSupplier) { String name = Lang.asId(name()); id = Create.asResource(name); + this.serializerSupplier = serializerSupplier; serializerObject = Registers.SERIALIZER_REGISTER.register(name, serializerSupplier); typeObject = Registers.TYPE_REGISTER.register(name, () -> RecipeType.simple(id)); type = typeObject; + isProcessingRecipe = false; } AllRecipeTypes(ProcessingRecipeFactory processingFactory) { this(() -> new ProcessingRecipeSerializer<>(processingFactory)); + isProcessingRecipe = true; } public static void register(IEventBus modEventBus) { - ShapedRecipe.setCraftingSize(9, 9); + ShapedRecipePattern.setCraftingSize(9, 9); Registers.SERIALIZER_REGISTER.register(modEventBus); Registers.TYPE_REGISTER.register(modEventBus); } @@ -120,24 +137,37 @@ public enum AllRecipeTypes implements IRecipeTypeInfo { @SuppressWarnings("unchecked") @Override - public > T getType() { - return (T) type.get(); + public > RecipeType getType() { + return (RecipeType) type.get(); } - public > Optional find(C inv, Level world) { + public > Optional> find(I inv, Level world) { return world.getRecipeManager() .getRecipeFor(getType(), inv, world); } - - public static boolean shouldIgnoreInAutomation(Recipe recipe) { - RecipeSerializer serializer = recipe.getSerializer(); + + public static boolean shouldIgnoreInAutomation(RecipeHolder recipe) { + RecipeSerializer serializer = recipe.value().getSerializer(); if (serializer != null && AllTags.AllRecipeSerializerTags.AUTOMATION_IGNORE.matches(serializer)) return true; return !CAN_BE_AUTOMATED.test(recipe); } + @Override + public @NotNull String getSerializedName() { + return id.toString(); + } + + public > MapCodec processingCodec() { + if (!isProcessingRecipe) + throw new AssertionError("AllRecipeTypes#processingCodec called on "+name()+", which is not a processing recipe"); + if (this == DEPLOYING || this == ITEM_APPLICATION) + return ItemApplicationRecipe.codec(this); + return ProcessingRecipeSerializer.codec(this); + } + private static class Registers { - private static final DeferredRegister> SERIALIZER_REGISTER = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, Create.ID); + private static final DeferredRegister> SERIALIZER_REGISTER = DeferredRegister.create(BuiltInRegistries.RECIPE_SERIALIZER, Create.ID); private static final DeferredRegister> TYPE_REGISTER = DeferredRegister.create(Registries.RECIPE_TYPE, Create.ID); } diff --git a/src/main/java/com/simibubi/create/AllRegistries.java b/src/main/java/com/simibubi/create/AllRegistries.java index 4b7d62b443..8d460e232d 100644 --- a/src/main/java/com/simibubi/create/AllRegistries.java +++ b/src/main/java/com/simibubi/create/AllRegistries.java @@ -6,19 +6,18 @@ import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.registries.IForgeRegistry; -import net.minecraftforge.registries.NewRegistryEvent; -import net.minecraftforge.registries.RegistryBuilder; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.registries.NewRegistryEvent; +import net.neoforged.neoforge.registries.RegistryBuilder; import java.util.function.Supplier; -@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) +@EventBusSubscriber(bus = EventBusSubscriber.Bus.MOD) public class AllRegistries { - public static Supplier> ARM_INTERACTION_POINT_TYPES; - public static Supplier> FAN_PROCESSING_TYPES; - public static Supplier> ITEM_ATTRIBUTE_TYPES; + public static final Registry ARM_INTERACTION_POINT_TYPES = new RegistryBuilder<>(Keys.ARM_INTERACTION_POINT_TYPES).sync(true).create(); + public static final Registry FAN_PROCESSING_TYPES = new RegistryBuilder<>(Keys.FAN_PROCESSING_TYPES).sync(true).create(); + public static final Registry ITEM_ATTRIBUTE_TYPES = new RegistryBuilder<>(AllRegistries.Keys.ITEM_ATTRIBUTE_TYPES).sync(true).create(); public static final class Keys { public static final ResourceKey> ARM_INTERACTION_POINT_TYPES = key("arm_interaction_point_types"); @@ -32,16 +31,8 @@ public class AllRegistries { @SubscribeEvent public static void registerRegistries(NewRegistryEvent event) { - ARM_INTERACTION_POINT_TYPES = event.create(new RegistryBuilder() - .setName(Keys.ARM_INTERACTION_POINT_TYPES.location()) - .disableSaving()); - - FAN_PROCESSING_TYPES = event.create(new RegistryBuilder() - .setName(Keys.FAN_PROCESSING_TYPES.location()) - .disableSaving()); - - ITEM_ATTRIBUTE_TYPES = event.create(new RegistryBuilder() - .setName(Keys.ITEM_ATTRIBUTE_TYPES.location()) - .disableSaving()); + event.register(AllRegistries.ARM_INTERACTION_POINT_TYPES); + event.register(AllRegistries.FAN_PROCESSING_TYPES); + event.register(AllRegistries.ITEM_ATTRIBUTE_TYPES); } } diff --git a/src/main/java/com/simibubi/create/AllSoundEvents.java b/src/main/java/com/simibubi/create/AllSoundEvents.java index f1d9efba19..d1ac02a609 100644 --- a/src/main/java/com/simibubi/create/AllSoundEvents.java +++ b/src/main/java/com/simibubi/create/AllSoundEvents.java @@ -27,24 +27,21 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.RegisterEvent; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.RegisterEvent; -//@EventBusSubscriber(bus = Bus.FORGE) public class AllSoundEvents { public static final Map ALL = new HashMap<>(); public static final SoundEntry - - SCHEMATICANNON_LAUNCH_BLOCK = create("schematicannon_launch_block").subtitle("Schematicannon fires") - .playExisting(SoundEvents.GENERIC_EXPLODE, .1f, 1.1f) - .category(SoundSource.BLOCKS) - .build(), + SCHEMATICANNON_LAUNCH_BLOCK = create("schematicannon_launch_block").subtitle("Schematicannon fires") + .playExisting(SoundEvents.GENERIC_EXPLODE.value(), .1f, 1.1f) + .category(SoundSource.BLOCKS) + .build(), SCHEMATICANNON_FINISH = create("schematicannon_finish").subtitle("Schematicannon dings") - .playExisting(SoundEvents.NOTE_BLOCK_BELL, 1, .7f) + .playExisting(SoundEvents.NOTE_BLOCK_BELL::value, 1, .7f) .category(SoundSource.BLOCKS) .build(), @@ -112,12 +109,12 @@ public class AllSoundEvents { .build(), SCROLL_VALUE = create("scroll_value").subtitle("Scroll-input clicks") - .playExisting(SoundEvents.NOTE_BLOCK_HAT, .124f, 1f) + .playExisting(SoundEvents.NOTE_BLOCK_HAT::value, .124f, 1f) .category(SoundSource.PLAYERS) .build(), CONFIRM = create("confirm").subtitle("Affirmative ding") - .playExisting(SoundEvents.NOTE_BLOCK_BELL, 0.5f, 0.8f) + .playExisting(SoundEvents.NOTE_BLOCK_BELL::value, 0.5f, 0.8f) .category(SoundSource.PLAYERS) .build(), @@ -126,7 +123,7 @@ public class AllSoundEvents { .build(), DENY = create("deny").subtitle("Declining boop") - .playExisting(SoundEvents.NOTE_BLOCK_BASS, 1f, 0.5f) + .playExisting(SoundEvents.NOTE_BLOCK_BASS::value, 1f, 0.5f) .category(SoundSource.PLAYERS) .build(), @@ -222,7 +219,7 @@ public class AllSoundEvents { .build(), COPPER_ARMOR_EQUIP = create("copper_armor_equip").subtitle("Diving equipment clinks") - .playExisting(SoundEvents.ARMOR_EQUIP_GOLD, 1f, 1f) + .playExisting(SoundEvents.ARMOR_EQUIP_GOLD.value(), 1f, 1f) .category(SoundSource.PLAYERS) .build(), @@ -466,8 +463,7 @@ public class AllSoundEvents { } - public record ConfiguredSoundEvent(Supplier event, float volume, float pitch) { - } + public record ConfiguredSoundEvent(Supplier event, float volume, float pitch) {} public static class SoundEntryBuilder { @@ -527,7 +523,7 @@ public class AllSoundEvents { } public SoundEntryBuilder playExisting(Holder event) { - return playExisting(event::get, 1, 1); + return playExisting(event::value, 1, 1); } public SoundEntry build() { @@ -560,6 +556,8 @@ public class AllSoundEvents { public abstract void write(JsonObject json); + public abstract Holder getMainEventHolder(); + public abstract SoundEvent getMainEvent(); public String getSubtitleKey() { @@ -638,7 +636,7 @@ public class AllSoundEvents { for (int i = 0; i < wrappedEvents.size(); i++) { ConfiguredSoundEvent wrapped = wrappedEvents.get(i); ResourceLocation location = getIdOf(i); - RegistryObject event = RegistryObject.create(location, ForgeRegistries.SOUND_EVENTS); + DeferredHolder event = DeferredHolder.create(Registries.SOUND_EVENT, location); compiledEvents.add(new CompiledSoundEvent(event, wrapped.volume(), wrapped.pitch())); } } @@ -651,14 +649,18 @@ public class AllSoundEvents { } } + @Override + public Holder getMainEventHolder() { + return compiledEvents.getFirst().event(); + } + @Override public SoundEvent getMainEvent() { - return compiledEvents.get(0) - .event().get(); + return compiledEvents.getFirst().event().get(); } protected ResourceLocation getIdOf(int i) { - return new ResourceLocation(id.getNamespace(), i == 0 ? id.getPath() : id.getPath() + "_compounded_" + i); + return ResourceLocation.fromNamespaceAndPath(id.getNamespace(), i == 0 ? id.getPath() : id.getPath() + "_compounded_" + i); } @Override @@ -699,7 +701,7 @@ public class AllSoundEvents { } } - private record CompiledSoundEvent(RegistryObject event, float volume, float pitch) { + private record CompiledSoundEvent(DeferredHolder event, float volume, float pitch) { } } @@ -707,7 +709,7 @@ public class AllSoundEvents { private static class CustomSoundEntry extends SoundEntry { protected List variants; - protected RegistryObject event; + protected DeferredHolder event; public CustomSoundEntry(ResourceLocation id, List variants, String subtitle, SoundSource category, int attenuationDistance) { @@ -717,7 +719,7 @@ public class AllSoundEvents { @Override public void prepare() { - event = RegistryObject.create(id, ForgeRegistries.SOUND_EVENTS); + event = DeferredHolder.create(Registries.SOUND_EVENT, id); } @Override @@ -726,6 +728,11 @@ public class AllSoundEvents { helper.register(location, SoundEvent.createVariableRangeEvent(location)); } + @Override + public Holder getMainEventHolder() { + return event; + } + @Override public SoundEvent getMainEvent() { return event.get(); diff --git a/src/main/java/com/simibubi/create/AllStructureProcessorTypes.java b/src/main/java/com/simibubi/create/AllStructureProcessorTypes.java index f767e2d80d..2bf0ace29b 100644 --- a/src/main/java/com/simibubi/create/AllStructureProcessorTypes.java +++ b/src/main/java/com/simibubi/create/AllStructureProcessorTypes.java @@ -4,14 +4,14 @@ import com.simibubi.create.content.schematics.SchematicProcessor; import net.minecraft.core.registries.Registries; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; public class AllStructureProcessorTypes { private static final DeferredRegister> REGISTER = DeferredRegister.create(Registries.STRUCTURE_PROCESSOR, Create.ID); - public static final RegistryObject> SCHEMATIC = REGISTER.register("schematic", () -> () -> SchematicProcessor.CODEC); + public static final DeferredHolder, StructureProcessorType> SCHEMATIC = REGISTER.register("schematic", () -> () -> SchematicProcessor.CODEC); public static void register(IEventBus modEventBus) { REGISTER.register(modEventBus); diff --git a/src/main/java/com/simibubi/create/AllTags.java b/src/main/java/com/simibubi/create/AllTags.java index c99802271f..b1d34c085d 100644 --- a/src/main/java/com/simibubi/create/AllTags.java +++ b/src/main/java/com/simibubi/create/AllTags.java @@ -1,15 +1,17 @@ package com.simibubi.create; +import static com.simibubi.create.AllTags.NameSpace.COMMON; import static com.simibubi.create.AllTags.NameSpace.CURIOS; -import static com.simibubi.create.AllTags.NameSpace.FORGE; import static com.simibubi.create.AllTags.NameSpace.MOD; import static com.simibubi.create.AllTags.NameSpace.QUARK; import static com.simibubi.create.AllTags.NameSpace.TIC; -import java.util.Collections; - import net.createmod.catnip.utility.lang.Lang; + +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.FluidTags; @@ -25,36 +27,32 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.IForgeRegistry; public class AllTags { - public static TagKey optionalTag(IForgeRegistry registry, - ResourceLocation id) { - return registry.tags() - .createOptionalTagKey(id, Collections.emptySet()); + public static TagKey optionalTag(Registry registry, ResourceLocation id) { + return TagKey.create(registry.key(), id); } - public static TagKey forgeTag(IForgeRegistry registry, String path) { - return optionalTag(registry, new ResourceLocation("forge", path)); + public static TagKey commonTag(Registry registry, String path) { + return optionalTag(registry, ResourceLocation.fromNamespaceAndPath("c", path)); } - public static TagKey forgeBlockTag(String path) { - return forgeTag(ForgeRegistries.BLOCKS, path); + public static TagKey commonBlockTag(String path) { + return commonTag(BuiltInRegistries.BLOCK, path); } - public static TagKey forgeItemTag(String path) { - return forgeTag(ForgeRegistries.ITEMS, path); + public static TagKey commonItemTag(String path) { + return commonTag(BuiltInRegistries.ITEM, path); } - public static TagKey forgeFluidTag(String path) { - return forgeTag(ForgeRegistries.FLUIDS, path); + public static TagKey commonFluidTag(String path) { + return commonTag(BuiltInRegistries.FLUID, path); } public enum NameSpace { MOD(Create.ID, false, true), - FORGE("forge"), + COMMON("c"), TIC("tconstruct"), QUARK("quark"), GS("galosphere"), @@ -108,8 +106,7 @@ public class AllTags { CORALS, - RELOCATION_NOT_SUPPORTED(FORGE), - WG_STONE(FORGE), + RELOCATION_NOT_SUPPORTED(COMMON), SLIMY_LOGS(TIC), NON_DOUBLE_DOOR(QUARK), @@ -136,9 +133,9 @@ public class AllTags { } AllBlockTags(NameSpace namespace, String path, boolean optional, boolean alwaysDatagen) { - ResourceLocation id = new ResourceLocation(namespace.id, path == null ? Lang.asId(name()) : path); + ResourceLocation id = ResourceLocation.fromNamespaceAndPath(namespace.id, path == null ? Lang.asId(name()) : path); if (optional) { - tag = optionalTag(ForgeRegistries.BLOCKS, id); + tag = optionalTag(BuiltInRegistries.BLOCK, id); } else { tag = BlockTags.create(id); } @@ -172,8 +169,6 @@ public class AllTags { CREATE_INGOTS, CRUSHED_RAW_MATERIALS, DEPLOYABLE_DRINK, - MODDED_STRIPPED_LOGS, - MODDED_STRIPPED_WOOD, PRESSURIZED_AIR_SOURCES, SANDPAPER, SEATS, @@ -187,14 +182,10 @@ public class AllTags { TRACKS, UPRIGHT_ON_BELT, VALVE_HANDLES, - VANILLA_STRIPPED_LOGS, - VANILLA_STRIPPED_WOOD, - STRIPPED_LOGS(FORGE), - STRIPPED_WOOD(FORGE), - PLATES(FORGE), - OBSIDIAN_DUST(FORGE,"dusts/obsidian"), - WRENCH(FORGE, "tools/wrench"), + PLATES(COMMON), + OBSIDIAN_DUST(COMMON,"dusts/obsidian"), + WRENCH(COMMON, "tools/wrench"), ALLURITE(MOD,"stone_types/galosphere/allurite"), AMETHYST(MOD,"stone_types/galosphere/amethyst"), @@ -225,9 +216,9 @@ public class AllTags { } AllItemTags(NameSpace namespace, String path, boolean optional, boolean alwaysDatagen) { - ResourceLocation id = new ResourceLocation(namespace.id, path == null ? Lang.asId(name()) : path); + ResourceLocation id = ResourceLocation.fromNamespaceAndPath(namespace.id, path == null ? Lang.asId(name()) : path); if (optional) { - tag = optionalTag(ForgeRegistries.ITEMS, id); + tag = optionalTag(BuiltInRegistries.ITEM, id); } else { tag = ItemTags.create(id); } @@ -257,8 +248,6 @@ public class AllTags { FAN_PROCESSING_CATALYSTS_SMOKING(MOD, "fan_processing_catalysts/smoking"), FAN_PROCESSING_CATALYSTS_SPLASHING(MOD, "fan_processing_catalysts/splashing"), - HONEY(FORGE) - ; public final TagKey tag; @@ -281,9 +270,9 @@ public class AllTags { } AllFluidTags(NameSpace namespace, String path, boolean optional, boolean alwaysDatagen) { - ResourceLocation id = new ResourceLocation(namespace.id, path == null ? Lang.asId(name()) : path); + ResourceLocation id = ResourceLocation.fromNamespaceAndPath(namespace.id, path == null ? Lang.asId(name()) : path); if (optional) { - tag = optionalTag(ForgeRegistries.FLUIDS, id); + tag = optionalTag(BuiltInRegistries.FLUID, id); } else { tag = FluidTags.create(id); } @@ -330,9 +319,9 @@ public class AllTags { } AllEntityTags(NameSpace namespace, String path, boolean optional, boolean alwaysDatagen) { - ResourceLocation id = new ResourceLocation(namespace.id, path == null ? Lang.asId(name()) : path); + ResourceLocation id = ResourceLocation.fromNamespaceAndPath(namespace.id, path == null ? Lang.asId(name()) : path); if (optional) { - tag = optionalTag(ForgeRegistries.ENTITY_TYPES, id); + tag = optionalTag(BuiltInRegistries.ENTITY_TYPE, id); } else { tag = TagKey.create(Registries.ENTITY_TYPE, id); } @@ -377,9 +366,9 @@ public class AllTags { } AllRecipeSerializerTags(NameSpace namespace, String path, boolean optional, boolean alwaysDatagen) { - ResourceLocation id = new ResourceLocation(namespace.id, path == null ? Lang.asId(name()) : path); + ResourceLocation id = ResourceLocation.fromNamespaceAndPath(namespace.id, path == null ? Lang.asId(name()) : path); if (optional) { - tag = optionalTag(ForgeRegistries.RECIPE_SERIALIZERS, id); + tag = optionalTag(BuiltInRegistries.RECIPE_SERIALIZER, id); } else { tag = TagKey.create(Registries.RECIPE_SERIALIZER, id); } @@ -387,7 +376,8 @@ public class AllTags { } public boolean matches(RecipeSerializer recipeSerializer) { - return ForgeRegistries.RECIPE_SERIALIZERS.getHolder(recipeSerializer).orElseThrow().is(tag); + ResourceKey> key = BuiltInRegistries.RECIPE_SERIALIZER.getResourceKey(recipeSerializer).orElseThrow(); + return BuiltInRegistries.RECIPE_SERIALIZER.getHolder(key).orElseThrow().is(tag); } private static void init() {} diff --git a/src/main/java/com/simibubi/create/Create.java b/src/main/java/com/simibubi/create/Create.java index c99ffe4234..ea93b96311 100644 --- a/src/main/java/com/simibubi/create/Create.java +++ b/src/main/java/com/simibubi/create/Create.java @@ -4,8 +4,6 @@ import java.util.Random; import org.slf4j.Logger; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.mojang.logging.LogUtils; import com.simibubi.create.api.behaviour.BlockSpoutingBehaviour; import com.simibubi.create.compat.Mods; @@ -13,6 +11,7 @@ import com.simibubi.create.compat.computercraft.ComputerCraftProxy; import com.simibubi.create.compat.curios.Curios; import com.simibubi.create.content.contraptions.ContraptionMovementSetting; import com.simibubi.create.content.decoration.palettes.AllPaletteBlocks; +import com.simibubi.create.content.equipment.armor.AllArmorMaterials; import com.simibubi.create.content.equipment.potatoCannon.BuiltinPotatoProjectileTypes; import com.simibubi.create.content.fluids.tank.BoilerHeaters; import com.simibubi.create.content.kinetics.TorquePropagator; @@ -28,11 +27,11 @@ import com.simibubi.create.content.trains.bogey.BogeySizes; import com.simibubi.create.content.trains.track.AllPortalTracks; import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.advancement.AllTriggers; -import com.simibubi.create.foundation.block.CopperRegistries; import com.simibubi.create.foundation.data.CreateRegistrate; import com.simibubi.create.foundation.item.ItemDescription; import com.simibubi.create.foundation.item.KineticStats; import com.simibubi.create.foundation.item.TooltipModifier; +import com.simibubi.create.foundation.recipe.AllIngredients; import com.simibubi.create.foundation.utility.AttachedRegistry; import com.simibubi.create.foundation.utility.CreateNBTProcessors; import com.simibubi.create.infrastructure.command.ServerLagger; @@ -43,21 +42,20 @@ import com.simibubi.create.infrastructure.worldgen.AllPlacementModifiers; import net.createmod.catnip.utility.FontHelper; import net.createmod.catnip.utility.lang.LangBuilder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.ModLoadingContext; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.ModLoadingContext; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.common.NeoForgeMod; +import net.neoforged.neoforge.registries.RegisterEvent; @Mod(Create.ID) public class Create { @@ -68,10 +66,6 @@ public class Create { public static final Logger LOGGER = LogUtils.getLogger(); - public static final Gson GSON = new GsonBuilder().setPrettyPrinting() - .disableHtmlEscaping() - .create(); - /** Use the {@link Random} of a local {@link Level} or {@link Entity} or create one */ @Deprecated public static final Random RANDOM = new Random(); @@ -97,22 +91,19 @@ public class Create { public static final GlobalLogisticsManager LOGISTICS = new GlobalLogisticsManager(); public static final ServerLagger LAGGER = new ServerLagger(); - public Create() { - onCtor(); + public Create(IEventBus eventBus, ModContainer modContainer) { + onCtor(eventBus, modContainer); } - public static void onCtor() { + public static void onCtor(IEventBus modEventBus, ModContainer modContainer) { ModLoadingContext modLoadingContext = ModLoadingContext.get(); - IEventBus modEventBus = FMLJavaModLoadingContext.get() - .getModEventBus(); - IEventBus forgeEventBus = MinecraftForge.EVENT_BUS; - REGISTRATE.registerEventListeners(modEventBus); AllSoundEvents.prepare(); AllTags.init(); AllCreativeModeTabs.register(modEventBus); + AllArmorMaterials.register(modEventBus); AllBlocks.register(); AllItems.register(); AllFluids.register(); @@ -120,16 +111,20 @@ public class Create { AllMenuTypes.register(); AllEntityTypes.register(); AllBlockEntityTypes.register(); - AllEnchantments.register(); AllRecipeTypes.register(modEventBus); AllParticleTypes.register(modEventBus); AllStructureProcessorTypes.register(modEventBus); AllEntityDataSerializers.register(modEventBus); - AllPackets.registerPackets(); AllFeatures.register(modEventBus); AllPlacementModifiers.register(modEventBus); + AllIngredients.register(modEventBus); + AllAttachmentTypes.register(modEventBus); + AllDataComponents.register(modEventBus); + AllMapDecorationTypes.register(modEventBus); - AllConfigs.register(modLoadingContext); + AllConfigs.register(modLoadingContext, modContainer); + + AllPackets.register(); AllArmInteractionPointTypes.register(modEventBus); AllFanProcessingTypes.register(modEventBus); @@ -148,18 +143,16 @@ public class Create { ComputerCraftProxy.register(); - ForgeMod.enableMilkFluid(); - CopperRegistries.inject(); + NeoForgeMod.enableMilkFluid(); modEventBus.addListener(Create::init); + modEventBus.addListener(Create::registerAdvancements); modEventBus.addListener(AllEntityTypes::registerEntityAttributes); modEventBus.addListener(EventPriority.LOWEST, CreateDatagen::gatherData); modEventBus.addListener(AllSoundEvents::register); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> CreateClient.onCtorClient(modEventBus, forgeEventBus)); - // FIXME: this is not thread-safe - Mods.CURIOS.executeIfInstalled(() -> () -> Curios.init(modEventBus, forgeEventBus)); + Mods.CURIOS.executeIfInstalled(() -> () -> Curios.init(modEventBus)); } public static void init(final FMLCommonSetupEvent event) { @@ -175,9 +168,14 @@ public class Create { // -- AttachedRegistry.unwrapAll(); + }); + } + + public static void registerAdvancements(final RegisterEvent event) { + if (event.getRegistry() == BuiltInRegistries.TRIGGER_TYPES) { AllAdvancements.register(); AllTriggers.register(); - }); + } } public static LangBuilder lang() { @@ -185,7 +183,7 @@ public class Create { } public static ResourceLocation asResource(String path) { - return new ResourceLocation(ID, path); + return ResourceLocation.fromNamespaceAndPath(ID, path); } } diff --git a/src/main/java/com/simibubi/create/CreateClient.java b/src/main/java/com/simibubi/create/CreateClient.java index 689b9f24b4..2879ad6185 100644 --- a/src/main/java/com/simibubi/create/CreateClient.java +++ b/src/main/java/com/simibubi/create/CreateClient.java @@ -40,9 +40,13 @@ import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.ComponentUtils; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.MutableComponent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; +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.neoforge.common.NeoForge; +@Mod(value = Create.ID, dist = Dist.CLIENT) public class CreateClient { public static final ModelSwapper MODEL_SWAPPER = new ModelSwapper(); @@ -61,7 +65,13 @@ public class CreateClient { public static final ClientResourceReloadListener RESOURCE_RELOAD_LISTENER = new ClientResourceReloadListener(); - public static void onCtorClient(IEventBus modEventBus, IEventBus forgeEventBus) { + public CreateClient(IEventBus modEventBus) { + onCtorClient(modEventBus); + } + + public static void onCtorClient(IEventBus modEventBus) { + IEventBus neoEventBus = NeoForge.EVENT_BUS; + modEventBus.addListener(CreateClient::clientInit); modEventBus.addListener(AllParticleTypes::registerFactories); @@ -69,10 +79,10 @@ public class CreateClient { MODEL_SWAPPER.registerListeners(modEventBus); - ZAPPER_RENDER_HANDLER.registerListeners(forgeEventBus); - POTATO_CANNON_RENDER_HANDLER.registerListeners(forgeEventBus); - - Mods.FTBLIBRARY.executeIfInstalled(() -> () -> FTBIntegration.init(modEventBus, forgeEventBus)); + ZAPPER_RENDER_HANDLER.registerListeners(neoEventBus); + POTATO_CANNON_RENDER_HANDLER.registerListeners(neoEventBus); + + Mods.FTBLIBRARY.executeIfInstalled(() -> () -> FTBIntegration.init(modEventBus, neoEventBus)); } public static void clientInit(final FMLClientSetupEvent event) { @@ -102,7 +112,7 @@ public class CreateClient { private static void setupConfigUIBackground() { ConfigScreen.backgrounds.put(Create.ID, (screen, graphics, partialTicks) -> { - CreateMainMenuScreen.PANORAMA.render(screen.getMinecraft().getDeltaFrameTime(), 1); + CreateMainMenuScreen.PANORAMA.render(graphics, screen.width, screen.height, 1, partialTicks); //RenderSystem.setShaderTexture(0, CreateMainMenuScreen.PANORAMA_OVERLAY_TEXTURES); RenderSystem.enableBlend(); diff --git a/src/main/java/com/simibubi/create/api/behaviour/BlockSpoutingBehaviour.java b/src/main/java/com/simibubi/create/api/behaviour/BlockSpoutingBehaviour.java index f3590e4b0b..f64711a59c 100644 --- a/src/main/java/com/simibubi/create/api/behaviour/BlockSpoutingBehaviour.java +++ b/src/main/java/com/simibubi/create/api/behaviour/BlockSpoutingBehaviour.java @@ -8,7 +8,7 @@ import com.simibubi.create.impl.behaviour.BlockSpoutingBehaviourImpl; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; public abstract class BlockSpoutingBehaviour { /** diff --git a/src/main/java/com/simibubi/create/api/connectivity/ConnectivityHandler.java b/src/main/java/com/simibubi/create/api/connectivity/ConnectivityHandler.java index c844b1bda1..5413c6866b 100644 --- a/src/main/java/com/simibubi/create/api/connectivity/ConnectivityHandler.java +++ b/src/main/java/com/simibubi/create/api/connectivity/ConnectivityHandler.java @@ -23,10 +23,9 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; public class ConnectivityHandler { @@ -215,7 +214,7 @@ public class ConnectivityHandler { } if (controller instanceof IMultiBlockEntityContainer.Fluid ifluidCon && ifluidCon.hasTank()) { FluidStack otherFluid = ifluidCon.getFluid(0); - if (!fluid.isEmpty() && !otherFluid.isEmpty() && !fluid.isFluidEqual(otherFluid)) + if (!fluid.isEmpty() && !otherFluid.isEmpty() && !FluidStack.isSameFluidSameComponents(fluid, otherFluid)) break Search; } } @@ -361,11 +360,9 @@ public class ConnectivityHandler { } if (be instanceof IMultiBlockEntityContainer.Inventory inv && inv.hasInventory()) - be.getCapability(ForgeCapabilities.ITEM_HANDLER) - .invalidate(); + be.getLevel().invalidateCapabilities(be.getBlockPos()); if (be instanceof IMultiBlockEntityContainer.Fluid fluid && fluid.hasTank()) - be.getCapability(ForgeCapabilities.FLUID_HANDLER) - .invalidate(); + be.getLevel().invalidateCapabilities(be.getBlockPos()); if (tryReconnect) formMulti(be.getType(), level, cache == null ? new SearchCache<>() : cache, frontier); diff --git a/src/main/java/com/simibubi/create/api/data/TrainHatInfoProvider.java b/src/main/java/com/simibubi/create/api/data/TrainHatInfoProvider.java index 0ed91ec8d1..e66cb4a951 100644 --- a/src/main/java/com/simibubi/create/api/data/TrainHatInfoProvider.java +++ b/src/main/java/com/simibubi/create/api/data/TrainHatInfoProvider.java @@ -9,13 +9,13 @@ import com.simibubi.create.Create; import com.simibubi.create.content.trains.schedule.hat.TrainHatInfo; import com.simibubi.create.content.trains.schedule.hat.TrainHatInfoReloadListener; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.registries.ForgeRegistries; public abstract class TrainHatInfoProvider implements DataProvider { protected final Map trainHatOffsets = new HashMap<>(); @@ -44,7 +44,7 @@ public abstract class TrainHatInfoProvider implements DataProvider { } protected void makeInfoFor(EntityType type, Vec3 offset, String part, int cubeIndex, float scale) { - this.trainHatOffsets.put(ForgeRegistries.ENTITY_TYPES.getKey(type), new TrainHatInfo(part, cubeIndex, offset, scale)); + this.trainHatOffsets.put(BuiltInRegistries.ENTITY_TYPE.getKey(type), new TrainHatInfo(part, cubeIndex, offset, scale)); } @Override diff --git a/src/main/java/com/simibubi/create/api/event/BlockEntityBehaviourEvent.java b/src/main/java/com/simibubi/create/api/event/BlockEntityBehaviourEvent.java index b0154691eb..fa843e2037 100644 --- a/src/main/java/com/simibubi/create/api/event/BlockEntityBehaviourEvent.java +++ b/src/main/java/com/simibubi/create/api/event/BlockEntityBehaviourEvent.java @@ -1,14 +1,14 @@ package com.simibubi.create.api.event; -import java.lang.reflect.Type; import java.util.Map; +import java.util.function.Consumer; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BehaviourType; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.eventbus.api.GenericEvent; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.neoforged.bus.api.Event; /** * Event that is fired just before a SmartBlockEntity is being deserialized
@@ -22,21 +22,29 @@ import net.minecraftforge.eventbus.api.GenericEvent; *
* Because of the earliness of this event, the added behaviours will have access * to the initial NBT read (unless the BE was placed, not loaded), thereby - * allowing block entities to store and retrieve data for injected behaviours. + * allowing block entities to store and retrieve data for injected behaviours.
+ *
+ * Example:
 {@code
+ * 		neoForgeEventBus.addListener((BlockEntityBehaviourEvent event) -> {
+ * 			event.forType(AllBlockEntityTypes.FUNNEL.get(), be -> {
+ * 				event.attach(new FunFunnelBehaviour(be));
+ * 			});
+ * 		});
+ * } 
  */
-public class BlockEntityBehaviourEvent extends GenericEvent {
-
-	private final T smartBlockEntity;
+public class BlockEntityBehaviourEvent extends Event {
+	private final SmartBlockEntity smartBlockEntity;
 	private final Map, BlockEntityBehaviour> behaviours;
 
-	public BlockEntityBehaviourEvent(T blockEntity, Map, BlockEntityBehaviour> behaviours) {
+	public BlockEntityBehaviourEvent(SmartBlockEntity blockEntity, Map, BlockEntityBehaviour> behaviours) {
 		smartBlockEntity = blockEntity;
 		this.behaviours = behaviours;
 	}
 
-	@Override
-	public Type getGenericType() {
-		return smartBlockEntity.getClass();
+	public  void forType(BlockEntityType type, Consumer action) {
+		if (smartBlockEntity.getType() == type) {
+			action.accept((T) smartBlockEntity);
+		}
 	}
 
 	public void attach(BlockEntityBehaviour behaviour) {
@@ -47,12 +55,4 @@ public class BlockEntityBehaviourEvent extends Gener
 		return behaviours.remove(type);
 	}
 
-	public T getBlockEntity() {
-		return smartBlockEntity;
-	}
-
-	public BlockState getBlockState() {
-		return smartBlockEntity.getBlockState();
-	}
-
 }
diff --git a/src/main/java/com/simibubi/create/api/event/PipeCollisionEvent.java b/src/main/java/com/simibubi/create/api/event/PipeCollisionEvent.java
index 753f15ebca..03a43f3b28 100644
--- a/src/main/java/com/simibubi/create/api/event/PipeCollisionEvent.java
+++ b/src/main/java/com/simibubi/create/api/event/PipeCollisionEvent.java
@@ -6,7 +6,7 @@ import net.minecraft.core.BlockPos;
 import net.minecraft.world.level.Level;
 import net.minecraft.world.level.block.state.BlockState;
 import net.minecraft.world.level.material.Fluid;
-import net.minecraftforge.eventbus.api.Event;
+import net.neoforged.bus.api.Event;
 
 /**
  * This Event is fired when two fluids meet in a pipe ({@link Flow})
diff --git a/src/main/java/com/simibubi/create/api/event/TrackGraphMergeEvent.java b/src/main/java/com/simibubi/create/api/event/TrackGraphMergeEvent.java index 137f8f4f53..5fc0fa2e03 100644 --- a/src/main/java/com/simibubi/create/api/event/TrackGraphMergeEvent.java +++ b/src/main/java/com/simibubi/create/api/event/TrackGraphMergeEvent.java @@ -2,12 +2,11 @@ package com.simibubi.create.api.event; import com.simibubi.create.content.trains.graph.TrackGraph; -import net.minecraftforge.eventbus.api.Event; +import net.neoforged.bus.api.Event; public class TrackGraphMergeEvent extends Event { private final TrackGraph mergedInto; private final TrackGraph mergedFrom; - public TrackGraphMergeEvent(TrackGraph from, TrackGraph into) { mergedInto = into; mergedFrom = from; diff --git a/src/main/java/com/simibubi/create/api/schematic/nbt/IPartialSafeNBT.java b/src/main/java/com/simibubi/create/api/schematic/nbt/IPartialSafeNBT.java index 2cd7948168..0830a43646 100644 --- a/src/main/java/com/simibubi/create/api/schematic/nbt/IPartialSafeNBT.java +++ b/src/main/java/com/simibubi/create/api/schematic/nbt/IPartialSafeNBT.java @@ -1,10 +1,11 @@ package com.simibubi.create.api.schematic.nbt; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public interface IPartialSafeNBT { /** * This will always be called from the logical server */ - void writeSafe(CompoundTag compound); + void writeSafe(CompoundTag compound, HolderLookup.Provider registries); } diff --git a/src/main/java/com/simibubi/create/api/schematic/nbt/SchematicSafeNBTRegistry.java b/src/main/java/com/simibubi/create/api/schematic/nbt/SchematicSafeNBTRegistry.java index 846f96a4ab..d3ca8d0401 100644 --- a/src/main/java/com/simibubi/create/api/schematic/nbt/SchematicSafeNBTRegistry.java +++ b/src/main/java/com/simibubi/create/api/schematic/nbt/SchematicSafeNBTRegistry.java @@ -2,6 +2,7 @@ package com.simibubi.create.api.schematic.nbt; import com.simibubi.create.impl.schematic.nbt.SchematicSafeNBTRegistryImpl; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -17,7 +18,7 @@ public class SchematicSafeNBTRegistry { * * @param blockEntityType The block entity type you would like to register this for * @param safeNBT The custom PartialSafeNBT provider you would like to register for this blockEntityType, - * your {@link ContextProvidingPartialSafeNBT#writeSafe(BlockEntity, CompoundTag)} method will be + * your {@link ContextProvidingPartialSafeNBT#writeSafe(BlockEntity, CompoundTag, HolderLookup.Provider)} method will be * called on the passed {@link ContextProvidingPartialSafeNBT} * when the block entities data is being prepared for placement. */ @@ -32,6 +33,6 @@ public class SchematicSafeNBTRegistry { /** * This will always be called from the logical server */ - void writeSafe(BlockEntity blockEntity, CompoundTag tag); + void writeSafe(BlockEntity blockEntity, CompoundTag tag, HolderLookup.Provider registries); } } diff --git a/src/main/java/com/simibubi/create/compat/Mods.java b/src/main/java/com/simibubi/create/compat/Mods.java index e4ce3adaaa..ae1742311e 100644 --- a/src/main/java/com/simibubi/create/compat/Mods.java +++ b/src/main/java/com/simibubi/create/compat/Mods.java @@ -3,20 +3,21 @@ package com.simibubi.create.compat; import java.util.Optional; import java.util.function.Supplier; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.createmod.catnip.utility.lang.Lang; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.fml.ModList; /** * For compatibility with and without another mod present, we have to define load conditions of the specific code */ public enum Mods { AETHER, + AETHER_II, COMPUTERCRAFT, CONNECTIVITY, CURIOS, @@ -49,22 +50,22 @@ public enum Mods { } public ResourceLocation rl(String path) { - return new ResourceLocation(id, path); + return ResourceLocation.fromNamespaceAndPath(id, path); } public Block getBlock(String id) { - return ForgeRegistries.BLOCKS.getValue(rl(id)); + return BuiltInRegistries.BLOCK.get(rl(id)); } public Item getItem(String id) { - return ForgeRegistries.ITEMS.getValue(rl(id)); + return BuiltInRegistries.ITEM.get(rl(id)); } public boolean contains(ItemLike entry) { if (!isLoaded()) return false; Item asItem = entry.asItem(); - return asItem != null && CatnipServices.REGISTRIES.getKeyOrThrow(asItem) + return asItem != null && RegisteredObjectsHelper.getKeyOrThrow(asItem) .getNamespace() .equals(id); } diff --git a/src/main/java/com/simibubi/create/compat/computercraft/AbstractComputerBehaviour.java b/src/main/java/com/simibubi/create/compat/computercraft/AbstractComputerBehaviour.java index 956aad0b6c..7cad0cc1e6 100644 --- a/src/main/java/com/simibubi/create/compat/computercraft/AbstractComputerBehaviour.java +++ b/src/main/java/com/simibubi/create/compat/computercraft/AbstractComputerBehaviour.java @@ -4,9 +4,9 @@ import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BehaviourType; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; +import dan200.computercraft.api.peripheral.IPeripheral; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; public class AbstractComputerBehaviour extends BlockEntityBehaviour { @@ -20,23 +20,19 @@ public class AbstractComputerBehaviour extends BlockEntityBehaviour { } @Override - public void read(CompoundTag nbt, boolean clientPacket) { + public void read(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { hasAttachedComputer = nbt.getBoolean("HasAttachedComputer"); - super.read(nbt, clientPacket); + super.read(nbt, registries, clientPacket); } @Override - public void write(CompoundTag nbt, boolean clientPacket) { + public void write(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { nbt.putBoolean("HasAttachedComputer", hasAttachedComputer); - super.write(nbt, clientPacket); + super.write(nbt, registries, clientPacket); } - public boolean isPeripheralCap(Capability cap) { - return false; - } - - public LazyOptional getPeripheralCapability() { - return LazyOptional.empty(); + public IPeripheral getPeripheralCapability() { + return null; } public void removePeripheral() {} diff --git a/src/main/java/com/simibubi/create/compat/computercraft/AttachedComputerPacket.java b/src/main/java/com/simibubi/create/compat/computercraft/AttachedComputerPacket.java index 0304e864be..38bbb20bc0 100644 --- a/src/main/java/com/simibubi/create/compat/computercraft/AttachedComputerPacket.java +++ b/src/main/java/com/simibubi/create/compat/computercraft/AttachedComputerPacket.java @@ -1,13 +1,22 @@ package com.simibubi.create.compat.computercraft; +import com.simibubi.create.AllPackets; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.SyncedBlockEntity; import com.simibubi.create.foundation.networking.BlockEntityDataPacket; +import io.netty.buffer.ByteBuf; + import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; public class AttachedComputerPacket extends BlockEntityDataPacket { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, packet -> packet.pos, + ByteBufCodecs.BOOL, packet -> packet.hasAttachedComputer, + AttachedComputerPacket::new + ); private final boolean hasAttachedComputer; @@ -16,16 +25,6 @@ public class AttachedComputerPacket extends BlockEntityDataPacket PERIPHERAL_CAPABILITY = - CapabilityManager.get(new CapabilityToken<>() { - }); - LazyOptional peripheral; - NonNullSupplier peripheralSupplier; + IPeripheral peripheral; + Supplier peripheralSupplier; + SmartBlockEntity be; - public ComputerBehaviour(SmartBlockEntity te) { - super(te); - this.peripheralSupplier = getPeripheralFor(te); + public ComputerBehaviour(SmartBlockEntity be) { + super(be); + this.peripheralSupplier = getPeripheralFor(be); + this.be = be; } - public static NonNullSupplier getPeripheralFor(SmartBlockEntity be) { + public static Supplier getPeripheralFor(SmartBlockEntity be) { if (be instanceof SpeedControllerBlockEntity scbe) return () -> new SpeedControllerPeripheral(scbe, scbe.targetSpeed); if (be instanceof DisplayLinkBlockEntity dlbe) @@ -51,25 +47,20 @@ public class ComputerBehaviour extends AbstractComputerBehaviour { return () -> new StationPeripheral(sbe); throw new IllegalArgumentException( - "No peripheral available for " + ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(be.getType())); + "No peripheral available for " + BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(be.getType())); } @Override - public boolean isPeripheralCap(Capability cap) { - return cap == PERIPHERAL_CAPABILITY; - } - - @Override - public LazyOptional getPeripheralCapability() { - if (peripheral == null || !peripheral.isPresent()) - peripheral = LazyOptional.of(peripheralSupplier); - return peripheral.cast(); + public IPeripheral getPeripheralCapability() { + if (peripheral == null) + peripheral = peripheralSupplier.get(); + return peripheral; } @Override public void removePeripheral() { if (peripheral != null) - peripheral.invalidate(); + getWorld().invalidateCapabilities(be.getBlockPos()); } } diff --git a/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/StationPeripheral.java b/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/StationPeripheral.java index 5f410b63e0..37b4e3daf9 100644 --- a/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/StationPeripheral.java +++ b/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/StationPeripheral.java @@ -6,13 +6,13 @@ import javax.annotation.Nullable; import org.jetbrains.annotations.NotNull; -import com.simibubi.create.AllPackets; import com.simibubi.create.compat.computercraft.implementation.CreateLuaTable; import com.simibubi.create.content.trains.entity.Train; import com.simibubi.create.content.trains.schedule.Schedule; import com.simibubi.create.content.trains.station.GlobalStation; import com.simibubi.create.content.trains.station.StationBlockEntity; import com.simibubi.create.content.trains.station.TrainEditPacket; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.StringHelper; import dan200.computercraft.api.lua.IArguments; @@ -28,7 +28,6 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; -import net.minecraftforge.network.PacketDistributor; public class StationPeripheral extends SyncedPeripheral { @@ -129,7 +128,7 @@ public class StationPeripheral extends SyncedPeripheral { public final void setTrainName(String name) throws LuaException { Train train = getTrainOrThrow(); train.name = Components.literal(name); - AllPackets.getChannel().send(PacketDistributor.ALL.noArg(), new TrainEditPacket.TrainEditReturnPacket(train.id, name, train.icon.getId(), train.mapColorIndex)); + CatnipServices.NETWORK.sendToAllClients(new TrainEditPacket.TrainEditReturnPacket(train.id, name, train.icon.getId(), train.mapColorIndex)); } @LuaFunction @@ -146,7 +145,7 @@ public class StationPeripheral extends SyncedPeripheral { if (schedule == null) throw new LuaException("train doesn't have a schedule"); - return fromCompoundTag(schedule.write()); + return fromCompoundTag(schedule.write(blockEntity.getLevel().registryAccess())); } @LuaFunction(mainThread = true) @@ -159,7 +158,7 @@ public class StationPeripheral extends SyncedPeripheral { throw new LuaException("Schedule must have at least one entry"); Train train = getTrainOrThrow(); - Schedule schedule = Schedule.fromTag(toCompoundTag(new CreateLuaTable(arguments.getTable(0)))); + Schedule schedule = Schedule.fromTag(blockEntity.getLevel().registryAccess(), toCompoundTag(new CreateLuaTable(arguments.getTable(0)))); boolean autoSchedule = train.runtime.getSchedule() == null || train.runtime.isAutoSchedule; train.runtime.setSchedule(schedule, autoSchedule); } diff --git a/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/SyncedPeripheral.java b/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/SyncedPeripheral.java index 7c0b1f7b11..954edc5b19 100644 --- a/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/SyncedPeripheral.java +++ b/src/main/java/com/simibubi/create/compat/computercraft/implementation/peripherals/SyncedPeripheral.java @@ -5,14 +5,13 @@ import java.util.concurrent.atomic.AtomicInteger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import com.simibubi.create.AllPackets; import com.simibubi.create.compat.computercraft.AttachedComputerPacket; import com.simibubi.create.compat.computercraft.implementation.ComputerBehaviour; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; +import net.createmod.catnip.platform.CatnipServices; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraftforge.network.PacketDistributor; public abstract class SyncedPeripheral implements IPeripheral { @@ -39,7 +38,7 @@ public abstract class SyncedPeripheral implements IP boolean hasAttachedComputer = computers.get() > 0; blockEntity.getBehaviour(ComputerBehaviour.TYPE).setHasAttachedComputer(hasAttachedComputer); - AllPackets.getChannel().send(PacketDistributor.ALL.noArg(), new AttachedComputerPacket(blockEntity.getBlockPos(), hasAttachedComputer)); + CatnipServices.NETWORK.sendToAllClients(new AttachedComputerPacket(blockEntity.getBlockPos(), hasAttachedComputer)); } @Override diff --git a/src/main/java/com/simibubi/create/compat/curios/Curios.java b/src/main/java/com/simibubi/create/compat/curios/Curios.java index 7adbb59be4..ba2bfecb50 100644 --- a/src/main/java/com/simibubi/create/compat/curios/Curios.java +++ b/src/main/java/com/simibubi/create/compat/curios/Curios.java @@ -10,14 +10,13 @@ import com.simibubi.create.AllTags; import com.simibubi.create.content.equipment.armor.BacktankUtil; import com.simibubi.create.content.equipment.goggles.GogglesItem; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.InterModComms; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.InterModComms; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.fml.event.lifecycle.InterModEnqueueEvent; import top.theillusivec4.curios.api.CuriosCapability; import top.theillusivec4.curios.api.SlotTypeMessage; import top.theillusivec4.curios.api.SlotTypePreset; @@ -35,10 +34,10 @@ public class Curios { * @return An optional of the Stacks Handler Map */ private static Optional> resolveCuriosMap(LivingEntity entity) { - return entity.getCapability(CuriosCapability.INVENTORY).map(ICuriosItemHandler::getCurios); + return Optional.ofNullable(entity.getCapability(CuriosCapability.INVENTORY)).map(ICuriosItemHandler::getCurios); } - public static void init(IEventBus modEventBus, IEventBus forgeEventBus) { + public static void init(IEventBus modEventBus) { modEventBus.addListener(Curios::onInterModEnqueue); modEventBus.addListener(Curios::onClientSetup); @@ -74,8 +73,7 @@ public class Curios { return stacks; }).orElse(new ArrayList<>())); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> modEventBus.addListener(CuriosRenderers::onLayerRegister)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> modEventBus.addListener(CuriosRenderers::onLayerRegister)); } private static void onInterModEnqueue(final InterModEnqueueEvent event) { diff --git a/src/main/java/com/simibubi/create/compat/curios/CuriosRenderers.java b/src/main/java/com/simibubi/create/compat/curios/CuriosRenderers.java index 740d251b00..745ad694d3 100644 --- a/src/main/java/com/simibubi/create/compat/curios/CuriosRenderers.java +++ b/src/main/java/com/simibubi/create/compat/curios/CuriosRenderers.java @@ -4,9 +4,9 @@ import com.simibubi.create.AllItems; import net.minecraft.client.Minecraft; import net.minecraft.client.model.geom.builders.LayerDefinition; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.EntityRenderersEvent; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.event.EntityRenderersEvent; import top.theillusivec4.curios.api.client.CuriosRendererRegistry; @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/com/simibubi/create/compat/curios/GogglesCurioRenderer.java b/src/main/java/com/simibubi/create/compat/curios/GogglesCurioRenderer.java index f40af962b0..ccb0b8dd63 100644 --- a/src/main/java/com/simibubi/create/compat/curios/GogglesCurioRenderer.java +++ b/src/main/java/com/simibubi/create/compat/curios/GogglesCurioRenderer.java @@ -20,14 +20,14 @@ import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; import top.theillusivec4.curios.api.SlotContext; import top.theillusivec4.curios.api.client.ICurioRenderer; @OnlyIn(Dist.CLIENT) public class GogglesCurioRenderer implements ICurioRenderer { - public static final ModelLayerLocation LAYER = new ModelLayerLocation(new ResourceLocation(Create.ID, "goggles"), "goggles"); + public static final ModelLayerLocation LAYER = new ModelLayerLocation(Create.asResource("goggles"), "goggles"); private final HumanoidModel model; diff --git a/src/main/java/com/simibubi/create/compat/dynamictrees/DynamicTree.java b/src/main/java/com/simibubi/create/compat/dynamictrees/DynamicTree.java index b1fbf7beda..b5743bdae5 100644 --- a/src/main/java/com/simibubi/create/compat/dynamictrees/DynamicTree.java +++ b/src/main/java/com/simibubi/create/compat/dynamictrees/DynamicTree.java @@ -4,19 +4,13 @@ import java.util.function.BiConsumer; import javax.annotation.Nullable; -import com.ferreusveritas.dynamictrees.api.TreeHelper; -import com.ferreusveritas.dynamictrees.block.branch.BranchBlock; -import com.ferreusveritas.dynamictrees.block.branch.TrunkShellBlock; -import com.ferreusveritas.dynamictrees.util.BranchDestructionData; import com.simibubi.create.foundation.utility.AbstractBlockBreakQueue; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; public class DynamicTree extends AbstractBlockBreakQueue { @@ -27,46 +21,47 @@ public class DynamicTree extends AbstractBlockBreakQueue { } public static boolean isDynamicBranch(Block block) { - return TreeHelper.isBranch(block) || block instanceof TrunkShellBlock; + //return TreeHelper.isBranch(block) || block instanceof TrunkShellBlock; + return false; } @Override public void destroyBlocks(Level world, ItemStack toDamage, @Nullable Player playerEntity, BiConsumer drop) { - BranchBlock start = TreeHelper.getBranch(world.getBlockState(startCutPos)); - if (start == null) //if start is null, it was not a branch - start = setBranchToShellMuse(world, world.getBlockState(startCutPos)); //we check for a trunk shell instead - - if (start == null) //if it is null again, it was neither a branch nor a trunk shell and thus we return - return; - - // Play and render block break sound and particles - world.levelEvent(null, 2001, startCutPos, Block.getId(world.getBlockState(startCutPos))); - - // Actually breaks the tree - BranchDestructionData data = start.destroyBranchFromNode(world, startCutPos, Direction.DOWN, false, playerEntity); - - // Feed all the tree drops to drop bi-consumer - data.leavesDrops.forEach(stackPos -> drop.accept(stackPos.pos.offset(startCutPos), stackPos.stack)); - start.getFamily().getCommonSpecies().getBranchesDrops(world, data.woodVolume).forEach(stack -> drop.accept(startCutPos, stack)); +// BranchBlock start = TreeHelper.getBranch(world.getBlockState(startCutPos)); +// if (start == null) //if start is null, it was not a branch +// start = setBranchToShellMuse(world, world.getBlockState(startCutPos)); //we check for a trunk shell instead +// +// if (start == null) //if it is null again, it was neither a branch nor a trunk shell and thus we return +// return; +// +// // Play and render block break sound and particles +// world.levelEvent(null, 2001, startCutPos, Block.getId(world.getBlockState(startCutPos))); +// +// // Actually breaks the tree +// BranchDestructionData data = start.destroyBranchFromNode(world, startCutPos, Direction.DOWN, false, playerEntity); +// +// // Feed all the tree drops to drop bi-consumer +// data.leavesDrops.forEach(stackPos -> drop.accept(stackPos.pos.offset(startCutPos), stackPos.stack)); +// start.getFamily().getCommonSpecies().getBranchesDrops(world, data.woodVolume).forEach(stack -> drop.accept(startCutPos, stack)); } - private BranchBlock setBranchToShellMuse(Level world, BlockState state) { - - Block block = state.getBlock(); - if (block instanceof TrunkShellBlock){ - TrunkShellBlock.ShellMuse muse = ((TrunkShellBlock)block).getMuse(world, startCutPos); - if (muse != null){ - startCutPos = muse.pos; //the cut pos is moved to the center of the trunk - return TreeHelper.getBranch(muse.state); - } - } - - return null; - } +// private BranchBlock setBranchToShellMuse(Level world, BlockState state) { +// +// Block block = state.getBlock(); +// if (block instanceof TrunkShellBlock){ +// TrunkShellBlock.ShellMuse muse = ((TrunkShellBlock)block).getMuse(world, startCutPos); +// if (muse != null){ +// startCutPos = muse.pos; //the cut pos is moved to the center of the trunk +// return TreeHelper.getBranch(muse.state); +// } +// } +// +// return null; +// } } diff --git a/src/main/java/com/simibubi/create/compat/framedblocks/FramedBlocksInSchematics.java b/src/main/java/com/simibubi/create/compat/framedblocks/FramedBlocksInSchematics.java index acb60c9534..6ce80d6f31 100644 --- a/src/main/java/com/simibubi/create/compat/framedblocks/FramedBlocksInSchematics.java +++ b/src/main/java/com/simibubi/create/compat/framedblocks/FramedBlocksInSchematics.java @@ -28,7 +28,7 @@ public class FramedBlocksInSchematics { if (blockEntity == null) return data; - data = blockEntity.saveWithFullMetadata(); + data = blockEntity.saveWithFullMetadata(blockEntity.getLevel().registryAccess()); List keysToRemove = new ArrayList<>(); for (String key : data.getAllKeys()) @@ -36,11 +36,11 @@ public class FramedBlocksInSchematics { keysToRemove.add(key); for (String key : keysToRemove) data.remove(key); - + if (data.getCompound("camo") .contains("fluid")) data.remove("camo"); - + if (data.getCompound("camo_two") .contains("fluid")) data.remove("camo_two"); @@ -52,7 +52,7 @@ public class FramedBlocksInSchematics { if (blockEntity == null) return ItemRequirement.NONE; - CompoundTag data = blockEntity.saveWithFullMetadata(); + CompoundTag data = blockEntity.saveWithFullMetadata(blockEntity.getLevel().registryAccess()); List list = new ArrayList<>(); if (data.getBoolean("intangible")) diff --git a/src/main/java/com/simibubi/create/compat/ftb/FTBIntegration.java b/src/main/java/com/simibubi/create/compat/ftb/FTBIntegration.java index 32864b7aae..37345d455b 100644 --- a/src/main/java/com/simibubi/create/compat/ftb/FTBIntegration.java +++ b/src/main/java/com/simibubi/create/compat/ftb/FTBIntegration.java @@ -2,17 +2,17 @@ package com.simibubi.create.compat.ftb; import com.simibubi.create.foundation.gui.menu.AbstractSimiContainerScreen; -import dev.ftb.mods.ftblibrary.FTBLibraryClient; +import dev.ftb.mods.ftblibrary.config.FTBLibraryClientConfig; import net.createmod.catnip.gui.AbstractSimiScreen; import net.minecraft.client.gui.screens.Screen; -import net.minecraftforge.client.event.ScreenEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.ScreenEvent; public class FTBIntegration { - private static int buttonStatePreviously = 0; - + private static boolean buttonStatePreviously; + public static void init(IEventBus modEventBus, IEventBus forgeEventBus) { forgeEventBus.addListener(EventPriority.HIGH, FTBIntegration::removeGUIClutterOpen); forgeEventBus.addListener(EventPriority.LOW, FTBIntegration::removeGUIClutterClose); @@ -23,14 +23,14 @@ public class FTBIntegration { return; if (!isCreate(event.getNewScreen())) return; - buttonStatePreviously = FTBLibraryClient.showButtons; - FTBLibraryClient.showButtons = 0; + buttonStatePreviously = FTBLibraryClientConfig.SIDEBAR_ENABLED.get(); + FTBLibraryClientConfig.SIDEBAR_ENABLED.set(false); } private static void removeGUIClutterClose(ScreenEvent.Closing event) { if (!isCreate(event.getScreen())) return; - FTBLibraryClient.showButtons = buttonStatePreviously; + FTBLibraryClientConfig.SIDEBAR_ENABLED.set(buttonStatePreviously); } private static boolean isCreate(Screen screen) { diff --git a/src/main/java/com/simibubi/create/compat/jei/BlueprintTransferHandler.java b/src/main/java/com/simibubi/create/compat/jei/BlueprintTransferHandler.java index 7356a422f2..932cbf2277 100644 --- a/src/main/java/com/simibubi/create/compat/jei/BlueprintTransferHandler.java +++ b/src/main/java/com/simibubi/create/compat/jei/BlueprintTransferHandler.java @@ -6,9 +6,9 @@ import javax.annotation.ParametersAreNonnullByDefault; import org.jetbrains.annotations.Nullable; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.equipment.blueprint.BlueprintAssignCompleteRecipePacket; import com.simibubi.create.content.equipment.blueprint.BlueprintMenu; +import net.createmod.catnip.platform.CatnipServices; import mezz.jei.api.constants.RecipeTypes; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; @@ -19,13 +19,14 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault -public class BlueprintTransferHandler implements IRecipeTransferHandler { +public class BlueprintTransferHandler implements IRecipeTransferHandler> { @Override - public Class getContainerClass() { + public Class getContainerClass() { return BlueprintMenu.class; } @@ -35,16 +36,16 @@ public class BlueprintTransferHandler implements IRecipeTransferHandler getRecipeType() { + public RecipeType> getRecipeType() { return RecipeTypes.CRAFTING; } @Override - public @Nullable IRecipeTransferError transferRecipe(BlueprintMenu menu, CraftingRecipe craftingRecipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { + public @Nullable IRecipeTransferError transferRecipe(BlueprintMenu menu, RecipeHolder craftingRecipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { if (!doTransfer) return null; - AllPackets.getChannel().sendToServer(new BlueprintAssignCompleteRecipePacket(craftingRecipe.getId())); + CatnipServices.NETWORK.sendToServer(new BlueprintAssignCompleteRecipePacket(craftingRecipe.id())); return null; } diff --git a/src/main/java/com/simibubi/create/compat/jei/ConversionRecipe.java b/src/main/java/com/simibubi/create/compat/jei/ConversionRecipe.java index cc41e9a908..594fc6e041 100644 --- a/src/main/java/com/simibubi/create/compat/jei/ConversionRecipe.java +++ b/src/main/java/com/simibubi/create/compat/jei/ConversionRecipe.java @@ -11,8 +11,9 @@ import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.Pro import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; -import net.minecraftforge.items.wrapper.RecipeWrapper; +import net.neoforged.neoforge.items.wrapper.RecipeWrapper; /** * Helper recipe type for displaying an item relationship in JEI @@ -22,12 +23,13 @@ public class ConversionRecipe extends ProcessingRecipe { static int counter = 0; - public static ConversionRecipe create(ItemStack from, ItemStack to) { + public static RecipeHolder create(ItemStack from, ItemStack to) { ResourceLocation recipeId = Create.asResource("conversion_" + counter++); - return new ProcessingRecipeBuilder<>(ConversionRecipe::new, recipeId) + ConversionRecipe recipe = new ProcessingRecipeBuilder<>(ConversionRecipe::new, recipeId) .withItemIngredients(Ingredient.of(from)) .withSingleItemOutput(to) .build(); + return new RecipeHolder<>(recipeId, recipe); } public ConversionRecipe(ProcessingRecipeParams params) { diff --git a/src/main/java/com/simibubi/create/compat/jei/CreateJEI.java b/src/main/java/com/simibubi/create/compat/jei/CreateJEI.java index 39d36d8672..159d6b29b2 100644 --- a/src/main/java/com/simibubi/create/compat/jei/CreateJEI.java +++ b/src/main/java/com/simibubi/create/compat/jei/CreateJEI.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -68,15 +67,16 @@ import com.simibubi.create.foundation.gui.menu.AbstractSimiContainerScreen; import com.simibubi.create.foundation.item.ItemHelper; import com.simibubi.create.foundation.recipe.IRecipeTypeInfo; import com.simibubi.create.foundation.utility.CreateLang; +import com.simibubi.create.foundation.utility.RecipeGenericsUtil; import com.simibubi.create.infrastructure.config.AllConfigs; import com.simibubi.create.infrastructure.config.CRecipes; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.constants.RecipeTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.helpers.IPlatformFluidHelper; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.category.IRecipeCategory; import mezz.jei.api.registration.IGuiHandlerRegistration; import mezz.jei.api.registration.IRecipeCatalystRegistration; @@ -94,12 +94,14 @@ import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.AbstractCookingRecipe; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.RecipeInput; import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.SmokingRecipe; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Blocks; -import net.minecraftforge.common.crafting.IShapedRecipe; -import net.minecraftforge.fml.ModList; +import net.neoforged.fml.ModList; @JeiPlugin @SuppressWarnings("unused") @@ -180,10 +182,10 @@ public class CreateJEI implements IModPlugin { autoShapeless = builder(BasinRecipe.class) .enableWhen(c -> c.allowShapelessInMixer) - .addAllRecipesIf(r -> r instanceof CraftingRecipe && !(r instanceof IShapedRecipe) - && r.getIngredients() + .addAllRecipesIf(r -> r.value() instanceof CraftingRecipe && !(r.value() instanceof ShapedRecipe) + && r.value().getIngredients() .size() > 1 - && !MechanicalPressBlockEntity.canCompress(r) && !AllRecipeTypes.shouldIgnoreInAutomation(r), + && !MechanicalPressBlockEntity.canCompress(r.value()) && !AllRecipeTypes.shouldIgnoreInAutomation(r), BasinRecipe::convertShapeless) .catalyst(AllBlocks.MECHANICAL_MIXER::get) .catalyst(AllBlocks.BASIN::get) @@ -193,7 +195,7 @@ public class CreateJEI implements IModPlugin { brewing = builder(BasinRecipe.class) .enableWhen(c -> c.allowBrewingInMixer) - .addRecipes(() -> PotionMixingRecipes.ALL) + .addRecipes(() -> RecipeGenericsUtil.cast(PotionMixingRecipes.createRecipes(Minecraft.getInstance().level))) .catalyst(AllBlocks.MECHANICAL_MIXER::get) .catalyst(AllBlocks.BASIN::get) .doubleItemIcon(AllBlocks.MECHANICAL_MIXER.get(), Blocks.BREWING_STAND) @@ -211,8 +213,8 @@ public class CreateJEI implements IModPlugin { autoSquare = builder(BasinRecipe.class) .enableWhen(c -> c.allowShapedSquareInPress) .addAllRecipesIf( - r -> (r instanceof CraftingRecipe) && !(r instanceof MechanicalCraftingRecipe) - && MechanicalPressBlockEntity.canCompress(r) && !AllRecipeTypes.shouldIgnoreInAutomation(r), + r -> (r.value() instanceof CraftingRecipe) && !(r.value() instanceof MechanicalCraftingRecipe) + && MechanicalPressBlockEntity.canCompress(r.value()) && !AllRecipeTypes.shouldIgnoreInAutomation(r), BasinRecipe::convertShapeless) .catalyst(AllBlocks.MECHANICAL_PRESS::get) .catalyst(AllBlocks.BASIN::get) @@ -254,7 +256,7 @@ public class CreateJEI implements IModPlugin { item_application = builder(ItemApplicationRecipe.class) .addTypedRecipes(AllRecipeTypes.ITEM_APPLICATION) - .addRecipes(LogStrippingFakeRecipes::createRecipes) + .addRecipes(() -> RecipeGenericsUtil.cast(LogStrippingFakeRecipes.createRecipes())) .itemIcon(AllItems.BRASS_HAND.get()) .emptyBackground(177, 60) .build("item_application", ItemApplicationCategory::new), @@ -289,12 +291,12 @@ public class CreateJEI implements IModPlugin { autoShaped = builder(CraftingRecipe.class) .enableWhen(c -> c.allowRegularCraftingInCrafter) - .addAllRecipesIf(r -> r instanceof CraftingRecipe && !(r instanceof IShapedRecipe) - && r.getIngredients() + .addAllRecipesIf(r -> r.value() instanceof CraftingRecipe && !(r.value() instanceof ShapedRecipe) + && r.value().getIngredients() .size() == 1 && !AllRecipeTypes.shouldIgnoreInAutomation(r)) .addTypedRecipesIf(() -> RecipeType.CRAFTING, - recipe -> recipe instanceof IShapedRecipe && !AllRecipeTypes.shouldIgnoreInAutomation(recipe)) + recipe -> recipe.value() instanceof ShapedRecipe && !AllRecipeTypes.shouldIgnoreInAutomation(recipe)) .catalyst(AllBlocks.MECHANICAL_CRAFTER::get) .itemIcon(AllBlocks.MECHANICAL_CRAFTER.get()) .emptyBackground(177, 107) @@ -321,7 +323,7 @@ public class CreateJEI implements IModPlugin { } - private > CategoryBuilder builder(Class recipeClass) { + private > CategoryBuilder builder(Class recipeClass) { return new CategoryBuilder<>(recipeClass); } @@ -361,8 +363,8 @@ public class CreateJEI implements IModPlugin { public void registerFluidSubtypes(ISubtypeRegistration registration, IPlatformFluidHelper platformFluidHelper) { PotionFluidSubtypeInterpreter interpreter = new PotionFluidSubtypeInterpreter(); PotionFluid potionFluid = AllFluids.POTION.get(); - registration.registerSubtypeInterpreter(ForgeTypes.FLUID_STACK, potionFluid.getSource(), interpreter); - registration.registerSubtypeInterpreter(ForgeTypes.FLUID_STACK, potionFluid.getFlowing(), interpreter); + registration.registerSubtypeInterpreter(NeoForgeTypes.FLUID_STACK, potionFluid.getSource(), interpreter); + registration.registerSubtypeInterpreter(NeoForgeTypes.FLUID_STACK, potionFluid.getFlowing(), interpreter); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -377,14 +379,14 @@ public class CreateJEI implements IModPlugin { registration.addGhostIngredientHandler(RedstoneRequesterScreen.class, new GhostIngredientHandler()); } - private class CategoryBuilder> { + private class CategoryBuilder> { private final Class recipeClass; private Predicate predicate = cRecipes -> true; private IDrawable background; private IDrawable icon; - private final List>> recipeListConsumers = new ArrayList<>(); + private final List>>> recipeListConsumers = new ArrayList<>(); private final List> catalysts = new ArrayList<>(); public CategoryBuilder(Class recipeClass) { @@ -401,24 +403,24 @@ public class CreateJEI implements IModPlugin { return this; } - public CategoryBuilder addRecipeListConsumer(Consumer> consumer) { + public CategoryBuilder addRecipeListConsumer(Consumer>> consumer) { recipeListConsumers.add(consumer); return this; } - public CategoryBuilder addRecipes(Supplier> collection) { + public CategoryBuilder addRecipes(Supplier>> collection) { return addRecipeListConsumer(recipes -> recipes.addAll(collection.get())); } @SuppressWarnings("unchecked") - public CategoryBuilder addAllRecipesIf(Predicate> pred) { - return addRecipeListConsumer(recipes -> consumeAllRecipes(recipe -> { + public CategoryBuilder addAllRecipesIf(Predicate> pred) { + return addRecipeListConsumer(recipes -> consumeAllRecipesOfType(recipe -> { if (pred.test(recipe)) - recipes.add((T) recipe); + recipes.add(recipe); })); } - public CategoryBuilder addAllRecipesIf(Predicate> pred, Function, T> converter) { + public CategoryBuilder addAllRecipesIf(Predicate> pred, Function, RecipeHolder> converter) { return addRecipeListConsumer(recipes -> consumeAllRecipes(recipe -> { if (pred.test(recipe)) { recipes.add(converter.apply(recipe)); @@ -429,17 +431,20 @@ public class CreateJEI implements IModPlugin { public CategoryBuilder addTypedRecipes(IRecipeTypeInfo recipeTypeEntry) { return addTypedRecipes(recipeTypeEntry::getType); } - - public CategoryBuilder addTypedRecipes(Supplier> recipeType) { - return addRecipeListConsumer(recipes -> CreateJEI.consumeTypedRecipes(recipes::add, recipeType.get())); + public > CategoryBuilder addTypedRecipes(Supplier> recipeType) { + return addRecipeListConsumer(recipes -> CreateJEI.consumeTypedRecipes(recipe -> { + if (recipeClass.isInstance(recipe.value())) + //noinspection unchecked - checked by if statement above + recipes.add((RecipeHolder) recipe); + }, recipeType.get())); } - public CategoryBuilder addTypedRecipes(Supplier> recipeType, Function, T> converter) { + public CategoryBuilder addTypedRecipes(Supplier> recipeType, Function, RecipeHolder> converter) { return addRecipeListConsumer(recipes -> CreateJEI.consumeTypedRecipes(recipe -> recipes.add(converter.apply(recipe)), recipeType.get())); } - public CategoryBuilder addTypedRecipesIf(Supplier> recipeType, Predicate> pred) { - return addRecipeListConsumer(recipes -> CreateJEI.consumeTypedRecipes(recipe -> { + public CategoryBuilder addTypedRecipesIf(Supplier> recipeType, Predicate> pred) { + return addRecipeListConsumer(recipes -> consumeTypedRecipesTyped(recipe -> { if (pred.test(recipe)) { recipes.add(recipe); } @@ -449,10 +454,10 @@ public class CreateJEI implements IModPlugin { public CategoryBuilder addTypedRecipesExcluding(Supplier> recipeType, Supplier> excluded) { return addRecipeListConsumer(recipes -> { - List> excludedRecipes = getTypedRecipes(excluded.get()); - CreateJEI.consumeTypedRecipes(recipe -> { - for (Recipe excludedRecipe : excludedRecipes) { - if (doInputsMatch(recipe, excludedRecipe)) { + List> excludedRecipes = getTypedRecipes(excluded.get()); + consumeTypedRecipesTyped(recipe -> { + for (RecipeHolder excludedRecipe : excludedRecipes) { + if (doInputsMatch(recipe.value(), excludedRecipe.value())) { return; } } @@ -463,10 +468,10 @@ public class CreateJEI implements IModPlugin { public CategoryBuilder removeRecipes(Supplier> recipeType) { return addRecipeListConsumer(recipes -> { - List> excludedRecipes = getTypedRecipes(recipeType.get()); + List> excludedRecipes = getTypedRecipes(recipeType.get()); recipes.removeIf(recipe -> { - for (Recipe excludedRecipe : excludedRecipes) - if (doInputsMatch(recipe, excludedRecipe) && doOutputsMatch(recipe, excludedRecipe)) + for (RecipeHolder excludedRecipe : excludedRecipes) + if (doInputsMatch(recipe.value(), excludedRecipe.value()) && doOutputsMatch(recipe.value(), excludedRecipe.value())) return true; return false; }); @@ -513,16 +518,16 @@ public class CreateJEI implements IModPlugin { } public CreateRecipeCategory build(String name, CreateRecipeCategory.Factory factory) { - Supplier> recipesSupplier; + Supplier>> recipesSupplier; if (predicate.test(AllConfigs.server().recipes)) { recipesSupplier = () -> { - List recipes = new ArrayList<>(); - for (Consumer> consumer : recipeListConsumers) + List> recipes = new ArrayList<>(); + for (Consumer>> consumer : recipeListConsumers) consumer.accept(recipes); return recipes; }; } else { - recipesSupplier = () -> Collections.emptyList(); + recipesSupplier = Collections::emptyList; } CreateRecipeCategory.Info info = new CreateRecipeCategory.Info<>( @@ -532,9 +537,27 @@ public class CreateJEI implements IModPlugin { allCategories.add(category); return category; } + + private void consumeAllRecipesOfType(Consumer> consumer) { + consumeAllRecipes(recipeHolder -> { + if (recipeClass.isInstance(recipeHolder.value())) { + //noinspection unchecked - this is checked by the if statement + consumer.accept((RecipeHolder) recipeHolder); + } + }); + } + + private void consumeTypedRecipesTyped(Consumer> consumer, RecipeType type) { + consumeTypedRecipes(recipeHolder -> { + if (recipeClass.isInstance(recipeHolder.value())) { + //noinspection unchecked - this is checked by the if statement + consumer.accept((RecipeHolder) recipeHolder); + } + }, type); + } } - public static void consumeAllRecipes(Consumer> consumer) { + public static void consumeAllRecipes(Consumer> consumer) { Minecraft.getInstance() .getConnection() .getRecipeManager() @@ -542,23 +565,23 @@ public class CreateJEI implements IModPlugin { .forEach(consumer); } - @SuppressWarnings("unchecked") - public static > void consumeTypedRecipes(Consumer consumer, RecipeType type) { - Map> map = Minecraft.getInstance() + @SuppressWarnings({"unchecked", "rawtypes"}) + public static > void consumeTypedRecipes(Consumer> consumer, RecipeType type) { + List> map = Minecraft.getInstance() .getConnection() - .getRecipeManager().recipes.get(type); - if (map != null) - map.values().forEach(recipe -> consumer.accept((T) recipe)); + .getRecipeManager().getAllRecipesFor((RecipeType) type); + if (!map.isEmpty()) + map.forEach(consumer); } - public static List> getTypedRecipes(RecipeType type) { - List> recipes = new ArrayList<>(); + public static List> getTypedRecipes(RecipeType type) { + List> recipes = new ArrayList<>(); consumeTypedRecipes(recipes::add, type); return recipes; } - public static List> getTypedRecipesExcluding(RecipeType type, Predicate> exclusionPred) { - List> recipes = getTypedRecipes(type); + public static List> getTypedRecipesExcluding(RecipeType type, Predicate> exclusionPred) { + List> recipes = getTypedRecipes(type); recipes.removeIf(exclusionPred); return recipes; } @@ -571,13 +594,13 @@ public class CreateJEI implements IModPlugin { return false; } ItemStack[] matchingStacks = recipe1.getIngredients() - .get(0) + .getFirst() .getItems(); if (matchingStacks.length == 0) { return false; } return recipe2.getIngredients() - .get(0) + .getFirst() .test(matchingStacks[0]); } diff --git a/src/main/java/com/simibubi/create/compat/jei/GhostIngredientHandler.java b/src/main/java/com/simibubi/create/compat/jei/GhostIngredientHandler.java index f9e2dd0094..214bc0c664 100644 --- a/src/main/java/com/simibubi/create/compat/jei/GhostIngredientHandler.java +++ b/src/main/java/com/simibubi/create/compat/jei/GhostIngredientHandler.java @@ -1,22 +1,24 @@ package com.simibubi.create.compat.jei; -import com.simibubi.create.AllPackets; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.ParametersAreNonnullByDefault; + import com.simibubi.create.content.logistics.filter.AttributeFilterScreen; import com.simibubi.create.foundation.gui.menu.AbstractSimiContainerScreen; import com.simibubi.create.foundation.gui.menu.GhostItemMenu; import com.simibubi.create.foundation.gui.menu.GhostItemSubmitPacket; + import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.handlers.IGhostIngredientHandler; import mezz.jei.api.ingredients.ITypedIngredient; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.renderer.Rect2i; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.LinkedList; -import java.util.List; - @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class GhostIngredientHandler> @@ -83,7 +85,7 @@ public class GhostIngredientHandler> return; // sync new filter contents with server - AllPackets.getChannel().sendToServer(new GhostItemSubmitPacket(stack, slotIndex)); + CatnipServices.NETWORK.sendToServer(new GhostItemSubmitPacket(stack, slotIndex)); } } } diff --git a/src/main/java/com/simibubi/create/compat/jei/PotionFluidSubtypeInterpreter.java b/src/main/java/com/simibubi/create/compat/jei/PotionFluidSubtypeInterpreter.java index 0950f04dbd..8e9fc7e4f8 100644 --- a/src/main/java/com/simibubi/create/compat/jei/PotionFluidSubtypeInterpreter.java +++ b/src/main/java/com/simibubi/create/compat/jei/PotionFluidSubtypeInterpreter.java @@ -2,43 +2,40 @@ package com.simibubi.create.compat.jei; import java.util.List; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.content.fluids.potion.PotionFluid.BottleType; import mezz.jei.api.ingredients.subtypes.IIngredientSubtypeInterpreter; import mezz.jei.api.ingredients.subtypes.UidContext; -import net.createmod.catnip.utility.NBTHelper; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.item.alchemy.Potion; -import net.minecraft.world.item.alchemy.PotionUtils; -import net.minecraftforge.fluids.FluidStack; +import net.minecraft.world.item.alchemy.PotionContents; +import net.neoforged.neoforge.fluids.FluidStack; /* From JEI's Potion item subtype interpreter */ public class PotionFluidSubtypeInterpreter implements IIngredientSubtypeInterpreter { - @Override public String apply(FluidStack ingredient, UidContext context) { - if (!ingredient.hasTag()) + if (ingredient.getComponentsPatch().isEmpty()) return IIngredientSubtypeInterpreter.NONE; - CompoundTag tag = ingredient.getOrCreateTag(); - Potion potionType = PotionUtils.getPotion(tag); - String potionTypeString = potionType.getName(""); - String bottleType = NBTHelper.readEnum(tag, "Bottle", BottleType.class) - .toString(); + PotionContents contents = ingredient.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY); + String potionTypeString = ingredient.getDescriptionId(); + String bottleType = ingredient.getOrDefault(AllDataComponents.POTION_FLUID_BOTTLE_TYPE, BottleType.REGULAR).name(); StringBuilder stringBuilder = new StringBuilder(potionTypeString); - List effects = PotionUtils.getCustomEffects(tag); + List effects = contents.customEffects(); stringBuilder.append(";") .append(bottleType); - for (MobEffectInstance effect : potionType.getEffects()) - stringBuilder.append(";") - .append(effect); + contents.potion().ifPresent(p -> { + for (MobEffectInstance effect : p.value().getEffects()) + stringBuilder.append(";") + .append(effect); + }); for (MobEffectInstance effect : effects) stringBuilder.append(";") .append(effect); return stringBuilder.toString(); } - } diff --git a/src/main/java/com/simibubi/create/compat/jei/StockKeeperTransferHandler.java b/src/main/java/com/simibubi/create/compat/jei/StockKeeperTransferHandler.java index 705014a65c..88f0681172 100644 --- a/src/main/java/com/simibubi/create/compat/jei/StockKeeperTransferHandler.java +++ b/src/main/java/com/simibubi/create/compat/jei/StockKeeperTransferHandler.java @@ -17,6 +17,7 @@ import com.simibubi.create.content.logistics.packager.InventorySummary; import com.simibubi.create.content.logistics.stockTicker.CraftableBigItemStack; import com.simibubi.create.content.logistics.stockTicker.StockKeeperRequestMenu; import com.simibubi.create.content.logistics.stockTicker.StockKeeperRequestScreen; +import com.simibubi.create.foundation.blockEntity.LegacyRecipeWrapper; import com.simibubi.create.foundation.utility.CreateLang; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; @@ -29,6 +30,7 @@ import mezz.jei.common.transfer.RecipeTransferOperationsResult; import mezz.jei.common.transfer.RecipeTransferUtil; import mezz.jei.library.transfer.RecipeTransferErrorMissingSlots; import mezz.jei.library.transfer.RecipeTransferErrorTooltip; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; @@ -37,10 +39,7 @@ import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.items.wrapper.RecipeWrapper; +import net.neoforged.neoforge.items.ItemStackHandler; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @@ -75,7 +74,7 @@ public class StockKeeperTransferHandler implements IRecipeTransferHandler result = new MutableObject<>(); if (level.isClientSide()) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> result + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> result .setValue(transferRecipeOnClient(container, recipe, recipeSlots, player, maxTransfer, doTransfer))); return result.getValue(); } @@ -98,13 +97,13 @@ public class StockKeeperTransferHandler implements IRecipeTransferHandler craftingSlots = new ArrayList<>(); for (int i = 0; i < outputDummy.getContainerSize(); i++) craftingSlots.add(new Slot(outputDummy, i, 0, 0)); List stacksByCount = summary.getStacksByCount(); - Container inputDummy = new RecipeWrapper(new ItemStackHandler(stacksByCount.size())); + Container inputDummy = new LegacyRecipeWrapper(new ItemStackHandler(stacksByCount.size())); Map availableItemStacks = new HashMap<>(); for (int j = 0; j < stacksByCount.size(); j++) { BigItemStack bigItemStack = stacksByCount.get(j); diff --git a/src/main/java/com/simibubi/create/compat/jei/ToolboxColoringRecipeMaker.java b/src/main/java/com/simibubi/create/compat/jei/ToolboxColoringRecipeMaker.java index 3c1f4dd387..c504122ba9 100644 --- a/src/main/java/com/simibubi/create/compat/jei/ToolboxColoringRecipeMaker.java +++ b/src/main/java/com/simibubi/create/compat/jei/ToolboxColoringRecipeMaker.java @@ -3,7 +3,6 @@ package com.simibubi.create.compat.jei; import com.simibubi.create.AllBlocks; import com.simibubi.create.Create; import net.minecraft.core.NonNullList; -import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.DyeItem; @@ -12,6 +11,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.ShapelessRecipe; import net.minecraft.world.level.block.Block; @@ -21,7 +21,7 @@ import java.util.stream.Stream; public final class ToolboxColoringRecipeMaker { // From JEI's ShulkerBoxColoringRecipeMaker - public static Stream createRecipes() { + public static Stream> createRecipes() { String group = "create.toolbox.color"; ItemStack baseShulkerStack = AllBlocks.TOOLBOXES.get(DyeColor.BROWN) .asStack(); @@ -42,8 +42,8 @@ public final class ToolboxColoringRecipeMaker { Block coloredShulkerBox = AllBlocks.TOOLBOXES.get(color) .get(); ItemStack output = new ItemStack(coloredShulkerBox); - ResourceLocation id = Create.asResource(group + "." + output.getDescriptionId()); - return new ShapelessRecipe(id, group, CraftingBookCategory.MISC, output, inputs); + ShapelessRecipe recipe = new ShapelessRecipe(group, CraftingBookCategory.MISC, output, inputs); + return new RecipeHolder<>(Create.asResource(group + "/" + color), recipe); }); } diff --git a/src/main/java/com/simibubi/create/compat/jei/category/BasinCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/BasinCategory.java index 25ec83c525..dbfeefe2fa 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/BasinCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/BasinCategory.java @@ -10,9 +10,10 @@ import com.simibubi.create.foundation.fluid.FluidIngredient; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.item.ItemHelper; import com.simibubi.create.foundation.utility.CreateLang; -import mezz.jei.api.forge.ForgeTypes; + import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import net.createmod.catnip.utility.Pair; @@ -20,7 +21,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; import org.apache.commons.lang3.mutable.MutableInt; import javax.annotation.ParametersAreNonnullByDefault; @@ -63,7 +64,7 @@ public class BasinCategory extends CreateRecipeCategory { builder .addSlot(RecipeIngredientRole.INPUT, 17 + xOffset + (i % 3) * 19, 51 - (i / 3) * 19) .setBackground(getRenderedSlot(), -1, -1) - .addIngredients(ForgeTypes.FLUID_STACK, withImprovedVisibility(fluidIngredient.getMatchingFluidStacks())) + .addIngredients(NeoForgeTypes.FLUID_STACK, withImprovedVisibility(fluidIngredient.getMatchingFluidStacks())) .addTooltipCallback(addFluidTooltip(fluidIngredient.getRequiredAmount())); i++; } @@ -90,7 +91,7 @@ public class BasinCategory extends CreateRecipeCategory { builder .addSlot(RecipeIngredientRole.OUTPUT, xPosition, yPosition) .setBackground(getRenderedSlot(), -1, -1) - .addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(fluidResult)) + .addIngredient(NeoForgeTypes.FLUID_STACK, withImprovedVisibility(fluidResult)) .addTooltipCallback(addFluidTooltip(fluidResult.getAmount())); i++; } diff --git a/src/main/java/com/simibubi/create/compat/jei/category/BlockCuttingCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/BlockCuttingCategory.java index d5c53cd804..0987069ffc 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/BlockCuttingCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/BlockCuttingCategory.java @@ -9,10 +9,9 @@ import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.StonecutterRecipe; import javax.annotation.ParametersAreNonnullByDefault; @@ -63,7 +62,7 @@ public class BlockCuttingCategory extends CreateRecipeCategory outputs = new ArrayList<>(); public CondensedBlockCuttingRecipe(Ingredient ingredient) { - super(new ResourceLocation(""), "", ingredient, ItemStack.EMPTY); + super("", ingredient, ItemStack.EMPTY); } public void addOutput(ItemStack stack) { @@ -98,19 +97,19 @@ public class BlockCuttingCategory extends CreateRecipeCategory condenseRecipes(List> stoneCuttingRecipes) { - List condensed = new ArrayList<>(); - Recipes: for (Recipe recipe : stoneCuttingRecipes) { - Ingredient i1 = recipe.getIngredients().get(0); - for (CondensedBlockCuttingRecipe condensedRecipe : condensed) { - if (ItemHelper.matchIngredients(i1, condensedRecipe.getIngredients().get(0))) { - condensedRecipe.addOutput(getResultItem(recipe)); + public static List> condenseRecipes(List> stoneCuttingRecipes) { + List> condensed = new ArrayList<>(); + Recipes: for (RecipeHolder recipe : stoneCuttingRecipes) { + Ingredient i1 = recipe.value().getIngredients().get(0); + for (RecipeHolder condensedRecipe : condensed) { + if (ItemHelper.matchIngredients(i1, condensedRecipe.value().getIngredients().get(0))) { + condensedRecipe.value().addOutput(getResultItem(recipe.value())); continue Recipes; } } CondensedBlockCuttingRecipe cr = new CondensedBlockCuttingRecipe(i1); - cr.addOutput(getResultItem(recipe)); - condensed.add(cr); + cr.addOutput(getResultItem(recipe.value())); + condensed.add(new RecipeHolder<>(recipe.id(), cr)); } return condensed; } diff --git a/src/main/java/com/simibubi/create/compat/jei/category/CreateRecipeCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/CreateRecipeCategory.java index 1ba9b1aa12..1a4fccf7e4 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/CreateRecipeCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/CreateRecipeCategory.java @@ -5,9 +5,10 @@ import com.simibubi.create.content.fluids.potion.PotionFluidHandler; import com.simibubi.create.content.processing.recipe.ProcessingOutput; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.utility.CreateLang; -import mezz.jei.api.forge.ForgeTypes; + import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.ingredient.IRecipeSlotTooltipCallback; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.RecipeType; import mezz.jei.api.recipe.category.IRecipeCategory; import mezz.jei.api.registration.IRecipeCatalystRegistration; @@ -21,7 +22,8 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.network.chat.Component; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; -import net.minecraftforge.fluids.FluidStack; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.neoforged.neoforge.fluids.FluidStack; import org.jetbrains.annotations.NotNull; import javax.annotation.ParametersAreNonnullByDefault; @@ -42,7 +44,7 @@ public abstract class CreateRecipeCategory> implements IReci protected final IDrawable background; protected final IDrawable icon; - private final Supplier> recipes; + private final Supplier>> recipes; private final List> catalysts; public CreateRecipeCategory(Info info) { @@ -76,7 +78,7 @@ public abstract class CreateRecipeCategory> implements IReci } public void registerRecipes(IRecipeRegistration registration) { - registration.addRecipes(type, recipes.get()); + registration.addRecipes(type, recipes.get().stream().map(RecipeHolder::value).toList()); } public void registerCatalysts(IRecipeCatalystRegistration registration) { @@ -133,14 +135,14 @@ public abstract class CreateRecipeCategory> implements IReci public static IRecipeSlotTooltipCallback addFluidTooltip(int mbAmount) { return (view, tooltip) -> { - Optional displayed = view.getDisplayedIngredient(ForgeTypes.FLUID_STACK); + Optional displayed = view.getDisplayedIngredient(NeoForgeTypes.FLUID_STACK); if (displayed.isEmpty()) return; FluidStack fluidStack = displayed.get(); if (fluidStack.getFluid().isSame(AllFluids.POTION.get())) { - Component name = fluidStack.getDisplayName(); + Component name = fluidStack.getHoverName(); if (tooltip.isEmpty()) tooltip.add(0, name); else @@ -182,7 +184,7 @@ public abstract class CreateRecipeCategory> implements IReci }; } - public record Info>(RecipeType recipeType, Component title, IDrawable background, IDrawable icon, Supplier> recipes, List> catalysts) { + public record Info>(RecipeType recipeType, Component title, IDrawable background, IDrawable icon, Supplier>> recipes, List> catalysts) { } public interface Factory> { diff --git a/src/main/java/com/simibubi/create/compat/jei/category/ItemDrainCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/ItemDrainCategory.java index 28751fa9e1..404a5b960a 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/ItemDrainCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/ItemDrainCategory.java @@ -12,23 +12,23 @@ import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder; import com.simibubi.create.foundation.gui.AllGuiTextures; import mezz.jei.api.constants.VanillaTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.runtime.IIngredientManager; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler.FluidAction; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; @ParametersAreNonnullByDefault public class ItemDrainCategory extends CreateRecipeCategory { @@ -39,44 +39,46 @@ public class ItemDrainCategory extends CreateRecipeCategory { super(info); } - public static void consumeRecipes(Consumer consumer, IIngredientManager ingredientManager) { + public static void consumeRecipes(Consumer> consumer, IIngredientManager ingredientManager) { for (ItemStack stack : ingredientManager.getAllIngredients(VanillaTypes.ITEM_STACK)) { if (PotionFluidHandler.isPotionItem(stack)) { FluidStack fluidFromPotionItem = PotionFluidHandler.getFluidFromPotionItem(stack); Ingredient potion = Ingredient.of(stack); - consumer.accept(new ProcessingRecipeBuilder<>(EmptyingRecipe::new, Create.asResource("potions")) - .withItemIngredients(potion) - .withFluidOutputs(fluidFromPotionItem) - .withSingleItemOutput(new ItemStack(Items.GLASS_BOTTLE)) - .build()); + ResourceLocation id = Create.asResource("potions"); + EmptyingRecipe recipe = new ProcessingRecipeBuilder<>(EmptyingRecipe::new, id) + .withItemIngredients(potion) + .withFluidOutputs(fluidFromPotionItem) + .withSingleItemOutput(new ItemStack(Items.GLASS_BOTTLE)) + .build(); + consumer.accept(new RecipeHolder<>(id, recipe)); continue; } - LazyOptional capability = - stack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM); - if (!capability.isPresent()) + IFluidHandlerItem capability = stack.getCapability(Capabilities.FluidHandler.ITEM); + if (capability == null) continue; ItemStack copy = stack.copy(); - capability = copy.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM); - IFluidHandlerItem handler = capability.orElse(null); - FluidStack extracted = handler.drain(1000, FluidAction.EXECUTE); - ItemStack result = handler.getContainer(); + capability = copy.getCapability(Capabilities.FluidHandler.ITEM); + FluidStack extracted = capability.drain(1000, FluidAction.EXECUTE); + ItemStack result = capability.getContainer(); if (extracted.isEmpty()) continue; if (result.isEmpty()) continue; Ingredient ingredient = Ingredient.of(stack); - ResourceLocation itemName = CatnipServices.REGISTRIES.getKeyOrThrow(stack.getItem()); - ResourceLocation fluidName = CatnipServices.REGISTRIES.getKeyOrThrow(extracted.getFluid()); + ResourceLocation itemName = RegisteredObjectsHelper.getKeyOrThrow(stack.getItem()); + ResourceLocation fluidName = RegisteredObjectsHelper.getKeyOrThrow(extracted.getFluid()); - consumer.accept(new ProcessingRecipeBuilder<>(EmptyingRecipe::new, - Create.asResource("empty_" + itemName.getNamespace() + "_" + itemName.getPath() + "_of_" - + fluidName.getNamespace() + "_" + fluidName.getPath())).withItemIngredients(ingredient) - .withFluidOutputs(extracted) - .withSingleItemOutput(result) - .build()); + ResourceLocation id = Create.asResource("empty_" + itemName.getNamespace() + "_" + itemName.getPath() + "_of_" + + fluidName.getNamespace() + "_" + fluidName.getPath()); + EmptyingRecipe recipe = new ProcessingRecipeBuilder<>(EmptyingRecipe::new, id) + .withItemIngredients(ingredient) + .withFluidOutputs(extracted) + .withSingleItemOutput(result) + .build(); + consumer.accept(new RecipeHolder<>(id, recipe)); } } @@ -89,7 +91,7 @@ public class ItemDrainCategory extends CreateRecipeCategory { builder .addSlot(RecipeIngredientRole.OUTPUT, 132, 8) .setBackground(getRenderedSlot(), -1, -1) - .addIngredient(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getResultingFluid())) + .addIngredient(NeoForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getResultingFluid())) .addTooltipCallback(addFluidTooltip(recipe.getResultingFluid().getAmount())); builder .addSlot(RecipeIngredientRole.OUTPUT, 132, 27) diff --git a/src/main/java/com/simibubi/create/compat/jei/category/MechanicalCraftingCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/MechanicalCraftingCategory.java index 8a8e5b28f1..8df4ee73b7 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/MechanicalCraftingCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/MechanicalCraftingCategory.java @@ -5,6 +5,10 @@ import java.util.List; import javax.annotation.ParametersAreNonnullByDefault; +import net.minecraft.world.item.Item; + +import net.minecraft.world.item.crafting.ShapedRecipe; + import org.jetbrains.annotations.NotNull; import com.mojang.blaze3d.systems.RenderSystem; @@ -30,7 +34,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.crafting.IShapedRecipe; + +import org.joml.Matrix4fStack; @ParametersAreNonnullByDefault public class MechanicalCraftingCategory extends CreateRecipeCategory { @@ -84,11 +89,11 @@ public class MechanicalCraftingCategory extends CreateRecipeCategory ? ((IShapedRecipe) recipe).getRecipeWidth() : 1; + return recipe instanceof ShapedRecipe ? ((ShapedRecipe) recipe).getWidth() : 1; } private static int getHeight(CraftingRecipe recipe) { - return recipe instanceof IShapedRecipe ? ((IShapedRecipe) recipe).getRecipeHeight() : 1; + return recipe instanceof ShapedRecipe ? ((ShapedRecipe) recipe).getHeight() : 1; } @Override @@ -154,8 +159,8 @@ public class MechanicalCraftingCategory extends CreateRecipeCategory list = new ArrayList<>(); MutableComponent crash = Components.translatable("jei.tooltip.error.crash"); diff --git a/src/main/java/com/simibubi/create/compat/jei/category/MysteriousItemConversionCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/MysteriousItemConversionCategory.java index 55764361b5..f4a19a2c83 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/MysteriousItemConversionCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/MysteriousItemConversionCategory.java @@ -9,6 +9,7 @@ import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.world.item.crafting.RecipeHolder; import javax.annotation.ParametersAreNonnullByDefault; import java.util.ArrayList; @@ -17,7 +18,7 @@ import java.util.List; @ParametersAreNonnullByDefault public class MysteriousItemConversionCategory extends CreateRecipeCategory { - public static final List RECIPES = new ArrayList<>(); + public static final List> RECIPES = new ArrayList<>(); static { RECIPES.add(ConversionRecipe.create(AllItems.EMPTY_BLAZE_BURNER.asStack(), AllBlocks.BLAZE_BURNER.asStack())); diff --git a/src/main/java/com/simibubi/create/compat/jei/category/PolishingCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/PolishingCategory.java index ba60e6b95d..812f2ba0b2 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/PolishingCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/PolishingCategory.java @@ -1,5 +1,6 @@ package com.simibubi.create.compat.jei.category; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllItems; import com.simibubi.create.content.equipment.sandPaper.SandPaperPolishingRecipe; import com.simibubi.create.content.processing.recipe.ProcessingOutput; @@ -11,7 +12,7 @@ import mezz.jei.api.recipe.RecipeIngredientRole; import net.createmod.catnip.gui.element.GuiGameElement; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.util.Unit; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -53,10 +54,8 @@ public class PolishingCategory extends CreateRecipeCategoryat(getBackground().getWidth() / 2 - 16, 0, 0) .scale(2) diff --git a/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java index bf7c7f5120..6d704054a3 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java @@ -14,6 +14,7 @@ import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; @@ -31,8 +32,9 @@ public abstract class ProcessingViaFanCategory> extends Crea } public static Supplier getFan(String name) { - return () -> AllBlocks.ENCASED_FAN.asStack() - .setHoverName(CreateLang.translateDirect("recipe." + name + ".fan").withStyle(style -> style.withItalic(false))); + ItemStack stack = AllBlocks.ENCASED_FAN.asStack(); + stack.set(DataComponents.CUSTOM_NAME, CreateLang.translateDirect("recipe." + name + ".fan").withStyle(style -> style.withItalic(false))); + return () -> stack; } @Override diff --git a/src/main/java/com/simibubi/create/compat/jei/category/SequencedAssemblyCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/SequencedAssemblyCategory.java index 20945896b0..8c173cb8bc 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/SequencedAssemblyCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/SequencedAssemblyCategory.java @@ -1,5 +1,14 @@ package com.simibubi.create.compat.jei.category; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.ParametersAreNonnullByDefault; + +import org.jetbrains.annotations.NotNull; + import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.compat.jei.category.sequencedAssembly.SequencedAssemblySubCategory; import com.simibubi.create.content.processing.sequenced.SequencedAssemblyRecipe; @@ -7,11 +16,12 @@ import com.simibubi.create.content.processing.sequenced.SequencedRecipe; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.gui.AllIcons; import com.simibubi.create.foundation.utility.CreateLang; + import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.createmod.catnip.utility.lang.Components; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; @@ -20,13 +30,6 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.NotNull; - -import javax.annotation.ParametersAreNonnullByDefault; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; @ParametersAreNonnullByDefault public class SequencedAssemblyCategory extends CreateRecipeCategory { @@ -73,7 +76,7 @@ public class SequencedAssemblyCategory extends CreateRecipeCategory sequencedRecipe) { - return subCategories.computeIfAbsent(CatnipServices.REGISTRIES.getKeyOrThrow(sequencedRecipe.getRecipe() + return subCategories.computeIfAbsent(RegisteredObjectsHelper.getKeyOrThrow(sequencedRecipe.getRecipe() .getSerializer()), rl -> sequencedRecipe.getAsAssemblyRecipe() .getJEISubCategory() diff --git a/src/main/java/com/simibubi/create/compat/jei/category/SpoutCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/SpoutCategory.java index 88f1cb2932..d7423e5258 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/SpoutCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/SpoutCategory.java @@ -16,23 +16,23 @@ import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.item.ItemHelper; import mezz.jei.api.constants.VanillaTypes; -import mezz.jei.api.forge.ForgeTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.ingredient.IRecipeSlotsView; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.runtime.IIngredientManager; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler.FluidAction; +import net.neoforged.neoforge.fluids.capability.IFluidHandlerItem; @ParametersAreNonnullByDefault public class SpoutCategory extends CreateRecipeCategory { @@ -43,51 +43,53 @@ public class SpoutCategory extends CreateRecipeCategory { super(info); } - public static void consumeRecipes(Consumer consumer, IIngredientManager ingredientManager) { - Collection fluidStacks = ingredientManager.getAllIngredients(ForgeTypes.FLUID_STACK); + public static void consumeRecipes(Consumer> consumer, IIngredientManager ingredientManager) { + Collection fluidStacks = ingredientManager.getAllIngredients(NeoForgeTypes.FLUID_STACK); for (ItemStack stack : ingredientManager.getAllIngredients(VanillaTypes.ITEM_STACK)) { if (PotionFluidHandler.isPotionItem(stack)) { FluidStack fluidFromPotionItem = PotionFluidHandler.getFluidFromPotionItem(stack); Ingredient bottle = Ingredient.of(Items.GLASS_BOTTLE); - consumer.accept(new ProcessingRecipeBuilder<>(FillingRecipe::new, Create.asResource("potions")) - .withItemIngredients(bottle) - .withFluidIngredients(FluidIngredient.fromFluidStack(fluidFromPotionItem)) - .withSingleItemOutput(stack) - .build()); + ResourceLocation id = Create.asResource("potions"); + FillingRecipe recipe = new ProcessingRecipeBuilder<>(FillingRecipe::new, id) + .withItemIngredients(bottle) + .withFluidIngredients(FluidIngredient.fromFluidStack(fluidFromPotionItem)) + .withSingleItemOutput(stack) + .build(); + consumer.accept(new RecipeHolder<>(id, recipe)); continue; } - LazyOptional capability = - stack.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM); - if (!capability.isPresent()) + IFluidHandlerItem capability = stack.getCapability(Capabilities.FluidHandler.ITEM); + if (capability == null) continue; for (FluidStack fluidStack : fluidStacks) { ItemStack copy = stack.copy(); - copy.getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM) - .ifPresent(fhi -> { - if (!GenericItemFilling.isFluidHandlerValid(copy, fhi)) - return; - FluidStack fluidCopy = fluidStack.copy(); - fluidCopy.setAmount(1000); - fhi.fill(fluidCopy, FluidAction.EXECUTE); - ItemStack container = fhi.getContainer(); - if (ItemHelper.sameItem(container, copy)) - return; - if (container.isEmpty()) - return; + IFluidHandlerItem fhi = copy.getCapability(Capabilities.FluidHandler.ITEM); + if (fhi != null) { + if (!GenericItemFilling.isFluidHandlerValid(copy, fhi)) + return; + FluidStack fluidCopy = fluidStack.copy(); + fluidCopy.setAmount(1000); + fhi.fill(fluidCopy, FluidAction.EXECUTE); + ItemStack container = fhi.getContainer(); + if (ItemHelper.sameItem(container, copy)) + return; + if (container.isEmpty()) + return; - Ingredient bucket = Ingredient.of(stack); - ResourceLocation itemName = CatnipServices.REGISTRIES.getKeyOrThrow(stack.getItem()); - ResourceLocation fluidName = CatnipServices.REGISTRIES.getKeyOrThrow(fluidCopy.getFluid()); - consumer.accept(new ProcessingRecipeBuilder<>(FillingRecipe::new, - Create.asResource("fill_" + itemName.getNamespace() + "_" + itemName.getPath() - + "_with_" + fluidName.getNamespace() + "_" + fluidName.getPath())) - .withItemIngredients(bucket) - .withFluidIngredients(FluidIngredient.fromFluidStack(fluidCopy)) - .withSingleItemOutput(container) - .build()); - }); + Ingredient bucket = Ingredient.of(stack); + ResourceLocation itemName = RegisteredObjectsHelper.getKeyOrThrow(stack.getItem()); + ResourceLocation fluidName = RegisteredObjectsHelper.getKeyOrThrow(fluidCopy.getFluid()); + ResourceLocation id = Create.asResource("fill_" + itemName.getNamespace() + "_" + itemName.getPath() + + "_with_" + fluidName.getNamespace() + "_" + fluidName.getPath()); + FillingRecipe recipe = new ProcessingRecipeBuilder<>(FillingRecipe::new, id) + .withItemIngredients(bucket) + .withFluidIngredients(FluidIngredient.fromFluidStack(fluidCopy)) + .withSingleItemOutput(container) + .build(); + consumer.accept(new RecipeHolder<>(id, recipe)); + } } } } @@ -101,7 +103,7 @@ public class SpoutCategory extends CreateRecipeCategory { builder .addSlot(RecipeIngredientRole.INPUT, 27, 32) .setBackground(getRenderedSlot(), -1, -1) - .addIngredients(ForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getRequiredFluid().getMatchingFluidStacks())) + .addIngredients(NeoForgeTypes.FLUID_STACK, withImprovedVisibility(recipe.getRequiredFluid().getMatchingFluidStacks())) .addTooltipCallback(addFluidTooltip(recipe.getRequiredFluid().getRequiredAmount())); builder .addSlot(RecipeIngredientRole.OUTPUT, 132, 51) diff --git a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedItemDrain.java b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedItemDrain.java index 7c9d97818b..b20ba3f9af 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedItemDrain.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedItemDrain.java @@ -1,16 +1,13 @@ package com.simibubi.create.compat.jei.category.animations; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.math.Axis; import com.simibubi.create.AllBlocks; import com.simibubi.create.foundation.fluid.FluidRenderer; import net.createmod.catnip.gui.UIRenderHelper; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.MultiBufferSource.BufferSource; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidStack; public class AnimatedItemDrain extends AnimatedKinetics { @@ -34,14 +31,12 @@ public class AnimatedItemDrain extends AnimatedKinetics { .scale(scale) .render(graphics); - BufferSource buffer = MultiBufferSource.immediate(Tesselator.getInstance() - .getBuilder()); UIRenderHelper.flipForGuiRender(matrixStack); matrixStack.scale(scale, scale, scale); float from = 2/16f; float to = 1f - from; - FluidRenderer.renderFluidBox(fluid.getFluid(), fluid.getAmount(), from, from, from, to, 3/4f, to, buffer, matrixStack, LightTexture.FULL_BRIGHT, false, true, fluid.getTag()); - buffer.endBatch(); + FluidRenderer.renderFluidBox(fluid.getFluid(), fluid.getAmount(), from, from, from, to, 3/4f, to, graphics.bufferSource(), matrixStack, LightTexture.FULL_BRIGHT, false, true, fluid.getComponents()); + graphics.flush(); matrixStack.popPose(); } diff --git a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java index 45b6d0314b..2698035c72 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java @@ -18,8 +18,8 @@ public abstract class AnimatedKinetics implements IDrawable { public int offset = 0; public static final ILightingSettings DEFAULT_LIGHTING = CustomLightingSettings.builder() - .firstLightRotation(12.5f, 45.0f) - .secondLightRotation(-20.0f, 50.0f) + .firstLightRotation(12.5f, -45.0f) + .secondLightRotation(-20.0f, -50.0f) .build(); /** diff --git a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedSpout.java b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedSpout.java index 31301e369a..f52c3417e8 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedSpout.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedSpout.java @@ -1,22 +1,21 @@ package com.simibubi.create.compat.jei.category.animations; +import java.util.List; + import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.math.Axis; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllPartialModels; import com.simibubi.create.foundation.fluid.FluidRenderer; + import net.createmod.catnip.gui.UIRenderHelper; import net.createmod.catnip.utility.AnimationTickHolder; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.MultiBufferSource.BufferSource; import net.minecraft.util.Mth; -import net.minecraftforge.fluids.FluidStack; -import java.util.List; +import net.neoforged.neoforge.fluids.FluidStack; public class AnimatedSpout extends AnimatedKinetics { @@ -67,15 +66,13 @@ public class AnimatedSpout extends AnimatedKinetics { .render(graphics); AnimatedKinetics.DEFAULT_LIGHTING.applyLighting(); - BufferSource buffer = MultiBufferSource.immediate(Tesselator.getInstance() - .getBuilder()); matrixStack.pushPose(); UIRenderHelper.flipForGuiRender(matrixStack); matrixStack.scale(16, 16, 16); float from = 3f / 16f; float to = 17f / 16f; FluidStack fluidStack = fluids.get(0); - FluidRenderer.renderFluidBox(fluidStack.getFluid(), fluidStack.getAmount(), from, from, from, to, to, to, buffer, matrixStack, LightTexture.FULL_BRIGHT, false, true, fluidStack.getTag()); + FluidRenderer.renderFluidBox(fluidStack.getFluid(), fluidStack.getAmount(), from, from, from, to, to, to, graphics.bufferSource(), matrixStack, LightTexture.FULL_BRIGHT, false, true, fluidStack.getComponents()); matrixStack.popPose(); float width = 1 / 128f * squeeze; @@ -85,8 +82,8 @@ public class AnimatedSpout extends AnimatedKinetics { matrixStack.translate(-0.5f, 0, -0.5f); from = -width / 2 + 0.5f; to = width / 2 + 0.5f; - FluidRenderer.renderFluidBox(fluidStack.getFluid(), fluidStack.getAmount(), from, 0, from, to, 2, to, buffer, matrixStack, LightTexture.FULL_BRIGHT, false, true, fluidStack.getTag()); - buffer.endBatch(); + FluidRenderer.renderFluidBox(fluidStack.getFluid(), fluidStack.getAmount(), from, 0, from, to, 2, to, graphics.bufferSource(), matrixStack, LightTexture.FULL_BRIGHT, false, true, fluidStack.getComponents()); + graphics.flush(); Lighting.setupFor3DItems(); matrixStack.popPose(); diff --git a/src/main/java/com/simibubi/create/compat/jei/category/sequencedAssembly/SequencedAssemblySubCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/sequencedAssembly/SequencedAssemblySubCategory.java index 929151c998..db439cc7c7 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/sequencedAssembly/SequencedAssemblySubCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/sequencedAssembly/SequencedAssemblySubCategory.java @@ -10,9 +10,10 @@ import com.simibubi.create.content.kinetics.deployer.DeployerApplicationRecipe; import com.simibubi.create.content.processing.sequenced.SequencedRecipe; import com.simibubi.create.foundation.fluid.FluidIngredient; import com.simibubi.create.foundation.utility.CreateLang; -import mezz.jei.api.forge.ForgeTypes; + import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.builder.IRecipeSlotBuilder; +import mezz.jei.api.neoforge.NeoForgeTypes; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import net.minecraft.ChatFormatting; @@ -74,7 +75,7 @@ public abstract class SequencedAssemblySubCategory { builder .addSlot(RecipeIngredientRole.INPUT, x + 4, 15) .setBackground(CreateRecipeCategory.getRenderedSlot(), -1, -1) - .addIngredients(ForgeTypes.FLUID_STACK, CreateRecipeCategory.withImprovedVisibility(fluidIngredient.getMatchingFluidStacks())) + .addIngredients(NeoForgeTypes.FLUID_STACK, CreateRecipeCategory.withImprovedVisibility(fluidIngredient.getMatchingFluidStacks())) .addTooltipCallback(CreateRecipeCategory.addFluidTooltip(fluidIngredient.getRequiredAmount())); } diff --git a/src/main/java/com/simibubi/create/compat/tconstruct/SpoutCasting.java b/src/main/java/com/simibubi/create/compat/tconstruct/SpoutCasting.java index 18df35cd14..2d7fa25c3c 100644 --- a/src/main/java/com/simibubi/create/compat/tconstruct/SpoutCasting.java +++ b/src/main/java/com/simibubi/create/compat/tconstruct/SpoutCasting.java @@ -5,23 +5,24 @@ import com.simibubi.create.compat.Mods; import com.simibubi.create.content.fluids.spout.SpoutBlockEntity; import com.simibubi.create.foundation.fluid.FluidHelper; import com.simibubi.create.infrastructure.config.AllConfigs; -import net.createmod.catnip.platform.CatnipServices; + +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandler.FluidAction; public class SpoutCasting extends BlockSpoutingBehaviour { private static final boolean TICON_PRESENT = Mods.TCONSTRUCT.isLoaded(); - ResourceLocation TABLE = new ResourceLocation("tconstruct", "table"); - ResourceLocation BASIN = new ResourceLocation("tconstruct", "basin"); + ResourceLocation TABLE = ResourceLocation.fromNamespaceAndPath("tconstruct", "table"); + ResourceLocation BASIN = ResourceLocation.fromNamespaceAndPath("tconstruct", "basin"); @Override public int fillBlock(Level level, BlockPos pos, SpoutBlockEntity spout, FluidStack availableFluid, @@ -33,21 +34,20 @@ public class SpoutCasting extends BlockSpoutingBehaviour { if (blockEntity == null) return 0; - IFluidHandler handler = blockEntity.getCapability(ForgeCapabilities.FLUID_HANDLER, Direction.UP) - .orElse(null); + IFluidHandler handler = level.getCapability(Capabilities.FluidHandler.BLOCK, blockEntity.getBlockPos(), Direction.UP); if (handler == null) return 0; if (handler.getTanks() != 1) return 0; - ResourceLocation registryName = CatnipServices.REGISTRIES.getKeyOrThrow(blockEntity.getType()); + ResourceLocation registryName = RegisteredObjectsHelper.getKeyOrThrow(blockEntity.getType()); if (!registryName.equals(TABLE) && !registryName.equals(BASIN)) return 0; if (!handler.isFluidValid(0, availableFluid)) return 0; FluidStack containedFluid = handler.getFluidInTank(0); - if (!(containedFluid.isEmpty() || containedFluid.isFluidEqual(availableFluid))) + if (!(containedFluid.isEmpty() || FluidStack.isSameFluidSameComponents(containedFluid, availableFluid))) return 0; // Do not fill if it would only partially fill the table (unless > 1000mb) diff --git a/src/main/java/com/simibubi/create/compat/thresholdSwitch/FunctionalStorage.java b/src/main/java/com/simibubi/create/compat/thresholdSwitch/FunctionalStorage.java index 4441b2f022..f14ac1a4d0 100644 --- a/src/main/java/com/simibubi/create/compat/thresholdSwitch/FunctionalStorage.java +++ b/src/main/java/com/simibubi/create/compat/thresholdSwitch/FunctionalStorage.java @@ -2,16 +2,16 @@ package com.simibubi.create.compat.thresholdSwitch; import com.simibubi.create.compat.Mods; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; public class FunctionalStorage implements ThresholdSwitchCompat { @Override public boolean isFromThisMod(BlockEntity blockEntity) { return blockEntity != null && Mods.FUNCTIONALSTORAGE.id() - .equals(CatnipServices.REGISTRIES.getKeyOrThrow(blockEntity.getType()) + .equals(RegisteredObjectsHelper.getKeyOrThrow(blockEntity.getType()) .getNamespace()); } diff --git a/src/main/java/com/simibubi/create/compat/thresholdSwitch/SophisticatedStorage.java b/src/main/java/com/simibubi/create/compat/thresholdSwitch/SophisticatedStorage.java index 7638c9a801..4b949d88e1 100644 --- a/src/main/java/com/simibubi/create/compat/thresholdSwitch/SophisticatedStorage.java +++ b/src/main/java/com/simibubi/create/compat/thresholdSwitch/SophisticatedStorage.java @@ -2,9 +2,10 @@ package com.simibubi.create.compat.thresholdSwitch; import com.simibubi.create.compat.Mods; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; public class SophisticatedStorage implements ThresholdSwitchCompat { @@ -13,7 +14,7 @@ public class SophisticatedStorage implements ThresholdSwitchCompat { if (be == null) return false; - String namespace = CatnipServices.REGISTRIES.getKeyOrThrow(be.getType()) + String namespace = RegisteredObjectsHelper.getKeyOrThrow(be.getType()) .getNamespace(); return @@ -23,7 +24,7 @@ public class SophisticatedStorage implements ThresholdSwitchCompat { @Override public long getSpaceInSlot(IItemHandler inv, int slot) { - return ((long) inv.getSlotLimit(slot) * inv.getStackInSlot(slot).getMaxStackSize()) / 64; + return ((long) inv.getSlotLimit(slot) * inv.getStackInSlot(slot).getOrDefault(DataComponents.MAX_STACK_SIZE, 64)) / 64; } } diff --git a/src/main/java/com/simibubi/create/compat/thresholdSwitch/StorageDrawers.java b/src/main/java/com/simibubi/create/compat/thresholdSwitch/StorageDrawers.java index 0932ef6031..22b8eec494 100644 --- a/src/main/java/com/simibubi/create/compat/thresholdSwitch/StorageDrawers.java +++ b/src/main/java/com/simibubi/create/compat/thresholdSwitch/StorageDrawers.java @@ -2,16 +2,16 @@ package com.simibubi.create.compat.thresholdSwitch; import com.simibubi.create.compat.Mods; -import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; public class StorageDrawers implements ThresholdSwitchCompat { @Override public boolean isFromThisMod(BlockEntity blockEntity) { return blockEntity != null && Mods.STORAGEDRAWERS.id() - .equals(CatnipServices.REGISTRIES.getKeyOrThrow(blockEntity.getType()) + .equals(RegisteredObjectsHelper.getKeyOrThrow(blockEntity.getType()) .getNamespace()); } diff --git a/src/main/java/com/simibubi/create/compat/thresholdSwitch/ThresholdSwitchCompat.java b/src/main/java/com/simibubi/create/compat/thresholdSwitch/ThresholdSwitchCompat.java index 841769c34d..9f66a302b6 100644 --- a/src/main/java/com/simibubi/create/compat/thresholdSwitch/ThresholdSwitchCompat.java +++ b/src/main/java/com/simibubi/create/compat/thresholdSwitch/ThresholdSwitchCompat.java @@ -1,7 +1,7 @@ package com.simibubi.create.compat.thresholdSwitch; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandler; public interface ThresholdSwitchCompat { diff --git a/src/main/java/com/simibubi/create/compat/trainmap/FTBChunksTrainMap.java b/src/main/java/com/simibubi/create/compat/trainmap/FTBChunksTrainMap.java index a1285a3d9f..f74b55c82d 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/FTBChunksTrainMap.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/FTBChunksTrainMap.java @@ -17,10 +17,10 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.renderer.Rect2i; import net.minecraft.network.chat.FormattedText; import net.minecraft.util.Mth; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.client.event.ScreenEvent; -import net.minecraftforge.fml.util.ObfuscationReflectionHelper; +import net.neoforged.fml.util.ObfuscationReflectionHelper; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.client.event.RenderTooltipEvent; +import net.neoforged.neoforge.client.event.ScreenEvent; public class FTBChunksTrainMap { diff --git a/src/main/java/com/simibubi/create/compat/trainmap/JourneyTrainMap.java b/src/main/java/com/simibubi/create/compat/trainmap/JourneyTrainMap.java index e05b26c369..6fabbbefea 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/JourneyTrainMap.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/JourneyTrainMap.java @@ -8,15 +8,15 @@ import com.simibubi.create.foundation.gui.RemovedGuiUtils; import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.infrastructure.config.AllConfigs; -import journeymap.client.api.display.Context.UI; -import journeymap.client.api.util.UIState; +import journeymap.api.v2.client.display.Context; +import journeymap.api.v2.client.util.UIState; import journeymap.client.ui.fullscreen.Fullscreen; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.renderer.Rect2i; import net.minecraft.network.chat.FormattedText; import net.minecraft.util.Mth; -import net.minecraftforge.client.event.InputEvent; +import net.neoforged.neoforge.client.event.InputEvent; public class JourneyTrainMap { @@ -52,7 +52,7 @@ public class JourneyTrainMap { UIState state = screen.getUiState(); if (state == null) return; - if (state.ui != UI.Fullscreen) + if (state.ui != Context.UI.Fullscreen) return; if (!state.active) return; diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapEvents.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapEvents.java index 54f2adb197..028b57cead 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapEvents.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapEvents.java @@ -4,53 +4,50 @@ import com.mojang.blaze3d.platform.InputConstants; import com.simibubi.create.compat.Mods; import net.minecraft.client.Minecraft; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.client.event.ScreenEvent; -import net.minecraftforge.event.TickEvent.ClientTickEvent; -import net.minecraftforge.event.TickEvent.Phase; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.client.event.RenderTooltipEvent; +import net.neoforged.neoforge.client.event.ScreenEvent; @EventBusSubscriber(value = Dist.CLIENT) public class TrainMapEvents { @SubscribeEvent - public static void tick(ClientTickEvent event) { - if (event.phase == Phase.START) - return; + public static void tick(ClientTickEvent.Post event) { Minecraft mc = Minecraft.getInstance(); if (mc.level == null) return; - + if (Mods.FTBCHUNKS.isLoaded()) FTBChunksTrainMap.tick(); if (Mods.JOURNEYMAP.isLoaded()) JourneyTrainMap.tick(); } - + @SubscribeEvent public static void mouseClick(InputEvent.MouseButton.Pre event) { if (event.getAction() != InputConstants.PRESS) return; - + if (Mods.FTBCHUNKS.isLoaded()) FTBChunksTrainMap.mouseClick(event); if (Mods.JOURNEYMAP.isLoaded()) JourneyTrainMap.mouseClick(event); } - + @SubscribeEvent public static void cancelTooltips(RenderTooltipEvent.Pre event) { if (Mods.FTBCHUNKS.isLoaded()) FTBChunksTrainMap.cancelTooltips(event); } - + @SubscribeEvent public static void renderGui(ScreenEvent.Render.Post event) { if (Mods.FTBCHUNKS.isLoaded()) FTBChunksTrainMap.renderGui(event); } - + } diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapManager.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapManager.java index 76f19b08e2..3ebb3272c8 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapManager.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapManager.java @@ -136,8 +136,8 @@ public class TrainMapManager { if (!trainEntry.ownerName.isBlank()) CreateLang.translate("train_map.train_owned_by", trainEntry.ownerName) - .color(blue) - .addTo(output); + .color(blue) + .addTo(output); switch (state) { @@ -178,12 +178,12 @@ public class TrainMapManager { if (!currentStation.isBlank()) { if (targetStationDistance == 0) CreateLang.translate("train_map.train_at_station", currentStation) - .color(darkBlue) - .addTo(output); + .color(darkBlue) + .addTo(output); else CreateLang.translate("train_map.train_moving_to_station", currentStation, targetStationDistance) - .color(darkBlue) - .addTo(output); + .color(darkBlue) + .addTo(output); } if (signalState != SignalState.NOT_WAITING) { @@ -204,12 +204,13 @@ public class TrainMapManager { Train trainWaitingFor = CreateClient.RAILWAYS.trains.get(waitingFor); if (trainWaitingFor != null) { CreateLang.translate("train_map.for_other_train", trainWaitingFor.name.getString()) - .color(blue) - .addTo(output); + .color(blue) + .addTo(output); trainFound = true; } } + if (!trainFound) { if (chainSignal) CreateLang.translate("train_map.cannot_traverse_section") diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapRenderer.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapRenderer.java index 6cc613bbf9..617d75b7ae 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapRenderer.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapRenderer.java @@ -229,26 +229,22 @@ public class TrainMapRenderer implements AutoCloseable { Matrix4f matrix4f = pPoseStack.last() .pose(); VertexConsumer vertexconsumer = pBufferSource.getBuffer(renderType); - vertexconsumer.vertex(matrix4f, 0.0F, HEIGHT, 0) - .color(255, 255, 255, 255) - .uv(0.0F, 1.0F) - .uv2(pPackedLight) - .endVertex(); - vertexconsumer.vertex(matrix4f, WIDTH, HEIGHT, 0) - .color(255, 255, 255, 255) - .uv(1.0F, 1.0F) - .uv2(pPackedLight) - .endVertex(); - vertexconsumer.vertex(matrix4f, WIDTH, 0.0F, 0) - .color(255, 255, 255, 255) - .uv(1.0F, 0.0F) - .uv2(pPackedLight) - .endVertex(); - vertexconsumer.vertex(matrix4f, 0.0F, 0.0F, 0) - .color(255, 255, 255, 255) - .uv(0.0F, 0.0F) - .uv2(pPackedLight) - .endVertex(); + vertexconsumer.addVertex(matrix4f, 0.0F, HEIGHT, 0) + .setColor(255, 255, 255, 255) + .setUv(0.0F, 1.0F) + .setLight(pPackedLight); + vertexconsumer.addVertex(matrix4f, WIDTH, HEIGHT, 0) + .setColor(255, 255, 255, 255) + .setUv(1.0F, 1.0F) + .setLight(pPackedLight); + vertexconsumer.addVertex(matrix4f, WIDTH, 0.0F, 0) + .setColor(255, 255, 255, 255) + .setUv(1.0F, 0.0F) + .setLight(pPackedLight); + vertexconsumer.addVertex(matrix4f, 0.0F, 0.0F, 0) + .setColor(255, 255, 255, 255) + .setUv(0.0F, 0.0F) + .setLight(pPackedLight); } public void close() { diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSync.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSync.java index d58fea1fd1..88c16d07a9 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSync.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSync.java @@ -6,13 +6,12 @@ import java.util.List; import java.util.UUID; import com.google.common.cache.Cache; -import com.simibubi.create.AllPackets; +import com.google.common.cache.CacheBuilder; import com.simibubi.create.Create; import com.simibubi.create.content.trains.entity.Carriage; import com.simibubi.create.content.trains.entity.Carriage.DimensionalCarriageEntity; import com.simibubi.create.content.trains.entity.Train; import com.simibubi.create.content.trains.entity.TravellingPoint; -import com.simibubi.create.content.trains.graph.DimensionPalette; import com.simibubi.create.content.trains.graph.EdgePointType; import com.simibubi.create.content.trains.schedule.ScheduleRuntime; import com.simibubi.create.content.trains.signal.SignalBlock.SignalType; @@ -21,16 +20,23 @@ import com.simibubi.create.content.trains.signal.SignalEdgeGroup; import com.simibubi.create.content.trains.station.GlobalStation; import com.simibubi.create.foundation.utility.TickBasedCache; +import io.netty.buffer.ByteBuf; +import net.createmod.catnip.codecs.stream.CatnipLargerStreamCodecs; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Pair; +import net.minecraft.core.UUIDUtil; +import net.minecraft.core.registries.Registries; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.event.TickEvent.ServerTickEvent; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.event.tick.ServerTickEvent; public class TrainMapSync { @@ -40,21 +46,38 @@ public class TrainMapSync { public static int ticks; public enum TrainState { - RUNNING, RUNNING_MANUALLY, DERAILED, SCHEDULE_INTERRUPTED, CONDUCTOR_MISSING, NAVIGATION_FAILED + RUNNING, RUNNING_MANUALLY, DERAILED, SCHEDULE_INTERRUPTED, CONDUCTOR_MISSING, NAVIGATION_FAILED; + + public static StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(TrainState.class); } public enum SignalState { - NOT_WAITING, WAITING_FOR_REDSTONE, BLOCK_SIGNAL, CHAIN_SIGNAL + NOT_WAITING, WAITING_FOR_REDSTONE, BLOCK_SIGNAL, CHAIN_SIGNAL; + + public static StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(SignalState.class); } public static class TrainMapSyncEntry { + public static StreamCodec STREAM_CODEC = CatnipLargerStreamCodecs.composite( + CatnipStreamCodecBuilders.array(ByteBufCodecs.FLOAT, Float.class), packet -> packet.positions, + CatnipStreamCodecBuilders.list(ResourceKey.streamCodec(Registries.DIMENSION)), packet -> packet.dimensions, + TrainState.STREAM_CODEC, packet -> packet.state, + SignalState.STREAM_CODEC, packet -> packet.signalState, + ByteBufCodecs.BOOL, packet -> packet.fueled, + ByteBufCodecs.BOOL, packet -> packet.backwards, + ByteBufCodecs.VAR_INT, packet -> packet.targetStationDistance, + ByteBufCodecs.STRING_UTF8, packet -> packet.ownerName, + ByteBufCodecs.STRING_UTF8, packet -> packet.targetStationName, + CatnipStreamCodecBuilders.nullable(UUIDUtil.STREAM_CODEC), packet -> packet.waitingForTrain, + TrainMapSyncEntry::new + ); // Clientside - public float[] prevPositions; + public Float[] prevPositions; public List> prevDims; // Updated every 5 ticks - public float[] positions; + public Float[] positions; public List> dimensions; public TrainState state = TrainState.RUNNING; public SignalState signalState = SignalState.NOT_WAITING; @@ -67,65 +90,22 @@ public class TrainMapSync { public String targetStationName = ""; public UUID waitingForTrain = null; - public void gatherDimensions(DimensionPalette dimensionPalette) { - for (ResourceKey resourceKey : dimensions) - if (resourceKey != null) - dimensionPalette.encode(resourceKey); - } + public TrainMapSyncEntry() {} - public void send(FriendlyByteBuf buffer, DimensionPalette dimensionPalette, boolean light) { - buffer.writeVarInt(positions.length); - for (float f : positions) - buffer.writeFloat(f); - - buffer.writeVarInt(dimensions.size()); - for (ResourceKey resourceKey : dimensions) - buffer.writeVarInt(resourceKey == null ? -1 : dimensionPalette.encode(resourceKey)); - - buffer.writeVarInt(state.ordinal()); - buffer.writeVarInt(signalState.ordinal()); - buffer.writeBoolean(fueled); - buffer.writeBoolean(backwards); - buffer.writeVarInt(targetStationDistance); - - if (light) - return; - - buffer.writeUtf(ownerName); - buffer.writeUtf(targetStationName); - - buffer.writeBoolean(waitingForTrain != null); - if (waitingForTrain != null) - buffer.writeUUID(waitingForTrain); - } - - public void receive(FriendlyByteBuf buffer, DimensionPalette dimensionPalette, boolean light) { - positions = new float[buffer.readVarInt()]; - for (int i = 0; i < positions.length; i++) - positions[i] = buffer.readFloat(); - - dimensions = new ArrayList<>(); - int dimensionsSize = buffer.readVarInt(); - for (int i = 0; i < dimensionsSize; i++) { - int index = buffer.readVarInt(); - dimensions.add(index == -1 ? null : dimensionPalette.decode(index)); - } - - state = TrainState.values()[buffer.readVarInt()]; - signalState = SignalState.values()[buffer.readVarInt()]; - fueled = buffer.readBoolean(); - backwards = buffer.readBoolean(); - targetStationDistance = buffer.readVarInt(); - - if (light) - return; - - ownerName = buffer.readUtf(); - targetStationName = buffer.readUtf(); - - waitingForTrain = null; - if (buffer.readBoolean()) - waitingForTrain = buffer.readUUID(); + public TrainMapSyncEntry(Float[] positions, List> dimensions, TrainState state, + SignalState signalState, boolean fueled, boolean backwards, int targetStationDistance, + String ownerName, String targetStationName, + UUID waitingForTrain) { + this.positions = positions; + this.dimensions = dimensions; + this.state = state; + this.signalState = signalState; + this.fueled = fueled; + this.backwards = backwards; + this.targetStationDistance = targetStationDistance; + this.ownerName = ownerName; + this.targetStationName = targetStationName; + this.waitingForTrain = waitingForTrain; } public void updateFrom(TrainMapSyncEntry other, boolean light) { @@ -143,8 +123,7 @@ public class TrainMapSync { if (prevDims != null) for (int i = 0; i < Math.min(prevDims.size(), dimensions.size()); i++) if (prevDims.get(i) != dimensions.get(i)) - for (int j = 0; j < 6; j++) - prevPositions[i * 6 + j] = positions[i * 6 + j]; + System.arraycopy(positions, i * 6, prevPositions, i * 6, 6); if (light) return; @@ -198,8 +177,7 @@ public class TrainMapSync { ServerPlayer player = weakReference.get(); if (player == null) continue; - AllPackets.getChannel() - .send(PacketDistributor.PLAYER.with(() -> player), packet); + CatnipServices.NETWORK.sendToClient(player, packet); } } @@ -207,7 +185,7 @@ public class TrainMapSync { TrainMapSyncEntry entry = new TrainMapSyncEntry(); boolean stopped = Math.abs(train.speed) < 0.05; - entry.positions = new float[train.carriages.size() * 6]; + entry.positions = new Float[train.carriages.size() * 6]; entry.dimensions = new ArrayList<>(); List carriages = train.carriages; @@ -279,7 +257,7 @@ public class TrainMapSync { .getPlayer(train.owner); if (owner != null) entry.ownerName = owner.getName() - .getString(); + .getString(); } if (train.derailed) { diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncClient.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncClient.java index 694240bfce..d44f936a66 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncClient.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncClient.java @@ -6,9 +6,9 @@ import java.util.Map; import java.util.Set; import java.util.UUID; -import com.simibubi.create.AllPackets; import com.simibubi.create.compat.trainmap.TrainMapSync.TrainMapSyncEntry; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.AnimationTickHolder; import net.createmod.catnip.utility.Pair; @@ -23,8 +23,7 @@ public class TrainMapSyncClient { public static void requestData() { ticks++; if (ticks % 5 == 0) - AllPackets.getChannel() - .sendToServer(new TrainMapSyncRequestPacket()); + CatnipServices.NETWORK.sendToServer(TrainMapSyncRequestPacket.INSTANCE); } public static void stopRequesting() { @@ -35,12 +34,11 @@ public class TrainMapSyncClient { public static void receive(TrainMapSyncPacket packet) { if (ticks == 0) return; - + lastPacket = AnimationTickHolder.getTicks(); lastPacket += AnimationTickHolder.getPartialTicks(); - Set staleEntries = new HashSet<>(); - staleEntries.addAll(currentData.keySet()); + Set staleEntries = new HashSet<>(currentData.keySet()); for (Pair pair : packet.entries) { UUID id = pair.getFirst(); diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncPacket.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncPacket.java index 76a5341e6b..7ddd3da3f7 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncPacket.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncPacket.java @@ -4,62 +4,49 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import com.simibubi.create.AllPackets; import com.simibubi.create.compat.trainmap.TrainMapSync.TrainMapSyncEntry; -import com.simibubi.create.content.trains.graph.DimensionPalette; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.UUIDUtil; import net.createmod.catnip.utility.Pair; import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.network.NetworkEvent.Context; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class TrainMapSyncPacket extends SimplePacketBase { +public class TrainMapSyncPacket implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.BOOL, packet -> packet.light, + CatnipStreamCodecBuilders.list(Pair.streamCodec(UUIDUtil.STREAM_CODEC, TrainMapSyncEntry.STREAM_CODEC)), packet -> packet.entries, + TrainMapSyncPacket::new + ); - public List> entries = new ArrayList<>(); public boolean light; + public List> entries = new ArrayList<>(); public TrainMapSyncPacket(boolean light) { this.light = light; } + public TrainMapSyncPacket(boolean light, List> entries) { + this.light = light; + this.entries = entries; + } + public void add(UUID trainId, TrainMapSyncEntry data) { entries.add(Pair.of(trainId, data)); } - public TrainMapSyncPacket(FriendlyByteBuf buffer) { - DimensionPalette dimensionPalette = DimensionPalette.receive(buffer); - light = buffer.readBoolean(); - - int size = buffer.readVarInt(); - for (int i = 0; i < size; i++) { - UUID id = buffer.readUUID(); - TrainMapSyncEntry entry = new TrainMapSyncEntry(); - entry.receive(buffer, dimensionPalette, light); - entries.add(Pair.of(id, entry)); - } + @Override + public void handle(LocalPlayer player) { + TrainMapSyncClient.receive(this); } @Override - public void write(FriendlyByteBuf buffer) { - DimensionPalette dimensionPalette = new DimensionPalette(); - for (Pair pair : entries) - pair.getSecond() - .gatherDimensions(dimensionPalette); - - dimensionPalette.send(buffer); - buffer.writeBoolean(light); - - buffer.writeVarInt(entries.size()); - for (Pair pair : entries) { - buffer.writeUUID(pair.getFirst()); - pair.getSecond() - .send(buffer, dimensionPalette, light); - } + public PacketTypeProvider getTypeProvider() { + return AllPackets.TRAIN_MAP_SYNC; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> TrainMapSyncClient.receive(this)); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncRequestPacket.java b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncRequestPacket.java index c6138a56db..0f03f54062 100644 --- a/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncRequestPacket.java +++ b/src/main/java/com/simibubi/create/compat/trainmap/TrainMapSyncRequestPacket.java @@ -1,23 +1,24 @@ package com.simibubi.create.compat.trainmap; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ServerboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.network.NetworkEvent.Context; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class TrainMapSyncRequestPacket extends SimplePacketBase { - - public TrainMapSyncRequestPacket() {} - - public TrainMapSyncRequestPacket(FriendlyByteBuf buffer) {} +public class TrainMapSyncRequestPacket implements ServerboundPacketPayload { + public static final TrainMapSyncRequestPacket INSTANCE = new TrainMapSyncRequestPacket(); + public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); @Override - public void write(FriendlyByteBuf buffer) {} - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> TrainMapSync.requestReceived(context.getSender())); - return true; + public void handle(ServerPlayer player) { + TrainMapSync.requestReceived(player); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.TRAIN_MAP_REQUEST; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java index 6cbe09cf57..d168439e34 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java @@ -12,11 +12,11 @@ import javax.annotation.Nullable; import org.apache.commons.lang3.mutable.MutableInt; import org.apache.commons.lang3.tuple.MutablePair; +import org.jetbrains.annotations.NotNull; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllItems; import com.simibubi.create.AllMovementBehaviours; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.Create; import com.simibubi.create.content.contraptions.actors.psi.PortableStorageInterfaceMovement; @@ -37,19 +37,21 @@ import com.simibubi.create.content.trains.entity.Train; import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.collision.Matrix3d; import com.simibubi.create.foundation.mixin.accessor.ServerLevelAccessor; +import net.createmod.catnip.platform.CatnipServices; import dev.engine_room.flywheel.api.backend.BackendManager; +import io.netty.handler.codec.DecoderException; import net.createmod.catnip.utility.VecHelper; import net.createmod.catnip.utility.math.AngleHelper; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; @@ -73,14 +75,11 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemp import net.minecraft.world.level.material.PushReaction; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.entity.IEntityAdditionalSpawnData; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkHooks; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.entity.IEntityWithComplexSpawn; -public abstract class AbstractContraptionEntity extends Entity implements IEntityAdditionalSpawnData { +public abstract class AbstractContraptionEntity extends Entity implements IEntityWithComplexSpawn { private static final EntityDataAccessor STALLED = SynchedEntityData.defineId(AbstractContraptionEntity.class, EntityDataSerializers.BOOLEAN); @@ -93,6 +92,8 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit protected boolean initialized; protected boolean prevPosInvalid; private boolean skipActorStop; + // temporary debug thing + private boolean receivedSpawnData; /* * staleTicks are a band-aid to prevent a frame or two of missing blocks between @@ -109,6 +110,10 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit collidingEntities = new IdentityHashMap<>(); } + public boolean hasReceivedSpawnData() { + return receivedSpawnData; + } + protected void setContraption(Contraption contraption) { this.contraption = contraption; if (contraption == null) @@ -165,8 +170,8 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit return; contraption.getSeatMapping() .put(passenger.getUUID(), seatIndex); - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> this), - new ContraptionSeatMappingPacket(getId(), contraption.getSeatMapping())); + + CatnipServices.NETWORK.sendToClientsTrackingEntity(this, new ContraptionSeatMappingPacket(getId(), contraption.getSeatMapping())); } @Override @@ -182,8 +187,9 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit .put("ContraptionDismountLocation", VecHelper.writeNBT(transformedVector)); contraption.getSeatMapping() .remove(passenger.getUUID()); - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> this), - new ContraptionSeatMappingPacket(getId(), contraption.getSeatMapping(), passenger.getId())); + + CatnipServices.NETWORK.sendToClientsTrackingEntity(this, + new ContraptionSeatMappingPacket(getId(), contraption.getSeatMapping(), passenger.getId())); } @Override @@ -242,15 +248,15 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit return null; Vec3 transformedVector = toGlobalVector(Vec3.atLowerCornerOf(seat) - .add(.5, passenger.getMyRidingOffset() + ySize - .15f, .5), partialTicks) + .add(.5, passenger.getVehicleAttachmentPoint(this).y + ySize - .15f, .5), partialTicks) .add(VecHelper.getCenterOf(BlockPos.ZERO)) .subtract(0.5, ySize, 0.5); return transformedVector; } @Override - protected boolean canAddPassenger(Entity p_184219_1_) { - if (p_184219_1_ instanceof OrientedContraptionEntity) + protected boolean canAddPassenger(@NotNull Entity pPassenger) { + if (pPassenger instanceof OrientedContraptionEntity) return true; return contraption.getSeatMapping() .size() < contraption.getSeats() @@ -280,8 +286,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit public void stopControlling(BlockPos controlsLocalPos) { getControllingPlayer().map(level()::getPlayerByUUID) .map(p -> (p instanceof ServerPlayer) ? ((ServerPlayer) p) : null) - .ifPresent(p -> AllPackets.getChannel().send(PacketDistributor.PLAYER.with(() -> p), - new ControlsStopControllingPacket())); + .ifPresent(p -> CatnipServices.NETWORK.sendToClient(p, ControlsStopControllingPacket.INSTANCE)); setControllingPlayer(null); } @@ -379,14 +384,9 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit tickContraption(); super.tick(); - if (level().isClientSide()) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { - // The visual will handle this with flywheel on. - if (!contraption.deferInvalidate || BackendManager.isBackendOn()) - return; - contraption.deferInvalidate = false; - ContraptionRenderInfo.invalidate(contraption); - }); + if (level().isClientSide()) { + AbstractContraptionEntityClient.invalidate(contraption); + } if (!(level() instanceof ServerLevelAccessor sl)) return; @@ -415,7 +415,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit float angle = AngleHelper.deg(-Mth.atan2(motion.x, motion.z)); angle = AngleHelper.angleLerp(0.4f, prevAngle, angle); if (level().isClientSide) { - living.lerpTo(0, 0, 0, 0, 0, 0, false); + living.lerpTo(0, 0, 0, 0, 0, 0); living.lerpHeadTo(0, 0); living.setYRot(angle); living.setXRot(0); @@ -427,8 +427,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit public void setBlock(BlockPos localPos, StructureBlockInfo newInfo) { contraption.blocks.put(localPos, newInfo); - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> this), - new ContraptionBlockChangedPacket(getId(), localPos, newInfo.state())); + CatnipServices.NETWORK.sendToClientsTrackingEntity(this, new ContraptionBlockChangedPacket(getId(), localPos, newInfo.state())); } protected abstract void tickContraption(); @@ -523,8 +522,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } protected void onContraptionStalled() { - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> this), - new ContraptionStallPacket(getId(), getX(), getY(), getZ(), getStalledAngle())); + CatnipServices.NETWORK.sendToClientsTrackingEntity(this, new ContraptionStallPacket(getId(), getX(), getY(), getZ(), getStalledAngle())); } protected boolean shouldActorTrigger(MovementContext context, StructureBlockInfo blockInfo, MovementBehaviour actor, @@ -599,20 +597,15 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } @Override - protected void defineSynchedData() { - this.entityData.define(STALLED, false); - this.entityData.define(CONTROLLED_BY, Optional.empty()); + protected void defineSynchedData(SynchedEntityData.Builder builder) { + builder.define(STALLED, false); + builder.define(CONTROLLED_BY, Optional.empty()); } @Override - public Packet getAddEntityPacket() { - return NetworkHooks.getEntitySpawningPacket(this); - } - - @Override - public void writeSpawnData(FriendlyByteBuf buffer) { + public void writeSpawnData(RegistryFriendlyByteBuf registryFriendlyByteBuf) { CompoundTag compound = new CompoundTag(); - writeAdditional(compound, true); + writeAdditional(compound, registryFriendlyByteBuf.registryAccess(), true); if (ContraptionData.isTooLargeForSync(compound)) { String info = getContraption().getType().id + " @" + position() + " (" + getStringUUID() + ")"; @@ -620,27 +613,30 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit compound = null; } - buffer.writeNbt(compound); + registryFriendlyByteBuf.writeNbt(compound); } @Override protected final void addAdditionalSaveData(CompoundTag compound) { - writeAdditional(compound, false); + writeAdditional(compound, registryAccess(), false); } - protected void writeAdditional(CompoundTag compound, boolean spawnPacket) { + protected void writeAdditional(CompoundTag compound, HolderLookup.Provider registries, boolean spawnPacket) { if (contraption != null) - compound.put("Contraption", contraption.writeNBT(spawnPacket)); + compound.put("Contraption", contraption.writeNBT(registries, spawnPacket)); compound.putBoolean("Stalled", isStalled()); compound.putBoolean("Initialized", initialized); } @Override - public void readSpawnData(FriendlyByteBuf additionalData) { - CompoundTag nbt = additionalData.readAnySizeNbt(); + public void readSpawnData(RegistryFriendlyByteBuf registryFriendlyByteBuf) { + CompoundTag nbt = readAnySizeNbt(registryFriendlyByteBuf); if (nbt != null) { readAdditional(nbt, true); + } else { + Create.LOGGER.warn("Null spawn data for AbstractContraptionEntity"); } + receivedSpawnData = true; } @Override @@ -648,6 +644,16 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit readAdditional(compound, false); } + @Nullable + private static CompoundTag readAnySizeNbt(RegistryFriendlyByteBuf buf) { + Tag tag = buf.readNbt(NbtAccounter.unlimitedHeap()); + if (tag != null && !(tag instanceof CompoundTag)) { + throw new DecoderException("Not a compound tag: " + tag); + } else { + return (CompoundTag) tag; + } + } + protected void readAdditional(CompoundTag compound, boolean spawnData) { if (compound.isEmpty()) return; @@ -667,8 +673,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit StructureTransform transform = makeStructureTransform(); contraption.stop(level()); - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> this), - new ContraptionDisassemblyPacket(this.getId(), transform)); + CatnipServices.NETWORK.sendToClientsTrackingEntity(this, new ContraptionDisassemblyPacket(this.getId(), transform)); contraption.addBlocksToWorld(level(), transform); contraption.addPassengersToWorld(level(), transform, getPassengers()); @@ -728,8 +733,8 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } @Override - public void onRemovedFromWorld() { - super.onRemovedFromWorld(); + public void onRemovedFromLevel() { + super.onRemovedFromLevel(); } @Override @@ -745,20 +750,20 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit @OnlyIn(Dist.CLIENT) static void handleStallPacket(ContraptionStallPacket packet) { - if (Minecraft.getInstance().level.getEntity(packet.entityID) instanceof AbstractContraptionEntity ce) - ce.handleStallInformation(packet.x, packet.y, packet.z, packet.angle); + if (Minecraft.getInstance().level.getEntity(packet.entityId()) instanceof AbstractContraptionEntity ce) + ce.handleStallInformation(packet.x(), packet.y(), packet.z(), packet.angle()); } @OnlyIn(Dist.CLIENT) static void handleBlockChangedPacket(ContraptionBlockChangedPacket packet) { - if (Minecraft.getInstance().level.getEntity(packet.entityID) instanceof AbstractContraptionEntity ce) - ce.handleBlockChange(packet.localPos, packet.newState); + if (Minecraft.getInstance().level.getEntity(packet.entityId()) instanceof AbstractContraptionEntity ce) + ce.handleBlockChange(packet.localPos(), packet.newState()); } @OnlyIn(Dist.CLIENT) static void handleDisassemblyPacket(ContraptionDisassemblyPacket packet) { - if (Minecraft.getInstance().level.getEntity(packet.entityID) instanceof AbstractContraptionEntity ce) - ce.moveCollidedEntitiesOnDisassembly(packet.transform); + if (Minecraft.getInstance().level.getEntity(packet.entityId()) instanceof AbstractContraptionEntity ce) + ce.moveCollidedEntitiesOnDisassembly(packet.transform()); } protected abstract float getStalledAngle(); @@ -923,10 +928,15 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } @Override - public void setSecondsOnFire(int p_70015_1_) { + public void igniteForTicks(int ticks) { // Contraptions no longer catch fire } + @Override + public boolean fireImmune() { + return true; + } + // Contraptions shouldn't activate pressure plates and tripwires @Override public boolean isIgnoringBlockTriggers() { @@ -944,4 +954,14 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit public boolean isPrevPosInvalid() { return prevPosInvalid; } + + private static class AbstractContraptionEntityClient { + private static void invalidate(Contraption contraption) { + // The visual will handle this with flywheel on. + if (!contraption.deferInvalidate || BackendManager.isBackendOn()) + return; + contraption.deferInvalidate = false; + ContraptionRenderInfo.invalidate(contraption); + } + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/AssemblyException.java b/src/main/java/com/simibubi/create/content/contraptions/AssemblyException.java index 5e53e00329..27725f045f 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/AssemblyException.java +++ b/src/main/java/com/simibubi/create/content/contraptions/AssemblyException.java @@ -4,6 +4,7 @@ import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.infrastructure.config.AllConfigs; 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.level.block.state.BlockState; @@ -14,12 +15,12 @@ public class AssemblyException extends Exception { public final Component component; private BlockPos position = null; - public static void write(CompoundTag compound, AssemblyException exception) { + public static void write(CompoundTag compound, HolderLookup.Provider registries, AssemblyException exception) { if (exception == null) return; CompoundTag nbt = new CompoundTag(); - nbt.putString("Component", Component.Serializer.toJson(exception.component)); + nbt.putString("Component", Component.Serializer.toJson(exception.component, registries)); if (exception.hasPosition()) nbt.putLong("Position", exception.getPosition() .asLong()); @@ -27,13 +28,13 @@ public class AssemblyException extends Exception { compound.put("LastException", nbt); } - public static AssemblyException read(CompoundTag compound) { + public static AssemblyException read(CompoundTag compound, HolderLookup.Provider registries) { if (!compound.contains("LastException")) return null; CompoundTag nbt = compound.getCompound("LastException"); String string = nbt.getString("Component"); - AssemblyException exception = new AssemblyException(Component.Serializer.fromJson(string)); + AssemblyException exception = new AssemblyException(Component.Serializer.fromJson(string, registries)); if (nbt.contains("Position")) exception.position = BlockPos.of(nbt.getLong("Position")); diff --git a/src/main/java/com/simibubi/create/content/contraptions/Contraption.java b/src/main/java/com/simibubi/create/content/contraptions/Contraption.java index 693ccdd9e1..a983b6dff9 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/Contraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/Contraption.java @@ -85,6 +85,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -122,12 +123,12 @@ import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.wrapper.CombinedInvWrapper; -import net.minecraftforge.registries.GameData; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.wrapper.CombinedInvWrapper; +import net.neoforged.neoforge.registries.GameData; public abstract class Contraption { @@ -340,7 +341,7 @@ public abstract class Contraption { && !BlockMovementChecks.isNotSupportive(world.getBlockState(attached), offset.getOpposite())) frontier.add(attached); } - + if (world.getBlockEntity(pos) instanceof ChainConveyorBlockEntity ccbe) ccbe.notifyConnectedToValidate(); @@ -632,7 +633,7 @@ public abstract class Contraption { if (blockEntity instanceof PoweredShaftBlockEntity) blockEntity = AllBlockEntityTypes.BRACKETED_KINETIC.create(pos, blockstate); if (blockEntity instanceof FactoryPanelBlockEntity fpbe) - fpbe.writeSafe(compoundnbt); + fpbe.writeSafe(compoundnbt, world.registryAccess()); return Pair.of(new StructureBlockInfo(pos, blockstate, compoundnbt), blockEntity); } @@ -670,9 +671,9 @@ public abstract class Contraption { return; CompoundTag nbt = structureBlockInfo.nbt(); - BlockPos controllerPos = nbt.contains("Controller") ? - toLocalPos(NbtUtils.readBlockPos(nbt.getCompound("Controller"))) : - localPos; + BlockPos controllerPos = NbtUtils.readBlockPos(nbt,"Controller") + .map(this::toLocalPos) + .orElse(localPos); nbt.put("Controller", NbtUtils.writeBlockPos(controllerPos)); if (multiBlockBE.isController() && multiBlockBE.getHeight() <= 1 && multiBlockBE.getWidth() <= 1) { @@ -689,7 +690,7 @@ public abstract class Contraption { BlockEntity blockEntity = world.getBlockEntity(pos); if (blockEntity == null) return null; - CompoundTag nbt = blockEntity.saveWithFullMetadata(); + CompoundTag nbt = blockEntity.saveWithFullMetadata(world.registryAccess()); nbt.remove("x"); nbt.remove("y"); nbt.remove("z"); @@ -726,9 +727,9 @@ public abstract class Contraption { if (!tag.contains("Controller", Tag.TAG_COMPOUND) && !tag.contains("Parts", Tag.TAG_LIST)) return; - BlockPos controllerPos = NbtUtils.readBlockPos(tag.getCompound("Controller")); + BlockPos controllerPos = NbtUtils.readBlockPos(tag, "Controller").orElseThrow(); tag.getList("Parts", Tag.TAG_COMPOUND).forEach(part -> { - BlockPos partPos = NbtUtils.readBlockPos((CompoundTag) part); + BlockPos partPos = NbtUtils.readBlockPos((CompoundTag) part, "Pos").orElseThrow(); StructureBlockInfo partInfo = this.blocks.get(partPos); capturedMultiblocks.put(controllerPos, partInfo); }); @@ -738,14 +739,14 @@ public abstract class Contraption { nbt.getList("Actors", Tag.TAG_COMPOUND) .forEach(c -> { CompoundTag comp = (CompoundTag) c; - StructureBlockInfo info = this.blocks.get(NbtUtils.readBlockPos(comp.getCompound("Pos"))); + StructureBlockInfo info = this.blocks.get(NbtUtils.readBlockPos(comp, "Pos").orElseThrow()); if (info == null) return; MovementContext context = MovementContext.readNBT(world, info, comp, this); getActors().add(MutablePair.of(info, context)); }); - disabledActors = NBTHelper.readItemList(nbt.getList("DisabledActors", Tag.TAG_COMPOUND)); + disabledActors = NBTHelper.readItemList(nbt.getList("DisabledActors", Tag.TAG_COMPOUND), world.registryAccess()); for (ItemStack stack : disabledActors) setActorsActive(stack, false); @@ -754,7 +755,7 @@ public abstract class Contraption { c -> superglue.add(SuperGlueEntity.readBoundingBox(c))); seats.clear(); - NBTHelper.iterateCompoundList(nbt.getList("Seats", Tag.TAG_COMPOUND), c -> seats.add(NbtUtils.readBlockPos(c))); + NBTHelper.iterateCompoundList(nbt.getList("Seats", Tag.TAG_COMPOUND), c -> seats.add(NbtUtils.readBlockPos(c, "Pos").orElseThrow())); seatMapping.clear(); NBTHelper.iterateCompoundList(nbt.getList("Passengers", Tag.TAG_COMPOUND), @@ -766,7 +767,7 @@ public abstract class Contraption { interactors.clear(); NBTHelper.iterateCompoundList(nbt.getList("Interactors", Tag.TAG_COMPOUND), c -> { - BlockPos pos = NbtUtils.readBlockPos(c.getCompound("Pos")); + BlockPos pos = NbtUtils.readBlockPos(c, "Pos").orElseThrow(); StructureBlockInfo structureBlockInfo = getBlocks().get(pos); if (structureBlockInfo == null) return; @@ -775,17 +776,17 @@ public abstract class Contraption { interactors.put(pos, behaviour); }); - storage.read(nbt, presentBlockEntities, spawnData); + storage.read(nbt, world.registryAccess(), presentBlockEntities, spawnData); if (nbt.contains("BoundsFront")) bounds = NBTHelper.readAABB(nbt.getList("BoundsFront", Tag.TAG_FLOAT)); stalled = nbt.getBoolean("Stalled"); hasUniversalCreativeCrate = nbt.getBoolean("BottomlessSupply"); - anchor = NbtUtils.readBlockPos(nbt.getCompound("Anchor")); + anchor = NbtUtils.readBlockPos(nbt, "Anchor").orElseThrow(); } - public CompoundTag writeNBT(boolean spawnPacket) { + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { CompoundTag nbt = new CompoundTag(); nbt.putString("Type", getType().id); @@ -798,7 +799,10 @@ public abstract class Contraption { Collection multiblockParts = capturedMultiblocks.get(controllerPos); ListTag partsNBT = new ListTag(); - multiblockParts.forEach(info -> partsNBT.add(NbtUtils.writeBlockPos(info.pos()))); + multiblockParts.forEach(info -> { + CompoundTag c = new CompoundTag(); + partsNBT.add(c.put("Pos", NbtUtils.writeBlockPos(info.pos()))); + }); tag.put("Parts", partsNBT); multiblocksNBT.add(tag); @@ -816,7 +820,7 @@ public abstract class Contraption { actorsNBT.add(compound); } - ListTag disabledActorsNBT = NBTHelper.writeItemList(disabledActors); + ListTag disabledActorsNBT = NBTHelper.writeItemList(disabledActors, registries); ListTag superglueNBT = new ListTag(); if (!spawnPacket) { @@ -827,7 +831,7 @@ public abstract class Contraption { } } - (spawnPacket ? getStorageForSpawnPacket() : storage).write(nbt, spawnPacket); + (spawnPacket ? getStorageForSpawnPacket() : storage).write(nbt, registries, spawnPacket); ListTag interactorNBT = new ListTag(); for (BlockPos pos : interactors.keySet()) { @@ -836,7 +840,11 @@ public abstract class Contraption { interactorNBT.add(c); } - nbt.put("Seats", NBTHelper.writeCompoundList(getSeats(), NbtUtils::writeBlockPos)); + nbt.put("Seats", NBTHelper.writeCompoundList(getSeats(), pos -> { + CompoundTag c = new CompoundTag(); + c.put("Pos", NbtUtils.writeBlockPos(pos)); + return c; + })); nbt.put("Passengers", NBTHelper.writeCompoundList(getSeatMapping().entrySet(), e -> { CompoundTag tag = new CompoundTag(); tag.put("Id", NbtUtils.createUUID(e.getKey())); @@ -941,7 +949,7 @@ public abstract class Contraption { tag.putInt("y", info.pos().getY()); tag.putInt("z", info.pos().getZ()); - BlockEntity be = BlockEntity.loadStatic(info.pos(), info.state(), tag); + BlockEntity be = BlockEntity.loadStatic(info.pos(), info.state(), tag, world.registryAccess()); if (be == null) return; be.setLevel(world); @@ -967,7 +975,7 @@ public abstract class Contraption { } private static StructureBlockInfo legacyReadStructureBlockInfo(CompoundTag blockListEntry, HolderGetter holderGetter) { - return new StructureBlockInfo(NbtUtils.readBlockPos(blockListEntry.getCompound("Pos")), + return new StructureBlockInfo(NbtUtils.readBlockPos(blockListEntry, "Pos").orElseThrow(), NbtUtils.readBlockState(holderGetter, blockListEntry.getCompound("Block")), blockListEntry.contains("Data") ? blockListEntry.getCompound("Data") : null); } @@ -1155,7 +1163,7 @@ public abstract class Contraption { } } - blockEntity.load(tag); + blockEntity.loadWithComponents(tag, world.registryAccess()); storage.addStorageToWorld(block, blockEntity); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionBlockChangedPacket.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionBlockChangedPacket.java index 313ad17ba8..ed61ea955a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionBlockChangedPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionBlockChangedPacket.java @@ -1,46 +1,35 @@ package com.simibubi.create.content.contraptions; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import io.netty.buffer.ByteBuf; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionBlockChangedPacket extends SimplePacketBase { +public record ContraptionBlockChangedPacket(int entityId, BlockPos localPos, BlockState newState) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ContraptionBlockChangedPacket::entityId, + BlockPos.STREAM_CODEC, ContraptionBlockChangedPacket::localPos, + CatnipStreamCodecs.BLOCK_STATE, ContraptionBlockChangedPacket::newState, + ContraptionBlockChangedPacket::new + ); - int entityID; - BlockPos localPos; - BlockState newState; - - public ContraptionBlockChangedPacket(int id, BlockPos pos, BlockState state) { - entityID = id; - localPos = pos; - newState = state; + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + AbstractContraptionEntity.handleBlockChangedPacket(this); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - buffer.writeBlockPos(localPos); - buffer.writeNbt(NbtUtils.writeBlockState(newState)); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_BLOCK_CHANGED; } - - @SuppressWarnings("deprecation") - public ContraptionBlockChangedPacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - localPos = buffer.readBlockPos(); - newState = NbtUtils.readBlockState(BuiltInRegistries.BLOCK.asLookup(), buffer.readNbt()); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> AbstractContraptionEntity.handleBlockChangedPacket(this))); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java index ae4899ed93..29706a4447 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java @@ -1,9 +1,22 @@ package com.simibubi.create.content.contraptions; +import static net.minecraft.world.entity.Entity.collideBoundingBox; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.commons.lang3.mutable.MutableBoolean; +import org.apache.commons.lang3.mutable.MutableFloat; +import org.apache.commons.lang3.mutable.MutableObject; +import org.apache.commons.lang3.tuple.MutablePair; + import com.google.common.base.Predicates; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllMovementBehaviours; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity.ContraptionRotationState; import com.simibubi.create.content.contraptions.ContraptionColliderLockPacket.ContraptionColliderLockPacketRequest; import com.simibubi.create.content.contraptions.actors.harvester.HarvesterMovementBehaviour; @@ -19,6 +32,8 @@ import com.simibubi.create.foundation.collision.OrientedBB; import com.simibubi.create.foundation.damageTypes.CreateDamageSources; import com.simibubi.create.foundation.utility.BlockHelper; import com.simibubi.create.infrastructure.config.AllConfigs; + +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Iterate; import net.createmod.catnip.utility.VecHelper; import net.minecraft.client.Minecraft; @@ -49,22 +64,8 @@ import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; -import org.apache.commons.lang3.mutable.MutableBoolean; -import org.apache.commons.lang3.mutable.MutableFloat; -import org.apache.commons.lang3.mutable.MutableObject; -import org.apache.commons.lang3.tuple.MutablePair; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; - -import static net.minecraft.world.entity.Entity.collideBoundingBox; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ContraptionCollider { @@ -91,8 +92,7 @@ public class ContraptionCollider { ContraptionRotationState rotation = null; if (world.isClientSide() && safetyLock.left != null && safetyLock.left.get() == contraptionEntity) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> saveClientPlayerFromClipping(contraptionEntity, contraptionMotion)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> saveClientPlayerFromClipping(contraptionEntity, contraptionMotion)); // After death, multiple refs to the client player may show up in the area boolean skipClientPlayer = false; @@ -107,8 +107,7 @@ public class ContraptionCollider { if (playerType == PlayerType.REMOTE) { if (!(contraption instanceof TranslatingContraption)) continue; - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> saveRemotePlayerFromClipping((Player) entity, contraptionEntity, contraptionMotion)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> saveRemotePlayerFromClipping((Player) entity, contraptionEntity, contraptionMotion)); continue; } @@ -203,7 +202,7 @@ public class ContraptionCollider { Vec3 collisionPosition = intersect.getCollisionPosition(); if (!isTemporal) { - Vec3 separation = intersect.asSeparationVec(entity.getStepHeight()); + Vec3 separation = intersect.asSeparationVec(entity.maxUpStep()); if (separation != null && !separation.equals(Vec3.ZERO)) { collisionResponse.setValue(currentResponse.add(separation)); timeOfImpact = 0; @@ -368,8 +367,7 @@ public class ContraptionCollider { entity.fallDistance = 0; for (Entity rider : entity.getIndirectPassengers()) if (getPlayerType(rider) == PlayerType.CLIENT) - AllPackets.getChannel() - .sendToServer(new ClientMotionPacket(rider.getDeltaMovement(), true, 0)); + CatnipServices.NETWORK.sendToServer(new ClientMotionPacket(rider.getDeltaMovement(), true, 0)); boolean canWalk = bounce != 0 || slide == 0; if (canWalk || !rotation.hasVerticalRotation()) { if (canWalk) @@ -393,8 +391,7 @@ public class ContraptionCollider { float limbSwing = Mth.sqrt((float) (d0 * d0 + d1 * d1)) * 4.0F; if (limbSwing > 1.0F) limbSwing = 1.0F; - AllPackets.getChannel() - .sendToServer(new ClientMotionPacket(entityMotion, true, limbSwing)); + CatnipServices.NETWORK.sendToServer(new ClientMotionPacket(entityMotion, true, limbSwing)); if (entity.onGround() && contraption instanceof TranslatingContraption) { safetyLock.setLeft(new WeakReference<>(contraptionEntity)); @@ -424,8 +421,7 @@ public class ContraptionCollider { if (packetCooldown > 0) packetCooldown--; if (packetCooldown == 0) { - AllPackets.getChannel() - .sendToServer(new ContraptionColliderLockPacketRequest(contraptionEntity.getId(), currentDiff)); + CatnipServices.NETWORK.sendToServer(new ContraptionColliderLockPacketRequest(contraptionEntity.getId(), currentDiff)); packetCooldown = 3; } } @@ -477,7 +473,7 @@ public class ContraptionCollider { AABB bb = entity.getBoundingBox() .deflate(1 / 4f, 0, 1 / 4f); double shortestDistance = Double.MAX_VALUE; - double yStart = entity.getStepHeight() + contraptionEntity.getY() + yStartOffset; + double yStart = entity.maxUpStep() + contraptionEntity.getY() + yStartOffset; double rayLength = Math.max(5, Math.abs(entity.getY() - yStart)); for (int rayIndex = 0; rayIndex < 4; rayIndex++) { @@ -537,8 +533,7 @@ public class ContraptionCollider { return entityMotion; if (playerType == PlayerType.CLIENT) { - AllPackets.getChannel() - .sendToServer(new TrainCollisionPacket((int) (damage * 16), contraptionEntity.getId())); + CatnipServices.NETWORK.sendToServer(new TrainCollisionPacket((int) (damage * 16), contraptionEntity.getId())); world.playSound((Player) entity, entity.blockPosition(), SoundEvents.PLAYER_ATTACK_CRIT, SoundSource.NEUTRAL, 1, .75f); } else { @@ -617,12 +612,12 @@ public class ContraptionCollider { boolean flag1 = p_20273_.y != vec3.y; boolean flag2 = p_20273_.z != vec3.z; boolean flag3 = flag1 && p_20273_.y < 0.0D; - if (e.getStepHeight() > 0.0F && flag3 && (flag || flag2)) { - Vec3 vec31 = collideBoundingBox(e, new Vec3(p_20273_.x, (double) e.getStepHeight(), p_20273_.z), aabb, + if (e.maxUpStep() > 0.0F && flag3 && (flag || flag2)) { + Vec3 vec31 = collideBoundingBox(e, new Vec3(p_20273_.x, (double) e.maxUpStep(), p_20273_.z), aabb, e.level(), list); - Vec3 vec32 = collideBoundingBox(e, new Vec3(0.0D, (double) e.getStepHeight(), 0.0D), + Vec3 vec32 = collideBoundingBox(e, new Vec3(0.0D, (double) e.maxUpStep(), 0.0D), aabb.expandTowards(p_20273_.x, 0.0D, p_20273_.z), e.level(), list); - if (vec32.y < (double) e.getStepHeight()) { + if (vec32.y < (double) e.maxUpStep()) { Vec3 vec33 = collideBoundingBox(e, new Vec3(p_20273_.x, 0.0D, p_20273_.z), aabb.move(vec32), e.level(), list) .add(vec32); @@ -646,7 +641,7 @@ public class ContraptionCollider { if (!entity.level().isClientSide) return PlayerType.SERVER; MutableBoolean isClient = new MutableBoolean(false); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> isClient.setValue(isClientPlayerEntity(entity))); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> isClient.setValue(isClientPlayerEntity(entity))); return isClient.booleanValue() ? PlayerType.CLIENT : PlayerType.REMOTE; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionColliderLockPacket.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionColliderLockPacket.java index 3b4ff0eeb4..5bb1a82e4c 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionColliderLockPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionColliderLockPacket.java @@ -1,78 +1,54 @@ package com.simibubi.create.content.contraptions; import com.simibubi.create.AllPackets; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.net.base.ServerboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.PacketDistributor; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionColliderLockPacket extends SimplePacketBase { +public record ContraptionColliderLockPacket(int contraption, double offset, int sender) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, ContraptionColliderLockPacket::contraption, + ByteBufCodecs.DOUBLE, ContraptionColliderLockPacket::offset, + ByteBufCodecs.VAR_INT, ContraptionColliderLockPacket::sender, + ContraptionColliderLockPacket::new + ); - protected int contraption; - protected double offset; - private int sender; - - public ContraptionColliderLockPacket(int contraption, double offset, int sender) { - this.contraption = contraption; - this.offset = offset; - this.sender = sender; - } - - public ContraptionColliderLockPacket(FriendlyByteBuf buffer) { - contraption = buffer.readVarInt(); - offset = buffer.readDouble(); - sender = buffer.readVarInt(); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + ContraptionCollider.lockPacketReceived(contraption, sender, offset); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(contraption); - buffer.writeDouble(offset); - buffer.writeVarInt(sender); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_COLLIDER_LOCK; } - @Override - public boolean handle(Context context) { - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> ContraptionCollider.lockPacketReceived(contraption, sender, offset)); - return true; - } + public record ContraptionColliderLockPacketRequest(int contraption, double offset) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, ContraptionColliderLockPacketRequest::contraption, + ByteBufCodecs.DOUBLE, ContraptionColliderLockPacketRequest::offset, + ContraptionColliderLockPacketRequest::new + ); - public static class ContraptionColliderLockPacketRequest extends SimplePacketBase { - - protected int contraption; - protected double offset; - - public ContraptionColliderLockPacketRequest(int contraption, double offset) { - this.contraption = contraption; - this.offset = offset; - } - - public ContraptionColliderLockPacketRequest(FriendlyByteBuf buffer) { - contraption = buffer.readVarInt(); - offset = buffer.readDouble(); + @Override + public void handle(ServerPlayer player) { + CatnipServices.NETWORK.sendToClientsTrackingEntity(player, new ContraptionColliderLockPacket(contraption, offset, player.getId())); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(contraption); - buffer.writeDouble(offset); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_COLLIDER_LOCK_REQUEST; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - AllPackets.getChannel() - .send(PacketDistributor.TRACKING_ENTITY.with(context::getSender), - new ContraptionColliderLockPacket(contraption, offset, context.getSender() - .getId())); - }); - return true; - } - } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionData.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionData.java index 158d306a76..fbd3a2efdb 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionData.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionData.java @@ -7,6 +7,7 @@ import com.simibubi.create.infrastructure.config.AllConfigs; import io.netty.buffer.Unpooled; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtAccounter; +import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; @@ -66,17 +67,17 @@ public class ContraptionData { /** * @return true if the given NBT is too large for a contraption to be picked up with a wrench. */ - public static boolean isTooLargeForPickup(CompoundTag data) { + public static boolean isTooLargeForPickup(Tag data) { return packetSize(data) > PICKUP_LIMIT; } /** * @return the size of the given NBT when put through a packet, in bytes. */ - public static long packetSize(CompoundTag data) { + public static long packetSize(Tag data) { FriendlyByteBuf test = new FriendlyByteBuf(Unpooled.buffer()); test.writeNbt(data); - NbtAccounter sizeTracker = new NbtAccounter(Long.MAX_VALUE); + NbtAccounter sizeTracker = NbtAccounter.unlimitedHeap(); test.readNbt(sizeTracker); long size = ((NbtAccounterAccessor) sizeTracker).create$getUsage(); test.release(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionDisassemblyPacket.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionDisassemblyPacket.java index 44d56748c7..891371fba1 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionDisassemblyPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionDisassemblyPacket.java @@ -1,38 +1,31 @@ package com.simibubi.create.content.contraptions; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import io.netty.buffer.ByteBuf; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionDisassemblyPacket extends SimplePacketBase { +public record ContraptionDisassemblyPacket(int entityId, StructureTransform transform) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ContraptionDisassemblyPacket::entityId, + StructureTransform.STREAM_CODEC, ContraptionDisassemblyPacket::transform, + ContraptionDisassemblyPacket::new + ); - int entityID; - StructureTransform transform; - - public ContraptionDisassemblyPacket(int entityID, StructureTransform transform) { - this.entityID = entityID; - this.transform = transform; - } - - public ContraptionDisassemblyPacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - transform = StructureTransform.fromBuffer(buffer); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + AbstractContraptionEntity.handleDisassemblyPacket(this); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - transform.writeToBuffer(buffer); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_DISASSEMBLE; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> AbstractContraptionEntity.handleDisassemblyPacket(this))); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java index 3b89798e68..7071583252 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java @@ -1,12 +1,20 @@ package com.simibubi.create.content.contraptions; +import java.lang.ref.WeakReference; +import java.util.Collection; + +import javax.annotation.Nullable; + +import org.apache.commons.lang3.mutable.MutableObject; + import com.simibubi.create.AllItems; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.sync.ContraptionInteractionPacket; import com.simibubi.create.content.trains.entity.CarriageContraptionEntity; import com.simibubi.create.content.trains.entity.TrainRelocator; import com.simibubi.create.foundation.utility.RaycastHelper; import com.simibubi.create.foundation.utility.RaycastHelper.PredicateTraceResult; + +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Couple; import net.createmod.catnip.utility.Iterate; import net.createmod.catnip.utility.VecHelper; @@ -24,30 +32,22 @@ import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.event.TickEvent.Phase; -import net.minecraftforge.event.TickEvent.PlayerTickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import org.apache.commons.lang3.mutable.MutableObject; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.event.tick.PlayerTickEvent; -import javax.annotation.Nullable; -import java.lang.ref.WeakReference; -import java.util.Collection; - -@EventBusSubscriber +@EventBusSubscriber(Dist.CLIENT) public class ContraptionHandlerClient { @SubscribeEvent @OnlyIn(Dist.CLIENT) - public static void preventRemotePlayersWalkingAnimations(PlayerTickEvent event) { - if (event.phase == Phase.START) + public static void preventRemotePlayersWalkingAnimations(PlayerTickEvent.Post event) { + if (!(event.getEntity() instanceof RemotePlayer remotePlayer)) return; - if (!(event.player instanceof RemotePlayer)) - return; - RemotePlayer remotePlayer = (RemotePlayer) event.player; + CompoundTag data = remotePlayer.getPersistentData(); if (!data.contains("LastOverrideLimbSwingUpdate")) return; @@ -106,7 +106,7 @@ public class ContraptionHandlerClient { BlockPos pos = rayTraceResult.getBlockPos(); if (contraptionEntity.handlePlayerInteraction(player, pos, face, hand)) { - AllPackets.getChannel().sendToServer(new ContraptionInteractionPacket(contraptionEntity, hand, pos, face)); + CatnipServices.NETWORK.sendToServer(new ContraptionInteractionPacket(contraptionEntity, hand, pos, face)); } else if (handleSpecialInteractions(contraptionEntity, player, pos, face, hand)) { } else continue; @@ -128,7 +128,7 @@ public class ContraptionHandlerClient { public static Couple getRayInputs(LocalPlayer player) { Minecraft mc = Minecraft.getInstance(); Vec3 origin = RaycastHelper.getTraceOrigin(player); - double reach = mc.gameMode.getPickRange(); + double reach = player.blockInteractionRange(); if (mc.hitResult != null && mc.hitResult.getLocation() != null) reach = Math.min(mc.hitResult.getLocation() .distanceTo(origin), reach); diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionMovementSetting.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionMovementSetting.java index a8296696b4..ba17cf6da7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionMovementSetting.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionMovementSetting.java @@ -2,12 +2,13 @@ package com.simibubi.create.content.contraptions; import com.simibubi.create.foundation.utility.AttachedRegistry; import com.simibubi.create.infrastructure.config.AllConfigs; + +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraftforge.common.extensions.IForgeBlock; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.extensions.IBlockExtension; import javax.annotation.Nullable; import java.util.Collection; @@ -16,7 +17,7 @@ import java.util.function.Supplier; public enum ContraptionMovementSetting { MOVABLE, NO_PICKUP, UNMOVABLE; - private static final AttachedRegistry> SETTING_SUPPLIERS = new AttachedRegistry<>(ForgeRegistries.BLOCKS); + private static final AttachedRegistry> SETTING_SUPPLIERS = new AttachedRegistry<>(BuiltInRegistries.BLOCK); public static void register(ResourceLocation block, Supplier settingSupplier) { SETTING_SUPPLIERS.register(block, settingSupplier); @@ -53,7 +54,7 @@ public enum ContraptionMovementSetting { register(Blocks.REINFORCED_DEEPSLATE, () -> AllConfigs.server().kinetics.reinforcedDeepslateMovement.get()); } - public interface IMovementSettingProvider extends IForgeBlock { + public interface IMovementSettingProvider extends IBlockExtension { ContraptionMovementSetting getContraptionMovementSetting(); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionRelocationPacket.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionRelocationPacket.java index 8513de073b..c4285cd114 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionRelocationPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionRelocationPacket.java @@ -1,34 +1,29 @@ package com.simibubi.create.content.contraptions; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionRelocationPacket extends SimplePacketBase { +public record ContraptionRelocationPacket(int entityId) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = ByteBufCodecs.INT.map( + ContraptionRelocationPacket::new, ContraptionRelocationPacket::entityId + ); - int entityID; - - public ContraptionRelocationPacket(int entityID) { - this.entityID = entityID; - } - - public ContraptionRelocationPacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + OrientedContraptionEntity.handleRelocationPacket(this); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_RELOCATION; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> OrientedContraptionEntity.handleRelocationPacket(this))); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionStallPacket.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionStallPacket.java index 0cb3ff2a1f..bc8374538b 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionStallPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionStallPacket.java @@ -1,53 +1,34 @@ package com.simibubi.create.content.contraptions; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionStallPacket extends SimplePacketBase { +public record ContraptionStallPacket(int entityId, double x, double y, double z, float angle) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ContraptionStallPacket::entityId, + ByteBufCodecs.DOUBLE, ContraptionStallPacket::x, + ByteBufCodecs.DOUBLE, ContraptionStallPacket::y, + ByteBufCodecs.DOUBLE, ContraptionStallPacket::z, + ByteBufCodecs.FLOAT, ContraptionStallPacket::angle, + ContraptionStallPacket::new + ); - int entityID; - double x; - double y; - double z; - float angle; - - public ContraptionStallPacket(int entityID, double posX, double posY, double posZ, float angle) { - this.entityID = entityID; - this.x = posX; - this.y = posY; - this.z = posZ; - this.angle = angle; - } - - public ContraptionStallPacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - x = buffer.readDouble(); - y = buffer.readDouble(); - z = buffer.readDouble(); - angle = buffer.readFloat(); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + AbstractContraptionEntity.handleStallPacket(this); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - writeAll(buffer, x, y, z); - buffer.writeFloat(angle); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_STALL; } - - @Override - public boolean handle(Context context) { - context.enqueueWork( - () -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> AbstractContraptionEntity.handleStallPacket(this))); - return true; - } - - private void writeAll(FriendlyByteBuf buffer, double... doubles) { - for (double d : doubles) - buffer.writeDouble(d); - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java index 80d0dd8ddd..4ce5bbc3a2 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java @@ -13,6 +13,7 @@ import net.createmod.catnip.utility.math.AngleHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.world.entity.Entity; @@ -21,8 +22,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; /** * Ex: Pistons, bearings
@@ -78,19 +79,16 @@ public class ControlledContraptionEntity extends AbstractContraptionEntity { @Override protected void readAdditional(CompoundTag compound, boolean spawnPacket) { super.readAdditional(compound, spawnPacket); - if (compound.contains("Controller")) // legacy - controllerPos = NbtUtils.readBlockPos(compound.getCompound("Controller")); - else - controllerPos = NbtUtils.readBlockPos(compound.getCompound("ControllerRelative")) - .offset(blockPosition()); + NbtUtils.readBlockPos(compound, "ControllerRelative") + .ifPresent(p -> controllerPos = p.offset(blockPosition())); if (compound.contains("Axis")) rotationAxis = NBTHelper.readEnum(compound, "Axis", Axis.class); angle = compound.getFloat("Angle"); } @Override - protected void writeAdditional(CompoundTag compound, boolean spawnPacket) { - super.writeAdditional(compound, spawnPacket); + protected void writeAdditional(CompoundTag compound, HolderLookup.Provider registries, boolean spawnPacket) { + super.writeAdditional(compound, registries, spawnPacket); compound.put("ControllerRelative", NbtUtils.writeBlockPos(controllerPos.subtract(blockPosition()))); if (rotationAxis != null) NBTHelper.writeEnum(compound, "Axis", rotationAxis); @@ -147,7 +145,9 @@ public class ControlledContraptionEntity extends AbstractContraptionEntity { @Override @OnlyIn(Dist.CLIENT) - public void lerpTo(double x, double y, double z, float yw, float pt, int inc, boolean t) {} + public void lerpTo(double pX, double pY, double pZ, float pYRot, float pXRot, int pSteps) { + super.lerpTo(pX, pY, pZ, pYRot, pXRot, pSteps); + } protected void tickContraption() { angleDelta = angle - prevAngle; diff --git a/src/main/java/com/simibubi/create/content/contraptions/MountedFluidStorage.java b/src/main/java/com/simibubi/create/content/contraptions/MountedFluidStorage.java index 53ddd303f6..f9f363b4c4 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/MountedFluidStorage.java +++ b/src/main/java/com/simibubi/create/content/contraptions/MountedFluidStorage.java @@ -1,24 +1,23 @@ package com.simibubi.create.content.contraptions; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.sync.ContraptionFluidPacket; import com.simibubi.create.content.fluids.tank.CreativeFluidTankBlockEntity; import com.simibubi.create.content.fluids.tank.CreativeFluidTankBlockEntity.CreativeSmartFluidTank; import com.simibubi.create.content.fluids.tank.FluidTankBlockEntity; import com.simibubi.create.foundation.fluid.SmartFluidTank; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.animation.LerpedFloat; import net.createmod.catnip.utility.animation.LerpedFloat.Chaser; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; public class MountedFluidStorage { @@ -62,7 +61,7 @@ public class MountedFluidStorage { packetCooldown--; else if (sendPacket) { sendPacket = false; - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> entity), + CatnipServices.NETWORK.sendToClientsTrackingEntity(entity, new ContraptionFluidPacket(entity.getId(), pos, tank.getFluid())); packetCooldown = 8; } @@ -97,11 +96,9 @@ public class MountedFluidStorage { if (blockEntity == null) return; - IFluidHandler teHandler = blockEntity.getCapability(ForgeCapabilities.FLUID_HANDLER) - .orElse(null); - if (!(teHandler instanceof SmartFluidTank)) + IFluidHandler teHandler = blockEntity.getLevel().getCapability(Capabilities.FluidHandler.BLOCK, blockEntity.getBlockPos(), null); + if (!(teHandler instanceof SmartFluidTank smartTank)) return; - SmartFluidTank smartTank = (SmartFluidTank) teHandler; tank.setFluid(smartTank.getFluid()); sendPacket = false; valid = true; @@ -115,12 +112,10 @@ public class MountedFluidStorage { if (tank instanceof CreativeSmartFluidTank) return; - LazyOptional capability = be.getCapability(ForgeCapabilities.FLUID_HANDLER); - IFluidHandler teHandler = capability.orElse(null); - if (!(teHandler instanceof SmartFluidTank)) + IFluidHandler teHandler = be.getLevel().getCapability(Capabilities.FluidHandler.BLOCK, be.getBlockPos(), null); + if (!(teHandler instanceof SmartFluidTank inv)) return; - SmartFluidTank inv = (SmartFluidTank) teHandler; inv.setFluid(tank.getFluid() .copy()); } @@ -129,21 +124,21 @@ public class MountedFluidStorage { return tank; } - public CompoundTag serialize() { + public CompoundTag serialize(HolderLookup.Provider registries) { if (!valid) return null; - CompoundTag tag = tank.writeToNBT(new CompoundTag()); + CompoundTag tag = tank.writeToNBT(registries, new CompoundTag()); tag.putInt("Capacity", tank.getCapacity()); if (tank instanceof CreativeSmartFluidTank) { NBTHelper.putMarker(tag, "Bottomless"); tag.put("ProvidedStack", tank.getFluid() - .writeToNBT(new CompoundTag())); + .saveOptional(registries)); } return tag; } - public static MountedFluidStorage deserialize(CompoundTag nbt) { + public static MountedFluidStorage deserialize(CompoundTag nbt, HolderLookup.Provider registries) { MountedFluidStorage storage = new MountedFluidStorage(null); if (nbt == null) return storage; @@ -153,7 +148,7 @@ public class MountedFluidStorage { storage.valid = true; if (nbt.contains("Bottomless")) { - FluidStack providedStack = FluidStack.loadFluidStackFromNBT(nbt.getCompound("ProvidedStack")); + FluidStack providedStack = FluidStack.parseOptional(registries, nbt.getCompound("ProvidedStack")); CreativeSmartFluidTank creativeSmartFluidTank = new CreativeSmartFluidTank(capacity, $ -> { }); creativeSmartFluidTank.setContainedFluid(providedStack); @@ -161,7 +156,7 @@ public class MountedFluidStorage { return storage; } - storage.tank.readFromNBT(nbt); + storage.tank.readFromNBT(registries, nbt); return storage; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/MountedStorage.java b/src/main/java/com/simibubi/create/content/contraptions/MountedStorage.java index 424e192c15..2edf3df9ac 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/MountedStorage.java +++ b/src/main/java/com/simibubi/create/content/contraptions/MountedStorage.java @@ -7,22 +7,25 @@ import com.simibubi.create.content.kinetics.crafter.MechanicalCrafterBlockEntity import com.simibubi.create.content.logistics.crate.BottomlessItemHandler; import com.simibubi.create.content.logistics.vault.ItemVaultBlockEntity; import com.simibubi.create.content.processing.recipe.ProcessingInventory; + import net.createmod.catnip.utility.NBTHelper; +import net.minecraft.core.HolderLookup; import net.minecraft.core.NonNullList; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.ContainerHelper; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BarrelBlockEntity; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.ChestBlockEntity; import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.ItemStackHandler; public class MountedStorage { @@ -51,26 +54,24 @@ public class MountedStorage { return true; try { - LazyOptional capability = be.getCapability(ForgeCapabilities.ITEM_HANDLER); - IItemHandler handler = capability.orElse(null); - if (handler instanceof ItemStackHandler) - return !(handler instanceof ProcessingInventory); - return canUseModdedInventory(be, handler); - + IItemHandler capability = be.getLevel().getCapability(Capabilities.ItemHandler.BLOCK, be.getBlockPos(), null); + if (capability instanceof ItemStackHandler) + return !(capability instanceof ProcessingInventory); + return canUseModdedInventory(be, capability); } catch (Exception e) { return false; } } public static boolean canUseModdedInventory(BlockEntity be, IItemHandler handler) { - if (!(handler instanceof IItemHandlerModifiable validItemHandler)) + if (!(handler instanceof IItemHandlerModifiable)) return false; BlockState blockState = be.getBlockState(); if (AllBlockTags.CONTRAPTION_INVENTORY_DENY.matches(blockState)) return false; // There doesn't appear to be much of a standard for tagging chests/barrels - String blockId = ForgeRegistries.BLOCKS.getKey(blockState.getBlock()) + String blockId = BuiltInRegistries.BLOCK.getKey(blockState.getBlock()) .getPath(); if (blockId.contains("ender")) return false; @@ -84,32 +85,35 @@ public class MountedStorage { } public void removeStorageFromWorld() { + Level level = blockEntity.getLevel(); + valid = false; if (blockEntity == null) return; + RegistryAccess registryAccess = level.registryAccess(); + if (blockEntity instanceof ChestBlockEntity) { - CompoundTag tag = blockEntity.saveWithFullMetadata(); + CompoundTag tag = blockEntity.saveWithFullMetadata(registryAccess); if (tag.contains("LootTable", 8)) return; handler = new ItemStackHandler(((ChestBlockEntity) blockEntity).getContainerSize()); NonNullList items = NonNullList.withSize(handler.getSlots(), ItemStack.EMPTY); - ContainerHelper.loadAllItems(tag, items); + ContainerHelper.loadAllItems(tag, items, registryAccess); for (int i = 0; i < items.size(); i++) handler.setStackInSlot(i, items.get(i)); valid = true; return; } - IItemHandler beHandler = blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER) - .orElse(dummyHandler); - if (beHandler == dummyHandler) + IItemHandler beHandler = level.getCapability(Capabilities.ItemHandler.BLOCK, blockEntity.getBlockPos(), null, blockEntity, null); + if (beHandler == null || beHandler == dummyHandler) return; // multiblock vaults need to provide individual invs - if (blockEntity instanceof ItemVaultBlockEntity) { - handler = ((ItemVaultBlockEntity) blockEntity).getInventoryOfBlock(); + if (blockEntity instanceof ItemVaultBlockEntity vbe) { + handler = vbe.getInventoryOfBlock(); valid = true; return; } @@ -141,13 +145,15 @@ public class MountedStorage { return; if (be instanceof ChestBlockEntity) { - CompoundTag tag = be.saveWithFullMetadata(); + RegistryAccess registryAccess = be.getLevel().registryAccess(); + + CompoundTag tag = be.saveWithFullMetadata(registryAccess); tag.remove("Items"); NonNullList items = NonNullList.withSize(handler.getSlots(), ItemStack.EMPTY); for (int i = 0; i < items.size(); i++) items.set(i, handler.getStackInSlot(i)); - ContainerHelper.saveAllItems(tag, items); - be.load(tag); + ContainerHelper.saveAllItems(tag, items, registryAccess); + be.loadWithComponents(tag, registryAccess); return; } @@ -156,12 +162,10 @@ public class MountedStorage { return; } - LazyOptional capability = be.getCapability(ForgeCapabilities.ITEM_HANDLER); - IItemHandler teHandler = capability.orElse(null); - if (!(teHandler instanceof IItemHandlerModifiable)) + IItemHandler capability = be.getLevel().getCapability(Capabilities.ItemHandler.BLOCK, be.getBlockPos(), null); + if (!(capability instanceof IItemHandlerModifiable inv)) return; - IItemHandlerModifiable inv = (IItemHandlerModifiable) teHandler; for (int slot = 0; slot < Math.min(inv.getSlots(), handler.getSlots()); slot++) inv.setStackInSlot(slot, handler.getStackInSlot(slot)); } @@ -170,11 +174,11 @@ public class MountedStorage { return handler; } - public CompoundTag serialize() { + public CompoundTag serialize(HolderLookup.Provider registries) { if (!valid) return null; - CompoundTag tag = handler.serializeNBT(); + CompoundTag tag = handler.serializeNBT(registries); if (noFuel) NBTHelper.putMarker(tag, "NoFuel"); if (handler instanceof ToolboxInventory) @@ -183,29 +187,28 @@ public class MountedStorage { return tag; NBTHelper.putMarker(tag, "Bottomless"); - tag.put("ProvidedStack", handler.getStackInSlot(0) - .serializeNBT()); + tag.put("ProvidedStack", handler.getStackInSlot(0).saveOptional(registries)); return tag; } - public static MountedStorage deserialize(CompoundTag nbt) { + public static MountedStorage deserialize(CompoundTag nbt, HolderLookup.Provider registries) { MountedStorage storage = new MountedStorage(null); storage.handler = new ItemStackHandler(); if (nbt == null) return storage; if (nbt.contains("Toolbox")) storage.handler = new ToolboxInventory(null); - + storage.valid = true; storage.noFuel = nbt.contains("NoFuel"); if (nbt.contains("Bottomless")) { - ItemStack providedStack = ItemStack.of(nbt.getCompound("ProvidedStack")); + ItemStack providedStack = ItemStack.parseOptional(registries, nbt.getCompound("ProvidedStack")); storage.handler = new BottomlessItemHandler(() -> providedStack); return storage; } - storage.handler.deserializeNBT(nbt); + storage.handler.deserializeNBT(registries, nbt); return storage; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/MountedStorageInteraction.java b/src/main/java/com/simibubi/create/content/contraptions/MountedStorageInteraction.java index db1c057984..308616d4ef 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/MountedStorageInteraction.java +++ b/src/main/java/com/simibubi/create/content/contraptions/MountedStorageInteraction.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.function.Supplier; import com.google.common.collect.ImmutableList; +import com.simibubi.create.foundation.blockEntity.LegacyRecipeWrapper; import com.simibubi.create.foundation.utility.CreateLang; import net.minecraft.network.chat.Component; @@ -14,8 +15,7 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ChestMenu; import net.minecraft.world.inventory.MenuType; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.wrapper.RecipeWrapper; +import net.neoforged.neoforge.items.IItemHandlerModifiable; public class MountedStorageInteraction { @@ -27,7 +27,6 @@ public class MountedStorageInteraction { int rows = Mth.clamp(slotCount / 9, 1, 6); MenuType menuType = menus.get(rows - 1); Component menuName = CreateLang.translateDirect("contraptions.moving_container", displayName); - return new MenuProvider() { @Override @@ -44,9 +43,9 @@ public class MountedStorageInteraction { }; } - public static class StorageInteractionContainer extends RecipeWrapper { + public static class StorageInteractionContainer extends LegacyRecipeWrapper { - private Supplier stillValid; + private final Supplier stillValid; public StorageInteractionContainer(IItemHandlerModifiable inv, Supplier stillValid) { super(inv); diff --git a/src/main/java/com/simibubi/create/content/contraptions/MountedStorageManager.java b/src/main/java/com/simibubi/create/content/contraptions/MountedStorageManager.java index 2decc9c531..4e3d9e82aa 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/MountedStorageManager.java +++ b/src/main/java/com/simibubi/create/content/contraptions/MountedStorageManager.java @@ -17,6 +17,7 @@ import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.lang.Components; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtUtils; @@ -31,13 +32,13 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.properties.ChestType; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction; -import net.minecraftforge.fluids.capability.templates.FluidTank; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.wrapper.CombinedInvWrapper; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.IFluidTank; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.IFluidHandler.FluidAction; +import net.neoforged.neoforge.fluids.capability.templates.FluidTank; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.wrapper.CombinedInvWrapper; public class MountedStorageManager { @@ -89,14 +90,14 @@ public class MountedStorageManager { fluidStorage.put(localPos, new MountedFluidStorage(be)); } - public void read(CompoundTag nbt, Map presentBlockEntities, boolean clientPacket) { + public void read(CompoundTag nbt, HolderLookup.Provider registries, Map presentBlockEntities, boolean clientPacket) { storage.clear(); NBTHelper.iterateCompoundList(nbt.getList("Storage", Tag.TAG_COMPOUND), c -> storage - .put(NbtUtils.readBlockPos(c.getCompound("Pos")), MountedStorage.deserialize(c.getCompound("Data")))); + .put(NbtUtils.readBlockPos(c, "Pos").orElseThrow(), MountedStorage.deserialize(c.getCompound("Data"), registries))); fluidStorage.clear(); NBTHelper.iterateCompoundList(nbt.getList("FluidStorage", Tag.TAG_COMPOUND), c -> fluidStorage - .put(NbtUtils.readBlockPos(c.getCompound("Pos")), MountedFluidStorage.deserialize(c.getCompound("Data")))); + .put(NbtUtils.readBlockPos(c, "Pos").orElseThrow(), MountedFluidStorage.deserialize(c.getCompound("Data"), registries))); if (clientPacket && presentBlockEntities != null) bindTanks(presentBlockEntities); @@ -133,7 +134,7 @@ public class MountedStorageManager { }); } - public void write(CompoundTag nbt, boolean clientPacket) { + public void write(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { ListTag storageNBT = new ListTag(); if (!clientPacket) for (BlockPos pos : storage.keySet()) { @@ -142,7 +143,7 @@ public class MountedStorageManager { if (!mountedStorage.isValid()) continue; c.put("Pos", NbtUtils.writeBlockPos(pos)); - c.put("Data", mountedStorage.serialize()); + c.put("Data", mountedStorage.serialize(registries)); storageNBT.add(c); } @@ -153,7 +154,7 @@ public class MountedStorageManager { if (!mountedStorage.isValid()) continue; c.put("Pos", NbtUtils.writeBlockPos(pos)); - c.put("Data", mountedStorage.serialize()); + c.put("Data", mountedStorage.serialize(registries)); fluidStorageNBT.add(c); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java index cdd6c9be6c..65ad62d8f4 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java @@ -8,6 +8,7 @@ import java.util.UUID; import javax.annotation.Nullable; import com.mojang.blaze3d.vertex.PoseStack; +import com.simibubi.create.AllAttachmentTypes; import com.simibubi.create.AllEntityTypes; import com.simibubi.create.content.contraptions.bearing.StabilizedContraption; import com.simibubi.create.content.contraptions.minecart.MinecartSim2020; @@ -26,6 +27,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.network.syncher.EntityDataAccessor; @@ -45,9 +47,8 @@ import net.minecraft.world.level.block.BaseRailBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.RailShape; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.util.LazyOptional; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; /** * Ex: Minecarts, Couplings
@@ -121,10 +122,10 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { } @Override - protected void defineSynchedData() { - super.defineSynchedData(); - entityData.define(COUPLING, Optional.empty()); - entityData.define(INITIAL_ORIENTATION, Direction.UP); + protected void defineSynchedData(SynchedEntityData.Builder builder) { + super.defineSynchedData(builder); + builder.define(COUPLING, Optional.empty()); + builder.define(INITIAL_ORIENTATION, Direction.UP); } @Override @@ -176,8 +177,8 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { } @Override - protected void writeAdditional(CompoundTag compound, boolean spawnPacket) { - super.writeAdditional(compound, spawnPacket); + protected void writeAdditional(CompoundTag compound, HolderLookup.Provider registries, boolean spawnPacket) { + super.writeAdditional(compound, registries, spawnPacket); if (motionBeforeStall != null) compound.put("CachedMotion", newDoubleList(motionBeforeStall.x, motionBeforeStall.y, motionBeforeStall.z)); @@ -280,12 +281,11 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { tickActors(); boolean isStalled = isStalled(); - LazyOptional capability = - riding.getCapability(CapabilityMinecartController.MINECART_CONTROLLER_CAPABILITY); - if (capability.isPresent()) { + if (riding.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) { + MinecartController controller = riding.getData(AllAttachmentTypes.MINECART_CONTROLLER); + if (!level().isClientSide()) - capability.orElse(null) - .setStalledExternally(isStalled); + controller.setStalledExternally(isStalled); } else { if (isStalled) { if (!wasStalled) @@ -405,13 +405,13 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { } protected void powerFurnaceCartWithFuelFromStorage(Entity riding) { - if (!(riding instanceof MinecartFurnace)) + if (!(riding instanceof MinecartFurnace furnaceCart)) return; - MinecartFurnace furnaceCart = (MinecartFurnace) riding; // Notify to not trigger serialization side-effects isSerializingFurnaceCart = true; - CompoundTag nbt = furnaceCart.serializeNBT(); + CompoundTag nbt = new CompoundTag(); + furnaceCart.saveAsPassenger(nbt); isSerializingFurnaceCart = false; int fuel = nbt.getInt("Fuel"); @@ -443,7 +443,7 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { nbt.putInt("Fuel", fuel); nbt.putDouble("PushX", 0); nbt.putDouble("PushZ", 0); - furnaceCart.deserializeNBT(nbt); + furnaceCart.load(nbt); } } @@ -607,7 +607,7 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { @OnlyIn(Dist.CLIENT) public static void handleRelocationPacket(ContraptionRelocationPacket packet) { - if (Minecraft.getInstance().level.getEntity(packet.entityID) instanceof OrientedContraptionEntity oce) + if (Minecraft.getInstance().level.getEntity(packet.entityId()) instanceof OrientedContraptionEntity oce) oce.nonDamageTicks = 10; } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/StructureTransform.java b/src/main/java/com/simibubi/create/content/contraptions/StructureTransform.java index 68b412b96f..2b703c5749 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/StructureTransform.java +++ b/src/main/java/com/simibubi/create/content/contraptions/StructureTransform.java @@ -4,18 +4,23 @@ import static net.minecraft.world.level.block.state.properties.BlockStatePropert import static net.minecraft.world.level.block.state.properties.BlockStateProperties.FACING; import static net.minecraft.world.level.block.state.properties.BlockStateProperties.HORIZONTAL_FACING; +import org.jetbrains.annotations.Nullable; + import com.simibubi.create.api.contraption.transformable.ContraptionTransformableRegistry; import com.simibubi.create.api.contraption.transformable.ITransformableBlock; import com.simibubi.create.api.contraption.transformable.ITransformableBlockEntity; - import com.simibubi.create.impl.contraption.transformable.ContraptionTransformableRegistryImpl; +import io.netty.buffer.ByteBuf; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; import net.createmod.catnip.utility.VecHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.level.block.BellBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FaceAttachedHorizontalDirectionalBlock; @@ -35,18 +40,29 @@ import net.minecraft.world.level.block.state.properties.SlabType; import net.minecraft.world.phys.Vec3; public class StructureTransform { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, transform -> transform.offset, + ByteBufCodecs.VAR_INT, transform -> transform.angle, + CatnipStreamCodecBuilders.nullable(CatnipStreamCodecs.AXIS), transform -> transform.rotationAxis, + CatnipStreamCodecBuilders.nullable(CatnipStreamCodecs.ROTATION), transform -> transform.rotation, + CatnipStreamCodecBuilders.nullable(CatnipStreamCodecs.MIRROR), transform -> transform.mirror, + StructureTransform::new + ); - // Assuming structures cannot be rotated around multiple axes at once - public Axis rotationAxis; public BlockPos offset; public int angle; + // Assuming structures cannot be rotated around multiple axes at once + @Nullable + public Axis rotationAxis; + @Nullable public Rotation rotation; + @Nullable public Mirror mirror; - private StructureTransform(BlockPos offset, int angle, Axis axis, Rotation rotation, Mirror mirror) { + private StructureTransform(BlockPos offset, int angle, @Nullable Axis axis, @Nullable Rotation rotation, @Nullable Mirror mirror) { this.offset = offset; this.angle = angle; - rotationAxis = axis; + this.rotationAxis = axis; this.rotation = rotation; this.mirror = mirror; } @@ -266,24 +282,4 @@ public class StructureTransform { facing = facing.getClockWise(rotationAxis); return facing; } - - public static StructureTransform fromBuffer(FriendlyByteBuf buffer) { - BlockPos readBlockPos = buffer.readBlockPos(); - int readAngle = buffer.readInt(); - int axisIndex = buffer.readVarInt(); - int rotationIndex = buffer.readVarInt(); - int mirrorIndex = buffer.readVarInt(); - return new StructureTransform(readBlockPos, readAngle, axisIndex == -1 ? null : Axis.values()[axisIndex], - rotationIndex == -1 ? null : Rotation.values()[rotationIndex], - mirrorIndex == -1 ? null : Mirror.values()[mirrorIndex]); - } - - public void writeToBuffer(FriendlyByteBuf buffer) { - buffer.writeBlockPos(offset); - buffer.writeInt(angle); - buffer.writeVarInt(rotationAxis == null ? -1 : rotationAxis.ordinal()); - buffer.writeVarInt(rotation == null ? -1 : rotation.ordinal()); - buffer.writeVarInt(mirror == null ? - 1 : mirror.ordinal()); - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/TrainCollisionPacket.java b/src/main/java/com/simibubi/create/content/contraptions/TrainCollisionPacket.java index 63317132ba..5018b66f1c 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/TrainCollisionPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/TrainCollisionPacket.java @@ -1,52 +1,41 @@ package com.simibubi.create.content.contraptions; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.trains.entity.CarriageContraptionEntity; import com.simibubi.create.foundation.damageTypes.CreateDamageSources; -import com.simibubi.create.foundation.networking.SimplePacketBase; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class TrainCollisionPacket extends SimplePacketBase { - - int damage; - int contraptionEntityId; - - public TrainCollisionPacket(int damage, int contraptionEntityId) { - this.damage = damage; - this.contraptionEntityId = contraptionEntityId; - } - - public TrainCollisionPacket(FriendlyByteBuf buffer) { - contraptionEntityId = buffer.readInt(); - damage = buffer.readInt(); - } +public record TrainCollisionPacket(int damage, int contraptionEntityId) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, TrainCollisionPacket::damage, + ByteBufCodecs.INT, TrainCollisionPacket::contraptionEntityId, + TrainCollisionPacket::new + ); @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(contraptionEntityId); - buffer.writeInt(damage); - } + public void handle(ServerPlayer player) { + Level level = player.level(); - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - Level level = player.level(); + Entity entity = level.getEntity(contraptionEntityId); + if (!(entity instanceof CarriageContraptionEntity cce)) + return; - Entity entity = level.getEntity(contraptionEntityId); - if (!(entity instanceof CarriageContraptionEntity cce)) - return; - - player.hurt(CreateDamageSources.runOver(level, cce), damage); - player.level().playSound(player, entity.blockPosition(), SoundEvents.PLAYER_ATTACK_CRIT, SoundSource.NEUTRAL, + player.hurt(CreateDamageSources.runOver(level, cce), damage); + player.level().playSound(player, entity.blockPosition(), SoundEvents.PLAYER_ATTACK_CRIT, SoundSource.NEUTRAL, 1, .75f); - }); - return true; } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.TRAIN_COLLISION; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/AttachedActorBlock.java b/src/main/java/com/simibubi/create/content/contraptions/actors/AttachedActorBlock.java index 7ffb86954e..20e536bd09 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/AttachedActorBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/AttachedActorBlock.java @@ -88,7 +88,7 @@ public abstract class AttachedActorBlock extends HorizontalDirectionalBlock } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlock.java b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlock.java index fc0115820d..b24edac181 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlock.java @@ -1,5 +1,6 @@ package com.simibubi.create.content.contraptions.actors.contraptionControls; +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllShapes; import com.simibubi.create.AllSoundEvents; @@ -13,27 +14,31 @@ import net.minecraft.world.entity.player.Player; 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.HorizontalDirectionalBlock; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.NotNull; + public class ContraptionControlsBlock extends ControlsBlock implements IBE { + public static final MapCodec CODEC = simpleCodec(ContraptionControlsBlock::new); + public ContraptionControlsBlock(Properties pProperties) { super(pProperties); } @Override - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, - BlockHitResult pHit) { - return onBlockEntityUse(pLevel, pPos, cte -> { + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + return onBlockEntityUse(level, pos, cte -> { cte.pressButton(); - if (!pLevel.isClientSide()) { + if (!level.isClientSide()) { cte.disabled = !cte.disabled; cte.notifyUpdate(); - ContraptionControlsBlockEntity.sendStatus(pPlayer, cte.filtering.getFilter(), !cte.disabled); + ContraptionControlsBlockEntity.sendStatus(player, cte.filtering.getFilter(), !cte.disabled); AllSoundEvents.CONTROLLER_CLICK.play(cte.getLevel(), null, cte.getBlockPos(), 1, cte.disabled ? 0.8f : 1.5f); } @@ -68,4 +73,8 @@ public class ContraptionControlsBlock extends ControlsBlock implements IBE codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlockEntity.java index d89cf9c078..e03e53cd57 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsBlockEntity.java @@ -20,6 +20,7 @@ import net.createmod.catnip.utility.math.AngleHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.entity.player.Player; @@ -93,15 +94,15 @@ public class ContraptionControlsBlockEntity extends SmartBlockEntity { } @Override - protected void read(CompoundTag tag, boolean clientPacket) { - super.read(tag, clientPacket); + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.read(tag, registries, clientPacket); disabled = tag.getBoolean("Disabled"); powered = tag.getBoolean("Powered"); } @Override - protected void write(CompoundTag tag, boolean clientPacket) { - super.write(tag, clientPacket); + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.write(tag, registries, clientPacket); tag.putBoolean("Disabled", disabled); tag.putBoolean("Powered", powered); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovement.java b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovement.java index faebc91ff6..ae8b416f24 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovement.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovement.java @@ -16,9 +16,8 @@ import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ContraptionControlsMovement implements MovementBehaviour { @@ -44,14 +43,14 @@ public class ContraptionControlsMovement implements MovementBehaviour { public static boolean isSameFilter(ItemStack stack1, ItemStack stack2) { if (stack1.isEmpty() && stack2.isEmpty()) return true; - return ItemHandlerHelper.canItemStacksStack(stack1, stack2); + return ItemStack.isSameItemSameComponents(stack1, stack2); } public static ItemStack getFilter(MovementContext ctx) { CompoundTag blockEntityData = ctx.blockEntityData; if (blockEntityData == null) return null; - return ItemStack.of(blockEntityData.getCompound("Filter")); + return ItemStack.parseOptional(ctx.world.registryAccess(), blockEntityData.getCompound("Filter")); } public static boolean isDisabledInitially(MovementContext ctx) { diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovingInteraction.java b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovingInteraction.java index 71603c623f..73109a7f5b 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovingInteraction.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionControlsMovingInteraction.java @@ -1,7 +1,6 @@ package com.simibubi.create.content.contraptions.actors.contraptionControls; import com.simibubi.create.AllMovementBehaviours; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; import com.simibubi.create.content.contraptions.Contraption; @@ -11,6 +10,8 @@ import com.simibubi.create.content.contraptions.behaviour.MovementContext; import com.simibubi.create.content.contraptions.behaviour.MovingInteractionBehaviour; import com.simibubi.create.content.contraptions.elevator.ElevatorContraption; import com.simibubi.create.content.contraptions.elevator.ElevatorTargetFloorPacket; +import net.createmod.catnip.platform.CatnipServices; + import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -18,7 +19,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.PacketDistributor; + import org.apache.commons.lang3.tuple.MutablePair; import java.util.Iterator; @@ -100,7 +101,7 @@ public class ContraptionControlsMovingInteraction extends MovingInteractionBehav } private void send(AbstractContraptionEntity contraptionEntity, ItemStack filter, boolean disable) { - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> contraptionEntity), + CatnipServices.NETWORK.sendToClientsTrackingEntity(contraptionEntity, new ContraptionDisableActorPacket(contraptionEntity.getId(), filter, !disable)); } @@ -118,7 +119,7 @@ public class ContraptionControlsMovingInteraction extends MovingInteractionBehav if (efs.currentTargetY == contraption.clientYTarget) return true; - AllPackets.getChannel().sendToServer(new ElevatorTargetFloorPacket(contraptionEntity, efs.currentTargetY)); + CatnipServices.NETWORK.sendToServer(new ElevatorTargetFloorPacket(contraptionEntity, efs.currentTargetY)); if (contraption.presentBlockEntities.get(ctx.localPos) instanceof ContraptionControlsBlockEntity cbe) cbe.pressButton(); return true; diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionDisableActorPacket.java b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionDisableActorPacket.java index 6122b53d05..12cf5fe2ee 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionDisableActorPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/contraptionControls/ContraptionDisableActorPacket.java @@ -1,70 +1,52 @@ package com.simibubi.create.content.contraptions.actors.contraptionControls; -import java.util.Iterator; import java.util.List; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; import com.simibubi.create.content.contraptions.Contraption; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionDisableActorPacket extends SimplePacketBase { +public record ContraptionDisableActorPacket(int entityId, ItemStack filter, boolean enable) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ContraptionDisableActorPacket::entityId, + ItemStack.OPTIONAL_STREAM_CODEC, ContraptionDisableActorPacket::filter, + ByteBufCodecs.BOOL, ContraptionDisableActorPacket::enable, + ContraptionDisableActorPacket::new + ); - private int entityID; - private ItemStack filter; - private boolean enable; - - public ContraptionDisableActorPacket(int entityID, ItemStack filter, boolean enable) { - this.entityID = entityID; - this.filter = filter; - this.enable = enable; - } + @Override + public void handle(LocalPlayer player) { + Entity entityByID = player.clientLevel.getEntity(entityId); + if (!(entityByID instanceof AbstractContraptionEntity ace)) + return; - public ContraptionDisableActorPacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - enable = buffer.readBoolean(); - filter = buffer.readItem(); + Contraption contraption = ace.getContraption(); + List disabledActors = contraption.getDisabledActors(); + if (filter.isEmpty()) + disabledActors.clear(); + + if (!enable) { + disabledActors.add(filter); + contraption.setActorsActive(filter, false); + return; + } + + disabledActors.removeIf(next -> ContraptionControlsMovement.isSameFilter(next, filter) || next.isEmpty()); + + contraption.setActorsActive(filter, true); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - buffer.writeBoolean(enable); - buffer.writeItem(filter); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_ACTOR_TOGGLE; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - Entity entityByID = Minecraft.getInstance().level.getEntity(entityID); - if (!(entityByID instanceof AbstractContraptionEntity ace)) - return; - - Contraption contraption = ace.getContraption(); - List disabledActors = contraption.getDisabledActors(); - if (filter.isEmpty()) - disabledActors.clear(); - - if (!enable) { - disabledActors.add(filter); - contraption.setActorsActive(filter, false); - return; - } - - for (Iterator iterator = disabledActors.iterator(); iterator.hasNext();) { - ItemStack next = iterator.next(); - if (ContraptionControlsMovement.isSameFilter(next, filter) || next.isEmpty()) - iterator.remove(); - } - - contraption.setActorsActive(filter, true); - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterBlock.java b/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterBlock.java index 31e8da7236..c6368b7db9 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterBlock.java @@ -1,13 +1,19 @@ package com.simibubi.create.content.contraptions.actors.harvester; +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.content.contraptions.actors.AttachedActorBlock; import com.simibubi.create.foundation.block.IBE; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.entity.BlockEntityType; +import org.jetbrains.annotations.NotNull; + public class HarvesterBlock extends AttachedActorBlock implements IBE { + public static final MapCodec CODEC = simpleCodec(HarvesterBlock::new); + public HarvesterBlock(Properties p_i48377_1_) { super(p_i48377_1_); } @@ -21,5 +27,9 @@ public class HarvesterBlock extends AttachedActorBlock implements IBE getBlockEntityType() { return AllBlockEntityTypes.HARVESTER.get(); } - + + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java index 38b886ba67..090d972f04 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java @@ -2,6 +2,8 @@ package com.simibubi.create.content.contraptions.actors.harvester; import javax.annotation.Nullable; +import net.neoforged.neoforge.common.SpecialPlantable; + import org.apache.commons.lang3.mutable.MutableBoolean; import com.simibubi.create.content.contraptions.behaviour.MovementBehaviour; @@ -34,7 +36,6 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.block.state.properties.Property; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.IPlantable; public class HarvesterMovementBehaviour implements MovementBehaviour { @@ -149,7 +150,7 @@ public class HarvesterMovementBehaviour implements MovementBehaviour { return false; } - if (state.getBlock() instanceof IPlantable) + if (state.getBlock() instanceof SpecialPlantable) return true; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughBlock.java b/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughBlock.java index ed70dfd0f6..3a280a04c5 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughBlock.java @@ -3,17 +3,23 @@ package com.simibubi.create.content.contraptions.actors.plough; import java.util.UUID; import com.mojang.authlib.GameProfile; +import com.mojang.serialization.MapCodec; import com.simibubi.create.content.contraptions.actors.AttachedActorBlock; import net.minecraft.server.level.ServerLevel; -import net.minecraftforge.common.util.FakePlayer; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; +import net.neoforged.neoforge.common.util.FakePlayer; + +import org.jetbrains.annotations.NotNull; public class PloughBlock extends AttachedActorBlock { - + + public static final MapCodec CODEC = simpleCodec(PloughBlock::new); + public PloughBlock(Properties p_i48377_1_) { super(p_i48377_1_); } - + /** * The OnHoeUse event takes a player, so we better not pass null */ @@ -21,11 +27,15 @@ public class PloughBlock extends AttachedActorBlock { public static final GameProfile PLOUGH_PROFILE = new GameProfile(UUID.fromString("9e2faded-eeee-4ec2-c314-dad129ae971d"), "Plough"); - + public PloughFakePlayer(ServerLevel world) { super(world, PLOUGH_PROFILE); } - + + } + + @Override + protected @NotNull MapCodec codec() { + return CODEC; } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableFluidInterfaceBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableFluidInterfaceBlockEntity.java index 99b3106343..e5834a1de7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableFluidInterfaceBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableFluidInterfaceBlockEntity.java @@ -1,56 +1,55 @@ package com.simibubi.create.content.contraptions.actors.psi; +import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.content.contraptions.Contraption; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; 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; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.fluids.capability.templates.FluidTank; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.capability.templates.FluidTank; public class PortableFluidInterfaceBlockEntity extends PortableStorageInterfaceBlockEntity { - protected LazyOptional capability; + protected IFluidHandler capability; public PortableFluidInterfaceBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { super(type, pos, state); capability = createEmptyHandler(); } + public static void registerCapabilities(RegisterCapabilitiesEvent event) { + event.registerBlockEntity( + Capabilities.FluidHandler.BLOCK, + AllBlockEntityTypes.PORTABLE_FLUID_INTERFACE.get(), + (be, context) -> be.capability + ); + } + @Override - public void startTransferringTo(Contraption contraption, float distance) { - LazyOptional oldcap = capability; - capability = LazyOptional.of(() -> new InterfaceFluidHandler(contraption.getSharedFluidTanks())); - oldcap.invalidate(); + public void startTransferringTo(Contraption contraption, float distance) {; + capability = new InterfaceFluidHandler(contraption.getSharedFluidTanks()); + invalidateCapability(); super.startTransferringTo(contraption, distance); } @Override protected void invalidateCapability() { - capability.invalidate(); + invalidateCapabilities(); } @Override protected void stopTransferring() { - LazyOptional oldcap = capability; capability = createEmptyHandler(); - oldcap.invalidate(); + invalidateCapability(); super.stopTransferring(); } - private LazyOptional createEmptyHandler() { - return LazyOptional.of(() -> new InterfaceFluidHandler(new FluidTank(0))); - } - - @Override - public LazyOptional getCapability(Capability cap, Direction side) { - if (isFluidHandlerCap(cap)) - return capability.cast(); - return super.getCapability(cap, side); + private IFluidHandler createEmptyHandler() { + return new InterfaceFluidHandler(new FluidTank(0)); } public class InterfaceFluidHandler implements IFluidHandler { diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableItemInterfaceBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableItemInterfaceBlockEntity.java index fd72d56279..6cf3d18720 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableItemInterfaceBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableItemInterfaceBlockEntity.java @@ -1,57 +1,56 @@ package com.simibubi.create.content.contraptions.actors.psi; +import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.content.contraptions.Contraption; import com.simibubi.create.foundation.item.ItemHandlerWrapper; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.ItemStackHandler; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.ItemStackHandler; public class PortableItemInterfaceBlockEntity extends PortableStorageInterfaceBlockEntity { - protected LazyOptional capability; + protected IItemHandlerModifiable capability; public PortableItemInterfaceBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { super(type, pos, state); capability = createEmptyHandler(); } + public static void registerCapabilities(RegisterCapabilitiesEvent event) { + event.registerBlockEntity( + Capabilities.ItemHandler.BLOCK, + AllBlockEntityTypes.PORTABLE_STORAGE_INTERFACE.get(), + (be, context) -> be.capability + ); + } + @Override public void startTransferringTo(Contraption contraption, float distance) { - LazyOptional oldCap = capability; - capability = LazyOptional.of(() -> new InterfaceItemHandler(contraption.getSharedInventory())); - oldCap.invalidate(); + capability = new InterfaceItemHandler(contraption.getSharedInventory()); + invalidateCapability(); super.startTransferringTo(contraption, distance); } @Override protected void stopTransferring() { - LazyOptional oldCap = capability; capability = createEmptyHandler(); - oldCap.invalidate(); + invalidateCapability(); super.stopTransferring(); } - private LazyOptional createEmptyHandler() { - return LazyOptional.of(() -> new InterfaceItemHandler(new ItemStackHandler(0))); + private IItemHandlerModifiable createEmptyHandler() { + return new InterfaceItemHandler(new ItemStackHandler(0)); } @Override protected void invalidateCapability() { - capability.invalidate(); - } - - @Override - public LazyOptional getCapability(Capability cap, Direction side) { - if (isItemHandlerCap(cap)) - return capability.cast(); - return super.getCapability(cap, side); + invalidateCapabilities(); } class InterfaceItemHandler extends ItemHandlerWrapper { @@ -75,7 +74,7 @@ public class PortableItemInterfaceBlockEntity extends PortableStorageInterfaceBl if (!canTransfer()) return stack; ItemStack insertItem = super.insertItem(slot, stack, simulate); - if (!simulate && !insertItem.equals(stack, false)) + if (!simulate && !ItemStack.isSameItemSameComponents(insertItem, stack)) onContentTransferred(); return insertItem; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceBlockEntity.java index 37704cdff7..39f7cf9dad 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceBlockEntity.java @@ -11,6 +11,7 @@ import com.simibubi.create.infrastructure.config.AllConfigs; import net.createmod.catnip.utility.animation.LerpedFloat; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; @@ -118,8 +119,8 @@ public abstract class PortableStorageInterfaceBlockEntity extends SmartBlockEnti } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.read(compound, registries, clientPacket); transferTimer = compound.getInt("Timer"); distance = compound.getFloat("Distance"); boolean poweredPreviously = powered; @@ -129,8 +130,8 @@ public abstract class PortableStorageInterfaceBlockEntity extends SmartBlockEnti } @Override - protected void write(CompoundTag compound, boolean clientPacket) { - super.write(compound, clientPacket); + protected void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.write(compound, registries, clientPacket); compound.putInt("Timer", transferTimer); compound.putFloat("Distance", distance); compound.putBoolean("Powered", powered); diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceMovement.java b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceMovement.java index d3e5ba1ea6..58a0b1daf0 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceMovement.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceMovement.java @@ -24,8 +24,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class PortableStorageInterfaceMovement implements MovementBehaviour { @@ -87,7 +87,7 @@ public class PortableStorageInterfaceMovement implements MovementBehaviour { if (!context.data.contains(_workingPos_)) return; - BlockPos pos = NbtUtils.readBlockPos(context.data.getCompound(_workingPos_)); + BlockPos pos = NbtUtils.readBlockPos(context.data, _workingPos_).orElseThrow(); Vec3 target = VecHelper.getCenterOf(pos); if (!context.stall && !onCarriage diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceRenderer.java index 4669c07cdf..583444bc12 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/psi/PortableStorageInterfaceRenderer.java @@ -16,6 +16,7 @@ import dev.engine_room.flywheel.lib.model.baked.PartialModel; import net.createmod.catnip.render.CachedBuffers; import net.createmod.catnip.render.SuperByteBuffer; import net.createmod.catnip.utility.AnimationTickHolder; +import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.animation.LerpedFloat; import net.createmod.catnip.utility.math.AngleHelper; import net.minecraft.client.renderer.LevelRenderer; @@ -91,7 +92,7 @@ public class PortableStorageInterfaceRenderer extends SafeBlockEntityRenderer { private static final int placementHelperId = PlacementHelpers.register(new PlacementHelper()); + public static final MapCodec CODEC = simpleCodec(RollerBlock::new); + public RollerBlock(Properties p_i48377_1_) { super(p_i48377_1_); } @@ -69,20 +76,17 @@ public class RollerBlock extends AttachedActorBlock implements IBE { @@ -100,4 +104,9 @@ public class RollerBlock extends AttachedActorBlock implements IBE codec() { + return CODEC; + } + } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerMovementBehaviour.java index 5a68775a7c..01ca9c19a5 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerMovementBehaviour.java @@ -37,12 +37,14 @@ import dev.engine_room.flywheel.api.visualization.VisualizationContext; import dev.engine_room.flywheel.api.visualization.VisualizationManager; import net.createmod.catnip.utility.Couple; import net.createmod.catnip.utility.Iterate; +import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.Pair; import net.createmod.catnip.utility.VecHelper; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.NbtUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; @@ -59,7 +61,6 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.SlabType; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.registries.ForgeRegistries; public class RollerMovementBehaviour extends BlockBreakingMovementBehaviour { @@ -159,7 +160,7 @@ public class RollerMovementBehaviour extends BlockBreakingMovementBehaviour { if (!context.data.contains("ReferencePos")) return; - BlockPos referencePos = NbtUtils.readBlockPos(context.data.getCompound("ReferencePos")); + BlockPos referencePos = NbtUtils.readBlockPos(context.data, "ReferencePos").orElseThrow(); for (BlockPos otherPos : getPositionsToBreak(context, referencePos)) if (!otherPos.equals(pos)) destroyBlock(context, otherPos); @@ -401,7 +402,7 @@ public class RollerMovementBehaviour extends BlockBreakingMovementBehaviour { } protected BlockState getStateToPaveWith(MovementContext context) { - return getStateToPaveWith(ItemStack.of(context.blockEntityData.getCompound("Filter"))); + return getStateToPaveWith(ItemStack.parseOptional(context.world.registryAccess(), context.blockEntityData.getCompound("Filter"))); } protected BlockState getStateToPaveWithAsSlab(MovementContext context) { @@ -413,7 +414,7 @@ public class RollerMovementBehaviour extends BlockBreakingMovementBehaviour { if (block == null) return null; - ResourceLocation rl = ForgeRegistries.BLOCKS.getKey(block); + ResourceLocation rl = BuiltInRegistries.BLOCK.getKey(block); String namespace = rl.getNamespace(); String blockName = rl.getPath(); int nameLength = blockName.length(); @@ -427,8 +428,7 @@ public class RollerMovementBehaviour extends BlockBreakingMovementBehaviour { possibleSlabLocations.add(blockName.substring(0, nameLength - 7) + "_slab"); for (String locationAttempt : possibleSlabLocations) { - Optional result = ForgeRegistries.BLOCKS.getHolder(new ResourceLocation(namespace, locationAttempt)) - .map(slabHolder -> slabHolder.value()); + Optional result = BuiltInRegistries.BLOCK.getOptional(ResourceLocation.fromNamespaceAndPath(namespace, locationAttempt)); if (result.isEmpty()) continue; return result.get() diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatBlock.java b/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatBlock.java index 11c6c964af..e3d0eea5f7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatBlock.java @@ -17,7 +17,7 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; @@ -34,15 +34,15 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition.Builder; import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.pathfinder.BlockPathTypes; import net.minecraft.world.level.pathfinder.PathComputationType; +import net.minecraft.world.level.pathfinder.PathType; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.EntityCollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.common.util.FakePlayer; +import net.neoforged.neoforge.common.util.FakePlayer; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @@ -108,8 +108,8 @@ public class SeatBlock extends Block implements ProperWaterloggedBlock { } @Override - public BlockPathTypes getBlockPathType(BlockState state, BlockGetter world, BlockPos pos, @Nullable Mob entity) { - return BlockPathTypes.RAIL; + public PathType getBlockPathType(BlockState state, BlockGetter world, BlockPos pos, @Nullable Mob entity) { + return PathType.RAIL; } @Override @@ -127,39 +127,37 @@ public class SeatBlock extends Block implements ProperWaterloggedBlock { } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult p_225533_6_) { + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (player.isShiftKeyDown() || player instanceof FakePlayer) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; - ItemStack heldItem = player.getItemInHand(hand); - DyeColor color = DyeColor.getColor(heldItem); + DyeColor color = DyeColor.getColor(stack); if (color != null && color != this.color) { - if (world.isClientSide) - return InteractionResult.SUCCESS; + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; BlockState newState = BlockHelper.copyProperties(state, AllBlocks.SEATS.get(color) .getDefaultState()); - world.setBlockAndUpdate(pos, newState); - return InteractionResult.SUCCESS; + level.setBlockAndUpdate(pos, newState); + return ItemInteractionResult.SUCCESS; } - List seats = world.getEntitiesOfClass(SeatEntity.class, new AABB(pos)); + List seats = level.getEntitiesOfClass(SeatEntity.class, new AABB(pos)); if (!seats.isEmpty()) { SeatEntity seatEntity = seats.get(0); List passengers = seatEntity.getPassengers(); if (!passengers.isEmpty() && passengers.get(0) instanceof Player) - return InteractionResult.PASS; - if (!world.isClientSide) { + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (!level.isClientSide) { seatEntity.ejectPassengers(); player.startRiding(seatEntity); } - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } - if (world.isClientSide) - return InteractionResult.SUCCESS; - sitDown(world, pos, getLeashed(world, player).or(player)); - return InteractionResult.SUCCESS; + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; + sitDown(level, pos, getLeashed(level, player).or(player)); + return ItemInteractionResult.SUCCESS; } public static boolean isSeatOccupied(Level world, BlockPos pos) { @@ -206,7 +204,7 @@ public class SeatBlock extends Block implements ProperWaterloggedBlock { } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatEntity.java b/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatEntity.java index fb9a258fa9..80116da048 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/seat/SeatEntity.java @@ -8,9 +8,8 @@ import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -23,14 +22,15 @@ import net.minecraft.world.entity.animal.frog.Frog; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.monster.Skeleton; import net.minecraft.world.entity.monster.Slime; +import net.minecraft.world.entity.monster.Spider; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.entity.IEntityAdditionalSpawnData; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.neoforge.common.util.FakePlayer; +import net.neoforged.neoforge.entity.IEntityWithComplexSpawn; -public class SeatEntity extends Entity implements IEntityAdditionalSpawnData { +public class SeatEntity extends Entity implements IEntityWithComplexSpawn { public SeatEntity(EntityType p_i48580_1_, Level p_i48580_2_) { super(p_i48580_1_, p_i48580_2_); @@ -59,25 +59,26 @@ public class SeatEntity extends Entity implements IEntityAdditionalSpawnData { protected void positionRider(Entity pEntity, Entity.MoveFunction pCallback) { if (!this.hasPassenger(pEntity)) return; - double d0 = this.getY() + this.getPassengersRidingOffset() + pEntity.getMyRidingOffset(); - pCallback.accept(pEntity, this.getX(), d0 + getCustomEntitySeatOffset(pEntity), this.getZ()); + double heightOffset = this.getPassengerRidingPosition(pEntity).y - pEntity.getVehicleAttachmentPoint(this).y; + + pCallback.accept(pEntity, this.getX(), 1.0 / 16.0 + heightOffset + getCustomEntitySeatOffset(pEntity), this.getZ()); } public static double getCustomEntitySeatOffset(Entity entity) { if (entity instanceof Slime) - return 0.25f; + return 0.0f; if (entity instanceof Parrot) - return 1 / 16f; + return 1 / 12f; if (entity instanceof Skeleton) return 1 / 8f; - if (entity instanceof Creeper) - return 1 / 8f; if (entity instanceof Cat) - return 1 / 8f; + return 1 / 12f; if (entity instanceof Wolf) return 1 / 16f; if (entity instanceof Frog) - return 1 / 8f + 1 / 64f; + return 1 / 16f + 1.75 / 64f; + if (entity instanceof Spider) + return 1 / 8.0; if (entity instanceof PackageEntity) return 1 / 4f; return 0; @@ -117,7 +118,7 @@ public class SeatEntity extends Entity implements IEntityAdditionalSpawnData { } @Override - protected void defineSynchedData() {} + protected void defineSynchedData(SynchedEntityData.Builder builder) {} @Override protected void readAdditionalSaveData(CompoundTag p_70037_1_) {} @@ -125,11 +126,6 @@ public class SeatEntity extends Entity implements IEntityAdditionalSpawnData { @Override protected void addAdditionalSaveData(CompoundTag p_213281_1_) {} - @Override - public Packet getAddEntityPacket() { - return NetworkHooks.getEntitySpawningPacket(this); - } - public static class Render extends EntityRenderer { public Render(EntityRendererProvider.Context context) { @@ -149,8 +145,8 @@ public class SeatEntity extends Entity implements IEntityAdditionalSpawnData { } @Override - public void writeSpawnData(FriendlyByteBuf buffer) {} + public void writeSpawnData(RegistryFriendlyByteBuf buffer) {} @Override - public void readSpawnData(FriendlyByteBuf additionalData) {} + public void readSpawnData(RegistryFriendlyByteBuf additionalData) {} } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsBlock.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsBlock.java index b784afb168..5dea4d7dbb 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsBlock.java @@ -1,5 +1,6 @@ package com.simibubi.create.content.contraptions.actors.trainControls; +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllShapes; import com.simibubi.create.content.contraptions.ContraptionWorld; import com.simibubi.create.content.equipment.wrench.IWrenchable; @@ -20,11 +21,15 @@ import net.minecraft.world.level.material.FluidState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.NotNull; + public class ControlsBlock extends HorizontalDirectionalBlock implements IWrenchable, ProperWaterloggedBlock { public static final BooleanProperty OPEN = BooleanProperty.create("open"); public static final BooleanProperty VIRTUAL = BooleanProperty.create("virtual"); + public static final MapCodec CODEC = simpleCodec(ControlsBlock::new); + public ControlsBlock(Properties p_54120_) { super(p_54120_); registerDefaultState(defaultBlockState().setValue(OPEN, false) @@ -73,4 +78,8 @@ public class ControlsBlock extends HorizontalDirectionalBlock implements IWrench return AllShapes.CONTROLS_COLLISION.get(pState.getValue(FACING)); } + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java index 2667c87e27..b67088e2d6 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java @@ -3,14 +3,14 @@ package com.simibubi.create.content.contraptions.actors.trainControls; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashSet; -import java.util.Vector; +import java.util.List; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import com.mojang.blaze3d.platform.InputConstants; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.ControlsUtil; import com.simibubi.create.foundation.utility.CreateLang; @@ -37,7 +37,7 @@ public class ControlsHandler { } public static void startControlling(AbstractContraptionEntity entity, BlockPos controllerLocalPos) { - entityRef = new WeakReference(entity); + entityRef = new WeakReference<>(entity); controlsPos = controllerLocalPos; Minecraft.getInstance().player.displayClientMessage( @@ -50,7 +50,7 @@ public class ControlsHandler { AbstractContraptionEntity abstractContraptionEntity = entityRef.get(); if (!currentlyPressed.isEmpty() && abstractContraptionEntity != null) - AllPackets.getChannel().sendToServer(new ControlsInputPacket(currentlyPressed, false, + CatnipServices.NETWORK.sendToServer(new ControlsInputPacket(currentlyPressed, false, abstractContraptionEntity.getId(), controlsPos, false)); packetCooldown = 0; @@ -74,12 +74,11 @@ public class ControlsHandler { .getWindow(), GLFW.GLFW_KEY_ESCAPE)) { BlockPos pos = controlsPos; stopControlling(); - AllPackets.getChannel() - .sendToServer(new ControlsInputPacket(currentlyPressed, false, entity.getId(), pos, true)); + CatnipServices.NETWORK.sendToServer(new ControlsInputPacket(currentlyPressed, false, entity.getId(), pos, true)); return; } - Vector controls = ControlsUtil.getControls(); + List controls = ControlsUtil.getControls(); Collection pressedKeys = new HashSet<>(); for (int i = 0; i < controls.size(); i++) { if (ControlsUtil.isActuallyPressed(controls.get(i))) @@ -93,14 +92,13 @@ public class ControlsHandler { // Released Keys if (!releasedKeys.isEmpty()) { - AllPackets.getChannel() - .sendToServer(new ControlsInputPacket(releasedKeys, false, entity.getId(), controlsPos, false)); + CatnipServices.NETWORK.sendToServer(new ControlsInputPacket(releasedKeys, false, entity.getId(), controlsPos, false)); // AllSoundEvents.CONTROLLER_CLICK.playAt(player.level, player.blockPosition(), 1f, .5f, true); } // Newly Pressed Keys if (!newKeys.isEmpty()) { - AllPackets.getChannel().sendToServer(new ControlsInputPacket(newKeys, true, entity.getId(), controlsPos, false)); + CatnipServices.NETWORK.sendToServer(new ControlsInputPacket(newKeys, true, entity.getId(), controlsPos, false)); packetCooldown = PACKET_RATE; // AllSoundEvents.CONTROLLER_CLICK.playAt(player.level, player.blockPosition(), 1f, .75f, true); } @@ -108,8 +106,7 @@ public class ControlsHandler { // Keepalive Pressed Keys if (packetCooldown == 0) { // if (!pressedKeys.isEmpty()) { - AllPackets.getChannel() - .sendToServer(new ControlsInputPacket(pressedKeys, true, entity.getId(), controlsPos, false)); + CatnipServices.NETWORK.sendToServer(new ControlsInputPacket(pressedKeys, true, entity.getId(), controlsPos, false)); packetCooldown = PACKET_RATE; // } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInputPacket.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInputPacket.java index 4853605364..bf18716c97 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInputPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInputPacket.java @@ -1,81 +1,64 @@ package com.simibubi.create.content.contraptions.actors.trainControls; -import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.UUID; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ControlsInputPacket extends SimplePacketBase { +public record ControlsInputPacket(List activatedButtons, boolean press, int contraptionEntityId, + BlockPos controlsPos, boolean stopControlling) implements ServerboundPacketPayload { - private Collection activatedButtons; - private boolean press; - private int contraptionEntityId; - private BlockPos controlsPos; - private boolean stopControlling; + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecBuilders.list(ByteBufCodecs.VAR_INT), ControlsInputPacket::activatedButtons, + ByteBufCodecs.BOOL, ControlsInputPacket::press, + ByteBufCodecs.INT, ControlsInputPacket::contraptionEntityId, + BlockPos.STREAM_CODEC, ControlsInputPacket::controlsPos, + ByteBufCodecs.BOOL, ControlsInputPacket::stopControlling, + ControlsInputPacket::new + ); - public ControlsInputPacket(Collection activatedButtons, boolean press, int contraptionEntityId, - BlockPos controlsPos, boolean stopControlling) { - this.contraptionEntityId = contraptionEntityId; - this.activatedButtons = activatedButtons; - this.press = press; - this.controlsPos = controlsPos; - this.stopControlling = stopControlling; - } - - public ControlsInputPacket(FriendlyByteBuf buffer) { - contraptionEntityId = buffer.readInt(); - activatedButtons = new ArrayList<>(); - press = buffer.readBoolean(); - int size = buffer.readVarInt(); - for (int i = 0; i < size; i++) - activatedButtons.add(buffer.readVarInt()); - controlsPos = buffer.readBlockPos(); - stopControlling = buffer.readBoolean(); + public ControlsInputPacket(Collection activatedButtons, boolean press, int contraptionEntityId, BlockPos controlsPos, boolean stopControlling) { + // given list is reused, copy it + this(List.copyOf(activatedButtons), press, contraptionEntityId, controlsPos, stopControlling); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(contraptionEntityId); - buffer.writeBoolean(press); - buffer.writeVarInt(activatedButtons.size()); - activatedButtons.forEach(buffer::writeVarInt); - buffer.writeBlockPos(controlsPos); - buffer.writeBoolean(stopControlling); - } + public void handle(ServerPlayer player) { + Level world = player.getCommandSenderWorld(); + UUID uniqueID = player.getUUID(); - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - Level world = player.getCommandSenderWorld(); - UUID uniqueID = player.getUUID(); + if (player.isSpectator() && press) + return; - if (player.isSpectator() && press) - return; + Entity entity = world.getEntity(contraptionEntityId); + if (!(entity instanceof AbstractContraptionEntity ace)) + return; + if (stopControlling) { + ace.stopControlling(controlsPos); + return; + } - Entity entity = world.getEntity(contraptionEntityId); - if (!(entity instanceof AbstractContraptionEntity ace)) - return; - if (stopControlling) { - ace.stopControlling(controlsPos); - return; - } - - if (ace.toGlobalVector(Vec3.atCenterOf(controlsPos), 0) + if (ace.toGlobalVector(Vec3.atCenterOf(controlsPos), 0) .closerThan(player.position(), 16)) - ControlsServerHandler.receivePressed(world, ace, controlsPos, uniqueID, activatedButtons, press); - }); - return true; + ControlsServerHandler.receivePressed(world, ace, controlsPos, uniqueID, activatedButtons, press); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTROLS_INPUT; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInteractionBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInteractionBehaviour.java index c513097a59..cbc563209f 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInteractionBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsInteractionBehaviour.java @@ -10,8 +10,7 @@ import com.simibubi.create.content.contraptions.behaviour.MovingInteractionBehav import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; public class ControlsInteractionBehaviour extends MovingInteractionBehaviour { @@ -35,8 +34,7 @@ public class ControlsInteractionBehaviour extends MovingInteractionBehaviour { contraptionEntity.setControllingPlayer(player.getUUID()); if (player.level().isClientSide) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> ControlsHandler.startControlling(contraptionEntity, localPos)); + ControlsHandler.startControlling(contraptionEntity, localPos); return true; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsMovementBehaviour.java index 9680662b1d..d29b39a0bb 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsMovementBehaviour.java @@ -16,8 +16,8 @@ import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; -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 ControlsMovementBehaviour implements MovementBehaviour { diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsStopControllingPacket.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsStopControllingPacket.java index 2434071495..2dde425420 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsStopControllingPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsStopControllingPacket.java @@ -1,23 +1,28 @@ package com.simibubi.create.content.contraptions.actors.trainControls; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.network.NetworkEvent.Context; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ControlsStopControllingPacket extends SimplePacketBase { +public enum ControlsStopControllingPacket implements ClientboundPacketPayload { + INSTANCE; - public ControlsStopControllingPacket() {} - - public ControlsStopControllingPacket(FriendlyByteBuf buffer) {} + public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); @Override - public void write(FriendlyByteBuf buffer) {} - - @Override - public boolean handle(Context context) { - context.enqueueWork(ControlsHandler::stopControlling); - return true; + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + ControlsHandler.stopControlling(); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTROLS_ABORT; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/BearingContraption.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/BearingContraption.java index ce4f40be7b..4e2c976bb7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/BearingContraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/BearingContraption.java @@ -1,5 +1,7 @@ package com.simibubi.create.content.contraptions.bearing; +import net.minecraft.core.HolderLookup; + import org.apache.commons.lang3.tuple.Pair; import com.simibubi.create.AllBlocks; @@ -72,8 +74,8 @@ public class BearingContraption extends Contraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); tag.putInt("Sails", sailBlocks); tag.putInt("Facing", facing.get3DDataValue()); return tag; diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlock.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlock.java index f04c93965f..b68b0b5834 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlock.java @@ -6,7 +6,9 @@ import com.simibubi.create.foundation.block.IBE; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -20,15 +22,14 @@ public class ClockworkBearingBlock extends BearingBlock implements IBE { + return ItemInteractionResult.FAIL; + if (stack.isEmpty()) { + if (!level.isClientSide) { + withBlockEntityDo(level, pos, be -> { if (be.running) { be.disassemble(); return; @@ -36,9 +37,9 @@ public class ClockworkBearingBlock extends BearingBlock implements IBE { + return ItemInteractionResult.FAIL; + if (stack.isEmpty()) { + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; + withBlockEntityDo(level, pos, be -> { if (be.running) { be.disassemble(); return; } be.assembleNextTick = true; }); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/MechanicalBearingBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/MechanicalBearingBlockEntity.java index 7d437a12be..a2b1883711 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/MechanicalBearingBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/MechanicalBearingBlockEntity.java @@ -19,6 +19,7 @@ import com.simibubi.create.foundation.utility.ServerSpeedProvider; import net.createmod.catnip.utility.math.AngleHelper; 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.util.Mth; @@ -73,19 +74,19 @@ public class MechanicalBearingBlockEntity extends GeneratingKineticBlockEntity } @Override - public void write(CompoundTag compound, boolean clientPacket) { + public void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { compound.putBoolean("Running", running); compound.putFloat("Angle", angle); if (sequencedAngleLimit >= 0) compound.putDouble("SequencedAngleLimit", sequencedAngleLimit); - AssemblyException.write(compound, lastException); - super.write(compound, clientPacket); + AssemblyException.write(compound, registries, lastException); + super.write(compound, registries, clientPacket); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { if (wasMoved) { - super.read(compound, clientPacket); + super.read(compound, registries, clientPacket); return; } @@ -93,8 +94,8 @@ public class MechanicalBearingBlockEntity extends GeneratingKineticBlockEntity running = compound.getBoolean("Running"); angle = compound.getFloat("Angle"); sequencedAngleLimit = compound.contains("SequencedAngleLimit") ? compound.getDouble("SequencedAngleLimit") : -1; - lastException = AssemblyException.read(compound); - super.read(compound, clientPacket); + lastException = AssemblyException.read(compound, registries); + super.read(compound, registries, clientPacket); if (!clientPacket) return; if (running) { diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/SailBlock.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/SailBlock.java index ffc5bbe571..55e69b1d4a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/SailBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/SailBlock.java @@ -24,6 +24,7 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; @@ -34,6 +35,7 @@ import net.minecraft.world.item.ShearsItem; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.pathfinder.PathComputationType; @@ -71,39 +73,37 @@ public class SailBlock extends WrenchableDirectionalBlock { .getOpposite()); } - @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { - ItemStack heldItem = player.getItemInHand(hand); + @Override + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { IPlacementHelper placementHelper = PlacementHelpers.get(placementHelperId); if (!player.isShiftKeyDown() && player.mayBuild()) { - if (placementHelper.matchesItem(heldItem)) { - placementHelper.getOffset(player, world, state, pos, ray) - .placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); - return InteractionResult.SUCCESS; + if (placementHelper.matchesItem(stack)) { + placementHelper.getOffset(player, level, state, pos, hitResult) + .placeInWorld(level, (BlockItem) stack.getItem(), player, hand, hitResult); + return ItemInteractionResult.SUCCESS; } } - if (heldItem.getItem() instanceof ShearsItem) { - if (!world.isClientSide) - world.playSound(null, pos, SoundEvents.SHEEP_SHEAR, SoundSource.BLOCKS, 1.0f, 1.0f); - applyDye(state, world, pos, ray.getLocation(), null); - return InteractionResult.SUCCESS; + if (stack.getItem() instanceof ShearsItem) { + if (!level.isClientSide) + level.playSound(null, pos, SoundEvents.SHEEP_SHEAR, SoundSource.BLOCKS, 1.0f, 1.0f); + applyDye(state, level, pos, hitResult.getLocation(), null); + return ItemInteractionResult.SUCCESS; } if (frame) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; - DyeColor color = DyeColor.getColor(heldItem); + DyeColor color = DyeColor.getColor(stack); if (color != null) { - if (!world.isClientSide) - world.playSound(null, pos, SoundEvents.DYE_USE, SoundSource.BLOCKS, 1.0f, 1.1f - world.random.nextFloat() * .2f); - applyDye(state, world, pos, ray.getLocation(), color); - return InteractionResult.SUCCESS; + if (!level.isClientSide) + level.playSound(null, pos, SoundEvents.DYE_USE, SoundSource.BLOCKS, 1.0f, 1.1f - level.random.nextFloat() * .2f); + applyDye(state, level, pos, hitResult.getLocation(), color); + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } public void applyDye(BlockState state, Level world, BlockPos pos, Vec3 hit, @Nullable DyeColor color) { @@ -182,12 +182,12 @@ public class SailBlock extends WrenchableDirectionalBlock { } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, - Player player) { - ItemStack pickBlock = super.getCloneItemStack(state, target, world, pos, player); + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, + Player player) { + ItemStack pickBlock = super.getCloneItemStack(state, target, level, pos, player); if (pickBlock.isEmpty()) return AllBlocks.SAIL.get() - .getCloneItemStack(state, target, world, pos, player); + .getCloneItemStack(state, target, level, pos, player); return pickBlock; } @@ -216,7 +216,7 @@ public class SailBlock extends WrenchableDirectionalBlock { } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java index 93befc6caf..6d94ba44e8 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java @@ -27,8 +27,8 @@ import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.properties.BlockStateProperties; -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 StabilizedBearingMovementBehaviour implements MovementBehaviour { diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedContraption.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedContraption.java index 67c9946244..fe522e587a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedContraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedContraption.java @@ -6,6 +6,7 @@ import com.simibubi.create.content.contraptions.ContraptionType; 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; @@ -41,8 +42,8 @@ public class StabilizedContraption extends Contraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); tag.putInt("Facing", facing.get3DDataValue()); return tag; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlock.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlock.java index ccbcee5d88..a2872018b2 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlock.java @@ -7,7 +7,9 @@ import net.createmod.catnip.utility.Couple; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -20,26 +22,24 @@ public class WindmillBearingBlock extends BearingBlock implements IBE { + return ItemInteractionResult.FAIL; + if (stack.isEmpty()) { + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; + withBlockEntityDo(level, pos, be -> { if (be.running) { be.disassemble(); return; } be.assembleNextTick = true; }); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlockEntity.java index 8d942487ac..1a66d306ed 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/WindmillBearingBlockEntity.java @@ -12,6 +12,7 @@ import com.simibubi.create.infrastructure.config.AllConfigs; import net.createmod.catnip.utility.lang.Lang; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -83,18 +84,18 @@ public class WindmillBearingBlockEntity extends MechanicalBearingBlockEntity { } @Override - public void write(CompoundTag compound, boolean clientPacket) { + public void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { compound.putFloat("LastGenerated", lastGeneratedSpeed); compound.putBoolean("QueueAssembly", queuedReassembly); - super.write(compound, clientPacket); + super.write(compound, registries, clientPacket); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { if (!wasMoved) lastGeneratedSpeed = compound.getFloat("LastGenerated"); queuedReassembly = compound.getBoolean("QueueAssembly"); - super.read(compound, clientPacket); + super.read(compound, registries, clientPacket); } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementBehaviour.java index 02f502258f..a2581ebc7e 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementBehaviour.java @@ -14,9 +14,9 @@ import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.items.ItemHandlerHelper; public interface MovementBehaviour { diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementContext.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementContext.java index e2d088a613..747a6f47bf 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementContext.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/MovementContext.java @@ -91,7 +91,7 @@ public class MovementContext { public FilterItemStack getFilterFromBE() { if (filter != null) return filter; - return filter = FilterItemStack.of(blockEntityData.getCompound("Filter")); + return filter = FilterItemStack.of(world.registryAccess(), blockEntityData.getCompound("Filter")); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/ContraptionBlockSource.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/ContraptionBlockSource.java deleted file mode 100644 index 870da5cdb0..0000000000 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/ContraptionBlockSource.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.simibubi.create.content.contraptions.behaviour.dispenser; - -import javax.annotation.Nullable; - -import com.simibubi.create.content.contraptions.behaviour.MovementContext; - -import net.minecraft.MethodsReturnNonnullByDefault; -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockSource; -import net.minecraft.core.Direction; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; - -@MethodsReturnNonnullByDefault -public class ContraptionBlockSource implements BlockSource { - private final BlockPos pos; - private final MovementContext context; - private final Direction overrideFacing; - - public ContraptionBlockSource(MovementContext context, BlockPos pos) { - this(context, pos, null); - } - - public ContraptionBlockSource(MovementContext context, BlockPos pos, @Nullable Direction overrideFacing) { - this.pos = pos; - this.context = context; - this.overrideFacing = overrideFacing; - } - - @Override - public double x() { - return (double)this.pos.getX() + 0.5D; - } - - @Override - public double y() { - return (double)this.pos.getY() + 0.5D; - } - - @Override - public double z() { - return (double)this.pos.getZ() + 0.5D; - } - - @Override - public BlockPos getPos() { - return pos; - } - - @Override - public BlockState getBlockState() { - if (context.state.hasProperty(BlockStateProperties.FACING) && overrideFacing != null) - return context.state.setValue(BlockStateProperties.FACING, overrideFacing); - return context.state; - } - - @Override - @Nullable - public T getEntity() { - return null; - } - - @Override - @Nullable - public ServerLevel getLevel() { - MinecraftServer server = context.world.getServer(); - return server != null ? server.getLevel(context.world.dimension()) : null; - } -} diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DispenserMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DispenserMovementBehaviour.java index 1018e98875..9bf635daef 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DispenserMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DispenserMovementBehaviour.java @@ -2,18 +2,27 @@ package com.simibubi.create.content.contraptions.behaviour.dispenser; import java.util.HashMap; +import org.jetbrains.annotations.Nullable; + import com.simibubi.create.content.contraptions.behaviour.MovementContext; import com.simibubi.create.foundation.mixin.accessor.DispenserBlockAccessor; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.core.dispenser.AbstractProjectileDispenseBehavior; +import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; import net.minecraft.core.dispenser.DispenseItemBehavior; +import net.minecraft.core.dispenser.ProjectileDispenseBehavior; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.level.block.entity.DispenserBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.phys.Vec3; public class DispenserMovementBehaviour extends DropperMovementBehaviour { @@ -30,8 +39,8 @@ public class DispenserMovementBehaviour extends DropperMovementBehaviour { MOVED_DISPENSE_ITEM_BEHAVIOURS.put(item, movedDispenseItemBehaviour); } - public static DispenseItemBehavior getDispenseMethod(ItemStack itemstack) { - return ((DispenserBlockAccessor) Blocks.DISPENSER).create$callGetDispenseMethod(itemstack); + public static DispenseItemBehavior getDispenseMethod(Level level, ItemStack itemstack) { + return ((DispenserBlockAccessor) Blocks.DISPENSER).create$callGetDispenseMethod(level, itemstack); } @Override @@ -60,9 +69,9 @@ public class DispenserMovementBehaviour extends DropperMovementBehaviour { return; } - DispenseItemBehavior behavior = getDispenseMethod(itemStack); - if (behavior instanceof AbstractProjectileDispenseBehavior) { // Projectile behaviours can be converted most of the time - IMovedDispenseItemBehaviour movedBehaviour = MovedProjectileDispenserBehaviour.of((AbstractProjectileDispenseBehavior) behavior); + DispenseItemBehavior behavior = getDispenseMethod(context.world, itemStack); + if (behavior instanceof ProjectileDispenseBehavior projectileDispenseBehavior) { // Projectile behaviours can be converted most of the time + IMovedDispenseItemBehaviour movedBehaviour = MovedProjectileDispenserBehaviour.of(projectileDispenseBehavior); setItemStackAt(location, movedBehaviour.dispense(itemStack, context, pos), context); MOVED_PROJECTILE_DISPENSE_BEHAVIOURS.put(itemStack.getItem(), movedBehaviour); // buffer conversion if successful return; @@ -72,7 +81,22 @@ public class DispenserMovementBehaviour extends DropperMovementBehaviour { facingVec = context.rotation.apply(facingVec); facingVec.normalize(); Direction clostestFacing = Direction.getNearest(facingVec.x, facingVec.y, facingVec.z); - ContraptionBlockSource blockSource = new ContraptionBlockSource(context, pos, clostestFacing); + + MinecraftServer server = context.world.getServer(); + ServerLevel serverLevel = server != null ? server.getLevel(context.world.dimension()) : null; + + BlockState state; + if (context.state.hasProperty(BlockStateProperties.FACING) && clostestFacing != null) { + state = context.state.setValue(BlockStateProperties.FACING, clostestFacing); + } else { + state = context.state; + } + + @Nullable DispenserBlockEntity blockEntity = null; + if (context.world.getBlockEntity(pos) instanceof DispenserBlockEntity dispenserBlockEntity) + blockEntity = dispenserBlockEntity; + + BlockSource blockSource = new BlockSource(serverLevel, pos, state, blockEntity); if (behavior.getClass() != DefaultDispenseItemBehavior.class) { // There is a dispense item behaviour registered for the vanilla dispenser setItemStackAt(location, behavior.dispense(blockSource, itemStack), context); diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DropperMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DropperMovementBehaviour.java index 65f73bbe26..b6484ea38c 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DropperMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/DropperMovementBehaviour.java @@ -10,6 +10,7 @@ import com.simibubi.create.foundation.item.ItemHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.ContainerHelper; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; @@ -40,17 +41,17 @@ public class DropperMovementBehaviour implements MovementBehaviour { private void collectItems(MovementContext context) { getStacks(context).stream() .filter(itemStack -> !itemStack.isEmpty() && itemStack.getItem() != Items.AIR - && itemStack.getMaxStackSize() > itemStack.getCount()) + && itemStack.getOrDefault(DataComponents.MAX_STACK_SIZE, 64) > itemStack.getCount()) .forEach(itemStack -> itemStack.grow(ItemHelper - .extract(context.contraption.getSharedInventory(), (otherItemStack) -> ItemStack.isSameItemSameTags(itemStack, otherItemStack), - ItemHelper.ExtractionCountMode.UPTO, itemStack.getMaxStackSize() - itemStack.getCount(), false) + .extract(context.contraption.getSharedInventory(), (otherItemStack) -> ItemStack.isSameItemSameComponents(itemStack, otherItemStack), + ItemHelper.ExtractionCountMode.UPTO, itemStack.getOrDefault(DataComponents.MAX_STACK_SIZE, 64) - itemStack.getCount(), false) .getCount())); } private void updateTemporaryData(MovementContext context) { if (!(context.temporaryData instanceof NonNullList) && context.world != null) { NonNullList stacks = NonNullList.withSize(getInvSize(), ItemStack.EMPTY); - ContainerHelper.loadAllItems(context.blockEntityData, stacks); + ContainerHelper.loadAllItems(context.blockEntityData, stacks, context.world.registryAccess()); context.temporaryData = stacks; } } @@ -68,7 +69,7 @@ public class DropperMovementBehaviour implements MovementBehaviour { ItemStack testStack = getItemStackAt(location, context); if (testStack == null || testStack.isEmpty()) continue; - if (testStack.getMaxStackSize() == 1) { + if (testStack.getOrDefault(DataComponents.MAX_STACK_SIZE, 64) == 1) { location = new DispenseItemLocation(false, ItemHelper.findFirstMatchingSlotIndex( context.contraption.getSharedInventory(), ItemHelper.sameItemPredicate(testStack))); if (!getItemStackAt(location, context).isEmpty()) @@ -84,7 +85,7 @@ public class DropperMovementBehaviour implements MovementBehaviour { NonNullList stacks = getStacks(context); if (stacks == null) return; - ContainerHelper.saveAllItems(context.blockEntityData, stacks); + ContainerHelper.saveAllItems(context.blockEntityData, stacks, context.world.registryAccess()); } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/IMovedDispenseItemBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/IMovedDispenseItemBehaviour.java index f1deec3e8c..758ddfa024 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/IMovedDispenseItemBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/IMovedDispenseItemBehaviour.java @@ -4,6 +4,7 @@ import com.simibubi.create.content.contraptions.behaviour.MovementContext; import net.minecraft.Util; import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; @@ -21,7 +22,7 @@ import net.minecraft.world.entity.projectile.ThrownPotion; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.SpawnEggItem; -import net.minecraft.world.item.alchemy.PotionUtils; +import net.minecraft.world.item.alchemy.PotionContents; import net.minecraft.world.item.alchemy.Potions; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; @@ -41,7 +42,7 @@ public interface IMovedDispenseItemBehaviour { if (!(itemStack.getItem() instanceof SpawnEggItem)) return super.dispenseStack(itemStack, context, pos, facing); if (context.world instanceof ServerLevel) { - EntityType entityType = ((SpawnEggItem) itemStack.getItem()).getType(itemStack.getTag()); + EntityType entityType = ((SpawnEggItem) itemStack.getItem()).getType(itemStack); Entity spawnedEntity = entityType.spawn((ServerLevel) context.world, itemStack, null, pos.offset(BlockPos.containing(facing.x + .7, facing.y + .7, facing.z + .7)), MobSpawnType.DISPENSER, facing.y < .5, false); @@ -60,8 +61,8 @@ public interface IMovedDispenseItemBehaviour { static void init() { MovedProjectileDispenserBehaviour movedPotionDispenseItemBehaviour = new MovedProjectileDispenserBehaviour() { @Override - protected Projectile getProjectileEntity(Level world, double x, double y, double z, ItemStack itemStack) { - return Util.make(new ThrownPotion(world, x, y, z), (p_218411_1_) -> p_218411_1_.setItem(itemStack)); + protected Projectile getProjectileEntity(Level world, double x, double y, double z, ItemStack itemStack, Direction facing) { + return Util.make(new ThrownPotion(world, x, y, z), (thrownPotion) -> thrownPotion.setItem(itemStack)); } protected float getProjectileInaccuracy() { @@ -134,10 +135,10 @@ public interface IMovedDispenseItemBehaviour { double z = pos.getZ() + facing.z * .7 + .5; context.world.addFreshEntity(Util.make( new SmallFireball(context.world, x, y, z, - random.nextGaussian() * 0.05D + facing.x + context.motion.x, + new Vec3(random.nextGaussian() * 0.05D + facing.x + context.motion.x, random.nextGaussian() * 0.05D + facing.y + context.motion.y, - random.nextGaussian() * 0.05D + facing.z + context.motion.z), - (p_229425_1_) -> p_229425_1_.setItem(itemStack))); + random.nextGaussian() * 0.05D + facing.z + context.motion.z).normalize()), + (smallFireball) -> smallFireball.setItem(itemStack))); itemStack.shrink(1); return itemStack; } @@ -162,7 +163,7 @@ public interface IMovedDispenseItemBehaviour { .is(FluidTags.WATER)) { this.successful = true; return placeItemInInventory(itemStack, - PotionUtils.setPotion(new ItemStack(Items.POTION), Potions.WATER), context, pos, facing); + PotionContents.createItemStack(Items.POTION, Potions.WATER), context, pos, facing); } else { return super.dispenseStack(itemStack, context, pos, facing); } @@ -178,7 +179,7 @@ public interface IMovedDispenseItemBehaviour { BlockState state = context.world.getBlockState(interactAt); Block block = state.getBlock(); if (block instanceof BucketPickup) { - ItemStack bucket = ((BucketPickup) block).pickupBlock(context.world, interactAt, state); + ItemStack bucket = ((BucketPickup) block).pickupBlock(null, context.world, interactAt, state); return placeItemInInventory(itemStack, bucket, context, pos, facing); } return super.dispenseStack(itemStack, context, pos, facing); diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedDefaultDispenseItemBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedDefaultDispenseItemBehaviour.java index 1ad03f1bcf..9121761f52 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedDefaultDispenseItemBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedDefaultDispenseItemBehaviour.java @@ -12,7 +12,7 @@ import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.DispenserBlock; import net.minecraft.world.level.block.entity.HopperBlockEntity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.items.ItemHandlerHelper; public class MovedDefaultDispenseItemBehaviour implements IMovedDispenseItemBehaviour { private static final MovedDefaultDispenseItemBehaviour DEFAULT_INSTANCE = new MovedDefaultDispenseItemBehaviour(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedProjectileDispenserBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedProjectileDispenserBehaviour.java index 2d99d36172..247aafa9f4 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedProjectileDispenserBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/behaviour/dispenser/MovedProjectileDispenserBehaviour.java @@ -3,10 +3,11 @@ package com.simibubi.create.content.contraptions.behaviour.dispenser; import javax.annotation.Nullable; import com.simibubi.create.content.contraptions.behaviour.MovementContext; -import com.simibubi.create.foundation.mixin.accessor.AbstractProjectileDispenseBehaviorAccessor; +import com.simibubi.create.foundation.mixin.accessor.ProjectileDispenseBehaviorAccessor; import net.minecraft.core.BlockPos; -import net.minecraft.core.dispenser.AbstractProjectileDispenseBehavior; +import net.minecraft.core.Direction; +import net.minecraft.core.dispenser.ProjectileDispenseBehavior; import net.minecraft.world.entity.projectile.Projectile; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -20,7 +21,7 @@ public abstract class MovedProjectileDispenserBehaviour extends MovedDefaultDisp double x = pos.getX() + facing.x * .7 + .5; double y = pos.getY() + facing.y * .7 + .5; double z = pos.getZ() + facing.z * .7 + .5; - Projectile projectile = this.getProjectileEntity(context.world, x, y, z, itemStack.copy()); + Projectile projectile = this.getProjectileEntity(context.world, x, y, z, itemStack.copy(), getClosestFacingDirection(facing)); if (projectile == null) return itemStack; Vec3 effectiveMovementVec = facing.scale(getProjectileVelocity()).add(context.motion); @@ -36,7 +37,7 @@ public abstract class MovedProjectileDispenserBehaviour extends MovedDefaultDisp } @Nullable - protected abstract Projectile getProjectileEntity(Level world, double x, double y, double z, ItemStack itemStack); + protected abstract Projectile getProjectileEntity(Level world, double x, double y, double z, ItemStack itemStack, Direction facing); protected float getProjectileInaccuracy() { return 6.0F; @@ -46,22 +47,22 @@ public abstract class MovedProjectileDispenserBehaviour extends MovedDefaultDisp return 1.1F; } - public static MovedProjectileDispenserBehaviour of(AbstractProjectileDispenseBehavior vanillaBehaviour) { - AbstractProjectileDispenseBehaviorAccessor accessor = (AbstractProjectileDispenseBehaviorAccessor) vanillaBehaviour; + public static MovedProjectileDispenserBehaviour of(ProjectileDispenseBehavior vanillaBehaviour) { + ProjectileDispenseBehaviorAccessor accessor = (ProjectileDispenseBehaviorAccessor) vanillaBehaviour; return new MovedProjectileDispenserBehaviour() { @Override - protected Projectile getProjectileEntity(Level world, double x, double y, double z, ItemStack itemStack) { - return accessor.create$callGetProjectile(world, new SimplePos(x, y, z), itemStack); + protected Projectile getProjectileEntity(Level world, double x, double y, double z, ItemStack itemStack, Direction facing) { + return accessor.create$getProjectileItem().asProjectile(world, new SimplePos(x, y, z), itemStack, facing); } @Override protected float getProjectileInaccuracy() { - return accessor.create$callGetUncertainty(); + return accessor.create$getDispenseConfig().uncertainty(); } @Override protected float getProjectileVelocity() { - return accessor.create$callGetPower(); + return accessor.create$getDispenseConfig().power(); } }; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/chassis/AbstractChassisBlock.java b/src/main/java/com/simibubi/create/content/contraptions/chassis/AbstractChassisBlock.java index 1cc4bb98fb..5efe56f9b8 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/chassis/AbstractChassisBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/chassis/AbstractChassisBlock.java @@ -12,7 +12,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; @@ -25,7 +25,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; public abstract class AbstractChassisBlock extends RotatedPillarBlock implements IWrenchable, IBE, ITransformableBlock { @@ -34,52 +34,50 @@ public abstract class AbstractChassisBlock extends RotatedPillarBlock implements } @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (!player.mayBuild()) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; - ItemStack heldItem = player.getItemInHand(handIn); - boolean isSlimeBall = heldItem.is(Tags.Items.SLIMEBALLS) || AllItems.SUPER_GLUE.isIn(heldItem); + boolean isSlimeBall = stack.is(Tags.Items.SLIMEBALLS) || AllItems.SUPER_GLUE.isIn(stack); - BooleanProperty affectedSide = getGlueableSide(state, hit.getDirection()); + BooleanProperty affectedSide = getGlueableSide(state, hitResult.getDirection()); if (affectedSide == null) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; if (isSlimeBall && state.getValue(affectedSide)) { for (Direction face : Iterate.directions) { BooleanProperty glueableSide = getGlueableSide(state, face); if (glueableSide != null && !state.getValue(glueableSide) - && glueAllowedOnSide(worldIn, pos, state, face)) { - if (worldIn.isClientSide) { - Vec3 vec = hit.getLocation(); - worldIn.addParticle(ParticleTypes.ITEM_SLIME, vec.x, vec.y, vec.z, 0, 0, 0); - return InteractionResult.SUCCESS; + && glueAllowedOnSide(level, pos, state, face)) { + if (level.isClientSide) { + Vec3 vec = hitResult.getLocation(); + level.addParticle(ParticleTypes.ITEM_SLIME, vec.x, vec.y, vec.z, 0, 0, 0); + return ItemInteractionResult.SUCCESS; } - AllSoundEvents.SLIME_ADDED.playOnServer(worldIn, pos, .5f, 1); + AllSoundEvents.SLIME_ADDED.playOnServer(level, pos, .5f, 1); state = state.setValue(glueableSide, true); } } - if (!worldIn.isClientSide) - worldIn.setBlockAndUpdate(pos, state); - return InteractionResult.SUCCESS; + if (!level.isClientSide) + level.setBlockAndUpdate(pos, state); + return ItemInteractionResult.SUCCESS; } - if ((!heldItem.isEmpty() || !player.isShiftKeyDown()) && !isSlimeBall) - return InteractionResult.PASS; + if ((!stack.isEmpty() || !player.isShiftKeyDown()) && !isSlimeBall) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; if (state.getValue(affectedSide) == isSlimeBall) - return InteractionResult.PASS; - if (!glueAllowedOnSide(worldIn, pos, state, hit.getDirection())) - return InteractionResult.PASS; - if (worldIn.isClientSide) { - Vec3 vec = hit.getLocation(); - worldIn.addParticle(ParticleTypes.ITEM_SLIME, vec.x, vec.y, vec.z, 0, 0, 0); - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (!glueAllowedOnSide(level, pos, state, hitResult.getDirection())) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (level.isClientSide) { + Vec3 vec = hitResult.getLocation(); + level.addParticle(ParticleTypes.ITEM_SLIME, vec.x, vec.y, vec.z, 0, 0, 0); + return ItemInteractionResult.SUCCESS; } - AllSoundEvents.SLIME_ADDED.playOnServer(worldIn, pos, .5f, 1); - worldIn.setBlockAndUpdate(pos, state.setValue(affectedSide, isSlimeBall)); - return InteractionResult.SUCCESS; + AllSoundEvents.SLIME_ADDED.playOnServer(level, pos, .5f, 1); + level.setBlockAndUpdate(pos, state.setValue(affectedSide, isSlimeBall)); + return ItemInteractionResult.SUCCESS; } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java index fc135c2863..c80f71ffed 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java @@ -24,11 +24,13 @@ import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollVa import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.infrastructure.config.AllConfigs; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Iterate; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Player; @@ -37,9 +39,8 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ChassisBlockEntity extends SmartBlockEntity { @@ -59,7 +60,7 @@ public class ChassisBlockEntity extends SmartBlockEntity { range.requiresWrench(); range.between(1, max); range.withClientCallback( - i -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> ChassisRangeDisplay.display(this))); + i -> CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> ChassisRangeDisplay.display(this))); range.setValue(max / 2); range.withFormatter(s -> String.valueOf(currentlySelectedRange)); behaviours.add(range); @@ -74,8 +75,8 @@ public class ChassisBlockEntity extends SmartBlockEntity { } @Override - protected void read(CompoundTag tag, boolean clientPacket) { - super.read(tag, clientPacket); + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.read(tag, registries, clientPacket); if (clientPacket) currentlySelectedRange = getRange(); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/chassis/StickerBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/chassis/StickerBlockEntity.java index baac9ee400..faa98bd20d 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/chassis/StickerBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/chassis/StickerBlockEntity.java @@ -10,17 +10,18 @@ import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import dev.engine_room.flywheel.lib.visualization.VisualizationHelper; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.animation.LerpedFloat; import net.createmod.catnip.utility.animation.LerpedFloat.Chaser; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class StickerBlockEntity extends SmartBlockEntity { @@ -59,7 +60,7 @@ public class StickerBlockEntity extends SmartBlockEntity { if (isAttachedToBlock() && piston.getValue(0) != piston.getValue() && piston.getValue() == 1) { SuperGlueItem.spawnParticles(level, worldPosition, getBlockState().getValue(StickerBlock.FACING), true); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> playSound(true)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> playSound(true)); } if (!update) @@ -67,10 +68,10 @@ public class StickerBlockEntity extends SmartBlockEntity { update = false; int target = isBlockStateExtended() ? 1 : 0; if (isAttachedToBlock() && target == 0 && piston.getChaseTarget() == 1) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> playSound(false)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> playSound(false)); piston.chase(target, .4f, Chaser.LINEAR); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> VisualizationHelper.queueUpdate(this)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> VisualizationHelper.queueUpdate(this)); } public boolean isAttachedToBlock() { @@ -82,13 +83,13 @@ public class StickerBlockEntity extends SmartBlockEntity { } @Override - protected void write(CompoundTag tag, boolean clientPacket) { - super.write(tag, clientPacket); + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.write(tag, registries, clientPacket); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.read(compound, registries, clientPacket); if (clientPacket) update = true; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorColumn.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorColumn.java index 74e4114b91..4e82c27dd3 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorColumn.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorColumn.java @@ -8,7 +8,6 @@ import java.util.Map; import java.util.Objects; import javax.annotation.Nullable; - import com.simibubi.create.AllBlocks; import com.simibubi.create.foundation.utility.BlockHelper; diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlock.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlock.java index cc9696235e..09e56db198 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlock.java @@ -1,17 +1,26 @@ package com.simibubi.create.content.contraptions.elevator; +import java.util.Optional; + +import javax.annotation.Nullable; + +import org.jetbrains.annotations.NotNull; + +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllItems; +import com.simibubi.create.api.schematic.requirement.ISpecialBlockItemRequirement; import com.simibubi.create.content.contraptions.elevator.ElevatorColumn.ColumnCoords; import com.simibubi.create.content.redstone.contact.RedstoneContactBlock; import com.simibubi.create.content.redstone.diodes.BrassDiodeBlock; -import com.simibubi.create.api.schematic.requirement.ISpecialBlockItemRequirement; import com.simibubi.create.content.schematics.requirement.ItemRequirement; import com.simibubi.create.foundation.block.IBE; import com.simibubi.create.foundation.block.WrenchableDirectionalBlock; import com.simibubi.create.foundation.utility.BlockHelper; + import net.createmod.catnip.gui.ScreenOpener; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -20,14 +29,17 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.SignalGetter; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.DirectionalBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -35,12 +47,9 @@ import net.minecraft.world.level.block.state.StateDefinition.Builder; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; - -import javax.annotation.Nullable; -import java.util.Optional; +import net.minecraft.world.phys.HitResult; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ElevatorContactBlock extends WrenchableDirectionalBlock implements IBE, ISpecialBlockItemRequirement { @@ -49,6 +58,8 @@ public class ElevatorContactBlock extends WrenchableDirectionalBlock public static final BooleanProperty CALLING = BooleanProperty.create("calling"); public static final BooleanProperty POWERING = BrassDiodeBlock.POWERING; + public static final MapCodec CODEC = simpleCodec(ElevatorContactBlock::new); + public ElevatorContactBlock(Properties pProperties) { super(pProperties); registerDefaultState(defaultBlockState().setValue(CALLING, false) @@ -187,7 +198,7 @@ public class ElevatorContactBlock extends WrenchableDirectionalBlock } @Override - public ItemStack getCloneItemStack(BlockGetter pLevel, BlockPos pPos, BlockState pState) { + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { return AllBlocks.REDSTONE_CONTACT.asStack(); } @@ -224,13 +235,11 @@ public class ElevatorContactBlock extends WrenchableDirectionalBlock } @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { - if (player != null && AllItems.WRENCH.isIn(player.getItemInHand(handIn))) - return InteractionResult.PASS; - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, - () -> () -> withBlockEntityDo(worldIn, pos, be -> this.displayScreen(be, player))); - return InteractionResult.SUCCESS; + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + if (player != null && AllItems.WRENCH.isIn(stack)) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> withBlockEntityDo(level, pos, be -> this.displayScreen(be, player))); + return ItemInteractionResult.SUCCESS; } @OnlyIn(value = Dist.CLIENT) @@ -244,4 +253,8 @@ public class ElevatorContactBlock extends WrenchableDirectionalBlock return state.getValue(POWERING) ? 10 : 0; } + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlockEntity.java index 52b97dbf93..0659b98bb7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactBlockEntity.java @@ -11,6 +11,7 @@ import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour import net.createmod.catnip.utility.Couple; import net.createmod.catnip.utility.NBTHelper; import net.minecraft.core.BlockPos; +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; @@ -42,8 +43,8 @@ public class ElevatorContactBlockEntity extends SmartBlockEntity { } @Override - protected void write(CompoundTag tag, boolean clientPacket) { - super.write(tag, clientPacket); + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.write(tag, registries, clientPacket); tag.putString("ShortName", shortName); tag.putString("LongName", longName); @@ -66,8 +67,8 @@ public class ElevatorContactBlockEntity extends SmartBlockEntity { } @Override - protected void read(CompoundTag tag, boolean clientPacket) { - super.read(tag, clientPacket); + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.read(tag, registries, clientPacket); shortName = tag.getString("ShortName"); longName = tag.getString("LongName"); diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactEditPacket.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactEditPacket.java index 2a8a4487dd..5c3d8d2358 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactEditPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorContactEditPacket.java @@ -1,17 +1,28 @@ package com.simibubi.create.content.contraptions.elevator; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.decoration.slidingDoor.DoorControl; import com.simibubi.create.foundation.networking.BlockEntityConfigurationPacket; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; public class ElevatorContactEditPacket extends BlockEntityConfigurationPacket { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, packet -> packet.pos, + ByteBufCodecs.stringUtf8(4), packet -> packet.shortName, + ByteBufCodecs.stringUtf8(90), packet -> packet.longName, + DoorControl.STREAM_CODEC, packet -> packet.doorControl, + ElevatorContactEditPacket::new + ); - private String shortName; - private String longName; - private DoorControl doorControl; + private final String shortName; + private final String longName; + private final DoorControl doorControl; public ElevatorContactEditPacket(BlockPos pos, String shortName, String longName, DoorControl doorControl) { super(pos); @@ -20,28 +31,14 @@ public class ElevatorContactEditPacket extends BlockEntityConfigurationPacket entity), + CatnipServices.NETWORK.sendToClientsTrackingEntity(entity, new ElevatorFloorListPacket(entity, namesList)); } @@ -109,11 +109,9 @@ public class ElevatorContraption extends PulleyContraption { throw new AssemblyException(CreateLang.translateDirect("gui.assembly.exception.no_contacts")); if (contacts > 1) throw new AssemblyException(CreateLang.translateDirect("gui.assembly.exception.too_many_contacts")); - ElevatorColumn column = ElevatorColumn.get(world, getGlobalColumn()); if (column != null && column.isActive()) throw new AssemblyException(CreateLang.translateDirect("gui.assembly.exception.column_conflict")); - startMoving(world); return true; } @@ -150,8 +148,8 @@ public class ElevatorContraption extends PulleyContraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); tag.putBoolean("Arrived", arrived); tag.put("Column", column.write()); tag.putInt("ContactY", contactYOffset); diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorControlsHandler.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorControlsHandler.java index 5f5e85288d..b90cc08c19 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorControlsHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorControlsHandler.java @@ -28,8 +28,8 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemp import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ElevatorControlsHandler { diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorFloorListPacket.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorFloorListPacket.java index 335af1c854..88934c227e 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorFloorListPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorFloorListPacket.java @@ -1,97 +1,80 @@ package com.simibubi.create.content.contraptions.elevator; +import java.util.List; + import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.net.base.ServerboundPacketPayload; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; import net.createmod.catnip.utility.Couple; import net.createmod.catnip.utility.IntAttached; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -import java.util.ArrayList; -import java.util.List; +public record ElevatorFloorListPacket(int entityId, List>> floors) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ElevatorFloorListPacket::entityId, + CatnipStreamCodecBuilders.list(IntAttached.streamCodec(Couple.streamCodec(ByteBufCodecs.STRING_UTF8))), ElevatorFloorListPacket::floors, + ElevatorFloorListPacket::new + ); -public class ElevatorFloorListPacket extends SimplePacketBase { - - private int entityId; - private List>> floorsList; - - public ElevatorFloorListPacket(AbstractContraptionEntity entity, List>> floorsList) { - this.entityId = entity.getId(); - this.floorsList = floorsList; - } - - public ElevatorFloorListPacket(FriendlyByteBuf buffer) { - entityId = buffer.readInt(); - int size = buffer.readInt(); - floorsList = new ArrayList<>(); - for (int i = 0; i < size; i++) - floorsList.add(IntAttached.with(buffer.readInt(), Couple.create(buffer.readUtf(), buffer.readUtf()))); + public ElevatorFloorListPacket(AbstractContraptionEntity entity, List>> floors) { + this(entity.getId(), floors); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityId); - buffer.writeInt(floorsList.size()); - for (IntAttached> entry : floorsList) { - buffer.writeInt(entry.getFirst()); - entry.getSecond() - .forEach(buffer::writeUtf); + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + Entity entityByID = player.clientLevel.getEntity(entityId); + if (!(entityByID instanceof AbstractContraptionEntity ace)) + return; + if (!(ace.getContraption() instanceof ElevatorContraption ec)) + return; + + ec.namesList = this.floors; + ec.syncControlDisplays(); + } + + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.UPDATE_ELEVATOR_FLOORS; + } + + public record RequestFloorList(int entityId) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = ByteBufCodecs.INT.map( + RequestFloorList::new, RequestFloorList::entityId + ); + + public RequestFloorList(AbstractContraptionEntity entity) { + this(entity.getId()); } - } - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - Entity entityByID = Minecraft.getInstance().level.getEntity(entityId); + @Override + public void handle(ServerPlayer sender) { + Entity entityByID = sender.level() + .getEntity(entityId); if (!(entityByID instanceof AbstractContraptionEntity ace)) return; if (!(ace.getContraption()instanceof ElevatorContraption ec)) return; - - ec.namesList = floorsList; - ec.syncControlDisplays(); - }); - return true; - } - - public static class RequestFloorList extends SimplePacketBase { - - private int entityId; - - public RequestFloorList(AbstractContraptionEntity entity) { - this.entityId = entity.getId(); - } - - public RequestFloorList(FriendlyByteBuf buffer) { - entityId = buffer.readInt(); - } - - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityId); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer sender = context.getSender(); - Entity entityByID = sender.level() - .getEntity(entityId); - if (!(entityByID instanceof AbstractContraptionEntity ace)) - return; - if (!(ace.getContraption()instanceof ElevatorContraption ec)) - return; - AllPackets.getChannel().send(PacketDistributor.PLAYER.with(() -> sender), + CatnipServices.NETWORK.sendToClient(sender, new ElevatorFloorListPacket(ace, ec.namesList)); - }); - return true; } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.REQUEST_FLOOR_LIST; + } } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlock.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlock.java index 03e64c0273..da1907bccc 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlock.java @@ -10,7 +10,9 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; @@ -27,20 +29,18 @@ public class ElevatorPulleyBlock extends HorizontalKineticBlock implements IBE { + return ItemInteractionResult.FAIL; + if (!stack.isEmpty()) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; + return onBlockEntityUseItemOn(level, pos, be -> { be.clicked(); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; }); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlockEntity.java index 16a8890563..07614da8ee 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorPulleyBlockEntity.java @@ -3,7 +3,6 @@ package com.simibubi.create.content.contraptions.elevator; import java.util.List; import com.simibubi.create.AllBlocks; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.content.contraptions.AssemblyException; import com.simibubi.create.content.contraptions.ControlledContraptionEntity; @@ -11,10 +10,12 @@ import com.simibubi.create.content.contraptions.elevator.ElevatorColumn.ColumnCo import com.simibubi.create.content.contraptions.pulley.PulleyBlockEntity; import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.infrastructure.config.AllConfigs; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -53,7 +54,7 @@ public class ElevatorPulleyBlockEntity extends PulleyBlockEntity { if (offset >= 0) resetContraptionToOffset(); if (level.isClientSide) { - AllPackets.getChannel().sendToServer(new ElevatorFloorListPacket.RequestFloorList(contraption)); + CatnipServices.NETWORK.sendToServer(new ElevatorFloorListPacket.RequestFloorList(contraption)); return; } @@ -138,15 +139,15 @@ public class ElevatorPulleyBlockEntity extends PulleyBlockEntity { } @Override - public void write(CompoundTag compound, boolean clientPacket) { - super.write(compound, clientPacket); + public void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.write(compound, registries, clientPacket); if (clientPacket) compound.putInt("ClientTarget", clientOffsetTarget); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.read(compound, registries, clientPacket); if (!clientPacket) return; diff --git a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorTargetFloorPacket.java b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorTargetFloorPacket.java index 82f8d1925f..12555e99ed 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorTargetFloorPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/elevator/ElevatorTargetFloorPacket.java @@ -1,64 +1,58 @@ package com.simibubi.create.content.contraptions.elevator; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; + +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ElevatorTargetFloorPacket extends SimplePacketBase { - - private int entityId; - private int targetY; +public record ElevatorTargetFloorPacket(int entityId, int targetY) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ElevatorTargetFloorPacket::entityId, + ByteBufCodecs.INT, ElevatorTargetFloorPacket::targetY, + ElevatorTargetFloorPacket::new + ); public ElevatorTargetFloorPacket(AbstractContraptionEntity entity, int targetY) { - this.targetY = targetY; - this.entityId = entity.getId(); - } - - public ElevatorTargetFloorPacket(FriendlyByteBuf buffer) { - entityId = buffer.readInt(); - targetY = buffer.readInt(); + this(entity.getId(), targetY); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityId); - buffer.writeInt(targetY); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer sender = context.getSender(); - Entity entityByID = sender.serverLevel() + public void handle(ServerPlayer sender) { + Entity entityByID = sender.serverLevel() .getEntity(entityId); - if (!(entityByID instanceof AbstractContraptionEntity ace)) - return; - if (!(ace.getContraption() instanceof ElevatorContraption ec)) - return; - if (ace.distanceToSqr(sender) > 50 * 50) - return; + if (!(entityByID instanceof AbstractContraptionEntity ace)) + return; + if (!(ace.getContraption() instanceof ElevatorContraption ec)) + return; + if (ace.distanceToSqr(sender) > 50 * 50) + return; - Level level = sender.level(); - ElevatorColumn elevatorColumn = ElevatorColumn.get(level, ec.getGlobalColumn()); - if (!elevatorColumn.contacts.contains(targetY)) - return; - if (ec.isTargetUnreachable(targetY)) - return; + Level level = sender.level(); + ElevatorColumn elevatorColumn = ElevatorColumn.get(level, ec.getGlobalColumn()); + if (!elevatorColumn.contacts.contains(targetY)) + return; + if (ec.isTargetUnreachable(targetY)) + return; - BlockPos pos = elevatorColumn.contactAt(targetY); - BlockState blockState = level.getBlockState(pos); - if (!(blockState.getBlock() instanceof ElevatorContactBlock ecb)) - return; + BlockPos pos = elevatorColumn.contactAt(targetY); + BlockState blockState = level.getBlockState(pos); + if (!(blockState.getBlock() instanceof ElevatorContactBlock ecb)) + return; - ecb.callToContactAndUpdate(elevatorColumn, blockState, level, pos, false); - }); - return true; + ecb.callToContactAndUpdate(elevatorColumn, blockState, level, pos, false); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.ELEVATOR_SET_FLOOR; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java index 9192921226..ed1682b8b4 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java @@ -13,7 +13,9 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; @@ -53,16 +55,15 @@ public class GantryCarriageBlock extends DirectionalAxisKineticBlock implements return context.getClickedFace(); } - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { + @Override + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (!player.mayBuild() || player.isShiftKeyDown()) - return InteractionResult.PASS; - if (player.getItemInHand(handIn) - .isEmpty()) { - withBlockEntityDo(worldIn, pos, be -> be.checkValidGantryShaft()); - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (stack.isEmpty()) { + withBlockEntityDo(level, pos, be -> be.checkValidGantryShaft()); + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlockEntity.java index 540ba53abe..2b0b715fb1 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlockEntity.java @@ -17,6 +17,7 @@ import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -30,7 +31,7 @@ public class GantryCarriageBlockEntity extends KineticBlockEntity implements IDi public GantryCarriageBlockEntity(BlockEntityType typeIn, BlockPos pos, BlockState state) { super(typeIn, pos, state); } - + @Override public void addBehaviours(List behaviours) { super.addBehaviours(behaviours); @@ -111,7 +112,7 @@ public class GantryCarriageBlockEntity extends KineticBlockEntity implements IDi if (ContraptionCollider.isCollidingWithWorld(level, contraption, worldPosition.relative(movementDirection), movementDirection)) return; - + if (contraption.containsBlockBreakers()) award(AllAdvancements.CONTRAPTION_ACTORS); @@ -129,15 +130,15 @@ public class GantryCarriageBlockEntity extends KineticBlockEntity implements IDi } @Override - protected void write(CompoundTag compound, boolean clientPacket) { - AssemblyException.write(compound, lastException); - super.write(compound, clientPacket); + protected void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + AssemblyException.write(compound, registries, lastException); + super.write(compound, registries, clientPacket); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - lastException = AssemblyException.read(compound); - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + lastException = AssemblyException.read(compound, registries); + super.read(compound, registries, clientPacket); } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraption.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraption.java index 447ff7bf84..7f234533bf 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraption.java @@ -7,6 +7,7 @@ import com.simibubi.create.content.contraptions.TranslatingContraption; 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.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; @@ -30,8 +31,8 @@ public class GantryContraption extends TranslatingContraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); tag.putInt("Facing", facing.get3DDataValue()); return tag; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java index 660fb274ba..809cc4facc 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java @@ -3,7 +3,6 @@ package com.simibubi.create.content.contraptions.gantry; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllEntityTypes; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; import com.simibubi.create.content.contraptions.Contraption; import com.simibubi.create.content.contraptions.ContraptionCollider; @@ -11,11 +10,14 @@ import com.simibubi.create.content.contraptions.StructureTransform; import com.simibubi.create.content.kinetics.gantry.GantryShaftBlock; import com.simibubi.create.content.kinetics.gantry.GantryShaftBlockEntity; import com.simibubi.create.foundation.utility.ServerSpeedProvider; + +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.VecHelper; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; @@ -24,9 +26,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class GantryContraptionEntity extends AbstractContraptionEntity { @@ -148,13 +149,14 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { } @Override - protected void writeAdditional(CompoundTag compound, boolean spawnPacket) { + protected void writeAdditional(CompoundTag compound, HolderLookup.Provider registries, boolean spawnPacket) { NBTHelper.writeEnum(compound, "GantryAxis", movementAxis); if (sequencedOffsetLimit >= 0) compound.putDouble("SequencedOffsetLimit", sequencedOffsetLimit); - super.writeAdditional(compound, spawnPacket); + super.writeAdditional(compound, registries, spawnPacket); } + @Override protected void readAdditional(CompoundTag compound, boolean spawnData) { movementAxis = NBTHelper.readEnum(compound, "GantryAxis", Direction.class); sequencedOffsetLimit = @@ -187,7 +189,7 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { @Override @OnlyIn(Dist.CLIENT) - public void lerpTo(double x, double y, double z, float yw, float pt, int inc, boolean t) {} + public void lerpTo(double pX, double pY, double pZ, float pYRot, float pXRot, int pSteps) {} @Override protected void handleStallInformation(double x, double y, double z, float angle) { @@ -221,20 +223,19 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { } public void sendPacket() { - AllPackets.getChannel() - .send(PacketDistributor.TRACKING_ENTITY.with(() -> this), + CatnipServices.NETWORK.sendToClientsTrackingEntity(this, new GantryContraptionUpdatePacket(getId(), getAxisCoord(), axisMotion, sequencedOffsetLimit)); } @OnlyIn(Dist.CLIENT) public static void handlePacket(GantryContraptionUpdatePacket packet) { - Entity entity = Minecraft.getInstance().level.getEntity(packet.entityID); + Entity entity = Minecraft.getInstance().level.getEntity(packet.entityID()); if (!(entity instanceof GantryContraptionEntity)) return; GantryContraptionEntity ce = (GantryContraptionEntity) entity; - ce.axisMotion = packet.motion; - ce.clientOffsetDiff = packet.coord - ce.getAxisCoord(); - ce.sequencedOffsetLimit = packet.sequenceLimit; + ce.axisMotion = packet.motion(); + ce.clientOffsetDiff = packet.coord() - ce.getAxisCoord(); + ce.sequencedOffsetLimit = packet.sequenceLimit(); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionUpdatePacket.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionUpdatePacket.java index 0ef5e7850a..1334fed601 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionUpdatePacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionUpdatePacket.java @@ -1,46 +1,33 @@ package com.simibubi.create.content.contraptions.gantry; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class GantryContraptionUpdatePacket extends SimplePacketBase { +public record GantryContraptionUpdatePacket(int entityID, double coord, double motion, double sequenceLimit) implements ClientboundPacketPayload { + public static StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, GantryContraptionUpdatePacket::entityID, + ByteBufCodecs.DOUBLE, GantryContraptionUpdatePacket::coord, + ByteBufCodecs.DOUBLE, GantryContraptionUpdatePacket::motion, + ByteBufCodecs.DOUBLE, GantryContraptionUpdatePacket::sequenceLimit, + GantryContraptionUpdatePacket::new + ); - int entityID; - double coord; - double motion; - double sequenceLimit; - - public GantryContraptionUpdatePacket(int entityID, double coord, double motion, double sequenceLimit) { - this.entityID = entityID; - this.coord = coord; - this.motion = motion; - this.sequenceLimit = sequenceLimit; - } - - public GantryContraptionUpdatePacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - coord = buffer.readFloat(); - motion = buffer.readFloat(); - sequenceLimit = buffer.readFloat(); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + GantryContraptionEntity.handlePacket(this); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - buffer.writeFloat((float) coord); - buffer.writeFloat((float) motion); - buffer.writeFloat((float) sequenceLimit); + public PacketTypeProvider getTypeProvider() { + return AllPackets.GANTRY_UPDATE; } - - @Override - public boolean handle(Context context) { - context.enqueueWork( - () -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> GantryContraptionEntity.handlePacket(this))); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/GlueEffectPacket.java b/src/main/java/com/simibubi/create/content/contraptions/glue/GlueEffectPacket.java index 817cdf9633..8f4bd859b5 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/GlueEffectPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/GlueEffectPacket.java @@ -1,53 +1,36 @@ package com.simibubi.create.content.contraptions.glue; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.client.Minecraft; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class GlueEffectPacket extends SimplePacketBase { - - private BlockPos pos; - private Direction direction; - private boolean fullBlock; - - public GlueEffectPacket(BlockPos pos, Direction direction, boolean fullBlock) { - this.pos = pos; - this.direction = direction; - this.fullBlock = fullBlock; - } - - public GlueEffectPacket(FriendlyByteBuf buffer) { - pos = buffer.readBlockPos(); - direction = Direction.from3DDataValue(buffer.readByte()); - fullBlock = buffer.readBoolean(); - } +public record GlueEffectPacket(BlockPos pos, Direction direction, boolean fullBlock) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, GlueEffectPacket::pos, + Direction.STREAM_CODEC, GlueEffectPacket::direction, + ByteBufCodecs.BOOL, GlueEffectPacket::fullBlock, + GlueEffectPacket::new + ); @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(pos); - buffer.writeByte(direction.get3DDataValue()); - buffer.writeBoolean(fullBlock); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::handleClient)); - return true; - } - @OnlyIn(Dist.CLIENT) - public void handleClient() { - Minecraft mc = Minecraft.getInstance(); - if (!mc.player.blockPosition().closerThan(pos, 100)) + public void handle(LocalPlayer player) { + if (!player.blockPosition().closerThan(pos, 100)) return; - SuperGlueItem.spawnParticles(mc.level, pos, direction, fullBlock); + SuperGlueItem.spawnParticles(player.clientLevel, pos, direction, fullBlock); + } + + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.GLUE_EFFECT; } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueEntity.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueEntity.java index 54d7add7cf..af6277147f 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueEntity.java @@ -4,6 +4,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; +import net.neoforged.neoforge.entity.IEntityWithComplexSpawn; + +import org.jetbrains.annotations.NotNull; + import com.simibubi.create.AllBlocks; import com.simibubi.create.AllEntityTypes; import com.simibubi.create.AllItems; @@ -25,9 +29,8 @@ import net.minecraft.core.Direction.AxisDirection; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; @@ -49,16 +52,13 @@ import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.PushReaction; -import net.minecraft.world.level.portal.PortalInfo; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.entity.IEntityAdditionalSpawnData; -import net.minecraftforge.network.NetworkHooks; -public class SuperGlueEntity extends Entity implements IEntityAdditionalSpawnData, ISpecialEntityItemRequirement { +public class SuperGlueEntity extends Entity implements IEntityWithComplexSpawn, ISpecialEntityItemRequirement { public static AABB span(BlockPos startPos, BlockPos endPos) { - return new AABB(startPos, endPos).expandTowards(1, 1, 1); + return new AABB(Vec3.atLowerCornerOf(startPos), Vec3.atLowerCornerOf(endPos)).expandTowards(1, 1, 1); } public static boolean isGlued(LevelAccessor level, BlockPos blockPos, Direction direction, @@ -109,7 +109,7 @@ public class SuperGlueEntity extends Entity implements IEntityAdditionalSpawnDat } @Override - protected void defineSynchedData() {} + protected void defineSynchedData(SynchedEntityData.Builder builder) {} public static boolean isValidFace(Level world, BlockPos pos, Direction direction) { BlockState state = world.getBlockState(pos); @@ -195,8 +195,8 @@ public class SuperGlueEntity extends Entity implements IEntityAdditionalSpawnDat } @Override - protected float getEyeHeight(Pose poseIn, EntityDimensions sizeIn) { - return 0.0F; + public @NotNull EntityDimensions getDimensions(@NotNull Pose pose) { + return super.getDimensions(pose).withEyeHeight(0.0F); } public void playPlaceSound() { @@ -267,19 +267,14 @@ public class SuperGlueEntity extends Entity implements IEntityAdditionalSpawnDat } @Override - public Packet getAddEntityPacket() { - return NetworkHooks.getEntitySpawningPacket(this); - } - - @Override - public void writeSpawnData(FriendlyByteBuf buffer) { + public void writeSpawnData(RegistryFriendlyByteBuf buffer) { CompoundTag compound = new CompoundTag(); addAdditionalSaveData(compound); buffer.writeNbt(compound); } @Override - public void readSpawnData(FriendlyByteBuf additionalData) { + public void readSpawnData(RegistryFriendlyByteBuf additionalData) { readAdditionalSaveData(additionalData.readNbt()); } @@ -302,15 +297,6 @@ public class SuperGlueEntity extends Entity implements IEntityAdditionalSpawnDat return PushReaction.IGNORE; } - public void setPortalEntrancePos() { - portalEntrancePos = blockPosition(); - } - - @Override - public PortalInfo findDimensionEntryPoint(ServerLevel pDestination) { - return super.findDimensionEntryPoint(pDestination); - } - public void spawnParticles() { AABB bb = getBoundingBox(); Vec3 origin = new Vec3(bb.minX, bb.minY, bb.minZ); diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueHandler.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueHandler.java index aa6b8809ff..cba66f79f5 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueHandler.java @@ -1,19 +1,22 @@ package com.simibubi.create.content.contraptions.glue; import com.simibubi.create.AllItems; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.BlockMovementChecks; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Iterate; import net.createmod.catnip.utility.levelWrappers.RayTraceLevel; import net.createmod.catnip.utility.placement.IPlacementHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponents; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; @@ -21,11 +24,9 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult.Type; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.event.level.BlockEvent.EntityPlaceEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.level.BlockEvent.EntityPlaceEvent; import java.util.HashSet; import java.util.Set; @@ -49,8 +50,7 @@ public class SuperGlueHandler { BlockPos relative = pos.relative(direction); if (SuperGlueEntity.isGlued(world, pos, direction, cached) && BlockMovementChecks.isMovementNecessary(world.getBlockState(relative), entity.level(), relative)) - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> entity), - new GlueEffectPacket(pos, direction, true)); + CatnipServices.NETWORK.sendToClientsTrackingAndSelf(entity, new GlueEffectPacket(pos, direction, true)); } if (entity instanceof Player) @@ -59,7 +59,7 @@ public class SuperGlueHandler { public static void glueInOffHandAppliesOnBlockPlace(EntityPlaceEvent event, BlockPos pos, Player placer) { ItemStack itemstack = placer.getOffhandItem(); - AttributeInstance reachAttribute = placer.getAttribute(ForgeMod.BLOCK_REACH.get()); + AttributeInstance reachAttribute = placer.getAttribute(Attributes.BLOCK_INTERACTION_RANGE); if (!AllItems.SUPER_GLUE.isIn(itemstack) || reachAttribute == null) return; if (AllItems.WRENCH.isIn(placer.getMainHandItem())) @@ -93,17 +93,18 @@ public class SuperGlueHandler { return; SuperGlueEntity entity = new SuperGlueEntity(world, SuperGlueEntity.span(gluePos, gluePos.relative(face))); - CompoundTag compoundnbt = itemstack.getTag(); - if (compoundnbt != null) - EntityType.updateCustomEntityTag(world, placer, entity, compoundnbt); + CustomData customData = itemstack.get(DataComponents.CUSTOM_DATA); + if (customData != null) + EntityType.updateCustomEntityTag(world, placer, entity, customData); if (SuperGlueEntity.isValidFace(world, gluePos, face)) { if (!world.isClientSide) { world.addFreshEntity(entity); - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> entity), + CatnipServices.NETWORK.sendToClientsTrackingEntity(entity, new GlueEffectPacket(gluePos, face, true)); } - itemstack.hurtAndBreak(1, placer, SuperGlueItem::onBroken); + if (placer.level() instanceof ServerLevel serverLevel) + itemstack.hurtAndBreak(1, serverLevel, placer, $ -> SuperGlueItem.onBroken(placer)); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueItem.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueItem.java index 0072462912..f69da386f2 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueItem.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueItem.java @@ -15,12 +15,12 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.Event.Result; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.common.util.TriState; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; @EventBusSubscriber public class SuperGlueItem extends Item { @@ -38,7 +38,7 @@ public class SuperGlueItem extends Item { if (event.getItemStack() .getItem() instanceof SuperGlueItem) - event.setUseBlock(Result.DENY); + event.setUseBlock(TriState.FALSE); } public SuperGlueItem(Properties properties) { @@ -50,11 +50,6 @@ public class SuperGlueItem extends Item { return false; } - @Override - public boolean canBeDepleted() { - return true; - } - public static void onBroken(Player player) {} @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRemovalPacket.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRemovalPacket.java index 830a34311a..4096af3477 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRemovalPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRemovalPacket.java @@ -1,49 +1,39 @@ package com.simibubi.create.content.contraptions.glue; +import com.simibubi.create.AllPackets; import com.simibubi.create.AllSoundEvents; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; + +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SuperGlueRemovalPacket extends SimplePacketBase { +public record SuperGlueRemovalPacket(int entityId, BlockPos soundSource) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, SuperGlueRemovalPacket::entityId, + BlockPos.STREAM_CODEC, SuperGlueRemovalPacket::soundSource, + SuperGlueRemovalPacket::new + ); - private int entityId; - private BlockPos soundSource; - - public SuperGlueRemovalPacket(int id, BlockPos soundSource) { - entityId = id; - this.soundSource = soundSource; - } - - public SuperGlueRemovalPacket(FriendlyByteBuf buffer) { - entityId = buffer.readInt(); - soundSource = buffer.readBlockPos(); + @Override + public void handle(ServerPlayer player) { + Entity entity = player.level().getEntity(entityId); + if (!(entity instanceof SuperGlueEntity superGlue)) + return; + double range = 32; + if (player.distanceToSqr(superGlue.position()) > range * range) + return; + AllSoundEvents.SLIME_ADDED.play(player.level(), null, soundSource, 0.5F, 0.5F); + superGlue.spawnParticles(); + entity.discard(); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityId); - buffer.writeBlockPos(soundSource); + public PacketTypeProvider getTypeProvider() { + return AllPackets.GLUE_REMOVED; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - Entity entity = player.level().getEntity(entityId); - if (!(entity instanceof SuperGlueEntity superGlue)) - return; - double range = 32; - if (player.distanceToSqr(superGlue.position()) > range * range) - return; - AllSoundEvents.SLIME_ADDED.play(player.level(), null, soundSource, 0.5F, 0.5F); - superGlue.spawnParticles(); - entity.discard(); - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRenderer.java index 748ec9e0fb..1047aeb314 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueRenderer.java @@ -4,8 +4,8 @@ import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class SuperGlueRenderer extends EntityRenderer { diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHandler.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHandler.java index 19cee16f3b..bdf4622b12 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHandler.java @@ -5,10 +5,10 @@ import java.util.Optional; import java.util.Set; import com.google.common.base.Objects; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.AllSpecialTextures; import com.simibubi.create.content.contraptions.chassis.AbstractChassisBlock; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.foundation.utility.RaycastHelper; @@ -21,6 +21,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; @@ -28,7 +29,7 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult.Type; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.ForgeMod; +import net.neoforged.neoforge.common.NeoForgeMod; public class SuperGlueSelectionHandler { @@ -74,8 +75,7 @@ public class SuperGlueSelectionHandler { selected = null; if (firstPos == null) { - double range = player.getAttribute(ForgeMod.BLOCK_REACH.get()) - .getValue() + 1; + double range = player.getAttributeValue(Attributes.BLOCK_INTERACTION_RANGE) + 1; Vec3 traceOrigin = RaycastHelper.getTraceOrigin(player); Vec3 traceTarget = RaycastHelper.getTraceTarget(player, range, traceOrigin); @@ -179,7 +179,7 @@ public class SuperGlueSelectionHandler { } private AABB getCurrentSelectionBox() { - return firstPos == null || hoveredPos == null ? null : new AABB(firstPos, hoveredPos).expandTowards(1, 1, 1); + return firstPos == null || hoveredPos == null ? null : new AABB(Vec3.atLowerCornerOf(firstPos), Vec3.atLowerCornerOf(hoveredPos)).expandTowards(1, 1, 1); } public boolean onMouseInput(boolean attack) { @@ -195,7 +195,7 @@ public class SuperGlueSelectionHandler { if (attack) { if (selected == null) return false; - AllPackets.getChannel().sendToServer(new SuperGlueRemovalPacket(selected.getId(), soundSourceForRemoval)); + CatnipServices.NETWORK.sendToServer(new SuperGlueRemovalPacket(selected.getId(), soundSourceForRemoval)); selected = null; clusterCooldown = 0; return true; @@ -253,7 +253,7 @@ public class SuperGlueSelectionHandler { public void confirm() { LocalPlayer player = Minecraft.getInstance().player; - AllPackets.getChannel().sendToServer(new SuperGlueSelectionPacket(firstPos, hoveredPos)); + CatnipServices.NETWORK.sendToServer(new SuperGlueSelectionPacket(firstPos, hoveredPos)); AllSoundEvents.SLIME_ADDED.playAt(player.level(), hoveredPos, 0.5F, 0.95F, false); player.level().playSound(player, hoveredPos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, 0.75f, 1); diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHelper.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHelper.java index c051d205d7..f94d4ef637 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHelper.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionHelper.java @@ -11,6 +11,8 @@ import net.createmod.catnip.utility.Iterate; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -74,7 +76,7 @@ public class SuperGlueSelectionHelper { ItemStack stack = items.get(slot); if (stack.isEmpty()) continue; - if (stack.getTag() != null && stack.getTag().contains("Unbreakable")) + if (stack.has(DataComponents.UNBREAKABLE)) return true; if (!stack.isDamageableItem()) continue; @@ -83,9 +85,8 @@ public class SuperGlueSelectionHelper { int charges = Math.min(requiredAmount, stack.getMaxDamage() - stack.getDamageValue()); - if (!simulate) - stack.hurtAndBreak(charges, player, i == -1 ? SuperGlueItem::onBroken : $ -> { - }); + if (!simulate && player.level() instanceof ServerLevel serverLevel) + stack.hurtAndBreak(charges, serverLevel, player, i == -1 ? $ -> SuperGlueItem.onBroken(player) : $ -> {}); requiredAmount -= charges; if (requiredAmount <= 0) diff --git a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionPacket.java b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionPacket.java index 0b88c576be..a97931f1d3 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/glue/SuperGlueSelectionPacket.java @@ -1,67 +1,54 @@ package com.simibubi.create.content.contraptions.glue; +import com.simibubi.create.AllPackets; import com.simibubi.create.foundation.advancement.AllAdvancements; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; + +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; import java.util.Set; -public class SuperGlueSelectionPacket extends SimplePacketBase { +public record SuperGlueSelectionPacket(BlockPos from, BlockPos to) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, SuperGlueSelectionPacket::from, + BlockPos.STREAM_CODEC, SuperGlueSelectionPacket::to, + SuperGlueSelectionPacket::new + ); - private BlockPos from; - private BlockPos to; + @Override + public void handle(ServerPlayer player) { + double range = player.getAttributeValue(Attributes.BLOCK_INTERACTION_RANGE) + 2; + if (player.distanceToSqr(Vec3.atCenterOf(to)) > range * range) + return; + if (!to.closerThan(from, 25)) + return; - public SuperGlueSelectionPacket(BlockPos from, BlockPos to) { - this.from = from; - this.to = to; - } + Set group = SuperGlueSelectionHelper.searchGlueGroup(player.level(), from, to, false); + if (group == null) + return; + if (!group.contains(to)) + return; + if (!SuperGlueSelectionHelper.collectGlueFromInventory(player, 1, true)) + return; - public SuperGlueSelectionPacket(FriendlyByteBuf buffer) { - from = buffer.readBlockPos(); - to = buffer.readBlockPos(); + AABB bb = SuperGlueEntity.span(from, to); + SuperGlueSelectionHelper.collectGlueFromInventory(player, 1, false); + SuperGlueEntity entity = new SuperGlueEntity(player.level(), bb); + player.level().addFreshEntity(entity); + entity.spawnParticles(); + + AllAdvancements.SUPER_GLUE.awardTo(player); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(from); - buffer.writeBlockPos(to); + public PacketTypeProvider getTypeProvider() { + return AllPackets.GLUE_IN_AREA; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - - double range = player.getAttribute(ForgeMod.BLOCK_REACH.get()) - .getValue() + 2; - if (player.distanceToSqr(Vec3.atCenterOf(to)) > range * range) - return; - if (!to.closerThan(from, 25)) - return; - - Set group = SuperGlueSelectionHelper.searchGlueGroup(player.level(), from, to, false); - if (group == null) - return; - if (!group.contains(to)) - return; - if (!SuperGlueSelectionHelper.collectGlueFromInventory(player, 1, true)) - return; - - AABB bb = SuperGlueEntity.span(from, to); - SuperGlueSelectionHelper.collectGlueFromInventory(player, 1, false); - SuperGlueEntity entity = new SuperGlueEntity(player.level(), bb); - player.level().addFreshEntity(entity); - entity.spawnParticles(); - - AllAdvancements.SUPER_GLUE.awardTo(player); - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingCreationPacket.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingCreationPacket.java index 09fff9c09c..83c9974823 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingCreationPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingCreationPacket.java @@ -1,39 +1,32 @@ package com.simibubi.create.content.contraptions.minecart; -import com.simibubi.create.foundation.networking.SimplePacketBase; -import net.minecraft.network.FriendlyByteBuf; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.vehicle.AbstractMinecart; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class CouplingCreationPacket extends SimplePacketBase { - - int id1, id2; +public record CouplingCreationPacket(int id1, int id2) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, CouplingCreationPacket::id1, + ByteBufCodecs.VAR_INT, CouplingCreationPacket::id2, + CouplingCreationPacket::new + ); public CouplingCreationPacket(AbstractMinecart cart1, AbstractMinecart cart2) { - id1 = cart1.getId(); - id2 = cart2.getId(); - } - - public CouplingCreationPacket(FriendlyByteBuf buffer) { - id1 = buffer.readInt(); - id2 = buffer.readInt(); + this(cart1.getId(), cart2.getId()); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(id1); - buffer.writeInt(id2); + public PacketTypeProvider getTypeProvider() { + return AllPackets.MINECART_COUPLING_CREATION; } @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer sender = context.getSender(); - if (sender != null) - CouplingHandler.tryToCoupleCarts(sender, sender.level(), id1, id2); - }); - return true; + public void handle(ServerPlayer player) { + CouplingHandler.tryToCoupleCarts(player, player.level(), id1, id2); } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java index 57a0a88941..b3c242260b 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java @@ -6,6 +6,7 @@ import java.util.function.Consumer; import javax.annotation.Nullable; +import com.simibubi.create.AllAttachmentTypes; import com.simibubi.create.AllItems; import com.simibubi.create.Create; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; @@ -22,11 +23,9 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.event.entity.EntityMountEvent; -import net.minecraftforge.eventbus.api.Event.Result; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.EntityMountEvent; @EventBusSubscriber public class CouplingHandler { @@ -34,15 +33,14 @@ public class CouplingHandler { @SubscribeEvent public static void preventEntitiesFromMoutingOccupiedCart(EntityMountEvent event) { Entity e = event.getEntityBeingMounted(); - LazyOptional optional = e.getCapability(CapabilityMinecartController.MINECART_CONTROLLER_CAPABILITY); - if (!optional.isPresent()) - return; - if (event.getEntityMounting() instanceof AbstractContraptionEntity) - return; - MinecartController controller = optional.orElse(null); - if (controller.isCoupledThroughContraption()) { - event.setCanceled(true); - event.setResult(Result.DENY); + + if (e.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) { + MinecartController controller = e.getData(AllAttachmentTypes.MINECART_CONTROLLER); + if (event.getEntityMounting() instanceof AbstractContraptionEntity) + return; + if (controller.isCoupledThroughContraption()) { + event.setCanceled(true); + } } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandlerClient.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandlerClient.java index ba587c505c..e746c745f1 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandlerClient.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandlerClient.java @@ -1,7 +1,8 @@ package com.simibubi.create.content.contraptions.minecart; import com.simibubi.create.AllItems; -import com.simibubi.create.AllPackets; +import net.createmod.catnip.platform.CatnipServices; + import net.createmod.catnip.utility.VecHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; @@ -43,7 +44,7 @@ public class CouplingHandlerClient { return; } spawnSelectionParticles(entity.getBoundingBox(), true); - AllPackets.getChannel().sendToServer(new CouplingCreationPacket(selectedCart, entity)); + CatnipServices.NETWORK.sendToServer(new CouplingCreationPacket(selectedCart, entity)); selectedCart = null; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java index 5ceb0fa658..fb9df76669 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java @@ -1,9 +1,10 @@ package com.simibubi.create.content.contraptions.minecart; +import com.simibubi.create.AllAttachmentTypes; import com.simibubi.create.AllItems; -import com.simibubi.create.content.contraptions.minecart.capability.CapabilityMinecartController; import com.simibubi.create.content.contraptions.minecart.capability.MinecartController; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Iterate; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; @@ -12,15 +13,13 @@ import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteract; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.EntityInteract; @EventBusSubscriber public class MinecartCouplingItem extends Item { @@ -32,17 +31,17 @@ public class MinecartCouplingItem extends Item { @SubscribeEvent(priority = EventPriority.HIGH) public static void handleInteractionWithMinecart(PlayerInteractEvent.EntityInteract event) { Entity interacted = event.getTarget(); - if (!(interacted instanceof AbstractMinecart)) + if (!(interacted instanceof AbstractMinecart minecart)) return; - AbstractMinecart minecart = (AbstractMinecart) interacted; Player player = event.getEntity(); if (player == null) return; - LazyOptional capability = - minecart.getCapability(CapabilityMinecartController.MINECART_CONTROLLER_CAPABILITY); - if (!capability.isPresent()) + if (!minecart.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) + return; + MinecartController controller = + minecart.getData(AllAttachmentTypes.MINECART_CONTROLLER); + if (!controller.isPresent()) return; - MinecartController controller = capability.orElse(null); ItemStack heldItem = player.getItemInHand(event.getHand()); if (AllItems.MINECART_COUPLING.isIn(heldItem)) { @@ -67,7 +66,7 @@ public class MinecartCouplingItem extends Item { return true; } if (world != null && world.isClientSide) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> cartClicked(player, minecart)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> cartClicked(player, minecart)); return true; } @@ -94,7 +93,7 @@ public class MinecartCouplingItem extends Item { @OnlyIn(Dist.CLIENT) private static void cartClicked(Player player, AbstractMinecart interacted) { - CouplingHandlerClient.onCartClicked(player, (AbstractMinecart) interacted); + CouplingHandlerClient.onCartClicked(player, interacted); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartSim2020.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartSim2020.java index 72d5c0e7aa..c6cd1f3297 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartSim2020.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartSim2020.java @@ -2,7 +2,7 @@ package com.simibubi.create.content.contraptions.minecart; import com.google.common.collect.Maps; import com.mojang.datafixers.util.Pair; -import com.simibubi.create.content.contraptions.minecart.capability.CapabilityMinecartController; +import com.simibubi.create.AllAttachmentTypes; import com.simibubi.create.content.contraptions.minecart.capability.MinecartController; import net.createmod.catnip.utility.VecHelper; import net.minecraft.Util; @@ -16,7 +16,6 @@ import net.minecraft.world.level.block.BaseRailBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.RailShape; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.util.LazyOptional; import java.util.Map; @@ -50,14 +49,14 @@ public class MinecartSim2020 { } public static boolean canAddMotion(AbstractMinecart c) { - if (c instanceof MinecartFurnace) - return Mth.equal(((MinecartFurnace) c).xPush, 0) - && Mth.equal(((MinecartFurnace) c).zPush, 0); - LazyOptional capability = - c.getCapability(CapabilityMinecartController.MINECART_CONTROLLER_CAPABILITY); - if (capability.isPresent() && capability.orElse(null) - .isStalled()) - return false; + if (c instanceof MinecartFurnace furnace) + return Mth.equal(furnace.xPush, 0) + && Mth.equal(furnace.zPush, 0); + + if (c.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) { + MinecartController controller = c.getData(AllAttachmentTypes.MINECART_CONTROLLER); + return !controller.isStalled(); + } return true; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/TrainCargoManager.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/TrainCargoManager.java index 6b045b69a4..5b3778f974 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/TrainCargoManager.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/TrainCargoManager.java @@ -10,12 +10,13 @@ import com.simibubi.create.content.contraptions.MountedStorageManager; import com.simibubi.create.foundation.fluid.CombinedTankWrapper; import net.minecraft.core.BlockPos; +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.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; -import net.minecraftforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.items.IItemHandlerModifiable; public class TrainCargoManager extends MountedStorageManager { @@ -45,33 +46,33 @@ public class TrainCargoManager extends MountedStorageManager { } @Override - public void write(CompoundTag nbt, boolean clientPacket) { - super.write(nbt, clientPacket); + public void write(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { + super.write(nbt, registries, clientPacket); nbt.putInt("TicksSinceLastExchange", ticksSinceLastExchange); } @Override - public void read(CompoundTag nbt, Map presentBlockEntities, boolean clientPacket) { - super.read(nbt, presentBlockEntities, clientPacket); + public void read(CompoundTag nbt, HolderLookup.Provider registries, Map presentBlockEntities, boolean clientPacket) { + super.read(nbt, registries, presentBlockEntities, clientPacket); ticksSinceLastExchange = nbt.getInt("TicksSinceLastExchange"); } public void resetIdleCargoTracker() { ticksSinceLastExchange = 0; } - + public void tickIdleCargoTracker() { ticksSinceLastExchange++; } - + public int getTicksSinceLastExchange() { return ticksSinceLastExchange; } - + public int getVersion() { return version.get(); } - + void changeDetected() { version.incrementAndGet(); resetIdleCargoTracker(); @@ -137,7 +138,7 @@ public class TrainCargoManager extends MountedStorageManager { changeDetected(); return drained; } - + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/CapabilityMinecartController.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/CapabilityMinecartController.java index 450aa2fffc..644a3c6e96 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/CapabilityMinecartController.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/CapabilityMinecartController.java @@ -11,34 +11,26 @@ import java.util.UUID; import javax.annotation.Nullable; +import com.simibubi.create.AllAttachmentTypes; import com.simibubi.create.AllItems; -import com.simibubi.create.Create; import com.simibubi.create.content.contraptions.minecart.CouplingHandler; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectLists; import net.createmod.catnip.utility.Iterate; import net.createmod.catnip.utility.WorldAttached; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityManager; -import net.minecraftforge.common.capabilities.CapabilityToken; -import net.minecraftforge.common.capabilities.ICapabilitySerializable; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.common.util.NonNullConsumer; -import net.minecraftforge.event.AttachCapabilitiesEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.level.ChunkEvent; +import net.neoforged.neoforge.event.entity.EntityEvent; +import net.neoforged.neoforge.event.entity.EntityLeaveLevelEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.level.ChunkEvent; -public class CapabilityMinecartController implements ICapabilitySerializable { +public class CapabilityMinecartController { /* Global map of loaded carts */ @@ -47,37 +39,6 @@ public class CapabilityMinecartController implements ICapabilitySerializable> queuedAdditions; static WorldAttached> queuedUnloads; - /** - * This callback wrapper ensures that the listeners map in the controller - * capability only ever contains one instance - */ - public static class MinecartRemovalListener implements NonNullConsumer> { - - private Level world; - private AbstractMinecart cart; - - public MinecartRemovalListener(Level world, AbstractMinecart cart) { - this.world = world; - this.cart = cart; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof MinecartRemovalListener; - } - - @Override - public int hashCode() { - return 100; - } - - @Override - public void accept(LazyOptional t) { - onCartRemoved(world, cart); - } - - } - static { loadedMinecartsByUUID = new WorldAttached<>($ -> new HashMap<>()); loadedMinecartsWithCoupling = new WorldAttached<>($ -> new HashSet<>()); @@ -111,40 +72,40 @@ public class CapabilityMinecartController implements ICapabilitySerializable capability = cart.getCapability(MINECART_CONTROLLER_CAPABILITY); - MinecartController controller = capability.orElse(null); - capability.addListener(new MinecartRemovalListener(world, cart)); - carts.put(uniqueID, controller); + if (cart.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) { + MinecartController controller = cart.getData(AllAttachmentTypes.MINECART_CONTROLLER); + carts.put(uniqueID, controller); - if (capability.isPresent()) { - MinecartController mc = capability.orElse(null); - if (mc.isLeadingCoupling()) { - cartsWithCoupling.add(uniqueID); + if (cart.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) { + MinecartController mc = cart.getData(AllAttachmentTypes.MINECART_CONTROLLER); + if (mc.isLeadingCoupling()) { + cartsWithCoupling.add(uniqueID); + } } + if (!world.isClientSide && controller != null) + controller.sendData(); } - if (!world.isClientSide && controller != null) - controller.sendData(); - } - queuedRemovals.clear(); - queued.clear(); + queuedRemovals.clear(); + queued.clear(); - List toRemove = new ArrayList<>(); - - for (Entry entry : carts.entrySet()) { - MinecartController controller = entry.getValue(); - if (controller != null) { - if (controller.isPresent()) { - controller.tick(); - continue; + List toRemove = new ArrayList<>(); + + for (Entry entry : carts.entrySet()) { + MinecartController controller = entry.getValue(); + if (controller != null) { + if (controller.isPresent()) { + controller.tick(); + continue; + } } + toRemove.add(entry.getKey()); + } + + for (UUID uuid : toRemove) { + keySet.remove(uuid); + cartsWithCoupling.remove(uuid); } - toRemove.add(entry.getKey()); - } - - for (UUID uuid : toRemove) { - keySet.remove(uuid); - cartsWithCoupling.remove(uuid); } } @@ -166,6 +127,8 @@ public class CapabilityMinecartController implements ICapabilitySerializable carts = loadedMinecartsByUUID.get(world); List unloads = queuedUnloads.get(world); UUID uniqueID = entity.getUUID(); @@ -213,59 +176,29 @@ public class CapabilityMinecartController implements ICapabilitySerializable MINECART_CONTROLLER_CAPABILITY = - CapabilityManager.get(new CapabilityToken<>() { - }); - - public static void attach(AttachCapabilitiesEvent event) { - Entity entity = event.getObject(); - if (!(entity instanceof AbstractMinecart)) + public static void attach(EntityEvent.EntityConstructing event) { + Entity entity = event.getEntity(); + if (!(entity instanceof AbstractMinecart abstractMinecart)) return; - CapabilityMinecartController capability = new CapabilityMinecartController((AbstractMinecart) entity); - ResourceLocation id = Create.asResource("minecart_controller"); - event.addCapability(id, capability); - event.addListener(() -> { - if (capability.cap.isPresent()) - capability.cap.invalidate(); - }); - queuedAdditions.get(entity.getCommandSenderWorld()) - .add((AbstractMinecart) entity); + MinecartController controller = new MinecartController(abstractMinecart); + abstractMinecart.setData(AllAttachmentTypes.MINECART_CONTROLLER, controller); + + queuedAdditions.get(entity.level()).add(abstractMinecart); + } + + public static void onEntityDeath(EntityLeaveLevelEvent event) { + if (event.getEntity() instanceof AbstractMinecart abstractMinecart) + onCartRemoved(event.getLevel(), abstractMinecart); } public static void startTracking(PlayerEvent.StartTracking event) { Entity entity = event.getTarget(); - if (!(entity instanceof AbstractMinecart)) + if (!(entity instanceof AbstractMinecart abstractMinecart)) return; - entity.getCapability(MINECART_CONTROLLER_CAPABILITY) - .ifPresent(MinecartController::sendData); + + if (entity.hasData(AllAttachmentTypes.MINECART_CONTROLLER)) { + entity.getData(AllAttachmentTypes.MINECART_CONTROLLER).sendData(abstractMinecart); + } } - - /* Capability provider */ - - private final LazyOptional cap; - private MinecartController handler; - - public CapabilityMinecartController(AbstractMinecart minecart) { - handler = new MinecartController(minecart); - cap = LazyOptional.of(() -> handler); - } - - @Override - public LazyOptional getCapability(Capability cap, Direction side) { - if (cap == MINECART_CONTROLLER_CAPABILITY) - return this.cap.cast(); - return LazyOptional.empty(); - } - - @Override - public CompoundTag serializeNBT() { - return handler.serializeNBT(); - } - - @Override - public void deserializeNBT(CompoundTag nbt) { - handler.deserializeNBT(nbt); - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java index f436bcb4d1..ad49858c83 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java @@ -1,20 +1,25 @@ package com.simibubi.create.content.contraptions.minecart.capability; +import com.mojang.serialization.Codec; import com.simibubi.create.AllPackets; import com.simibubi.create.Create; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; import com.simibubi.create.content.contraptions.OrientedContraptionEntity; import com.simibubi.create.content.contraptions.minecart.CouplingHandler; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.Couple; import net.createmod.catnip.utility.Iterate; import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.VecHelper; +import net.createmod.catnip.utility.lang.Lang; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.Tag; import net.minecraft.tags.BlockTags; import net.minecraft.util.Mth; +import net.minecraft.util.StringRepresentable; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.vehicle.AbstractMinecart; import net.minecraft.world.entity.vehicle.Minecart; @@ -22,9 +27,13 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.PoweredRailBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.util.INBTSerializable; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.attachment.IAttachmentHolder; +import net.neoforged.neoforge.attachment.IAttachmentSerializer; + +import net.neoforged.neoforge.common.util.INBTSerializable; + import org.apache.commons.lang3.mutable.MutableBoolean; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.lang.ref.WeakReference; @@ -39,7 +48,10 @@ import java.util.UUID; */ public class MinecartController implements INBTSerializable { - public static MinecartController EMPTY; + public static final MinecartController EMPTY = new MinecartController.Empty(); + + public static final IAttachmentSerializer SERIALIZER = Type.SERIALIZER; + private boolean needsEntryRefresh; private WeakReference weakRef; @@ -62,10 +74,22 @@ public class MinecartController implements INBTSerializable { needsEntryRefresh = true; } + public final boolean isEmpty() { + return getType() == Type.EMPTY; + } + + @NotNull + protected Type getType() { + return Type.NORMAL; + } + public void tick() { AbstractMinecart cart = cart(); Level world = getWorld(); + if (cart == null || world == null) + return; + if (needsEntryRefresh) { CapabilityMinecartController.queuedAdditions.get(world).add(cart); needsEntryRefresh = false; @@ -93,7 +117,7 @@ public class MinecartController implements INBTSerializable { return; } List passengers = cart.getPassengers(); - if (passengers.isEmpty() || !(passengers.get(0) instanceof AbstractContraptionEntity)) { + if (passengers.isEmpty() || !(passengers.getFirst() instanceof AbstractContraptionEntity)) { return; } Level world = cart.level(); @@ -151,9 +175,7 @@ public class MinecartController implements INBTSerializable { public float getCouplingLength(boolean leading) { Optional optional = couplings.get(leading); - if (optional.isPresent()) - return optional.get().length; - return 0; + return optional.map(couplingData -> couplingData.length).orElse(0F); } public void decouple() { @@ -169,10 +191,10 @@ public class MinecartController implements INBTSerializable { } public void removeConnection(boolean main) { - if (hasContraptionCoupling(main) && !getWorld().isClientSide) { + if (hasContraptionCoupling(main) && getWorld() != null && !getWorld().isClientSide) { List passengers = cart().getPassengers(); if (!passengers.isEmpty()) { - Entity entity = passengers.get(0); + Entity entity = passengers.getFirst(); if (entity instanceof AbstractContraptionEntity) ((AbstractContraptionEntity) entity).disassemble(); } @@ -192,31 +214,27 @@ public class MinecartController implements INBTSerializable { boolean forward = current.isLeadingCoupling(); int safetyCount = 1000; - while (true) { + do { if (safetyCount-- <= 0) { Create.LOGGER.warn("Infinite loop in coupling iteration"); return; } cartsToFlip.add(current); current = CouplingHandler.getNextInCouplingChain(getWorld(), current, forward); - if (current == null || current == MinecartController.EMPTY) - break; - } + } while (current != null && current != MinecartController.EMPTY); for (MinecartController minecartController : cartsToFlip) { - MinecartController mc = minecartController; - mc.couplings.forEachWithContext((opt, leading) -> opt.ifPresent(cd -> { + minecartController.couplings.forEachWithContext((opt, leading) -> opt.ifPresent(cd -> { cd.flip(); if (!cd.contraption) return; - List passengers = mc.cart() + List passengers = minecartController.cart() .getPassengers(); if (passengers.isEmpty()) return; - Entity entity = passengers.get(0); - if (!(entity instanceof OrientedContraptionEntity)) + Entity entity = passengers.getFirst(); + if (!(entity instanceof OrientedContraptionEntity contraption)) return; - OrientedContraptionEntity contraption = (OrientedContraptionEntity) entity; UUID couplingId = contraption.getCouplingId(); if (couplingId == cd.mainCartID) { contraption.setCouplingId(cd.connectedCartID); @@ -227,11 +245,11 @@ public class MinecartController implements INBTSerializable { return; } })); - mc.couplings = mc.couplings.swap(); - mc.needsEntryRefresh = true; - if (mc == this) + minecartController.couplings = minecartController.couplings.swap(); + minecartController.needsEntryRefresh = true; + if (minecartController == this) continue; - mc.sendData(); + minecartController.sendData(); } } } @@ -247,7 +265,7 @@ public class MinecartController implements INBTSerializable { @Nullable public UUID getCoupledCart(boolean asMain) { Optional optional = couplings.get(asMain); - if (!optional.isPresent()) + if (optional.isEmpty()) return null; CouplingData couplingData = optional.get(); return asMain ? couplingData.connectedCartID : couplingData.mainCartID; @@ -270,31 +288,38 @@ public class MinecartController implements INBTSerializable { if (isStalled(internal) == stall) return; - AbstractMinecart cart = cart(); - if (stall) { + @Nullable AbstractMinecart cart = cart(); + if (stall && cart != null) { stallData.set(internal, Optional.of(new StallData(cart))); sendData(); return; } - if (!isStalled(!internal)) + if (!isStalled(!internal) && cart != null) stallData.get(internal) - .get() - .release(cart); + .ifPresent(data -> data.release(cart)); stallData.set(internal, Optional.empty()); sendData(); } public void sendData() { - if (getWorld().isClientSide) + sendData(null); + } + + public void sendData(@Nullable AbstractMinecart cart) { + if (cart != null) { + this.weakRef = new WeakReference<>(cart); + needsEntryRefresh = true; + } + + if (getWorld() == null || getWorld().isClientSide) return; - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(this::cart), - new MinecartControllerUpdatePacket(this)); + CatnipServices.NETWORK.sendToClientsTrackingEntity(this.cart(), new MinecartControllerUpdatePacket(this, getWorld().registryAccess())); } @Override - public CompoundTag serializeNBT() { + public CompoundTag serializeNBT(@NotNull HolderLookup.Provider provider) { CompoundTag compoundNBT = new CompoundTag(); stallData.forEachWithContext((opt, internal) -> opt @@ -306,7 +331,7 @@ public class MinecartController implements INBTSerializable { } @Override - public void deserializeNBT(CompoundTag nbt) { + public void deserializeNBT(@NotNull HolderLookup.Provider provider, CompoundTag nbt) { Optional internalSD = Optional.empty(); Optional externalSD = Optional.empty(); Optional mainCD = Optional.empty(); @@ -335,11 +360,13 @@ public class MinecartController implements INBTSerializable { } public static MinecartController empty() { - return EMPTY != null ? EMPTY : (EMPTY = new MinecartController(null)); + return EMPTY; } - private Level getWorld() { - return cart().getCommandSenderWorld(); + private @Nullable Level getWorld() { + if (cart() == null) + return null; + return cart().level(); } private static class CouplingData { @@ -430,4 +457,189 @@ public class MinecartController implements INBTSerializable { } } + private static class Empty extends MinecartController { + + private Empty() { + super(null); + } + + public Empty(AbstractMinecart minecart) { + super(minecart); + } + + @Override + @NotNull + protected Type getType() { + return Type.EMPTY; + } + + private static void warn() { + Create.LOGGER.warn("Method called on EMPTY MinecartController"); + } + + @Override + public void tick() { + warn(); + } + + @Override + public boolean isFullyCoupled() { + warn(); + return false; + } + + @Override + public boolean isLeadingCoupling() { + warn(); + return false; + } + + @Override + public boolean isConnectedToCoupling() { + warn(); + return false; + } + + @Override + public boolean isCoupledThroughContraption() { + warn(); + return false; + } + + @Override + public boolean hasContraptionCoupling(boolean current) { + warn(); + return false; + } + + @Override + public float getCouplingLength(boolean leading) { + warn(); + return 0.0f; + } + + @Override + public void decouple() { + warn(); + } + + @Override + public void removeConnection(boolean main) { + warn(); + } + + @Override + public void prepareForCoupling(boolean isLeading) { + warn(); + } + + @Override + public void coupleWith(boolean isLeading, UUID coupled, float length, boolean contraption) { + warn(); + } + + @Nullable + @Override + public UUID getCoupledCart(boolean asMain) { + warn(); + return null; + } + + @Override + public boolean isStalled() { + warn(); + return false; + } + + @Override + public void setStalledExternally(boolean stall) { + warn(); + } + + @Override + public void sendData() { + super.sendData(); + } + + @Override + public CompoundTag serializeNBT(@NotNull HolderLookup.Provider provider) { + return super.serializeNBT(provider); + } + + @Override + public void deserializeNBT(@NotNull HolderLookup.Provider provider, CompoundTag nbt) { + super.deserializeNBT(provider, nbt); + } + + @Override + public boolean isPresent() { + return super.isPresent(); + } + + @Override + public AbstractMinecart cart() { + return super.cart(); + } + } + + protected enum Type implements StringRepresentable { + EMPTY(new IAttachmentSerializer<>() { + @Override + public @NotNull MinecartController read(@NotNull IAttachmentHolder holder, @NotNull CompoundTag tag, @NotNull HolderLookup.Provider provider) { + return MinecartController.EMPTY; + } + + @Override + public CompoundTag write(@NotNull MinecartController attachment, @NotNull HolderLookup.Provider provider) { + return attachment.serializeNBT(provider); + } + }), + NORMAL(new IAttachmentSerializer<>() { + @Override + public @NotNull MinecartController read(@NotNull IAttachmentHolder holder, @NotNull CompoundTag tag, @NotNull HolderLookup.Provider provider) { + MinecartController controller = new MinecartController(null); + controller.deserializeNBT(provider, tag); + return controller; + } + + @Override + public @Nullable CompoundTag write(@NotNull MinecartController attachment, @NotNull HolderLookup.Provider provider) { + return attachment.serializeNBT(provider); + } + }); + + public static Codec CODEC = StringRepresentable.fromValues(Type::values); + + private final IAttachmentSerializer serializer; + + private static final IAttachmentSerializer SERIALIZER = new IAttachmentSerializer<>() { + @Override + public @NotNull MinecartController read(@NotNull IAttachmentHolder holder, @NotNull CompoundTag tag, @NotNull HolderLookup.Provider provider) { + return Type.valueOf(tag.getString("Type")).getSerializer().read(holder, tag, provider); + } + + @Override + public @Nullable CompoundTag write(MinecartController attachment, @NotNull HolderLookup.Provider provider) { + CompoundTag tag = attachment.serializeNBT(provider); + if (tag != null) { + tag.putString("Type", attachment.getType().name()); + } + return tag; + } + }; + + Type(IAttachmentSerializer serializer) { + this.serializer = serializer; + } + + public IAttachmentSerializer getSerializer() { + return serializer; + } + + @Override + public @NotNull String getSerializedName() { + return Lang.asId(name()); + } + } + } diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartControllerUpdatePacket.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartControllerUpdatePacket.java index 009edc376a..cdb0ca6854 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartControllerUpdatePacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartControllerUpdatePacket.java @@ -1,55 +1,58 @@ package com.simibubi.create.content.contraptions.minecart.capability; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.infrastructure.codec.CreateStreamCodecs; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientLevel; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.simibubi.create.AllAttachmentTypes; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; + +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import net.minecraft.world.entity.vehicle.AbstractMinecart; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class MinecartControllerUpdatePacket extends SimplePacketBase { +public record MinecartControllerUpdatePacket(int entityId, @Nullable CompoundTag nbt) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, MinecartControllerUpdatePacket::entityId, + CatnipStreamCodecBuilders.nullable(ByteBufCodecs.COMPOUND_TAG), MinecartControllerUpdatePacket::nbt, + MinecartControllerUpdatePacket::new + ); - int entityID; - CompoundTag nbt; - - public MinecartControllerUpdatePacket(MinecartController controller) { - entityID = controller.cart() - .getId(); - nbt = controller.serializeNBT(); - } - - public MinecartControllerUpdatePacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - nbt = buffer.readNbt(); + public MinecartControllerUpdatePacket(MinecartController controller, @NotNull HolderLookup.Provider registries) { + this(controller.cart().getId(), controller.isEmpty() ? null : controller.serializeNBT(registries)); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - buffer.writeNbt(nbt); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::handleCL)); - return true; - } - @OnlyIn(Dist.CLIENT) - private void handleCL() { - ClientLevel world = Minecraft.getInstance().level; - if (world == null) - return; - Entity entityByID = world.getEntity(entityID); + public void handle(LocalPlayer player) { + Entity entityByID = player.clientLevel.getEntity(entityId); if (entityByID == null) return; - entityByID.getCapability(CapabilityMinecartController.MINECART_CONTROLLER_CAPABILITY) - .ifPresent(mc -> mc.deserializeNBT(nbt)); + if (entityByID.hasData(AllAttachmentTypes.MINECART_CONTROLLER) && entityByID instanceof AbstractMinecart cart) { + if (nbt == null) { + entityByID.setData(AllAttachmentTypes.MINECART_CONTROLLER, MinecartController.EMPTY); + } else { + MinecartController controller = new MinecartController(cart); + controller.deserializeNBT(player.registryAccess(), nbt); + cart.setData(AllAttachmentTypes.MINECART_CONTROLLER, controller); + } + } } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.MINECART_CONTROLLER; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlock.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlock.java index 4d03db03a3..284a84fc7a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlock.java @@ -1,5 +1,14 @@ package com.simibubi.create.content.contraptions.mounted; +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import org.jetbrains.annotations.NotNull; + +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllShapes; @@ -9,6 +18,7 @@ import com.simibubi.create.api.schematic.requirement.ISpecialBlockItemRequiremen import com.simibubi.create.content.schematics.requirement.ItemRequirement; import com.simibubi.create.content.schematics.requirement.ItemRequirement.ItemUseType; import com.simibubi.create.foundation.block.IBE; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; @@ -17,6 +27,7 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.vehicle.AbstractMinecart; @@ -52,11 +63,6 @@ import net.minecraft.world.phys.shapes.EntityCollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.List; - public class CartAssemblerBlock extends BaseRailBlock implements IBE, IWrenchable, ISpecialBlockItemRequirement { @@ -67,6 +73,8 @@ public class CartAssemblerBlock extends BaseRailBlock public static final Property RAIL_TYPE = EnumProperty.create("rail_type", CartAssembleRailType.class); + public static final MapCodec CODEC = simpleCodec(CartAssemblerBlock::new); + public CartAssemblerBlock(Properties properties) { super(true, properties); registerDefaultState(defaultBlockState().setValue(POWERED, false) @@ -159,13 +167,9 @@ public class CartAssemblerBlock extends BaseRailBlock } @Override - @Nonnull - public InteractionResult use(@Nonnull BlockState state, @Nonnull Level world, @Nonnull BlockPos pos, Player player, - @Nonnull InteractionHand hand, @Nonnull BlockHitResult blockRayTraceResult) { - - ItemStack itemStack = player.getItemInHand(hand); + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { Item previousItem = getRailItem(state); - Item heldItem = itemStack.getItem(); + Item heldItem = stack.getItem(); if (heldItem != previousItem) { CartAssembleRailType newType = null; @@ -173,19 +177,19 @@ public class CartAssemblerBlock extends BaseRailBlock if (heldItem == type.getItem()) newType = type; if (newType == null) - return InteractionResult.PASS; - world.playSound(null, pos, SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 1, 1); - world.setBlockAndUpdate(pos, state.setValue(RAIL_TYPE, newType)); + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + level.playSound(null, pos, SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 1, 1); + level.setBlockAndUpdate(pos, state.setValue(RAIL_TYPE, newType)); if (!player.isCreative()) { - itemStack.shrink(1); + stack.shrink(1); player.getInventory() .placeItemBackInInventory(new ItemStack(previousItem)); } - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override @@ -316,7 +320,7 @@ public class CartAssemblerBlock extends BaseRailBlock } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } @@ -370,4 +374,9 @@ public class CartAssemblerBlock extends BaseRailBlock return Direction.NORTH; } } + + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java index ce52a5fcea..79a462009a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java @@ -3,12 +3,12 @@ package com.simibubi.create.content.contraptions.mounted; import java.util.List; import java.util.UUID; +import com.simibubi.create.AllAttachmentTypes; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.contraptions.AssemblyException; import com.simibubi.create.content.contraptions.IDisplayAssemblyExceptions; import com.simibubi.create.content.contraptions.OrientedContraptionEntity; import com.simibubi.create.content.contraptions.minecart.CouplingHandler; -import com.simibubi.create.content.contraptions.minecart.capability.CapabilityMinecartController; import com.simibubi.create.content.contraptions.minecart.capability.MinecartController; import com.simibubi.create.content.redstone.rail.ControllerRailBlock; import com.simibubi.create.foundation.advancement.AllAdvancements; @@ -28,6 +28,7 @@ import net.createmod.catnip.utility.lang.Lang; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.HolderLookup; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; @@ -39,10 +40,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.RailShape; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -@EventBusSubscriber public class CartAssemblerBlockEntity extends SmartBlockEntity implements IDisplayAssemblyExceptions { private static final int assemblyCooldown = 8; @@ -120,10 +118,8 @@ public class CartAssemblerBlockEntity extends SmartBlockEntity implements IDispl .isEmpty()) return; - LazyOptional optional = - cart.getCapability(CapabilityMinecartController.MINECART_CONTROLLER_CAPABILITY); - if (optional.isPresent() && optional.orElse(null) - .isCoupledThroughContraption()) + MinecartController optional = cart.getData(AllAttachmentTypes.MINECART_CONTROLLER); + if (optional != MinecartController.empty() && optional.isCoupledThroughContraption()) return; CartMovementMode mode = CartMovementMode.values()[movementMode.value]; @@ -169,10 +165,12 @@ public class CartAssemblerBlockEntity extends SmartBlockEntity implements IDispl entity.startRiding(cart); if (cart instanceof MinecartFurnace) { - CompoundTag nbt = cart.serializeNBT(); - nbt.putDouble("PushZ", 0); - nbt.putDouble("PushX", 0); - cart.deserializeNBT(nbt); + CompoundTag nbt = new CompoundTag(); + if (cart.save(nbt)) { + nbt.putDouble("PushZ", 0); + nbt.putDouble("PushX", 0); + cart.load(nbt); + } } if (contraption.containsBlockBreakers()) @@ -225,10 +223,11 @@ public class CartAssemblerBlockEntity extends SmartBlockEntity implements IDispl protected void disassembleCart(AbstractMinecart cart) { cart.ejectPassengers(); if (cart instanceof MinecartFurnace) { - CompoundTag nbt = cart.serializeNBT(); + CompoundTag nbt = new CompoundTag(); + cart.saveAsPassenger(nbt); nbt.putDouble("PushZ", cart.getDeltaMovement().x); nbt.putDouble("PushX", cart.getDeltaMovement().z); - cart.deserializeNBT(nbt); + cart.load(nbt); } } @@ -241,15 +240,15 @@ public class CartAssemblerBlockEntity extends SmartBlockEntity implements IDispl } @Override - public void write(CompoundTag compound, boolean clientPacket) { - AssemblyException.write(compound, lastException); - super.write(compound, clientPacket); + public void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + AssemblyException.write(compound, registries, lastException); + super.write(compound, registries, clientPacket); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - lastException = AssemblyException.read(compound); - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + lastException = AssemblyException.read(compound, registries); + super.read(compound, registries, clientPacket); } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/ItemHandlerModifiableFromIInventory.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/ItemHandlerModifiableFromIInventory.java index 326e08ee35..7d2efd5409 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/ItemHandlerModifiableFromIInventory.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/ItemHandlerModifiableFromIInventory.java @@ -4,10 +4,10 @@ import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import net.minecraft.MethodsReturnNonnullByDefault; +import net.minecraft.core.component.DataComponents; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.items.IItemHandlerModifiable; @MethodsReturnNonnullByDefault @@ -52,7 +52,7 @@ public class ItemHandlerModifiableFromIInventory implements IItemHandlerModifiab if (!existing.isEmpty()) { - if (!ItemHandlerHelper.canItemStacksStack(stack, existing)) + if (!ItemStack.isSameItemSameComponents(stack, existing)) return stack; limit -= existing.getCount(); @@ -67,7 +67,7 @@ public class ItemHandlerModifiableFromIInventory implements IItemHandlerModifiab { if (existing.isEmpty()) { - setStackInSlot(slot, reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack); + setStackInSlot(slot, reachedLimit ? stack.copyWithCount(limit) : stack); } else { @@ -75,7 +75,7 @@ public class ItemHandlerModifiableFromIInventory implements IItemHandlerModifiab } } - return reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, stack.getCount()- limit) : ItemStack.EMPTY; + return reachedLimit ? stack.copyWithCount(stack.getCount() - limit) : ItemStack.EMPTY; } @Override @@ -92,7 +92,7 @@ public class ItemHandlerModifiableFromIInventory implements IItemHandlerModifiab if (existing.isEmpty()) return ItemStack.EMPTY; - int toExtract = Math.min(amount, existing.getMaxStackSize()); + int toExtract = Math.min(amount, existing.getOrDefault(DataComponents.MAX_STACK_SIZE, 64)); if (existing.getCount() <= toExtract) { @@ -110,10 +110,10 @@ public class ItemHandlerModifiableFromIInventory implements IItemHandlerModifiab { if (!simulate) { - setStackInSlot(slot, ItemHandlerHelper.copyStackWithSize(existing, existing.getCount() - toExtract)); + setStackInSlot(slot, existing.copyWithCount(existing.getCount() - toExtract)); } - return ItemHandlerHelper.copyStackWithSize(existing, toExtract); + return existing.copyWithCount(toExtract); } } @@ -135,6 +135,6 @@ public class ItemHandlerModifiableFromIInventory implements IItemHandlerModifiab private int getStackLimit(int slot, ItemStack stack) { - return Math.min(getSlotLimit(slot), stack.getMaxStackSize()); + return Math.min(getSlotLimit(slot), stack.getOrDefault(DataComponents.MAX_STACK_SIZE, 64)); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java index 7477e38469..012b7c534a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java @@ -1,5 +1,6 @@ package com.simibubi.create.content.contraptions.mounted; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllItems; import com.simibubi.create.AllMovementBehaviours; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; @@ -16,12 +17,14 @@ import com.simibubi.create.infrastructure.config.AllConfigs; import net.createmod.catnip.utility.NBTHelper; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockSource; import net.minecraft.core.Direction; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; import net.minecraft.core.dispenser.DispenseItemBehavior; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.BlockTags; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; @@ -37,9 +40,12 @@ import net.minecraft.world.level.block.DispenserBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.RailShape; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.minecraft.world.phys.Vec3; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; + +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; + import org.apache.commons.lang3.tuple.MutablePair; import javax.annotation.Nullable; @@ -76,16 +82,16 @@ public class MinecartContraptionItem extends Item { // Taken and adjusted from MinecartItem private static final DispenseItemBehavior DISPENSER_BEHAVIOR = new DefaultDispenseItemBehavior() { private final DefaultDispenseItemBehavior behaviourDefaultDispenseItem = new DefaultDispenseItemBehavior(); - @Override public ItemStack execute(BlockSource source, ItemStack stack) { - Direction direction = source.getBlockState() + Direction direction = source.state() .getValue(DispenserBlock.FACING); - Level world = source.getLevel(); - double d0 = source.x() + (double) direction.getStepX() * 1.125D; - double d1 = Math.floor(source.y()) + (double) direction.getStepY(); - double d2 = source.z() + (double) direction.getStepZ() * 1.125D; - BlockPos blockpos = source.getPos() + ServerLevel world = source.level(); + Vec3 vec3 = source.center(); + double d0 = vec3.x() + (double) direction.getStepX() * 1.125D; + double d1 = Math.floor(vec3.y()) + (double) direction.getStepY(); + double d2 = vec3.z() + (double) direction.getStepZ() * 1.125D; + BlockPos blockpos = source.pos() .relative(direction); BlockState blockstate = world.getBlockState(blockpos); RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock @@ -117,8 +123,8 @@ public class MinecartContraptionItem extends Item { } AbstractMinecart abstractminecartentity = AbstractMinecart.createMinecart(world, d0, d1 + d3, d2, - ((MinecartContraptionItem) stack.getItem()).minecartType); - if (stack.hasCustomHoverName()) + ((MinecartContraptionItem) stack.getItem()).minecartType, stack, null); + if (stack.has(DataComponents.CUSTOM_NAME)) abstractminecartentity.setCustomName(stack.getHoverName()); world.addFreshEntity(abstractminecartentity); addContraptionToMinecart(world, stack, abstractminecartentity, direction); @@ -129,8 +135,8 @@ public class MinecartContraptionItem extends Item { @Override protected void playSound(BlockSource source) { - source.getLevel() - .levelEvent(1000, source.getPos(), 0); + source.level() + .levelEvent(1000, source.pos(), 0); } }; @@ -144,7 +150,7 @@ public class MinecartContraptionItem extends Item { return InteractionResult.FAIL; } else { ItemStack itemstack = context.getItemInHand(); - if (!world.isClientSide) { + if (world instanceof ServerLevel serverlevel) { RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock ? ((BaseRailBlock) blockstate.getBlock()).getRailDirection(blockstate, world, blockpos, null) : RailShape.NORTH_SOUTH; @@ -154,9 +160,9 @@ public class MinecartContraptionItem extends Item { } AbstractMinecart abstractminecartentity = - AbstractMinecart.createMinecart(world, (double) blockpos.getX() + 0.5D, - (double) blockpos.getY() + 0.0625D + d0, (double) blockpos.getZ() + 0.5D, this.minecartType); - if (itemstack.hasCustomHoverName()) + AbstractMinecart.createMinecart(serverlevel, (double) blockpos.getX() + 0.5D, + (double) blockpos.getY() + 0.0625D + d0, (double) blockpos.getZ() + 0.5D, this.minecartType, itemstack, null); + if (itemstack.has(DataComponents.CUSTOM_NAME)) abstractminecartentity.setCustomName(itemstack.getHoverName()); Player player = context.getPlayer(); world.addFreshEntity(abstractminecartentity); @@ -171,9 +177,8 @@ public class MinecartContraptionItem extends Item { public static void addContraptionToMinecart(Level world, ItemStack itemstack, AbstractMinecart cart, @Nullable Direction newFacing) { - CompoundTag tag = itemstack.getOrCreateTag(); - if (tag.contains("Contraption")) { - CompoundTag contraptionTag = tag.getCompound("Contraption"); + if (itemstack.has(AllDataComponents.MINECRAFT_CONTRAPTION_DATA)) { + CompoundTag contraptionTag = itemstack.get(AllDataComponents.MINECRAFT_CONTRAPTION_DATA); Direction intialOrientation = NBTHelper.readEnum(contraptionTag, "InitialOrientation", Direction.class); @@ -243,9 +248,10 @@ public class MinecartContraptionItem extends Item { if (AllMovementBehaviours.getBehaviour(pair.left.state())instanceof PortableStorageInterfaceMovement psim) psim.reset(pair.right); - ItemStack generatedStack = create(type, oce).setHoverName(entity.getCustomName()); + ItemStack generatedStack = create(type, oce); + generatedStack.set(DataComponents.CUSTOM_NAME, entity.getCustomName()); - if (ContraptionData.isTooLargeForPickup(generatedStack.serializeNBT())) { + if (ContraptionData.isTooLargeForPickup(generatedStack.saveOptional(event.getLevel().registryAccess()))) { MutableComponent message = CreateLang.translateDirect("contraption.minecart_contraption_too_big") .withStyle(ChatFormatting.RED); player.displayClientMessage(message, true); @@ -285,15 +291,14 @@ public class MinecartContraptionItem extends Item { return stack; CompoundTag tag = entity.getContraption() - .writeNBT(false); + .writeNBT(entity.registryAccess(), false); tag.remove("UUID"); tag.remove("Pos"); tag.remove("Motion"); NBTHelper.writeEnum(tag, "InitialOrientation", entity.getInitialOrientation()); - stack.getOrCreateTag() - .put("Contraption", tag); + stack.set(AllDataComponents.MINECRAFT_CONTRAPTION_DATA, tag); return stack; } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/MountedContraption.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/MountedContraption.java index 9c2da8de72..76b6f0f5c1 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/MountedContraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/MountedContraption.java @@ -4,6 +4,8 @@ import static com.simibubi.create.content.contraptions.mounted.CartAssemblerBloc import java.util.Queue; +import net.minecraft.core.HolderLookup; + import org.apache.commons.lang3.tuple.Pair; import com.simibubi.create.AllBlocks; @@ -30,7 +32,7 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.RailShape; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.phys.AABB; -import net.minecraftforge.items.wrapper.InvWrapper; +import net.neoforged.neoforge.items.wrapper.InvWrapper; public class MountedContraption extends Contraption { @@ -124,8 +126,8 @@ public class MountedContraption extends Contraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); NBTHelper.writeEnum(tag, "RotationMode", rotationMode); return tag; } @@ -156,4 +158,5 @@ public class MountedContraption extends Contraption { storage.attachExternal(new ContraptionInvWrapper(true, new InvWrapper(container))); } + } diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/LinearActuatorBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/piston/LinearActuatorBlockEntity.java index 22dd3b27cf..ebfe7bd2f8 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/LinearActuatorBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/LinearActuatorBlockEntity.java @@ -18,6 +18,7 @@ import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.foundation.utility.ServerSpeedProvider; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -218,14 +219,14 @@ public abstract class LinearActuatorBlockEntity extends KineticBlockEntity } @Override - protected void write(CompoundTag compound, boolean clientPacket) { + protected void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { compound.putBoolean("Running", running); compound.putBoolean("Waiting", waitingForSpeedChange); compound.putFloat("Offset", offset); if (sequencedOffsetLimit >= 0) compound.putDouble("SequencedOffsetLimit", sequencedOffsetLimit); - AssemblyException.write(compound, lastException); - super.write(compound, clientPacket); + AssemblyException.write(compound, registries, lastException); + super.write(compound, registries, clientPacket); if (clientPacket && forceMove) { compound.putBoolean("ForceMovement", forceMove); @@ -234,7 +235,7 @@ public abstract class LinearActuatorBlockEntity extends KineticBlockEntity } @Override - protected void read(CompoundTag compound, boolean clientPacket) { + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { boolean forceMovement = compound.contains("ForceMovement"); float offsetBefore = offset; @@ -243,8 +244,8 @@ public abstract class LinearActuatorBlockEntity extends KineticBlockEntity offset = compound.getFloat("Offset"); sequencedOffsetLimit = compound.contains("SequencedOffsetLimit") ? compound.getDouble("SequencedOffsetLimit") : -1; - lastException = AssemblyException.read(compound); - super.read(compound, clientPacket); + lastException = AssemblyException.read(compound, registries); + super.read(compound, registries, clientPacket); if (!clientPacket) return; diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlock.java b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlock.java index 5c56a87360..ba4effe7f8 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlock.java @@ -17,7 +17,9 @@ import net.minecraft.util.RandomSource; import net.minecraft.util.StringRepresentable; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; @@ -32,7 +34,7 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; public class MechanicalPistonBlock extends DirectionalAxisKineticBlock implements IBE { @@ -61,41 +63,37 @@ public class MechanicalPistonBlock extends DirectionalAxisKineticBlock implement } @Override - public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (!player.mayBuild()) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; if (player.isShiftKeyDown()) - return InteractionResult.PASS; - if (!player.getItemInHand(handIn) - .is(Tags.Items.SLIMEBALLS)) { - if (player.getItemInHand(handIn) - .isEmpty()) { - withBlockEntityDo(worldIn, pos, be -> be.assembleNextTick = true); - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (!stack.is(Tags.Items.SLIMEBALLS)) { + if (stack.isEmpty()) { + withBlockEntityDo(level, pos, be -> be.assembleNextTick = true); + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } if (state.getValue(STATE) != PistonState.RETRACTED) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; Direction direction = state.getValue(FACING); - if (hit.getDirection() != direction) - return InteractionResult.PASS; + if (hitResult.getDirection() != direction) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; if (((MechanicalPistonBlock) state.getBlock()).isSticky) - return InteractionResult.PASS; - if (worldIn.isClientSide) { - Vec3 vec = hit.getLocation(); - worldIn.addParticle(ParticleTypes.ITEM_SLIME, vec.x, vec.y, vec.z, 0, 0, 0); - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (level.isClientSide) { + Vec3 vec = hitResult.getLocation(); + level.addParticle(ParticleTypes.ITEM_SLIME, vec.x, vec.y, vec.z, 0, 0, 0); + return ItemInteractionResult.SUCCESS; } - AllSoundEvents.SLIME_ADDED.playOnServer(worldIn, pos, .5f, 1); + AllSoundEvents.SLIME_ADDED.playOnServer(level, pos, .5f, 1); if (!player.isCreative()) - player.getItemInHand(handIn) - .shrink(1); - worldIn.setBlockAndUpdate(pos, AllBlocks.STICKY_MECHANICAL_PISTON.getDefaultState() + stack.shrink(1); + level.setBlockAndUpdate(pos, AllBlocks.STICKY_MECHANICAL_PISTON.getDefaultState() .setValue(FACING, direction) .setValue(AXIS_ALONG_FIRST_COORDINATE, state.getValue(AXIS_ALONG_FIRST_COORDINATE))); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } @Override @@ -143,7 +141,7 @@ public class MechanicalPistonBlock extends DirectionalAxisKineticBlock implement } @Override - public void playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { + public BlockState playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { Direction direction = state.getValue(FACING); BlockPos pistonHead = null; BlockPos pistonBase = pos; @@ -184,7 +182,7 @@ public class MechanicalPistonBlock extends DirectionalAxisKineticBlock implement break; } - super.playerWillDestroy(worldIn, pos, state, player); + return super.playerWillDestroy(worldIn, pos, state, player); } public static int maxAllowedPistonPoles() { diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlockEntity.java index 454be0101b..a14c78ee98 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonBlockEntity.java @@ -16,6 +16,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -33,15 +34,15 @@ public class MechanicalPistonBlockEntity extends LinearActuatorBlockEntity { } @Override - protected void read(CompoundTag compound, boolean clientPacket) { + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { extensionLength = compound.getInt("ExtensionLength"); - super.read(compound, clientPacket); + super.read(compound, registries, clientPacket); } @Override - protected void write(CompoundTag tag, boolean clientPacket) { + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { tag.putInt("ExtensionLength", extensionLength); - super.write(tag, clientPacket); + super.write(tag, registries, clientPacket); } @Override @@ -87,7 +88,7 @@ public class MechanicalPistonBlockEntity extends LinearActuatorBlockEntity { level.addFreshEntity(movedContraption); AllSoundEvents.CONTRAPTION_ASSEMBLE.playOnServer(level, worldPosition); - + if (contraption.containsBlockBreakers()) award(AllAdvancements.CONTRAPTION_ACTORS); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonGenerator.java b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonGenerator.java index f28a426d00..9a871ecd49 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonGenerator.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonGenerator.java @@ -11,7 +11,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.piston.PistonBaseBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.PistonType; -import net.minecraftforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.client.model.generators.ModelFile; public class MechanicalPistonGenerator extends SpecialBlockStateGen { diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonHeadBlock.java b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonHeadBlock.java index cecd5a2ab6..8e6882f333 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonHeadBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/MechanicalPistonHeadBlock.java @@ -15,6 +15,7 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.state.BlockState; @@ -51,13 +52,13 @@ public class MechanicalPistonHeadBlock extends WrenchableDirectionalBlock implem } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, - Player player) { + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, + Player player) { return AllBlocks.PISTON_EXTENSION_POLE.asStack(); } @Override - public void playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { + public BlockState playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { Direction direction = state.getValue(FACING); BlockPos pistonHead = pos; BlockPos pistonBase = null; @@ -85,7 +86,7 @@ public class MechanicalPistonHeadBlock extends WrenchableDirectionalBlock implem .setValue(MechanicalPistonBlock.STATE, PistonState.RETRACTED)); } - super.playerWillDestroy(worldIn, pos, state, player); + return super.playerWillDestroy(worldIn, pos, state, player); } @Override @@ -101,7 +102,7 @@ public class MechanicalPistonHeadBlock extends WrenchableDirectionalBlock implem @Override public BlockState updateShape(BlockState state, Direction direction, BlockState neighbourState, LevelAccessor world, BlockPos pos, BlockPos neighbourPos) { - if (state.getValue(BlockStateProperties.WATERLOGGED)) + if (state.getValue(BlockStateProperties.WATERLOGGED)) world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); return state; } @@ -111,9 +112,9 @@ public class MechanicalPistonHeadBlock extends WrenchableDirectionalBlock implem FluidState FluidState = context.getLevel().getFluidState(context.getClickedPos()); return super.getStateForPlacement(context).setValue(BlockStateProperties.WATERLOGGED, Boolean.valueOf(FluidState.getType() == Fluids.WATER)); } - + @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/PistonContraption.java b/src/main/java/com/simibubi/create/content/contraptions/piston/PistonContraption.java index 817c9cd936..fee46b46cd 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/PistonContraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/PistonContraption.java @@ -12,6 +12,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Queue; +import net.minecraft.core.HolderLookup; +import net.minecraft.world.phys.Vec3; + import org.apache.commons.lang3.tuple.Pair; import com.simibubi.create.content.contraptions.AssemblyException; @@ -126,9 +129,9 @@ public class PistonContraption extends TranslatingContraption { extensionLength = extensionsInBack + extensionsInFront; initialExtensionProgress = extensionsInFront; pistonExtensionCollisionBox = new AABB( - BlockPos.ZERO.relative(direction, -1), - BlockPos.ZERO.relative(direction, -extensionLength - 1)).expandTowards(1, - 1, 1); + Vec3.atLowerCornerOf(BlockPos.ZERO.relative(direction, -1)), + Vec3.atLowerCornerOf(BlockPos.ZERO.relative(direction, -extensionLength - 1)) + ).expandTowards(1, 1, 1); if (extensionLength == 0) throw AssemblyException.noPistonPoles(); @@ -233,8 +236,8 @@ public class PistonContraption extends TranslatingContraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); tag.putInt("InitialLength", initialExtensionProgress); tag.putInt("ExtensionLength", extensionLength); tag.putInt("Orientation", orientation.get3DDataValue()); diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java b/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java index ec8affdd86..ed3a87ecd8 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java @@ -22,6 +22,7 @@ import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -58,7 +59,7 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme } @Override - public void playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { + public BlockState playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) { Axis axis = state.getValue(FACING) .getAxis(); Direction direction = Direction.get(AxisDirection.POSITIVE, axis); @@ -106,7 +107,7 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme } } - super.playerWillDestroy(worldIn, pos, state, player); + return super.playerWillDestroy(worldIn, pos, state, player); } @Override @@ -125,15 +126,12 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { - ItemStack heldItem = player.getItemInHand(hand); - + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { IPlacementHelper placementHelper = PlacementHelpers.get(placementHelperId); - if (placementHelper.matchesItem(heldItem) && !player.isShiftKeyDown()) - return placementHelper.getOffset(player, world, state, pos, ray).placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); + if (placementHelper.matchesItem(stack) && !player.isShiftKeyDown()) + return placementHelper.getOffset(player, level, state, pos, hitResult).placeInWorld(level, (BlockItem) stack.getItem(), player, hand, hitResult); - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override @@ -156,7 +154,7 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java index b770e2050b..1a434e3399 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java @@ -10,12 +10,14 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SimpleWaterloggedBlock; import net.minecraft.world.level.block.entity.BlockEntity; @@ -59,25 +61,24 @@ public class PulleyBlock extends HorizontalAxisKineticBlock implements IBE be.assembleNextTick = true); - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (stack.isEmpty()) { + withBlockEntityDo(level, pos, be -> be.assembleNextTick = true); + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override public Class getBlockEntityClass() { return PulleyBlockEntity.class; } - + @Override public BlockEntityType getBlockEntityType() { return AllBlockEntityTypes.ROPE_PULLEY.get(); @@ -91,7 +92,7 @@ public class PulleyBlock extends HorizontalAxisKineticBlock implements IBE NbtUtils.readBlockPos(t, "Pos").orElseThrow()); - if (compound.contains("MirrorParent")) { - mirrorParent = NbtUtils.readBlockPos(compound.getCompound("MirrorParent")); + if (mirrorParent != null) { offset = 0; if (prevMirrorParent == null || !prevMirrorParent.equals(mirrorParent)) sharedMirrorContraption = null; } - if (compound.contains("MirrorChildren")) - mirrorChildren = NBTHelper.readCompoundList(compound.getList("MirrorChildren", Tag.TAG_COMPOUND), - NbtUtils::readBlockPos); - if (mirrorParent == null) sharedMirrorContraption = null; } @Override - public void write(CompoundTag compound, boolean clientPacket) { + public void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { compound.putInt("InitialOffset", initialOffset); - super.write(compound, clientPacket); + super.write(compound, registries, clientPacket); if (mirrorParent != null) compound.put("MirrorParent", NbtUtils.writeBlockPos(mirrorParent)); if (mirrorChildren != null) - compound.put("MirrorChildren", NBTHelper.writeCompoundList(mirrorChildren, NbtUtils::writeBlockPos)); + compound.put("MirrorChildren", NBTHelper.writeCompoundList(mirrorChildren, p -> { + CompoundTag tag = new CompoundTag(); + tag.put("Pos", NbtUtils.writeBlockPos(p)); + return tag; + })); } public void startMirroringOther(BlockPos parent) { diff --git a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyContraption.java b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyContraption.java index 8310a4cae6..917bf3e589 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyContraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyContraption.java @@ -5,6 +5,7 @@ import com.simibubi.create.content.contraptions.ContraptionType; import com.simibubi.create.content.contraptions.TranslatingContraption; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.Level; @@ -42,8 +43,8 @@ public class PulleyContraption extends TranslatingContraption { } @Override - public CompoundTag writeNBT(boolean spawnPacket) { - CompoundTag tag = super.writeNBT(spawnPacket); + public CompoundTag writeNBT(HolderLookup.Provider registries, boolean spawnPacket) { + CompoundTag tag = super.writeNBT(registries, spawnPacket); tag.putInt("InitialOffset", initialOffset); return tag; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyRenderer.java index 4f7ca4b89a..dbbc2b171b 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyRenderer.java @@ -71,10 +71,10 @@ public class PulleyRenderer extends AbstractPulleyRenderer { return offset; } - + @Override public int getViewDistance() { return 128; } - + } diff --git a/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfo.java b/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfo.java index d6f2d45835..ea0113fc0d 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfo.java +++ b/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfo.java @@ -24,7 +24,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; public class ContraptionRenderInfo { public static final SuperByteBufferCache.Compartment> CONTRAPTION = new SuperByteBufferCache.Compartment<>(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfoManager.java b/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfoManager.java index 796744c49b..df53495dd3 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfoManager.java +++ b/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionRenderInfoManager.java @@ -9,9 +9,9 @@ import net.createmod.catnip.utility.WorldAttached; import net.minecraft.client.Minecraft; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; @EventBusSubscriber(Dist.CLIENT) public class ContraptionRenderInfoManager { diff --git a/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionVisual.java b/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionVisual.java index 30ca7f229b..bcbcf0e1f3 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionVisual.java +++ b/src/main/java/com/simibubi/create/content/contraptions/render/ContraptionVisual.java @@ -28,7 +28,7 @@ import dev.engine_room.flywheel.api.visualization.VisualizationContext; import dev.engine_room.flywheel.api.visualization.VisualizerRegistry; import dev.engine_room.flywheel.lib.instance.InstanceTypes; import dev.engine_room.flywheel.lib.instance.TransformedInstance; -import dev.engine_room.flywheel.lib.model.baked.ForgeMultiBlockModelBuilder; +import dev.engine_room.flywheel.lib.model.baked.MultiBlockModelBuilder; import dev.engine_room.flywheel.lib.task.ForEachPlan; import dev.engine_room.flywheel.lib.task.NestedPlan; import dev.engine_room.flywheel.lib.task.PlanMap; @@ -45,7 +45,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.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraftforge.client.model.data.ModelData; public class ContraptionVisual extends AbstractEntityVisual implements DynamicVisual, TickableVisual, LightUpdatedVisual, ShaderLightVisual { protected static final int LIGHT_PADDING = 1; @@ -91,8 +90,7 @@ public class ContraptionVisual extends Abst } }; - model = new ForgeMultiBlockModelBuilder(modelWorld, blocks.positions()) - .modelDataLookup(pos -> contraption.modelData.getOrDefault(pos, ModelData.EMPTY)) + model = new MultiBlockModelBuilder(modelWorld, blocks.positions()) .build(); var instancer = embedding.instancerProvider() diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/ClientMotionPacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/ClientMotionPacket.java index 7054c907ab..d52f7adb52 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/ClientMotionPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/ClientMotionPacket.java @@ -1,58 +1,42 @@ package com.simibubi.create.content.contraptions.sync; import com.simibubi.create.AllPackets; -import com.simibubi.create.foundation.networking.SimplePacketBase; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.platform.CatnipServices; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ClientMotionPacket extends SimplePacketBase { +public record ClientMotionPacket(Vec3 motion, boolean onGround, float limbSwing) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecs.VEC3, ClientMotionPacket::motion, + ByteBufCodecs.BOOL, ClientMotionPacket::onGround, + ByteBufCodecs.FLOAT, ClientMotionPacket::limbSwing, + ClientMotionPacket::new + ); - private Vec3 motion; - private boolean onGround; - private float limbSwing; - - public ClientMotionPacket(Vec3 motion, boolean onGround, float limbSwing) { - this.motion = motion; - this.onGround = onGround; - this.limbSwing = limbSwing; - } - - public ClientMotionPacket(FriendlyByteBuf buffer) { - motion = new Vec3(buffer.readFloat(), buffer.readFloat(), buffer.readFloat()); - onGround = buffer.readBoolean(); - limbSwing = buffer.readFloat(); + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.CLIENT_MOTION; } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeFloat((float) motion.x); - buffer.writeFloat((float) motion.y); - buffer.writeFloat((float) motion.z); - buffer.writeBoolean(onGround); - buffer.writeFloat(limbSwing); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer sender = context.getSender(); - if (sender == null) - return; - sender.setDeltaMovement(motion); - sender.setOnGround(onGround); - if (onGround) { - sender.causeFallDamage(sender.fallDistance, 1, sender.damageSources().fall()); - sender.fallDistance = 0; - sender.connection.aboveGroundTickCount = 0; - sender.connection.aboveGroundVehicleTickCount = 0; - } - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> sender), + public void handle(ServerPlayer sender) { + if (sender == null) + return; + sender.setDeltaMovement(motion); + sender.setOnGround(onGround); + if (onGround) { + sender.causeFallDamage(sender.fallDistance, 1, sender.damageSources().fall()); + sender.fallDistance = 0; + sender.connection.aboveGroundTickCount = 0; + sender.connection.aboveGroundVehicleTickCount = 0; + } + CatnipServices.NETWORK.sendToClientsTrackingEntity(sender, new LimbSwingUpdatePacket(sender.getId(), sender.position(), limbSwing)); - }); - return true; } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionFluidPacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionFluidPacket.java index 2c94225b87..a31d28ae72 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionFluidPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionFluidPacket.java @@ -1,49 +1,39 @@ package com.simibubi.create.content.contraptions.sync; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionFluidPacket extends SimplePacketBase { +public record ContraptionFluidPacket(int entityId, BlockPos localPos, FluidStack fluid) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ContraptionFluidPacket::entityId, + BlockPos.STREAM_CODEC, ContraptionFluidPacket::localPos, + FluidStack.OPTIONAL_STREAM_CODEC, ContraptionFluidPacket::fluid, + ContraptionFluidPacket::new + ); - private int entityId; - private BlockPos localPos; - private FluidStack containedFluid; - - public ContraptionFluidPacket(int entityId, BlockPos localPos, FluidStack containedFluid) { - this.entityId = entityId; - this.localPos = localPos; - this.containedFluid = containedFluid; - } - - public ContraptionFluidPacket(FriendlyByteBuf buffer) { - entityId = buffer.readInt(); - localPos = buffer.readBlockPos(); - containedFluid = FluidStack.readFromPacket(buffer); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + Entity entityByID = player.clientLevel.getEntity(entityId); + if (!(entityByID instanceof AbstractContraptionEntity contraptionEntity)) + return; + contraptionEntity.getContraption().handleContraptionFluidPacket(localPos, fluid); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityId); - buffer.writeBlockPos(localPos); - containedFluid.writeToPacket(buffer); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - Entity entityByID = Minecraft.getInstance().level.getEntity(entityId); - if (!(entityByID instanceof AbstractContraptionEntity)) - return; - AbstractContraptionEntity contraptionEntity = (AbstractContraptionEntity) entityByID; - contraptionEntity.getContraption().handleContraptionFluidPacket(localPos, containedFluid); - }); - return true; + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_FLUID; } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java index 12deecf630..d4a4276cdc 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java @@ -1,69 +1,57 @@ package com.simibubi.create.content.contraptions.sync; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.AABB; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionInteractionPacket extends SimplePacketBase { - - private InteractionHand interactionHand; - private int target; - private BlockPos localPos; - private Direction face; +public record ContraptionInteractionPacket(InteractionHand hand, int target, BlockPos localPos, Direction face) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecBuilders.nullable(CatnipStreamCodecs.HAND), ContraptionInteractionPacket::hand, + ByteBufCodecs.INT, ContraptionInteractionPacket::target, + BlockPos.STREAM_CODEC, ContraptionInteractionPacket::localPos, + Direction.STREAM_CODEC, ContraptionInteractionPacket::face, + ContraptionInteractionPacket::new + ); public ContraptionInteractionPacket(AbstractContraptionEntity target, InteractionHand hand, BlockPos localPos, Direction side) { - this.interactionHand = hand; - this.localPos = localPos; - this.target = target.getId(); - this.face = side; - } - - public ContraptionInteractionPacket(FriendlyByteBuf buffer) { - target = buffer.readInt(); - int handId = buffer.readInt(); - interactionHand = handId == -1 ? null : InteractionHand.values()[handId]; - localPos = buffer.readBlockPos(); - face = Direction.from3DDataValue(buffer.readShort()); + this(hand, target.getId(), localPos, side); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(target); - buffer.writeInt(interactionHand == null ? -1 : interactionHand.ordinal()); - buffer.writeBlockPos(localPos); - buffer.writeShort(face.get3DDataValue()); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_INTERACT; } @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer sender = context.getSender(); - if (sender == null) - return; - Entity entityByID = sender.level().getEntity(target); - if (!(entityByID instanceof AbstractContraptionEntity)) - return; - AbstractContraptionEntity contraptionEntity = (AbstractContraptionEntity) entityByID; - AABB bb = contraptionEntity.getBoundingBox(); - double boundsExtra = Math.max(bb.getXsize(), bb.getYsize()); - double d = sender.getAttribute(ForgeMod.BLOCK_REACH.get()).getValue() + 10 + boundsExtra; - if (!sender.hasLineOfSight(entityByID)) - d -= 3; - d *= d; - if (sender.distanceToSqr(entityByID) > d) - return; - if (contraptionEntity.handlePlayerInteraction(sender, localPos, face, interactionHand)) - sender.swing(interactionHand, true); - }); - return true; + public void handle(ServerPlayer sender) { + if (sender == null) + return; + Entity entityByID = sender.level().getEntity(target); + if (!(entityByID instanceof AbstractContraptionEntity contraptionEntity)) + return; + AABB bb = contraptionEntity.getBoundingBox(); + double boundsExtra = Math.max(bb.getXsize(), bb.getYsize()); + double d = sender.getAttributeValue(Attributes.BLOCK_INTERACTION_RANGE) + 10 + boundsExtra; + if (!sender.hasLineOfSight(entityByID)) + d -= 3; + d *= d; + if (sender.distanceToSqr(entityByID) > d) + return; + if (contraptionEntity.handlePlayerInteraction(sender, localPos, face, hand)) + sender.swing(hand, true); } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java index eaa136d035..fac27267be 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java @@ -4,74 +4,54 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import io.netty.buffer.ByteBuf; import net.createmod.catnip.utility.VecHelper; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.UUIDUtil; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ContraptionSeatMappingPacket extends SimplePacketBase { - - private Map mapping; - private int entityID; - private int dismountedID; +public record ContraptionSeatMappingPacket(int entityId, Map mapping, int dismountedId) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, ContraptionSeatMappingPacket::entityId, + ByteBufCodecs.map(HashMap::new, UUIDUtil.STREAM_CODEC, ByteBufCodecs.INT), ContraptionSeatMappingPacket::mapping, + ByteBufCodecs.INT, ContraptionSeatMappingPacket::dismountedId, + ContraptionSeatMappingPacket::new + ); public ContraptionSeatMappingPacket(int entityID, Map mapping) { this(entityID, mapping, -1); } - public ContraptionSeatMappingPacket(int entityID, Map mapping, int dismountedID) { - this.entityID = entityID; - this.mapping = mapping; - this.dismountedID = dismountedID; - } - - public ContraptionSeatMappingPacket(FriendlyByteBuf buffer) { - entityID = buffer.readInt(); - dismountedID = buffer.readInt(); - mapping = new HashMap<>(); - short size = buffer.readShort(); - for (int i = 0; i < size; i++) - mapping.put(buffer.readUUID(), (int) buffer.readShort()); - } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityID); - buffer.writeInt(dismountedID); - buffer.writeShort(mapping.size()); - mapping.forEach((k, v) -> { - buffer.writeUUID(k); - buffer.writeShort(v); - }); - } + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + Entity entityByID = player.clientLevel.getEntity(entityId); + if (!(entityByID instanceof AbstractContraptionEntity contraptionEntity)) + return; - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - Entity entityByID = Minecraft.getInstance().level.getEntity(entityID); - if (!(entityByID instanceof AbstractContraptionEntity)) - return; - AbstractContraptionEntity contraptionEntity = (AbstractContraptionEntity) entityByID; - - if (dismountedID != -1) { - Entity dismountedByID = Minecraft.getInstance().level.getEntity(dismountedID); - if (Minecraft.getInstance().player != dismountedByID) - return; - Vec3 transformedVector = contraptionEntity.getPassengerPosition(dismountedByID, 1); - if (transformedVector != null) - dismountedByID.getPersistentData() + if (dismountedId == player.getId()) { + Vec3 transformedVector = contraptionEntity.getPassengerPosition(player, 1); + if (transformedVector != null) + player.getPersistentData() .put("ContraptionDismountLocation", VecHelper.writeNBT(transformedVector)); - } + } - contraptionEntity.getContraption() + contraptionEntity.getContraption() .setSeatMapping(mapping); - }); - return true; } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONTRAPTION_SEAT_MAPPING; + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/LimbSwingUpdatePacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/LimbSwingUpdatePacket.java index cfde843d67..0f74dd4bd9 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/LimbSwingUpdatePacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/LimbSwingUpdatePacket.java @@ -1,58 +1,44 @@ package com.simibubi.create.content.contraptions.sync; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import com.simibubi.create.infrastructure.codec.CreateStreamCodecs; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientLevel; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class LimbSwingUpdatePacket extends SimplePacketBase { +public record LimbSwingUpdatePacket(int entityId, Vec3 position, float limbSwing) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, LimbSwingUpdatePacket::entityId, + CatnipStreamCodecs.VEC3, LimbSwingUpdatePacket::position, + ByteBufCodecs.FLOAT, LimbSwingUpdatePacket::limbSwing, + LimbSwingUpdatePacket::new + ); - private int entityId; - private Vec3 position; - private float limbSwing; - - public LimbSwingUpdatePacket(int entityId, Vec3 position, float limbSwing) { - this.entityId = entityId; - this.position = position; - this.limbSwing = limbSwing; - } - - public LimbSwingUpdatePacket(FriendlyByteBuf buffer) { - entityId = buffer.readInt(); - position = new Vec3(buffer.readDouble(), buffer.readDouble(), buffer.readDouble()); - limbSwing = buffer.readFloat(); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + Entity entity = player.clientLevel.getEntity(entityId); + if (entity == null) + return; + CompoundTag data = entity.getPersistentData(); + data.putInt("LastOverrideLimbSwingUpdate", 0); + data.putFloat("OverrideLimbSwing", limbSwing); + entity.lerpTo(position.x, position.y, position.z, entity.getYRot(), + entity.getXRot(), 2); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(entityId); - buffer.writeDouble(position.x); - buffer.writeDouble(position.y); - buffer.writeDouble(position.z); - buffer.writeFloat(limbSwing); + public PacketTypeProvider getTypeProvider() { + return AllPackets.LIMBSWING_UPDATE; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ClientLevel world = Minecraft.getInstance().level; - if (world == null) - return; - Entity entity = world.getEntity(entityId); - if (entity == null) - return; - CompoundTag data = entity.getPersistentData(); - data.putInt("LastOverrideLimbSwingUpdate", 0); - data.putFloat("OverrideLimbSwing", limbSwing); - entity.lerpTo(position.x, position.y, position.z, entity.getYRot(), - entity.getXRot(), 2, false); - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenu.java b/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenu.java index e23b1709ab..7fb724d6d5 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenu.java +++ b/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenu.java @@ -15,13 +15,13 @@ import org.joml.Matrix4f; import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; -import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat.Mode; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllKeys; -import com.simibubi.create.AllPackets; import com.simibubi.create.Create; import com.simibubi.create.content.kinetics.base.DirectionalKineticBlock; import com.simibubi.create.content.kinetics.base.HorizontalAxisKineticBlock; @@ -38,6 +38,7 @@ import net.createmod.catnip.gui.element.GuiGameElement; import net.createmod.catnip.gui.element.RenderElement; import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.AnimationTickHolder; +import net.createmod.catnip.utility.RegisteredObjectsHelper; import net.createmod.catnip.utility.math.AngleHelper; import net.createmod.catnip.utility.theme.Color; import net.createmod.ponder.enums.PonderGuiTextures; @@ -109,7 +110,7 @@ public class RadialWrenchMenu extends AbstractSimiScreen { private final RenderElement iconDown = RenderElement.of(AllIcons.I_PRIORITY_LOW); public static Optional tryCreateFor(BlockState state, BlockPos pos, @Nullable Level level) { - if (BLOCK_BLACKLIST.contains(CatnipServices.REGISTRIES.getKeyOrThrow(state.getBlock()))) + if (BLOCK_BLACKLIST.contains(RegisteredObjectsHelper.getKeyOrThrow(state.getBlock()))) return Optional.empty(); var propertiesForState = VALID_PROPERTIES.entrySet().stream().filter(entry -> state.hasProperty(entry.getKey())).toList(); @@ -327,20 +328,19 @@ public class RadialWrenchMenu extends AbstractSimiScreen { RenderSystem.setShader(GameRenderer::getPositionColorShader); Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferbuilder = tesselator.getBuilder(); - bufferbuilder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); + BufferBuilder bufferbuilder = tesselator.begin(Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); Matrix4f mat = poseStack.last().pose(); - bufferbuilder.vertex(mat, 0, 0, 0).color(r, g, b, 0.75f).endVertex(); + bufferbuilder.addVertex(mat, 0, 0, 0).setColor(r, g, b, 0.75f); - bufferbuilder.vertex(mat, 5, -5, 0).color(r, g, b, 0.4f).endVertex(); - bufferbuilder.vertex(mat, 3, -4.5f, 0).color(r, g, b, 0.4f).endVertex(); - bufferbuilder.vertex(mat, 0, -4.2f, 0).color(r, g, b, 0.4f).endVertex(); - bufferbuilder.vertex(mat, -3, -4.5f, 0).color(r, g, b, 0.4f).endVertex(); - bufferbuilder.vertex(mat, -5, -5, 0).color(r, g, b, 0.4f).endVertex(); + bufferbuilder.addVertex(mat, 5, -5, 0).setColor(r, g, b, 0.4f); + bufferbuilder.addVertex(mat, 3, -4.5f, 0).setColor(r, g, b, 0.4f); + bufferbuilder.addVertex(mat, 0, -4.2f, 0).setColor(r, g, b, 0.4f); + bufferbuilder.addVertex(mat, -3, -4.5f, 0).setColor(r, g, b, 0.4f); + bufferbuilder.addVertex(mat, -5, -5, 0).setColor(r, g, b, 0.4f); - tesselator.end(); + BufferUploader.drawWithShader(bufferbuilder.buildOrThrow()); poseStack.popPose(); } @@ -348,18 +348,18 @@ public class RadialWrenchMenu extends AbstractSimiScreen { private void submitChange() { BlockState selectedState = allStates.get(selectedStateIndex); if (selectedState != state) { - AllPackets.getChannel().sendToServer(new RadialWrenchMenuSubmitPacket(pos, selectedState)); + CatnipServices.NETWORK.sendToServer(new RadialWrenchMenuSubmitPacket(pos, selectedState)); } onClose(); } @Override - public void renderBackground(GuiGraphics graphics) { + public void renderBackground(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) { Color color = BACKGROUND_COLOR - .scaleAlpha(Math.min(1, (ticksOpen + AnimationTickHolder.getPartialTicks()) / 20f)); + .scaleAlpha(Math.min(1, (ticksOpen + AnimationTickHolder.getPartialTicks()) / 20f)); - graphics.fillGradient(0, 0, this.width, this.height, color.getRGB(), color.getRGB()); + guiGraphics.fillGradient(0, 0, this.width, this.height, color.getRGB(), color.getRGB()); } @Override @@ -386,11 +386,11 @@ public class RadialWrenchMenu extends AbstractSimiScreen { } @Override - public boolean mouseScrolled(double pMouseX, double pMouseY, double pDelta) { + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { if (propertiesForState.size() < 2) - return super.mouseScrolled(pMouseX, pMouseY, pDelta); + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); - int indexDelta = (int) Math.round(Math.signum(-pDelta)); + int indexDelta = (int) Math.round(Math.signum(-scrollY)); int newIndex = selectedPropertyIndex + indexDelta; if (newIndex < 0) diff --git a/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenuSubmitPacket.java b/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenuSubmitPacket.java index a8c98a9cc0..ce7d02c7bc 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenuSubmitPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/wrench/RadialWrenchMenuSubmitPacket.java @@ -1,50 +1,38 @@ package com.simibubi.create.content.contraptions.wrench; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.equipment.wrench.IWrenchable; import com.simibubi.create.content.kinetics.base.KineticBlockEntity; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import io.netty.buffer.ByteBuf; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import net.createmod.catnip.net.base.ServerboundPacketPayload; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.registries.GameData; -public class RadialWrenchMenuSubmitPacket extends SimplePacketBase { +public record RadialWrenchMenuSubmitPacket(BlockPos blockPos, BlockState newState) implements ServerboundPacketPayload { + public static StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, RadialWrenchMenuSubmitPacket::blockPos, + CatnipStreamCodecs.BLOCK_STATE, RadialWrenchMenuSubmitPacket::newState, + RadialWrenchMenuSubmitPacket::new + ); - private final BlockPos blockPos; - private final BlockState newState; - - public RadialWrenchMenuSubmitPacket(BlockPos blockPos, BlockState newState) { - this.blockPos = blockPos; - this.newState = newState; - } - - public RadialWrenchMenuSubmitPacket(FriendlyByteBuf buffer) { - this.blockPos = buffer.readBlockPos(); - this.newState = buffer.readById(GameData.getBlockStateIDMap()); + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.RADIAL_WRENCH_MENU_SUBMIT; } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(blockPos); - buffer.writeId(GameData.getBlockStateIDMap(), newState); - } + public void handle(ServerPlayer player) { + Level level = player.level(); - @Override - public boolean handle(NetworkEvent.Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - Level level = player.level(); + BlockState updatedState = Block.updateFromNeighbourShapes(newState, level, blockPos); + KineticBlockEntity.switchToBlockState(level, blockPos, updatedState); - BlockState updatedState = Block.updateFromNeighbourShapes(newState, level, blockPos); - KineticBlockEntity.switchToBlockState(level, blockPos, updatedState); - - IWrenchable.playRotateSound(level, blockPos); - }); - return true; + IWrenchable.playRotateSound(level, blockPos); } } diff --git a/src/main/java/com/simibubi/create/content/decoration/MetalLadderBlock.java b/src/main/java/com/simibubi/create/content/decoration/MetalLadderBlock.java index 7cbc03e682..74e22425fd 100644 --- a/src/main/java/com/simibubi/create/content/decoration/MetalLadderBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/MetalLadderBlock.java @@ -15,8 +15,9 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -29,9 +30,8 @@ import net.minecraft.world.level.block.LadderBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.ForgeMod; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class MetalLadderBlock extends LadderBlock implements IWrenchable { @@ -77,16 +77,14 @@ public class MetalLadderBlock extends LadderBlock implements IWrenchable { } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (player.isShiftKeyDown() || !player.mayBuild()) - return InteractionResult.PASS; - ItemStack heldItem = player.getItemInHand(hand); + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; IPlacementHelper helper = PlacementHelpers.get(placementHelperId); - if (helper.matchesItem(heldItem)) - return helper.getOffset(player, world, state, pos, ray) - .placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); - return InteractionResult.PASS; + if (helper.matchesItem(stack)) + return helper.getOffset(player, level, state, pos, hitResult) + .placeInWorld(level, (BlockItem) stack.getItem(), player, hand, hitResult); + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @MethodsReturnNonnullByDefault @@ -122,8 +120,8 @@ public class MetalLadderBlock extends LadderBlock implements IWrenchable { int range = AllConfigs.server().equipment.placementAssistRange.get(); if (player != null) { - AttributeInstance reach = player.getAttribute(ForgeMod.BLOCK_REACH.get()); - if (reach != null && reach.hasModifier(ExtendoGripItem.singleRangeAttributeModifier)) + AttributeInstance reach = player.getAttribute(Attributes.BLOCK_INTERACTION_RANGE); + if (reach != null && reach.hasModifier(ExtendoGripItem.singleRangeAttributeModifier.id())) range += 4; } diff --git a/src/main/java/com/simibubi/create/content/decoration/TrainTrapdoorBlock.java b/src/main/java/com/simibubi/create/content/decoration/TrainTrapdoorBlock.java index a0d34b8068..dc15204978 100644 --- a/src/main/java/com/simibubi/create/content/decoration/TrainTrapdoorBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/TrainTrapdoorBlock.java @@ -17,18 +17,18 @@ import net.minecraft.world.phys.BlockHitResult; public class TrainTrapdoorBlock extends TrapDoorBlock implements IWrenchable { - public TrainTrapdoorBlock(Properties p_57526_) { - super(p_57526_, SlidingDoorBlock.TRAIN_SET_TYPE.get()); + public TrainTrapdoorBlock(Properties properties) { + super(SlidingDoorBlock.TRAIN_SET_TYPE.get(), properties); } - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, - BlockHitResult pHit) { - pState = pState.cycle(OPEN); - pLevel.setBlock(pPos, pState, 2); - if (pState.getValue(WATERLOGGED)) - pLevel.scheduleTick(pPos, Fluids.WATER, Fluids.WATER.getTickDelay(pLevel)); - playSound(pPlayer, pLevel, pPos, pState.getValue(OPEN)); - return InteractionResult.sidedSuccess(pLevel.isClientSide); + @Override + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + state = state.cycle(OPEN); + level.setBlock(pos, state, 2); + if (state.getValue(WATERLOGGED)) + level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); + playSound(player, level, pos, state.getValue(OPEN)); + return InteractionResult.sidedSuccess(level.isClientSide); } @Override diff --git a/src/main/java/com/simibubi/create/content/decoration/bracket/BracketGenerator.java b/src/main/java/com/simibubi/create/content/decoration/bracket/BracketGenerator.java index 30a2b01426..128880f6d0 100644 --- a/src/main/java/com/simibubi/create/content/decoration/bracket/BracketGenerator.java +++ b/src/main/java/com/simibubi/create/content/decoration/bracket/BracketGenerator.java @@ -9,7 +9,7 @@ import com.tterrag.registrate.util.nullness.NonNullFunction; import net.minecraft.world.item.BlockItem; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.client.model.generators.ModelFile; public class BracketGenerator extends DirectionalAxisBlockStateGen { diff --git a/src/main/java/com/simibubi/create/content/decoration/bracket/BracketedBlockEntityBehaviour.java b/src/main/java/com/simibubi/create/content/decoration/bracket/BracketedBlockEntityBehaviour.java index 4a85fa16d0..ea76fac664 100644 --- a/src/main/java/com/simibubi/create/content/decoration/bracket/BracketedBlockEntityBehaviour.java +++ b/src/main/java/com/simibubi/create/content/decoration/bracket/BracketedBlockEntityBehaviour.java @@ -2,6 +2,8 @@ package com.simibubi.create.content.decoration.bracket; import java.util.function.Predicate; +import net.minecraft.core.HolderLookup; + import org.jetbrains.annotations.Nullable; import com.simibubi.create.content.contraptions.StructureTransform; @@ -113,7 +115,7 @@ public class BracketedBlockEntityBehaviour extends BlockEntityBehaviour { } @Override - public void write(CompoundTag nbt, boolean clientPacket) { + public void write(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { if (isBracketPresent() && isBracketValid(bracket)) { nbt.put("Bracket", NbtUtils.writeBlockState(bracket)); } @@ -121,11 +123,11 @@ public class BracketedBlockEntityBehaviour extends BlockEntityBehaviour { NBTHelper.putMarker(nbt, "Redraw"); reRender = false; } - super.write(nbt, clientPacket); + super.write(nbt, registries, clientPacket); } @Override - public void read(CompoundTag nbt, boolean clientPacket) { + public void read(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { if (nbt.contains("Bracket")) { bracket = null; BlockState readBlockState = NbtUtils.readBlockState(blockEntity.blockHolderGetter(), nbt.getCompound("Bracket")); @@ -134,7 +136,7 @@ public class BracketedBlockEntityBehaviour extends BlockEntityBehaviour { } if (clientPacket && nbt.contains("Redraw")) getWorld().sendBlockUpdated(getPos(), blockEntity.getBlockState(), blockEntity.getBlockState(), 16); - super.read(nbt, clientPacket); + super.read(nbt, registries, clientPacket); } } diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java index 263bce99ed..9e63bde1de 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java @@ -14,7 +14,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.util.RandomSource; 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 CopycatBarsModel extends CopycatModel { diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlock.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlock.java index e251642d5f..2cbebcab5c 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlock.java @@ -18,10 +18,9 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.SpawnPlacements.Type; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -46,9 +45,9 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.data.ModelDataManager; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.model.data.ModelDataManager; public abstract class CopycatBlock extends Block implements IBE, IWrenchable { @@ -88,50 +87,47 @@ public abstract class CopycatBlock extends Block implements IBE { + return onBlockEntityUseItemOn(level, pos, ufte -> { if (ufte.getMaterial() .is(material.getBlock())) { if (!ufte.cycleMaterial()) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; ufte.getLevel() .playSound(null, ufte.getBlockPos(), SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, .75f, .95f); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } if (ufte.hasCustomMaterial()) - return InteractionResult.PASS; - if (pLevel.isClientSide()) - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (level.isClientSide()) + return ItemInteractionResult.SUCCESS; ufte.setMaterial(material); - ufte.setConsumedItem(itemInHand); + ufte.setConsumedItem(stack); ufte.getLevel() .playSound(null, ufte.getBlockPos(), material.getSoundType() .getPlaceSound(), SoundSource.BLOCKS, 1, .75f); - if (pPlayer.isCreative()) - return InteractionResult.SUCCESS; + if (player.isCreative()) + return ItemInteractionResult.SUCCESS; - itemInHand.shrink(1); - if (itemInHand.isEmpty()) - pPlayer.setItemInHand(pHand, ItemStack.EMPTY); - return InteractionResult.SUCCESS; + stack.shrink(1); + if (stack.isEmpty()) + player.setItemInHand(hand, ItemStack.EMPTY); + return ItemInteractionResult.SUCCESS; }); } @@ -229,10 +225,11 @@ public abstract class CopycatBlock extends Block implements IBE ufte.setConsumedItem(ItemStack.EMPTY)); + return pState; } @Override @@ -255,7 +252,7 @@ public abstract class CopycatBlock extends Block implements IBE entityType) { - return false; - } - @Override public void fallOn(Level pLevel, BlockState pState, BlockPos pPos, Entity pEntity, float p_152430_) { BlockState material = getMaterial(pLevel, pPos); diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlockEntity.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlockEntity.java index c8b956d03c..eeae833695 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBlockEntity.java @@ -13,6 +13,8 @@ import com.simibubi.create.api.schematic.nbt.IPartialSafeNBT; import net.createmod.catnip.utility.Iterate; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.component.DataComponentPatch; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.world.item.ItemStack; @@ -20,8 +22,7 @@ import net.minecraft.world.level.block.TrapDoorBlock; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.client.model.data.ModelData; import java.util.List; @@ -100,7 +101,7 @@ public class CopycatBlockEntity extends SmartBlockEntity } public void setConsumedItem(ItemStack stack) { - consumedItem = ItemHandlerHelper.copyStackWithSize(stack, 1); + consumedItem = stack.copyWithCount(1); setChanged(); } @@ -132,10 +133,10 @@ public class CopycatBlockEntity extends SmartBlockEntity } @Override - protected void read(CompoundTag tag, boolean clientPacket) { - super.read(tag, clientPacket); + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.read(tag, registries, clientPacket); - consumedItem = ItemStack.of(tag.getCompound("Item")); + consumedItem = ItemStack.parseOptional(registries, tag.getCompound("Item")); BlockState prevMaterial = material; if (!tag.contains("Material")) { @@ -164,23 +165,22 @@ public class CopycatBlockEntity extends SmartBlockEntity } @Override - public void writeSafe(CompoundTag tag) { - super.writeSafe(tag); + public void writeSafe(CompoundTag tag, HolderLookup.Provider registries) { + super.writeSafe(tag, registries); - ItemStack stackWithoutNBT = consumedItem.copy(); - stackWithoutNBT.setTag(null); + ItemStack stackWithoutComponents = new ItemStack(consumedItem.getItemHolder(), consumedItem.getCount(), DataComponentPatch.EMPTY); - write(tag, stackWithoutNBT, material); + write(tag, registries, stackWithoutComponents, material); } @Override - protected void write(CompoundTag tag, boolean clientPacket) { - super.write(tag, clientPacket); - write(tag, consumedItem, material); + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.write(tag, registries, clientPacket); + write(tag, registries, consumedItem, material); } - protected void write(CompoundTag tag, ItemStack stack, BlockState material) { - tag.put("Item", stack.serializeNBT()); + protected void write(CompoundTag tag, HolderLookup.Provider registries, ItemStack stack, BlockState material) { + tag.put("Item", stack.saveOptional(registries)); tag.put("Material", NbtUtils.writeBlockState(material)); } diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatModel.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatModel.java index fc022af546..088b92c788 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatModel.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatModel.java @@ -22,9 +22,9 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.client.model.data.ModelData.Builder; -import net.minecraftforge.client.model.data.ModelProperty; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData.Builder; +import net.neoforged.neoforge.client.model.data.ModelProperty; public abstract class CopycatModel extends BakedModelWrapperWithData { diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelBlock.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelBlock.java index d731727452..a37e819da5 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelBlock.java @@ -11,6 +11,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -71,20 +72,17 @@ public class CopycatPanelBlock extends WaterloggedCopycatBlock { } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { - + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (!player.isShiftKeyDown() && player.mayBuild()) { - ItemStack heldItem = player.getItemInHand(hand); IPlacementHelper placementHelper = PlacementHelpers.get(placementHelperId); - if (placementHelper.matchesItem(heldItem)) { - placementHelper.getOffset(player, world, state, pos, ray) - .placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); - return InteractionResult.SUCCESS; + if (placementHelper.matchesItem(stack)) { + placementHelper.getOffset(player, level, state, pos, hitResult) + .placeInWorld(level, (BlockItem) stack.getItem(), player, hand, hitResult); + return ItemInteractionResult.SUCCESS; } } - return super.use(state, world, pos, player, hand, ray); + return super.useItemOn(stack, state, level, pos, player, hand, hitResult); } @Override @@ -159,7 +157,7 @@ public class CopycatPanelBlock extends WaterloggedCopycatBlock { } @Override - public boolean isPathfindable(BlockState pState, BlockGetter pLevel, BlockPos pPos, PathComputationType pType) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelModel.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelModel.java index 33ec5b74f5..fac240d120 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelModel.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatPanelModel.java @@ -20,7 +20,7 @@ import net.minecraft.world.level.block.DirectionalBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; public class CopycatPanelModel extends CopycatModel { diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepBlock.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepBlock.java index 9d9d1075d7..b3b17d2196 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepBlock.java @@ -17,6 +17,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -52,18 +53,15 @@ public class CopycatStepBlock extends WaterloggedCopycatBlock { } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { - + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (!player.isShiftKeyDown() && player.mayBuild()) { - ItemStack heldItem = player.getItemInHand(hand); IPlacementHelper helper = PlacementHelpers.get(placementHelperId); - if (helper.matchesItem(heldItem)) - return helper.getOffset(player, world, state, pos, ray) - .placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); + if (helper.matchesItem(stack)) + return helper.getOffset(player, level, state, pos, hitResult) + .placeInWorld(level, (BlockItem) stack.getItem(), player, hand, hitResult); } - return super.use(state, world, pos, player, hand, ray); + return super.useItemOn(stack, state, level, pos, player, hand, hitResult); } @Override @@ -131,7 +129,7 @@ public class CopycatStepBlock extends WaterloggedCopycatBlock { } @Override - public boolean isPathfindable(BlockState pState, BlockGetter pLevel, BlockPos pPos, PathComputationType pType) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepModel.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepModel.java index 873ac7e4c6..552b923647 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepModel.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatStepModel.java @@ -17,7 +17,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Half; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData; public class CopycatStepModel extends CopycatModel { diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/FilteredBlockAndTintGetter.java b/src/main/java/com/simibubi/create/content/decoration/copycat/FilteredBlockAndTintGetter.java index a2f58340b3..2a8808da66 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/FilteredBlockAndTintGetter.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/FilteredBlockAndTintGetter.java @@ -14,7 +14,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.client.model.data.ModelDataManager; +import net.neoforged.neoforge.client.model.data.ModelDataManager; public class FilteredBlockAndTintGetter implements BlockAndTintGetter { @@ -25,7 +25,7 @@ public class FilteredBlockAndTintGetter implements BlockAndTintGetter { this.wrapped = wrapped; this.filter = filter; } - + @Override public BlockEntity getBlockEntity(BlockPos pPos) { return filter.test(pPos) ? wrapped.getBlockEntity(pPos) : null; @@ -65,10 +65,5 @@ public class FilteredBlockAndTintGetter implements BlockAndTintGetter { public int getBlockTint(BlockPos pBlockPos, ColorResolver pColorResolver) { return wrapped.getBlockTint(pBlockPos, pColorResolver); } - - @Override - public @Nullable ModelDataManager getModelDataManager() { - return wrapped.getModelDataManager(); - } - + } diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/SpecialCopycatPanelBlockState.java b/src/main/java/com/simibubi/create/content/decoration/copycat/SpecialCopycatPanelBlockState.java index 3cf375ace1..6d840fa2d9 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/SpecialCopycatPanelBlockState.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/SpecialCopycatPanelBlockState.java @@ -9,8 +9,8 @@ import net.minecraft.core.Direction.Axis; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.DirectionalBlock; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.generators.BlockModelProvider; -import net.minecraftforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.client.model.generators.BlockModelProvider; +import net.neoforged.neoforge.client.model.generators.ModelFile; public class SpecialCopycatPanelBlockState extends SpecialBlockStateGen { @@ -19,7 +19,7 @@ public class SpecialCopycatPanelBlockState extends SpecialBlockStateGen { public SpecialCopycatPanelBlockState(String name) { this.name = name; } - + @Override protected int getXRotation(BlockState state) { return facing(state) == Direction.UP ? 0 : facing(state) == Direction.DOWN ? 180 : 0; @@ -43,4 +43,4 @@ public class SpecialCopycatPanelBlockState extends SpecialBlockStateGen { : models.getExistingFile(prov.modLoc("block/copycat_panel/" + name)); } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/content/decoration/encasing/EncasableBlock.java b/src/main/java/com/simibubi/create/content/decoration/encasing/EncasableBlock.java index d53cf96175..f1a7500cc1 100644 --- a/src/main/java/com/simibubi/create/content/decoration/encasing/EncasableBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/encasing/EncasableBlock.java @@ -6,6 +6,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -19,10 +20,10 @@ import net.minecraft.world.phys.BlockHitResult; */ public interface EncasableBlock { /** - * This method should be called in the {@link Block#use(BlockState, Level, BlockPos, Player, InteractionHand, BlockHitResult)} method. + * This method should be called in the {@link Block#useItemOn(ItemStack, BlockState, Level, BlockPos, Player, InteractionHand, BlockHitResult)} method. */ - default InteractionResult tryEncase(BlockState state, Level level, BlockPos pos, ItemStack heldItem, Player player, InteractionHand hand, - BlockHitResult ray) { + default ItemInteractionResult tryEncase(BlockState state, Level level, BlockPos pos, ItemStack heldItem, Player player, InteractionHand hand, + BlockHitResult ray) { List encasedVariants = EncasingRegistry.getVariants(state.getBlock()); for (Block block : encasedVariants) { if (block instanceof EncasedBlock encased) { @@ -30,14 +31,14 @@ public interface EncasableBlock { continue; if (level.isClientSide) - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; encased.handleEncasing(state, level, pos, heldItem, player, hand, ray); playEncaseSound(level, pos); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } default void playEncaseSound(Level level, BlockPos pos) { diff --git a/src/main/java/com/simibubi/create/content/decoration/girder/ConnectedGirderModel.java b/src/main/java/com/simibubi/create/content/decoration/girder/ConnectedGirderModel.java index 469d0e935d..286a6378e1 100644 --- a/src/main/java/com/simibubi/create/content/decoration/girder/ConnectedGirderModel.java +++ b/src/main/java/com/simibubi/create/content/decoration/girder/ConnectedGirderModel.java @@ -16,9 +16,9 @@ import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.client.model.data.ModelData.Builder; -import net.minecraftforge.client.model.data.ModelProperty; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.client.model.data.ModelData.Builder; +import net.neoforged.neoforge.client.model.data.ModelProperty; public class ConnectedGirderModel extends CTModel { diff --git a/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlock.java b/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlock.java index bcdab909ad..f720d7a44e 100644 --- a/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlock.java @@ -32,6 +32,7 @@ import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; @@ -96,42 +97,40 @@ public class GirderBlock extends Block implements SimpleWaterloggedBlock, IWrenc } @Override - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, - BlockHitResult pHit) { - if (pPlayer == null) - return InteractionResult.PASS; + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + if (player == null) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; - ItemStack itemInHand = pPlayer.getItemInHand(pHand); - if (AllBlocks.SHAFT.isIn(itemInHand)) { - KineticBlockEntity.switchToBlockState(pLevel, pPos, AllBlocks.METAL_GIRDER_ENCASED_SHAFT.getDefaultState() - .setValue(WATERLOGGED, pState.getValue(WATERLOGGED)) - .setValue(TOP, pState.getValue(TOP)) - .setValue(BOTTOM, pState.getValue(BOTTOM)) - .setValue(GirderEncasedShaftBlock.HORIZONTAL_AXIS, pState.getValue(X) || pHit.getDirection() + if (AllBlocks.SHAFT.isIn(stack)) { + KineticBlockEntity.switchToBlockState(level, pos, AllBlocks.METAL_GIRDER_ENCASED_SHAFT.getDefaultState() + .setValue(WATERLOGGED, state.getValue(WATERLOGGED)) + .setValue(TOP, state.getValue(TOP)) + .setValue(BOTTOM, state.getValue(BOTTOM)) + .setValue(GirderEncasedShaftBlock.HORIZONTAL_AXIS, state.getValue(X) || hitResult.getDirection() .getAxis() == Axis.Z ? Axis.Z : Axis.X)); - pLevel.playSound(null, pPos, SoundEvents.NETHERITE_BLOCK_HIT, SoundSource.BLOCKS, 0.5f, 1.25f); - if (!pLevel.isClientSide && !pPlayer.isCreative()) { - itemInHand.shrink(1); - if (itemInHand.isEmpty()) - pPlayer.setItemInHand(pHand, ItemStack.EMPTY); + level.playSound(null, pos, SoundEvents.NETHERITE_BLOCK_HIT, SoundSource.BLOCKS, 0.5f, 1.25f); + if (!level.isClientSide && !player.isCreative()) { + stack.shrink(1); + if (stack.isEmpty()) + player.setItemInHand(hand, ItemStack.EMPTY); } - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } - if (AllItems.WRENCH.isIn(itemInHand) && !pPlayer.isShiftKeyDown()) { - if (GirderWrenchBehavior.handleClick(pLevel, pPos, pState, pHit)) - return InteractionResult.sidedSuccess(pLevel.isClientSide); - return InteractionResult.FAIL; + if (AllItems.WRENCH.isIn(stack) && !player.isShiftKeyDown()) { + if (GirderWrenchBehavior.handleClick(level, pos, state, hitResult)) + return ItemInteractionResult.sidedSuccess(level.isClientSide); + return ItemInteractionResult.FAIL; } IPlacementHelper helper = PlacementHelpers.get(placementHelperId); - if (helper.matchesItem(itemInHand)) - return helper.getOffset(pPlayer, pLevel, pState, pPos, pHit) - .placeInWorld(pLevel, (BlockItem) itemInHand.getItem(), pPlayer, pHand, pHit); + if (helper.matchesItem(stack)) + return helper.getOffset(player, level, state, pos, hitResult) + .placeInWorld(level, (BlockItem) stack.getItem(), player, hand, hitResult); - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override @@ -196,7 +195,7 @@ public class GirderBlock extends Block implements SimpleWaterloggedBlock, IWrenc for (Direction d : Iterate.directions) state = updateState(level, pos, state, d); - return state.setValue(WATERLOGGED, Boolean.valueOf(ifluidstate.getType() == Fluids.WATER)); + return state.setValue(WATERLOGGED, ifluidstate.getType() == Fluids.WATER); } public static BlockState updateState(LevelAccessor level, BlockPos pos, BlockState state, Direction d) { @@ -308,7 +307,7 @@ public class GirderBlock extends Block implements SimpleWaterloggedBlock, IWrenc } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlockStateGenerator.java b/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlockStateGenerator.java index ea857c9388..9f35450c9f 100644 --- a/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlockStateGenerator.java +++ b/src/main/java/com/simibubi/create/content/decoration/girder/GirderBlockStateGenerator.java @@ -7,7 +7,7 @@ import com.tterrag.registrate.providers.RegistrateBlockstateProvider; import net.createmod.catnip.utility.Iterate; import net.minecraft.core.Direction.Axis; import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.model.generators.MultiPartBlockStateBuilder; +import net.neoforged.neoforge.client.model.generators.MultiPartBlockStateBuilder; public class GirderBlockStateGenerator { diff --git a/src/main/java/com/simibubi/create/content/decoration/girder/GirderPlacementHelper.java b/src/main/java/com/simibubi/create/content/decoration/girder/GirderPlacementHelper.java index 8988517538..7d0e9b7bdf 100644 --- a/src/main/java/com/simibubi/create/content/decoration/girder/GirderPlacementHelper.java +++ b/src/main/java/com/simibubi/create/content/decoration/girder/GirderPlacementHelper.java @@ -10,13 +10,14 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.common.ForgeMod; +import net.neoforged.neoforge.common.NeoForgeMod; import java.util.List; import java.util.function.Predicate; @@ -80,8 +81,8 @@ public class GirderPlacementHelper implements IPlacementHelper { for (Direction dir : directions) { int range = AllConfigs.server().equipment.placementAssistRange.get(); if (player != null) { - AttributeInstance reach = player.getAttribute(ForgeMod.BLOCK_REACH.get()); - if (reach != null && reach.hasModifier(ExtendoGripItem.singleRangeAttributeModifier)) + AttributeInstance reach = player.getAttribute(Attributes.BLOCK_INTERACTION_RANGE); + if (reach != null && reach.hasModifier(ExtendoGripItem.singleRangeAttributeModifier.id())) range += 4; } int poles = attachedPoles(world, pos, dir); diff --git a/src/main/java/com/simibubi/create/content/decoration/girder/GirderWrenchBehavior.java b/src/main/java/com/simibubi/create/content/decoration/girder/GirderWrenchBehavior.java index 140ac8bda5..014e127cd2 100644 --- a/src/main/java/com/simibubi/create/content/decoration/girder/GirderWrenchBehavior.java +++ b/src/main/java/com/simibubi/create/content/decoration/girder/GirderWrenchBehavior.java @@ -28,8 +28,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class GirderWrenchBehavior { diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteBlocks.java b/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteBlocks.java index 59b5088bd2..b00bd3b8c8 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteBlocks.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteBlocks.java @@ -26,10 +26,10 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.GlassBlock; +import net.minecraft.world.level.block.TransparentBlock; import net.minecraft.world.level.block.state.properties.WoodType; import net.minecraft.world.level.material.MapColor; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; public class AllPaletteBlocks { @@ -39,16 +39,15 @@ public class AllPaletteBlocks { // Windows and Glass - public static final BlockEntry TILED_GLASS = REGISTRATE.block("tiled_glass", GlassBlock::new) + public static final BlockEntry TILED_GLASS = REGISTRATE.block("tiled_glass", TransparentBlock::new) .initialProperties(() -> Blocks.GLASS) .addLayer(() -> RenderType::cutout) - .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_COLORLESS), RecipeCategory.BUILDING_BLOCKS, - c::get)) + .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_BLOCKS_COLORLESS), RecipeCategory.BUILDING_BLOCKS, c)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/")) .loot((t, g) -> t.dropWhenSilkTouch(g)) - .tag(Tags.Blocks.GLASS_COLORLESS, BlockTags.IMPERMEABLE) + .tag(Tags.Blocks.GLASS_BLOCKS_COLORLESS, BlockTags.IMPERMEABLE) .item() - .tag(Tags.Items.GLASS_COLORLESS) + .tag(Tags.Items.GLASS_BLOCKS_COLORLESS) .build() .register(); @@ -61,7 +60,7 @@ public class AllPaletteBlocks { public static final BlockEntry TILED_GLASS_PANE = WindowGen.standardGlassPane("tiled_glass", TILED_GLASS, Create.asResource("block/palettes/tiled_glass"), - new ResourceLocation("block/glass_pane_top"), () -> RenderType::cutoutMipped); + ResourceLocation.withDefaultNamespace("block/glass_pane_top"), () -> RenderType::cutoutMipped); public static final BlockEntry FRAMED_GLASS_PANE = framedGlassPane("framed_glass", FRAMED_GLASS, () -> AllSpriteShifts.FRAMED_GLASS), diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteStoneTypes.java b/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteStoneTypes.java index d8a981ab24..8dd49b8bad 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteStoneTypes.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/AllPaletteStoneTypes.java @@ -5,12 +5,12 @@ import com.simibubi.create.Create; import com.simibubi.create.foundation.data.CreateRegistrate; import com.tterrag.registrate.util.nullness.NonNullSupplier; import net.createmod.catnip.utility.lang.Lang; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.material.MapColor; -import net.minecraftforge.registries.ForgeRegistries; import java.util.function.Function; @@ -89,7 +89,7 @@ public enum AllPaletteStoneTypes { paletteStoneVariants.baseBlock = baseBlock; String id = Lang.asId(paletteStoneVariants.name()); paletteStoneVariants.materialTag = - AllTags.optionalTag(ForgeRegistries.ITEMS, Create.asResource("stone_types/" + id)); + AllTags.optionalTag(BuiltInRegistries.ITEM, Create.asResource("stone_types/" + id)); paletteStoneVariants.variants = new PalettesVariantEntry(id, paletteStoneVariants); } } diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassBlock.java b/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassBlock.java index 3781375458..9c38ac1915 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassBlock.java @@ -3,13 +3,13 @@ package com.simibubi.create.content.decoration.palettes; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.GlassBlock; +import net.minecraft.world.level.block.TransparentBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; -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 ConnectedGlassBlock extends GlassBlock { +public class ConnectedGlassBlock extends TransparentBlock { public ConnectedGlassBlock(Properties p_i48392_1_) { super(p_i48392_1_); @@ -18,8 +18,7 @@ public class ConnectedGlassBlock extends GlassBlock { @Override @OnlyIn(Dist.CLIENT) public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) { - return adjacentBlockState.getBlock() instanceof ConnectedGlassBlock ? true - : super.skipRendering(state, adjacentBlockState, side); + return adjacentBlockState.getBlock() instanceof ConnectedGlassBlock || super.skipRendering(state, adjacentBlockState, side); } @Override diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassPaneBlock.java b/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassPaneBlock.java index 8a67e55f6b..d00b6ec3b5 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassPaneBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/ConnectedGlassPaneBlock.java @@ -2,8 +2,8 @@ package com.simibubi.create.content.decoration.palettes; import net.minecraft.core.Direction; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ConnectedGlassPaneBlock extends GlassPaneBlock { diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPartial.java b/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPartial.java index 9b2fb0ab05..c9b5cc9a72 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPartial.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPartial.java @@ -31,7 +31,7 @@ import net.minecraft.world.level.block.SlabBlock; import net.minecraft.world.level.block.StairBlock; import net.minecraft.world.level.block.WallBlock; import net.minecraft.world.level.block.state.BlockBehaviour.Properties; -import net.minecraftforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.client.model.generators.ModelFile; public abstract class PaletteBlockPartial { @@ -110,8 +110,7 @@ public abstract class PaletteBlockPartial { @Override protected StairBlock createBlock(Supplier block) { - return new StairBlock(() -> block.get() - .defaultBlockState(), Properties.copy(block.get())); + return new StairBlock(block.get().defaultBlockState(), Properties.ofFullCopy(block.get())); } @Override @@ -151,7 +150,7 @@ public abstract class PaletteBlockPartial { @Override protected SlabBlock createBlock(Supplier block) { - return new SlabBlock(Properties.copy(block.get())); + return new SlabBlock(Properties.ofFullCopy(block.get())); } @Override @@ -201,9 +200,9 @@ public abstract class PaletteBlockPartial { p.stonecutting(DataIngredient.tag(type.materialTag), category, c::get, 2); DataIngredient ingredient = DataIngredient.items(c.get()); ShapelessRecipeBuilder.shapeless(category, patternBlock.get()) - .requires(ingredient) - .requires(ingredient) - .unlockedBy("has_" + c.getName(), ingredient.getCritereon(p)) + .requires(ingredient.toVanilla()) + .requires(ingredient.toVanilla()) + .unlockedBy("has_" + c.getName(), ingredient.getCriterion(p)) .save(p, Create.ID + ":" + c.getName() + "_recycling"); } @@ -224,7 +223,7 @@ public abstract class PaletteBlockPartial { @Override protected WallBlock createBlock(Supplier block) { - return new WallBlock(Properties.copy(block.get()).forceSolidOn()); + return new WallBlock(Properties.ofFullCopy(block.get()).forceSolidOn()); } @Override @@ -260,8 +259,8 @@ public abstract class PaletteBlockPartial { ShapedRecipeBuilder.shaped(category, c.get(), 6) .pattern("XXX") .pattern("XXX") - .define('X', ingredient) - .unlockedBy("has_" + p.safeName(ingredient), ingredient.getCritereon(p)) + .define('X', ingredient.toVanilla()) + .unlockedBy("has_" + p.safeName(ingredient), ingredient.getCriterion(p)) .save(p, p.safeId(c.get())); } diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPattern.java b/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPattern.java index 7010c2fc77..b95375423a 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPattern.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/PaletteBlockPattern.java @@ -33,9 +33,9 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockBehaviour.Properties; import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.generators.ConfiguredModel; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.model.generators.ConfiguredModel; public class PaletteBlockPattern { @@ -228,7 +228,7 @@ public class PaletteBlockPattern { ResourceLocation resLoc = texture.srcFactory.apply(variant); ResourceLocation resLocTarget = texture.targetFactory.apply(variant); return CTSpriteShifter.getCT(texture.type, resLoc, - new ResourceLocation(resLocTarget.getNamespace(), resLocTarget.getPath() + "_connected")); + ResourceLocation.fromNamespaceAndPath(resLocTarget.getNamespace(), resLocTarget.getPath() + "_connected")); } @FunctionalInterface diff --git a/src/main/java/com/simibubi/create/content/decoration/palettes/WindowBlock.java b/src/main/java/com/simibubi/create/content/decoration/palettes/WindowBlock.java index 8c617a0cdd..9f4d852c13 100644 --- a/src/main/java/com/simibubi/create/content/decoration/palettes/WindowBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/palettes/WindowBlock.java @@ -2,8 +2,8 @@ package com.simibubi.create.content.decoration.palettes; import net.minecraft.core.Direction; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class WindowBlock extends ConnectedGlassBlock { diff --git a/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlock.java b/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlock.java index d19809b56b..d441f7c8f3 100644 --- a/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlock.java @@ -2,6 +2,7 @@ package com.simibubi.create.content.decoration.placard; import java.util.List; +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllShapes; @@ -21,6 +22,7 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; @@ -41,13 +43,17 @@ import net.minecraft.world.level.material.FluidState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.items.ItemHandlerHelper; + +import org.jetbrains.annotations.NotNull; public class PlacardBlock extends FaceAttachedHorizontalDirectionalBlock implements ProperWaterloggedBlock, IBE, ISpecialBlockItemRequirement, IWrenchable { public static final BooleanProperty POWERED = BlockStateProperties.POWERED; + public static final MapCodec CODEC = simpleCodec(PlacardBlock::new); + public PlacardBlock(Properties p_53182_) { super(p_53182_); registerDefaultState(defaultBlockState().setValue(WATERLOGGED, false) @@ -115,50 +121,49 @@ public class PlacardBlock extends FaceAttachedHorizontalDirectionalBlock } @Override - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player player, InteractionHand pHand, - BlockHitResult pHit) { + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (player.isShiftKeyDown()) - return InteractionResult.PASS; - if (pLevel.isClientSide) - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; - ItemStack inHand = player.getItemInHand(pHand); - return onBlockEntityUse(pLevel, pPos, pte -> { + ItemStack inHand = player.getItemInHand(hand); + return onBlockEntityUseItemOn(level, pos, pte -> { ItemStack inBlock = pte.getHeldItem(); if (!player.mayBuild() || inHand.isEmpty() || !inBlock.isEmpty()) { if (inBlock.isEmpty()) - return InteractionResult.FAIL; + return ItemInteractionResult.FAIL; if (inHand.isEmpty()) - return InteractionResult.FAIL; - if (pState.getValue(POWERED)) - return InteractionResult.FAIL; + return ItemInteractionResult.FAIL; + if (state.getValue(POWERED)) + return ItemInteractionResult.FAIL; boolean test = inBlock.getItem() instanceof FilterItem ? FilterItemStack.of(inBlock) - .test(pLevel, inHand) : ItemHandlerHelper.canItemStacksStack(inHand, inBlock); + .test(level, inHand) : ItemStack.isSameItemSameComponents(inHand, inBlock); if (!test) { - AllSoundEvents.DENY.play(pLevel, null, pPos, 1, 1); - return InteractionResult.SUCCESS; + AllSoundEvents.DENY.play(level, null, pos, 1, 1); + return ItemInteractionResult.SUCCESS; } - AllSoundEvents.CONFIRM.play(pLevel, null, pPos, 1, 1); - pLevel.setBlock(pPos, pState.setValue(POWERED, true), 3); - updateNeighbours(pState, pLevel, pPos); + AllSoundEvents.CONFIRM.play(level, null, pos, 1, 1); + level.setBlock(pos, state.setValue(POWERED, true), 3); + updateNeighbours(state, level, pos); pte.poweredTicks = 19; pte.notifyUpdate(); - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; } - pLevel.playSound(null, pPos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, 1, 1); - pte.setHeldItem(ItemHandlerHelper.copyStackWithSize(inHand, 1)); + level.playSound(null, pos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, 1, 1); + pte.setHeldItem(inHand.copyWithCount(1)); if (!player.isCreative()) { inHand.shrink(1); if (inHand.isEmpty()) - player.setItemInHand(pHand, ItemStack.EMPTY); + player.setItemInHand(hand, ItemStack.EMPTY); } - return InteractionResult.SUCCESS; + return ItemInteractionResult.SUCCESS; }); } @@ -225,4 +230,9 @@ public class PlacardBlock extends FaceAttachedHorizontalDirectionalBlock return AllBlockEntityTypes.PLACARD.get(); } + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } + } diff --git a/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlockEntity.java b/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlockEntity.java index 1e262ae5b6..879680a9ad 100644 --- a/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/decoration/placard/PlacardBlockEntity.java @@ -5,6 +5,7 @@ import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import net.createmod.catnip.utility.VecHelper; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.core.particles.DustParticleOptions; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; @@ -53,18 +54,18 @@ public class PlacardBlockEntity extends SmartBlockEntity { } @Override - protected void write(CompoundTag tag, boolean clientPacket) { + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { tag.putInt("PoweredTicks", poweredTicks); - tag.put("Item", heldItem.serializeNBT()); - super.write(tag, clientPacket); + tag.put("Item", heldItem.saveOptional(registries)); + super.write(tag, registries, clientPacket); } @Override - protected void read(CompoundTag tag, boolean clientPacket) { + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { int prevTicks = poweredTicks; poweredTicks = tag.getInt("PoweredTicks"); - heldItem = ItemStack.of(tag.getCompound("Item")); - super.read(tag, clientPacket); + heldItem = ItemStack.parseOptional(registries, tag.getCompound("Item")); + super.read(tag, registries, clientPacket); if (clientPacket && prevTicks < poweredTicks) spawnParticles(); diff --git a/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControl.java b/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControl.java index 7c2a800a6a..b721fc6fb9 100644 --- a/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControl.java +++ b/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControl.java @@ -8,19 +8,24 @@ import com.simibubi.create.foundation.gui.widget.ScrollInput; import com.simibubi.create.foundation.gui.widget.SelectionScrollInput; import com.simibubi.create.foundation.utility.CreateLang; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; import net.createmod.catnip.utility.Pair; import net.createmod.catnip.utility.lang.Components; import net.createmod.catnip.utility.lang.Lang; import net.minecraft.client.Minecraft; import net.minecraft.core.Direction; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; -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 enum DoorControl { ALL, NORTH, EAST, SOUTH, WEST, NONE; + public static final StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(DoorControl.class); + private static String[] valuesAsString() { DoorControl[] values = values(); return Arrays.stream(values) diff --git a/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControlBehaviour.java b/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControlBehaviour.java index 5b139e5619..af887c6278 100644 --- a/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControlBehaviour.java +++ b/src/main/java/com/simibubi/create/content/decoration/slidingDoor/DoorControlBehaviour.java @@ -5,6 +5,7 @@ import com.simibubi.create.foundation.blockEntity.behaviour.BehaviourType; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import net.createmod.catnip.utility.NBTHelper; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public class DoorControlBehaviour extends BlockEntityBehaviour { @@ -26,15 +27,15 @@ public class DoorControlBehaviour extends BlockEntityBehaviour { } @Override - public void write(CompoundTag nbt, boolean clientPacket) { + public void write(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { NBTHelper.writeEnum(nbt, "DoorControl", mode); - super.write(nbt, clientPacket); + super.write(nbt, registries, clientPacket); } @Override - public void read(CompoundTag nbt, boolean clientPacket) { + public void read(CompoundTag nbt, HolderLookup.Provider registries, boolean clientPacket) { mode = NBTHelper.readEnum(nbt, "DoorControl", DoorControl.class); - super.read(nbt, clientPacket); + super.read(nbt, registries, clientPacket); } @Override diff --git a/src/main/java/com/simibubi/create/content/decoration/slidingDoor/SlidingDoorBlock.java b/src/main/java/com/simibubi/create/content/decoration/slidingDoor/SlidingDoorBlock.java index d56751224c..29d99b1e0b 100644 --- a/src/main/java/com/simibubi/create/content/decoration/slidingDoor/SlidingDoorBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/slidingDoor/SlidingDoorBlock.java @@ -14,7 +14,6 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; @@ -44,13 +43,15 @@ import net.minecraft.world.phys.shapes.VoxelShape; public class SlidingDoorBlock extends DoorBlock implements IWrenchable, IBE, IHaveBigOutline { public static final Supplier TRAIN_SET_TYPE = - () -> new BlockSetType("train", true, SoundType.NETHERITE_BLOCK, SoundEvents.IRON_DOOR_CLOSE, + () -> new BlockSetType("train", true, true, true, + BlockSetType.PressurePlateSensitivity.EVERYTHING, SoundType.NETHERITE_BLOCK, SoundEvents.IRON_DOOR_CLOSE, SoundEvents.IRON_DOOR_OPEN, SoundEvents.IRON_TRAPDOOR_CLOSE, SoundEvents.IRON_TRAPDOOR_OPEN, SoundEvents.METAL_PRESSURE_PLATE_CLICK_OFF, SoundEvents.METAL_PRESSURE_PLATE_CLICK_ON, SoundEvents.STONE_BUTTON_CLICK_OFF, SoundEvents.STONE_BUTTON_CLICK_ON); public static final Supplier GLASS_SET_TYPE = - () -> new BlockSetType("train", true, SoundType.NETHERITE_BLOCK, SoundEvents.IRON_DOOR_CLOSE, + () -> new BlockSetType("train", true, true, true, + BlockSetType.PressurePlateSensitivity.EVERYTHING, SoundType.NETHERITE_BLOCK, SoundEvents.IRON_DOOR_CLOSE, SoundEvents.IRON_DOOR_OPEN, SoundEvents.IRON_TRAPDOOR_CLOSE, SoundEvents.IRON_TRAPDOOR_OPEN, SoundEvents.METAL_PRESSURE_PLATE_CLICK_OFF, SoundEvents.METAL_PRESSURE_PLATE_CLICK_ON, SoundEvents.STONE_BUTTON_CLICK_OFF, SoundEvents.STONE_BUTTON_CLICK_ON); @@ -66,8 +67,8 @@ public class SlidingDoorBlock extends DoorBlock implements IWrenchable, IBE { @@ -51,7 +51,7 @@ public class SlidingDoorRenderer extends SafeBlockEntityRenderer partials = - AllPartialModels.FOLDING_DOORS.get(ForgeRegistries.BLOCKS.getKey(blockState.getBlock())); + AllPartialModels.FOLDING_DOORS.get(BuiltInRegistries.BLOCK.getKey(blockState.getBlock())); boolean flip = blockState.getValue(DoorBlock.HINGE) == DoorHingeSide.RIGHT; for (boolean left : Iterate.trueAndFalse) { diff --git a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlock.java b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlock.java index 4037a008b2..746eb65b1d 100644 --- a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlock.java @@ -20,6 +20,7 @@ import net.minecraft.util.RandomSource; import net.minecraft.util.StringRepresentable; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -112,18 +113,16 @@ public class WhistleBlock extends Block implements IBE, IWre } @Override - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, - BlockHitResult pHit) { - if (pPlayer == null) - return InteractionResult.PASS; + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + if (player == null) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; - ItemStack heldItem = pPlayer.getItemInHand(pHand); - if (AllBlocks.STEAM_WHISTLE.isIn(heldItem)) { - incrementSize(pLevel, pPos); - return InteractionResult.SUCCESS; + if (AllBlocks.STEAM_WHISTLE.isIn(stack)) { + incrementSize(level, pos); + return ItemInteractionResult.SUCCESS; } - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } public static void incrementSize(LevelAccessor pLevel, BlockPos pPos) { @@ -137,7 +136,7 @@ public class WhistleBlock extends Block implements IBE, IWre for (int i = 1; i <= 6; i++) { BlockState blockState = pLevel.getBlockState(currentPos); float pVolume = (soundtype.getVolume() + 1.0F) / 2.0F; - SoundEvent growSound = SoundEvents.NOTE_BLOCK_XYLOPHONE.get(); + SoundEvent growSound = SoundEvents.NOTE_BLOCK_XYLOPHONE.value(); SoundEvent hitSound = soundtype.getHitSound(); if (AllBlocks.STEAM_WHISTLE_EXTENSION.has(blockState)) { @@ -223,7 +222,7 @@ public class WhistleBlock extends Block implements IBE, IWre } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + protected boolean isPathfindable(BlockState state, PathComputationType pathComputationType) { return false; } diff --git a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlockEntity.java b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlockEntity.java index 910924e047..26a00bb4e8 100644 --- a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleBlockEntity.java @@ -15,6 +15,7 @@ import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import com.simibubi.create.foundation.utility.CreateLang; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.VecHelper; import net.createmod.catnip.utility.animation.LerpedFloat; import net.createmod.catnip.utility.animation.LerpedFloat.Chaser; @@ -23,6 +24,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.util.Mth; @@ -30,9 +32,8 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class WhistleBlockEntity extends SmartBlockEntity implements IHaveGoggleInformation { @@ -90,19 +91,19 @@ public class WhistleBlockEntity extends SmartBlockEntity implements IHaveGoggleI || isVirtual()); animation.chase(powered ? 1 : 0, powered ? .5f : .4f, powered ? Chaser.EXP : Chaser.LINEAR); animation.tickChaser(); - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.tickAudio(getOctave(), powered)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> this.tickAudio(getOctave(), powered)); } @Override - protected void write(CompoundTag tag, boolean clientPacket) { + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { tag.putInt("Pitch", pitch); - super.write(tag, clientPacket); + super.write(tag, registries, clientPacket); } @Override - protected void read(CompoundTag tag, boolean clientPacket) { + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { pitch = tag.getInt("Pitch"); - super.read(tag, clientPacket); + super.read(tag, registries, clientPacket); } @Override diff --git a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleExtenderBlock.java b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleExtenderBlock.java index 0663c00ec0..049ce1ae2e 100644 --- a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleExtenderBlock.java +++ b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleExtenderBlock.java @@ -13,6 +13,7 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.util.StringRepresentable; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; @@ -72,17 +73,15 @@ public class WhistleExtenderBlock extends Block implements IWrenchable { } @Override - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, - BlockHitResult pHit) { - if (pPlayer == null || !AllBlocks.STEAM_WHISTLE.isIn(pPlayer.getItemInHand(pHand))) - return InteractionResult.PASS; - Level level = pLevel; - BlockPos findRoot = findRoot(level, pPos); + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { + if (player == null || !AllBlocks.STEAM_WHISTLE.isIn(stack)) + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + BlockPos findRoot = findRoot(level, pos); BlockState blockState = level.getBlockState(findRoot); if (blockState.getBlock()instanceof WhistleBlock whistle) - return whistle.use(blockState, pLevel, findRoot, pPlayer, pHand, - new BlockHitResult(pHit.getLocation(), pHit.getDirection(), findRoot, pHit.isInside())); - return InteractionResult.PASS; + return whistle.useItemOn(stack, blockState, level, findRoot, player, hand, + new BlockHitResult(hitResult.getLocation(), hitResult.getDirection(), findRoot, hitResult.isInside())); + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; } @Override @@ -96,8 +95,7 @@ public class WhistleExtenderBlock extends Block implements IWrenchable { } @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter level, BlockPos pos, - Player player) { + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { return AllBlocks.STEAM_WHISTLE.asStack(); } diff --git a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleGenerator.java b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleGenerator.java index 2923980a79..393d61a352 100644 --- a/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleGenerator.java +++ b/src/main/java/com/simibubi/create/content/decoration/steamWhistle/WhistleGenerator.java @@ -9,7 +9,7 @@ import com.tterrag.registrate.providers.RegistrateBlockstateProvider; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.generators.ModelFile; +import net.neoforged.neoforge.client.model.generators.ModelFile; public class WhistleGenerator extends SpecialBlockStateGen { diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/AllArmorMaterials.java b/src/main/java/com/simibubi/create/content/equipment/armor/AllArmorMaterials.java index 7a2f67020f..ccf87d2282 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/AllArmorMaterials.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/AllArmorMaterials.java @@ -1,90 +1,86 @@ package com.simibubi.create.content.equipment.armor; +import java.util.EnumMap; +import java.util.List; import java.util.function.Supplier; -import com.google.common.base.Suppliers; import com.simibubi.create.AllItems; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.Create; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.item.ArmorItem.Type; +import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.registries.DeferredRegister; -public enum AllArmorMaterials implements ArmorMaterial { +public class AllArmorMaterials { + private static final DeferredRegister ARMOR_MATERIALS = DeferredRegister.create(Registries.ARMOR_MATERIAL, Create.ID); - COPPER(Create.asResource("copper").toString(), 7, new int[] { 2, 4, 3, 1 }, 25, () -> AllSoundEvents.COPPER_ARMOR_EQUIP.getMainEvent(), 0.0F, 0.0F, - () -> Ingredient.of(Items.COPPER_INGOT)), + public static final Holder COPPER = register( + "copper", + new int[] { 2, 4, 3, 1, 4 }, + 7, + AllSoundEvents.COPPER_ARMOR_EQUIP.getMainEventHolder(), + 0.0F, + 0.0F, + () -> Ingredient.of(Items.COPPER_INGOT) + ); - CARDBOARD(Create.asResource("cardboard") - .toString(), 4, new int[] { 1, 1, 1, 1 }, 25, () -> SoundEvents.ARMOR_EQUIP_LEATHER, 0.0F, 0.0F, - () -> Ingredient.of(AllItems.CARDBOARD)) + public static final Holder CARDBOARD = register( + "cardboard", + new int[] { 1, 1, 1, 1, 2 }, + 4, + SoundEvents.ARMOR_EQUIP_LEATHER, + 0.0F, + 0.0F, + () -> Ingredient.of(AllItems.CARDBOARD) + ); - ; + private static Holder register( + String name, + int[] defense, + int enchantmentValue, + Holder equipSound, + float toughness, + float knockbackResistance, + Supplier repairIngredient + ) { + List list = List.of(new ArmorMaterial.Layer(Create.asResource(name))); + return register(name, defense, enchantmentValue, equipSound, toughness, knockbackResistance, repairIngredient, list); + } + private static Holder register( + String name, + int[] defense, + int enchantmentValue, + Holder equipSound, + float toughness, + float knockbackResistance, + Supplier repairIngridient, + List layers + ) { + EnumMap enummap = new EnumMap<>(ArmorItem.Type.class); + + for (ArmorItem.Type armoritem$type : ArmorItem.Type.values()) { + enummap.put(armoritem$type, defense[armoritem$type.ordinal()]); + } + + return ARMOR_MATERIALS.register(name, + () -> new ArmorMaterial(enummap, enchantmentValue, equipSound, repairIngridient, layers, toughness, knockbackResistance) + ); + } + + public static void register(IEventBus eventBus) { + ARMOR_MATERIALS.register(eventBus); + } + + // FIXME 1.21: rehook-up durability private static final int[] MAX_DAMAGE_ARRAY = new int[] { 11, 16, 15, 13 }; - private final String name; - private final int maxDamageFactor; - private final int[] damageReductionAmountArray; - private final int enchantability; - private final Supplier soundEvent; - private final float toughness; - private final float knockbackResistance; - private final Supplier repairMaterial; - - private AllArmorMaterials(String name, int maxDamageFactor, int[] damageReductionAmountArray, int enchantability, - Supplier soundEvent, float toughness, float knockbackResistance, Supplier repairMaterial) { - this.name = name; - this.maxDamageFactor = maxDamageFactor; - this.damageReductionAmountArray = damageReductionAmountArray; - this.enchantability = enchantability; - this.soundEvent = soundEvent; - this.toughness = toughness; - this.knockbackResistance = knockbackResistance; - this.repairMaterial = Suppliers.memoize(repairMaterial::get); - } - - @Override - public int getEnchantmentValue() { - return this.enchantability; - } - - @Override - public SoundEvent getEquipSound() { - return this.soundEvent.get(); - } - - @Override - public Ingredient getRepairIngredient() { - return this.repairMaterial.get(); - } - - @Override - public String getName() { - return this.name; - } - - @Override - public float getToughness() { - return this.toughness; - } - - @Override - public float getKnockbackResistance() { - return this.knockbackResistance; - } - - @Override - public int getDurabilityForType(Type pType) { - return MAX_DAMAGE_ARRAY[pType.ordinal()] * this.maxDamageFactor; - } - - @Override - public int getDefenseForType(Type pType) { - return this.damageReductionAmountArray[pType.ordinal()]; - } } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java index 8ef93ce505..5bba27b222 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java @@ -2,6 +2,7 @@ package com.simibubi.create.content.equipment.armor; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; +import com.simibubi.create.foundation.mixin.accessor.EntityRenderDispatcherAccessor; import net.createmod.catnip.render.CachedBuffers; import net.createmod.catnip.render.SuperByteBuffer; @@ -82,7 +83,7 @@ public class BacktankArmorLayer public static void registerOnAll(EntityRenderDispatcher renderManager) { for (EntityRenderer renderer : renderManager.getSkinMap().values()) registerOn(renderer); - for (EntityRenderer renderer : renderManager.renderers.values()) + for (EntityRenderer renderer : ((EntityRenderDispatcherAccessor) renderManager).create$getRenderers().values()) registerOn(renderer); } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankBlock.java b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankBlock.java index d27598596e..985097de87 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankBlock.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankBlock.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; import com.simibubi.create.AllBlockEntityTypes; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllEnchantments; import com.simibubi.create.AllShapes; import com.simibubi.create.content.kinetics.base.HorizontalKineticBlock; @@ -15,11 +16,12 @@ import com.simibubi.create.foundation.block.IBE; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.DataComponents; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; @@ -46,7 +48,7 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.common.util.FakePlayer; +import net.neoforged.neoforge.common.util.FakePlayer; public class BacktankBlock extends HorizontalKineticBlock implements IBE, SimpleWaterloggedBlock, ISpecialBlockItemRequirement { @@ -112,23 +114,16 @@ public class BacktankBlock extends HorizontalKineticBlock implements IBE { - be.setCapacityEnchantLevel(stack.getEnchantmentLevel(AllEnchantments.CAPACITY.get())); - be.setAirLevel(stack.getOrCreateTag() - .getInt("Air")); - CompoundTag vanillaTag = stack.getOrCreateTag(); - if (stack.hasCustomHoverName()) + be.setCapacityEnchantLevel(stack.getEnchantmentLevel(worldIn.holderOrThrow(AllEnchantments.CAPACITY))); + be.setAirLevel(stack.getOrDefault(AllDataComponents.BACKTANK_AIR, 0)); + if (stack.has(DataComponents.CUSTOM_NAME)) be.setCustomName(stack.getHoverName()); - CompoundTag nbt = stack.serializeNBT(); - CompoundTag forgeCapsTag = nbt.contains("ForgeCaps") ? nbt.getCompound("ForgeCaps") : null; - be.setTags(vanillaTag, forgeCapsTag); + be.setComponentPatch(stack.getComponentsPatch()); }); } @Override - @SuppressWarnings("deprecation") - // Re-adding ForgeCaps to item here as there is no loot function that can modify - // outside of the vanilla tag public List getDrops(BlockState pState, LootParams.Builder pBuilder) { List lootDrops = super.getDrops(pState, pBuilder); @@ -136,8 +131,8 @@ public class BacktankBlock extends HorizontalKineticBlock implements IBE blockEntityOptional = getBlockEntityOptional(blockGetter, pos); + Optional blockEntityOptional = getBlockEntityOptional(pLevel, pos); - CompoundTag forgeCapsTag = blockEntityOptional.map(BacktankBlockEntity::getForgeCapsTag) - .orElse(null); - CompoundTag vanillaTag = blockEntityOptional.map(BacktankBlockEntity::getVanillaTag) - .orElse(new CompoundTag()); + DataComponentPatch components = blockEntityOptional.map(BacktankBlockEntity::getComponentPatch) + .orElse(DataComponentPatch.EMPTY); int air = blockEntityOptional.map(BacktankBlockEntity::getAirLevel) .orElse(0); - ItemStack stack = new ItemStack(item, 1, forgeCapsTag); - vanillaTag.putInt("Air", air); - stack.setTag(vanillaTag); + ItemStack stack = new ItemStack(item.builtInRegistryHolder(), 1, components); + stack.set(AllDataComponents.BACKTANK_AIR, air); return stack; } @@ -213,7 +202,7 @@ public class BacktankBlock extends HorizontalKineticBlock implements IBE type, BlockPos pos, BlockState state) { super(type, pos, state); defaultName = getDefaultName(state); - vanillaTag = new CompoundTag(); - forgeCapsTag = null; + componentPatch = DataComponentPatch.EMPTY; } public static Component getDefaultName(BlockState state) { @@ -115,34 +114,30 @@ public class BacktankBlockEntity extends KineticBlockEntity implements Nameable } @Override - protected void write(CompoundTag compound, boolean clientPacket) { - super.write(compound, clientPacket); + protected void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.write(compound, registries, clientPacket); compound.putInt("Air", airLevel); compound.putInt("Timer", airLevelTimer); compound.putInt("CapacityEnchantment", capacityEnchantLevel); - + if (this.customName != null) - compound.putString("CustomName", Component.Serializer.toJson(this.customName)); - - compound.put("VanillaTag", vanillaTag); - if (forgeCapsTag != null) - compound.put("ForgeCapsTag", forgeCapsTag); + compound.putString("CustomName", Component.Serializer.toJson(this.customName, registries)); + + compound.put("Components", DataComponentPatch.CODEC.encodeStart(NbtOps.INSTANCE, componentPatch).getOrThrow()); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.read(compound, registries, clientPacket); int prev = airLevel; airLevel = compound.getInt("Air"); airLevelTimer = compound.getInt("Timer"); capacityEnchantLevel = compound.getInt("CapacityEnchantment"); - - if (compound.contains("CustomName", 8)) - this.customName = Component.Serializer.fromJson(compound.getString("CustomName")); - - vanillaTag = compound.getCompound("VanillaTag"); - forgeCapsTag = compound.contains("ForgeCapsTag") ? compound.getCompound("ForgeCapsTag") : null; + if (compound.contains("CustomName", 8)) + this.customName = Component.Serializer.fromJson(compound.getString("CustomName"), registries); + + componentPatch = DataComponentPatch.CODEC.decode(NbtOps.INSTANCE, compound).getOrThrow().getFirst(); if (prev != 0 && prev != airLevel && airLevel == BacktankUtil.maxAir(capacityEnchantLevel) && clientPacket) playFilledEffect(); } @@ -181,18 +176,13 @@ public class BacktankBlockEntity extends KineticBlockEntity implements Nameable public void setCapacityEnchantLevel(int capacityEnchantLevel) { this.capacityEnchantLevel = capacityEnchantLevel; } - - public void setTags(CompoundTag vanillaTag, @Nullable CompoundTag forgeCapsTag) { - this.vanillaTag = vanillaTag; - this.forgeCapsTag = forgeCapsTag; + + public void setComponentPatch(DataComponentPatch componentPatch) { + this.componentPatch = componentPatch; } - public CompoundTag getVanillaTag() { - return vanillaTag; - } - - public CompoundTag getForgeCapsTag() { - return forgeCapsTag; + public DataComponentPatch getComponentPatch() { + return componentPatch; } } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankItem.java b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankItem.java index aeee4ae61d..e8bafe166b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankItem.java @@ -1,8 +1,8 @@ package com.simibubi.create.content.equipment.armor; -import com.simibubi.create.content.equipment.armor.CapacityEnchantment.ICapacityEnchantable; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.foundation.item.LayeredArmorItem; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; import net.minecraft.world.InteractionResult; @@ -21,14 +21,14 @@ import org.jetbrains.annotations.Nullable; import java.util.Locale; import java.util.function.Supplier; -public class BacktankItem extends BaseArmorItem implements ICapacityEnchantable { +public class BacktankItem extends BaseArmorItem { public static final EquipmentSlot SLOT = EquipmentSlot.CHEST; public static final ArmorItem.Type TYPE = ArmorItem.Type.CHESTPLATE; public static final int BAR_COLOR = 0xEFEFEF; private final Supplier blockItem; - public BacktankItem(ArmorMaterial material, Properties properties, ResourceLocation textureLoc, Supplier placeable) { + public BacktankItem(Holder material, Properties properties, ResourceLocation textureLoc, Supplier placeable) { super(material, TYPE, properties, textureLoc); this.blockItem = placeable; } @@ -50,11 +50,6 @@ public class BacktankItem extends BaseArmorItem implements ICapacityEnchantable .useOn(ctx); } - @Override - public boolean canBeDepleted() { - return false; - } - @Override public boolean isEnchantable(ItemStack p_77616_1_) { return true; @@ -80,8 +75,7 @@ public class BacktankItem extends BaseArmorItem implements ICapacityEnchantable } public static int getRemainingAir(ItemStack stack) { - CompoundTag orCreateTag = stack.getOrCreateTag(); - return orCreateTag.getInt("Air"); + return stack.getOrDefault(AllDataComponents.BACKTANK_AIR, 0); } public static class BacktankBlockItem extends BlockItem { @@ -103,7 +97,7 @@ public class BacktankItem extends BaseArmorItem implements ICapacityEnchantable } public static class Layered extends BacktankItem implements LayeredArmorItem { - public Layered(ArmorMaterial material, Properties properties, ResourceLocation textureLoc, Supplier placeable) { + public Layered(Holder material, Properties properties, ResourceLocation textureLoc, Supplier placeable) { super(material, properties, textureLoc, placeable); } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankUtil.java b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankUtil.java index c73001e31d..41041b1eb2 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankUtil.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankUtil.java @@ -1,14 +1,23 @@ package com.simibubi.create.content.equipment.armor; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllEnchantments; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.AllTags; import com.simibubi.create.foundation.utility.CreateLang; +import com.simibubi.create.foundation.utility.DistExecutor; import com.simibubi.create.infrastructure.config.AllConfigs; + +import it.unimi.dsi.fastutil.objects.Object2IntMap.Entry; import net.createmod.catnip.utility.lang.Components; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket; import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket; @@ -18,12 +27,9 @@ import net.minecraft.util.Mth; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Function; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.ItemEnchantments; +import net.neoforged.api.distmarker.Dist; public class BacktankUtil { @@ -61,18 +67,15 @@ public class BacktankUtil { return getAir(backtank) > 0; } - public static float getAir(ItemStack backtank) { - CompoundTag tag = backtank.getOrCreateTag(); - return Math.min(tag.getFloat("Air"), maxAir(backtank)); + public static int getAir(ItemStack backtank) { + return Math.min(backtank.getOrDefault(AllDataComponents.BACKTANK_AIR, 0), maxAir(backtank)); } - public static void consumeAir(LivingEntity entity, ItemStack backtank, float i) { - CompoundTag tag = backtank.getOrCreateTag(); + public static void consumeAir(LivingEntity entity, ItemStack backtank, int i) { int maxAir = maxAir(backtank); - float air = getAir(backtank); - float newAir = Math.max(air - i, 0); - tag.putFloat("Air", Math.min(newAir, maxAir)); - backtank.setTag(tag); + int air = getAir(backtank); + int newAir = Math.max(air - i, 0); + backtank.set(AllDataComponents.BACKTANK_AIR, Math.min(newAir, maxAir)); if (!(entity instanceof ServerPlayer player)) return; @@ -101,7 +104,15 @@ public class BacktankUtil { } public static int maxAir(ItemStack backtank) { - return maxAir(backtank.getEnchantmentLevel(AllEnchantments.CAPACITY.get())); + int enchantLevel = 0; + ItemEnchantments enchants = backtank.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY); + for (Entry> entry : enchants.entrySet()) { + if (entry.getKey().is(AllEnchantments.CAPACITY)) { + enchantLevel = entry.getIntValue(); + break; + } + } + return maxAir(enchantLevel); } public static int maxAir(int enchantLevel) { @@ -121,8 +132,8 @@ public class BacktankUtil { List backtanks = getAllWithAir(entity); if (backtanks.isEmpty()) return false; - float cost = ((float) maxAirWithoutEnchants()) / usesPerTank; - consumeAir(entity, backtanks.get(0), cost); + int cost = maxAirWithoutEnchants() / usesPerTank; + consumeAir(entity, backtanks.getFirst(), cost); return true; } @@ -153,9 +164,9 @@ public class BacktankUtil { return Math.round(13.0F - (float) stack.getDamageValue() / stack.getMaxDamage() * 13.0F); if (backtanks.size() == 1) - return backtanks.get(0) + return backtanks.getFirst() .getItem() - .getBarWidth(backtanks.get(0)); + .getBarWidth(backtanks.getFirst()); // If there is more than one backtank, average the bar widths. int sumBarWidth = backtanks.stream() diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/BaseArmorItem.java b/src/main/java/com/simibubi/create/content/equipment/armor/BaseArmorItem.java index 1c7e016af1..5597d66abf 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/BaseArmorItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/BaseArmorItem.java @@ -1,5 +1,6 @@ package com.simibubi.create.content.equipment.armor; +import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EquipmentSlot; @@ -7,18 +8,20 @@ import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; + import java.util.Locale; public class BaseArmorItem extends ArmorItem { protected final ResourceLocation textureLoc; - public BaseArmorItem(ArmorMaterial armorMaterial, ArmorItem.Type type, Properties properties, ResourceLocation textureLoc) { + public BaseArmorItem(Holder armorMaterial, ArmorItem.Type type, Properties properties, ResourceLocation textureLoc) { super(armorMaterial, type, properties.stacksTo(1)); this.textureLoc = textureLoc; } @Override - public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type) { - return String.format(Locale.ROOT, "%s:textures/models/armor/%s_layer_%d%s.png", textureLoc.getNamespace(), textureLoc.getPath(), slot == EquipmentSlot.LEGS ? 2 : 1, type == null ? "" : String.format(Locale.ROOT, "_%s", type)); + public @Nullable ResourceLocation getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, ArmorMaterial.Layer layer, boolean innerModel) { + return ResourceLocation.parse(String.format(Locale.ROOT, "%s:textures/models/armor/%s_layer_%d.png", textureLoc.getNamespace(), textureLoc.getPath(), slot == EquipmentSlot.LEGS ? 2 : 1)); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/CapacityEnchantment.java b/src/main/java/com/simibubi/create/content/equipment/armor/CapacityEnchantment.java deleted file mode 100644 index d1109caa28..0000000000 --- a/src/main/java/com/simibubi/create/content/equipment/armor/CapacityEnchantment.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.simibubi.create.content.equipment.armor; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.EnchantmentCategory; - -public class CapacityEnchantment extends Enchantment { - - public CapacityEnchantment(Rarity rarity, EnchantmentCategory category, EquipmentSlot[] slots) { - super(rarity, category, slots); - } - - @Override - public int getMaxLevel() { - return 3; - } - - @Override - public boolean canApplyAtEnchantingTable(ItemStack stack) { - return stack.getItem() instanceof ICapacityEnchantable; - } - - public interface ICapacityEnchantable { - } - -} diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandler.java b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandler.java index c9f0803b70..6101f2085b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandler.java @@ -13,13 +13,14 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.NeutralMob; import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.goal.WrappedGoal; import net.minecraft.world.entity.ai.goal.target.TargetGoal; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; -import net.minecraftforge.event.entity.living.LivingEvent.LivingVisibilityEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.EntityEvent; +import net.neoforged.neoforge.event.entity.living.LivingEvent; +import net.neoforged.neoforge.event.tick.EntityTickEvent; @EventBusSubscriber public class CardboardArmorHandler { @@ -27,30 +28,32 @@ public class CardboardArmorHandler { @SubscribeEvent public static void playerHitboxChangesWhenHidingAsBox(EntityEvent.Size event) { Entity entity = event.getEntity(); - if (!entity.isAddedToWorld()) + if (!entity.isAddedToLevel()) return; if (!testForStealth(entity)) return; - - event.setNewSize(EntityDimensions.fixed(0.6F, 0.8F)); - event.setNewEyeHeight(0.6F); - + + event.setNewSize(EntityDimensions.fixed(0.6F, 0.8F).withEyeHeight(0.6F)); + if (!entity.level() .isClientSide() && entity instanceof Player p) AllAdvancements.CARDBOARD_ARMOR.awardTo(p); } @SubscribeEvent - public static void playersStealthWhenWearingCardboard(LivingVisibilityEvent event) { + public static void playersStealthWhenWearingCardboard(LivingEvent.LivingVisibilityEvent event) { LivingEntity entity = event.getEntity(); if (!testForStealth(entity)) return; event.modifyVisibility(0); } + // FIXME 1.21: should this be pre or post? @SubscribeEvent - public static void mobsMayLoseTargetWhenItIsWearingCardboard(LivingTickEvent event) { - LivingEntity entity = event.getEntity(); + public static void mobsMayLoseTargetWhenItIsWearingCardboard(EntityTickEvent.Pre event) { + if (!(event.getEntity() instanceof LivingEntity entity)) + return; + if (entity.tickCount % 16 != 0) return; if (!(entity instanceof Mob mob)) @@ -59,11 +62,10 @@ public class CardboardArmorHandler { if (testForStealth(mob.getTarget())) { mob.setTarget(null); if (mob.targetSelector != null) - mob.targetSelector.getRunningGoals() - .forEach(wrappedGoal -> { - if (wrappedGoal.getGoal() instanceof TargetGoal tg) - tg.stop(); - }); + for (WrappedGoal goal : mob.targetSelector.getAvailableGoals()) { + if (goal.isRunning() && goal.getGoal() instanceof TargetGoal tg) + tg.stop(); + } } if (entity instanceof NeutralMob nMob && entity.level() instanceof ServerLevel sl) { diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandlerClient.java b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandlerClient.java index 0b523a6022..69c04112c8 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandlerClient.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorHandlerClient.java @@ -15,13 +15,12 @@ import net.minecraft.client.CameraType; import net.minecraft.client.Minecraft; import net.minecraft.util.Mth; import net.minecraft.world.entity.player.Player; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RenderPlayerEvent; -import net.minecraftforge.event.TickEvent.Phase; -import net.minecraftforge.event.TickEvent.PlayerTickEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.RenderPlayerEvent; +import net.neoforged.neoforge.event.tick.PlayerTickEvent; @EventBusSubscriber(value = Dist.CLIENT) public class CardboardArmorHandlerClient { @@ -29,10 +28,8 @@ public class CardboardArmorHandlerClient { private static final Cache BOXES_PLAYERS_ARE_HIDING_AS = new TickBasedCache<>(20, true); @SubscribeEvent - public static void keepCacheAliveDesignDespiteNotRendering(PlayerTickEvent event) { - if (event.phase == Phase.START) - return; - Player player = event.player; + public static void keepCacheAliveDesignDespiteNotRendering(PlayerTickEvent.Post event) { + Player player = event.getEntity(); if (!CardboardArmorHandler.testForStealth(player)) return; try { diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorStealthOverlay.java b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorStealthOverlay.java index 40f49fa718..3469e29cf1 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorStealthOverlay.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardArmorStealthOverlay.java @@ -1,6 +1,7 @@ package com.simibubi.create.content.equipment.armor; import com.simibubi.create.Create; +import com.simibubi.create.foundation.mixin.accessor.GuiAccessor; import net.createmod.catnip.utility.animation.LerpedFloat; import net.createmod.catnip.utility.animation.LerpedFloat.Chaser; @@ -11,13 +12,12 @@ import net.minecraft.client.player.LocalPlayer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; public class CardboardArmorStealthOverlay extends Gui implements IClientItemExtensions { public CardboardArmorStealthOverlay() { - super(Minecraft.getInstance(), Minecraft.getInstance() - .getItemRenderer()); + super(Minecraft.getInstance()); } private static final ResourceLocation PACKAGE_BLUR_LOCATION = Create.asResource("textures/misc/package_blur.png"); @@ -41,9 +41,7 @@ public class CardboardArmorStealthOverlay extends Gui implements IClientItemExte float value = opacity.getValue(partialTick); if (value == 0) return; - screenWidth = width; - screenHeight = height; - renderTextureOverlay(new GuiGraphics(mc, mc.renderBuffers() + ((GuiAccessor) this).create$renderTextureOverlay(new GuiGraphics(mc, mc.renderBuffers() .bufferSource()), PACKAGE_BLUR_LOCATION, value); } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardHelmetItem.java b/src/main/java/com/simibubi/create/content/equipment/armor/CardboardHelmetItem.java deleted file mode 100644 index eab4121bc1..0000000000 --- a/src/main/java/com/simibubi/create/content/equipment/armor/CardboardHelmetItem.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.simibubi.create.content.equipment.armor; - -import java.util.function.Consumer; - -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; - -public class CardboardHelmetItem extends CardboardArmorItem { - - public CardboardHelmetItem(Type type, Properties properties) { - super(type, properties); - } - - @Override - @OnlyIn(Dist.CLIENT) - public void initializeClient(Consumer consumer) { - super.initializeClient(consumer); - consumer.accept(new CardboardArmorStealthOverlay()); - } - -} diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java b/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java index 9f675cfb0d..003b79d7f3 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java @@ -1,6 +1,8 @@ package com.simibubi.create.content.equipment.armor; import net.createmod.catnip.utility.NBTHelper; + +import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.FluidTags; import net.minecraft.world.entity.Entity; @@ -12,16 +14,16 @@ import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.tick.EntityTickEvent; @EventBusSubscriber public class DivingBootsItem extends BaseArmorItem { public static final EquipmentSlot SLOT = EquipmentSlot.FEET; public static final ArmorItem.Type TYPE = ArmorItem.Type.BOOTS; - public DivingBootsItem(ArmorMaterial material, Properties properties, ResourceLocation textureLoc) { + public DivingBootsItem(Holder material, Properties properties, ResourceLocation textureLoc) { super(material, TYPE, properties, textureLoc); } @@ -40,9 +42,12 @@ public class DivingBootsItem extends BaseArmorItem { return stack; } + // FIXME 1.21: should this be pre or post? @SubscribeEvent - public static void accellerateDescentUnderwater(LivingTickEvent event) { - LivingEntity entity = event.getEntity(); + public static void accelerateDescentUnderwater(EntityTickEvent.Pre event) { + if (!(event.getEntity() instanceof LivingEntity entity)) + return; + if (!affects(entity)) return; diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/DivingHelmetItem.java b/src/main/java/com/simibubi/create/content/equipment/armor/DivingHelmetItem.java index e63bc16a51..b3591f7134 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/DivingHelmetItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/DivingHelmetItem.java @@ -1,6 +1,9 @@ package com.simibubi.create.content.equipment.armor; import com.simibubi.create.foundation.advancement.AllAdvancements; + +import net.minecraft.core.Holder; +import net.minecraft.core.component.DataComponents; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.effect.MobEffectInstance; @@ -15,9 +18,9 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.Level; -import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.tick.EntityTickEvent; import java.util.List; import java.util.Map; @@ -27,33 +30,25 @@ public class DivingHelmetItem extends BaseArmorItem { public static final EquipmentSlot SLOT = EquipmentSlot.HEAD; public static final ArmorItem.Type TYPE = ArmorItem.Type.HELMET; - public DivingHelmetItem(ArmorMaterial material, Properties properties, ResourceLocation textureLoc) { + public DivingHelmetItem(Holder material, Properties properties, ResourceLocation textureLoc) { super(material, TYPE, properties, textureLoc); } @Override - public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) { - if (enchantment == Enchantments.AQUA_AFFINITY) { + public boolean supportsEnchantment(ItemStack stack, Holder enchantment) { + if (enchantment.is(Enchantments.AQUA_AFFINITY)) return false; - } - return super.canApplyAtEnchantingTable(stack, enchantment); + return super.supportsEnchantment(stack, enchantment); } @Override - public int getEnchantmentLevel(ItemStack stack, Enchantment enchantment) { - if (enchantment == Enchantments.AQUA_AFFINITY) { + public int getEnchantmentLevel(ItemStack stack, Holder enchantment) { + if (enchantment.is(Enchantments.AQUA_AFFINITY)) { return 1; } return super.getEnchantmentLevel(stack, enchantment); } - @Override - public Map getAllEnchantments(ItemStack stack) { - Map map = super.getAllEnchantments(stack); - map.put(Enchantments.AQUA_AFFINITY, 1); - return map; - } - public static boolean isWornBy(Entity entity) { return !getWornItem(entity).isEmpty(); } @@ -69,9 +64,12 @@ public class DivingHelmetItem extends BaseArmorItem { return stack; } + // FIXME 1.21: should this be pre or post? @SubscribeEvent - public static void breatheUnderwater(LivingTickEvent event) { - LivingEntity entity = event.getEntity(); + public static void breatheUnderwater(EntityTickEvent.Pre event) { + if (!(event.getEntity() instanceof LivingEntity entity)) + return; + Level world = entity.level(); boolean second = world.getGameTime() % 20 == 0; boolean drowning = entity.getAirSupply() == 0; @@ -85,8 +83,7 @@ public class DivingHelmetItem extends BaseArmorItem { return; boolean lavaDiving = entity.isInLava(); - if (!helmet.getItem() - .isFireResistant() && lavaDiving) + if (!helmet.has(DataComponents.FIRE_RESISTANT) && lavaDiving) return; if (!entity.canDrownInFluidType(entity.getEyeInFluidType()) && !lavaDiving) @@ -102,8 +99,7 @@ public class DivingHelmetItem extends BaseArmorItem { if (entity instanceof ServerPlayer sp) AllAdvancements.DIVING_SUIT_LAVA.awardTo(sp); if (backtanks.stream() - .noneMatch(backtank -> backtank.getItem() - .isFireResistant())) + .noneMatch(backtank -> backtank.has(DataComponents.FIRE_RESISTANT))) return; } @@ -114,7 +110,7 @@ public class DivingHelmetItem extends BaseArmorItem { entity.getPersistentData() .putInt("VisualBacktankAir", Math.round(backtanks.stream() .map(BacktankUtil::getAir) - .reduce(0f, Float::sum))); + .reduce(0, Integer::sum))); if (!second) return; diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteBacktankFirstPersonRenderer.java b/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteBacktankFirstPersonRenderer.java index 9d995838a2..67389d21c2 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteBacktankFirstPersonRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteBacktankFirstPersonRenderer.java @@ -16,11 +16,11 @@ import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.HumanoidArm; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RenderArmEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.RenderArmEvent; @EventBusSubscriber(value = Dist.CLIENT) public class NetheriteBacktankFirstPersonRenderer { diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteDivingHandler.java b/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteDivingHandler.java index 1344273c41..fdecb835b1 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteDivingHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/NetheriteDivingHandler.java @@ -2,14 +2,15 @@ package com.simibubi.create.content.equipment.armor; import com.simibubi.create.AllTags.AllItemTags; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.event.entity.living.LivingEquipmentChangeEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.living.LivingEquipmentChangeEvent; @EventBusSubscriber public final class NetheriteDivingHandler { @@ -19,7 +20,7 @@ public final class NetheriteDivingHandler { @SubscribeEvent public static void onLivingEquipmentChange(LivingEquipmentChangeEvent event) { EquipmentSlot slot = event.getSlot(); - if (slot.getType() != EquipmentSlot.Type.ARMOR) { + if (slot.getType() != EquipmentSlot.Type.HUMANOID_ARMOR) { return; } @@ -56,7 +57,7 @@ public final class NetheriteDivingHandler { } public static boolean isNetheriteArmor(ItemStack stack) { - return stack.getItem() instanceof ArmorItem armorItem && armorItem.isFireResistant(); + return stack.getItem() instanceof ArmorItem && stack.has(DataComponents.FIRE_RESISTANT); } public static void setBit(LivingEntity entity, EquipmentSlot slot) { diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/RemainingAirOverlay.java b/src/main/java/com/simibubi/create/content/equipment/armor/RemainingAirOverlay.java index 0474b6ad89..1f5e5315c7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/RemainingAirOverlay.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/RemainingAirOverlay.java @@ -5,24 +5,25 @@ import com.simibubi.create.AllItems; import net.createmod.catnip.gui.element.GuiGameElement; import net.createmod.catnip.utility.lang.Components; import net.createmod.catnip.utility.theme.Color; +import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.LayeredDraw; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.component.DataComponents; import net.minecraft.network.chat.Component; import net.minecraft.tags.FluidTags; import net.minecraft.util.StringUtil; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.GameType; -import net.minecraftforge.client.gui.overlay.ForgeGui; -import net.minecraftforge.client.gui.overlay.IGuiOverlay; import java.util.List; -public class RemainingAirOverlay implements IGuiOverlay { +public class RemainingAirOverlay implements LayeredDraw.Layer { public static final RemainingAirOverlay INSTANCE = new RemainingAirOverlay(); @Override - public void render(ForgeGui gui, GuiGraphics graphics, float partialTick, int width, int height) { + public void render(GuiGraphics guiGraphics, DeltaTracker deltaTracker) { Minecraft mc = Minecraft.getInstance(); if (mc.options.hideGui || mc.gameMode.getPlayerMode() == GameType.SPECTATOR) return; @@ -41,22 +42,22 @@ public class RemainingAirOverlay implements IGuiOverlay { int timeLeft = player.getPersistentData() .getInt("VisualBacktankAir"); - PoseStack poseStack = graphics.pose(); + PoseStack poseStack = guiGraphics.pose(); poseStack.pushPose(); ItemStack backtank = getDisplayedBacktank(player); - poseStack.translate(width / 2 + 90, height - 53 + (backtank.getItem() - .isFireResistant() ? 9 : 0), 0); + poseStack.translate(guiGraphics.guiWidth() / 2 + 90, guiGraphics.guiHeight() - 53 + (backtank + .has(DataComponents.FIRE_RESISTANT) ? 9 : 0), 0); - Component text = Components.literal(StringUtil.formatTickDuration(Math.max(0, timeLeft - 1) * 20)); + Component text = Components.literal(StringUtil.formatTickDuration(Math.max(0, timeLeft - 1) * 20, mc.level.tickRateManager().tickrate())); GuiGameElement.of(backtank) .at(0, 0) - .render(graphics); + .render(guiGraphics); int color = 0xFF_FFFFFF; if (timeLeft < 60 && timeLeft % 2 == 0) { color = Color.mixColors(0xFF_FF0000, color, Math.max(timeLeft / 60f, .25f)); } - graphics.drawString(mc.font, text, 16, 5, color); + guiGraphics.drawString(mc.font, text, 16, 5, color); poseStack.popPose(); } @@ -64,7 +65,7 @@ public class RemainingAirOverlay implements IGuiOverlay { public static ItemStack getDisplayedBacktank(LocalPlayer player) { List backtanks = BacktankUtil.getAllWithAir(player); if (!backtanks.isEmpty()) { - return backtanks.get(0); + return backtanks.getFirst(); } return AllItems.COPPER_BACKTANK.asStack(); } diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/TrimmableArmorModelGenerator.java b/src/main/java/com/simibubi/create/content/equipment/armor/TrimmableArmorModelGenerator.java index 9f01f16b33..f01b50912f 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/TrimmableArmorModelGenerator.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/TrimmableArmorModelGenerator.java @@ -12,7 +12,8 @@ import net.minecraft.data.models.model.TextureMapping; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.Item; -import net.minecraftforge.client.model.generators.ItemModelBuilder; + +import net.neoforged.neoforge.client.model.generators.ItemModelBuilder; public class TrimmableArmorModelGenerator { public static void generate(DataGenContext c, RegistrateItemModelProvider p) { @@ -24,7 +25,7 @@ public class TrimmableArmorModelGenerator { String trimId = data.name(item.getMaterial()); ResourceLocation trimModelLoc = modelLoc.withSuffix("_" + trimId + "_trim"); ResourceLocation trimLoc = - new ResourceLocation("trims/items/" + item.getType().getName() + "_trim_" + trimId); + ResourceLocation.withDefaultNamespace("trims/items/" + item.getType().getName() + "_trim_" + trimId); String parent = "item/generated"; if (item.getMaterial() == AllArmorMaterials.CARDBOARD) { trimLoc = Create.asResource("trims/items/card_" + item.getType().getName() + "_trim_" + trimId); diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlock.java b/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlock.java index 5467bc4032..307adcaf70 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlock.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlock.java @@ -32,18 +32,12 @@ public abstract class AbstractBellBlock exte @Override public VoxelShape getShape(BlockState state, BlockGetter reader, BlockPos pos, CollisionContext selection) { Direction facing = state.getValue(FACING); - switch (state.getValue(ATTACHMENT)) { - case CEILING: - return AllShapes.BELL_CEILING.get(facing); - case DOUBLE_WALL: - return AllShapes.BELL_DOUBLE_WALL.get(facing); - case FLOOR: - return AllShapes.BELL_FLOOR.get(facing); - case SINGLE_WALL: - return AllShapes.BELL_WALL.get(facing); - default: - return Shapes.block(); - } + return switch (state.getValue(ATTACHMENT)) { + case CEILING -> AllShapes.BELL_CEILING.get(facing); + case DOUBLE_WALL -> AllShapes.BELL_DOUBLE_WALL.get(facing); + case FLOOR -> AllShapes.BELL_FLOOR.get(facing); + case SINGLE_WALL -> AllShapes.BELL_WALL.get(facing); + }; } @Override diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlockEntity.java b/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlockEntity.java index 99ebb218b3..db0caef001 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/AbstractBellBlockEntity.java @@ -9,12 +9,13 @@ import dev.engine_room.flywheel.lib.model.baked.PartialModel; import net.createmod.catnip.utility.NBTHelper; 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.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public abstract class AbstractBellBlockEntity extends SmartBlockEntity { @@ -54,16 +55,16 @@ public abstract class AbstractBellBlockEntity extends SmartBlockEntity { } @Override - protected void write(CompoundTag tag, boolean clientPacket) { - super.write(tag, clientPacket); + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.write(tag, registries, clientPacket); if (!clientPacket || ringingTicks != 0 || !isRinging) return; NBTHelper.writeEnum(tag, "Ringing", ringDirection); } @Override - protected void read(CompoundTag tag, boolean clientPacket) { - super.read(tag, clientPacket); + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.read(tag, registries, clientPacket); if (!clientPacket || !tag.contains("Ringing")) return; ringDirection = NBTHelper.readEnum(tag, "Ringing", Direction.class); diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java b/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java index 7fa1115e72..64d761e3f5 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java @@ -4,6 +4,8 @@ import javax.annotation.ParametersAreNonnullByDefault; import com.mojang.brigadier.StringReader; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; +import com.simibubi.create.foundation.particle.AirParticleData; import com.simibubi.create.foundation.particle.ICustomParticleDataWithSprite; import net.createmod.catnip.platform.CatnipServices; @@ -15,8 +17,11 @@ import net.minecraft.client.particle.SpriteSet; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault @@ -25,24 +30,13 @@ public abstract class BasicParticleData implements ParticleO public BasicParticleData() { } @Override - public Deserializer> getDeserializer() { - BasicParticleData data = this; - return new ParticleOptions.Deserializer>() { - @Override - public BasicParticleData fromCommand(ParticleType> arg0, StringReader reader) { - return data; - } - - @Override - public BasicParticleData fromNetwork(ParticleType> type, FriendlyByteBuf buffer) { - return data; - } - }; + public StreamCodec> getStreamCodec() { + return StreamCodec.unit(this); } @Override - public Codec> getCodec(ParticleType> type) { - return Codec.unit(this); + public MapCodec> getCodec(ParticleType> type) { + return MapCodec.unit(this); } public interface IBasicParticleFactory { @@ -58,12 +52,4 @@ public abstract class BasicParticleData implements ParticleO return animatedSprite -> (data, worldIn, x, y, z, vx, vy, vz) -> getBasicFactory().makeParticle(worldIn, x, y, z, vx, vy, vz, animatedSprite); } - - @Override - public String writeToString() { - return CatnipServices.REGISTRIES.getKeyOrThrow(getType()).toString(); - } - - @Override - public void writeToNetwork(FriendlyByteBuf buffer) { } } diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/CustomRotationParticle.java b/src/main/java/com/simibubi/create/content/equipment/bell/CustomRotationParticle.java index f0de0c17a7..2cbdf88070 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/CustomRotationParticle.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/CustomRotationParticle.java @@ -66,9 +66,9 @@ public class CustomRotationParticle extends SimpleAnimatedParticle { float minV = getV0(); float maxV = getV1(); int brightness = ShadersModHelper.isShaderPackInUse() ? LightTexture.pack(12, 15) : getLightColor(partialTicks); - builder.vertex(vertices[0].x(), vertices[0].y(), vertices[0].z()).uv(maxU, maxV).color(rCol, gCol, bCol, alpha).uv2(brightness).endVertex(); - builder.vertex(vertices[1].x(), vertices[1].y(), vertices[1].z()).uv(maxU, minV).color(rCol, gCol, bCol, alpha).uv2(brightness).endVertex(); - builder.vertex(vertices[2].x(), vertices[2].y(), vertices[2].z()).uv(minU, minV).color(rCol, gCol, bCol, alpha).uv2(brightness).endVertex(); - builder.vertex(vertices[3].x(), vertices[3].y(), vertices[3].z()).uv(minU, maxV).color(rCol, gCol, bCol, alpha).uv2(brightness).endVertex(); + builder.addVertex(vertices[0].x(), vertices[0].y(), vertices[0].z()).setUv(maxU, maxV).setColor(rCol, gCol, bCol, alpha).setLight(brightness); + builder.addVertex(vertices[1].x(), vertices[1].y(), vertices[1].z()).setUv(maxU, minV).setColor(rCol, gCol, bCol, alpha).setLight(brightness); + builder.addVertex(vertices[2].x(), vertices[2].y(), vertices[2].z()).setUv(minU, minV).setColor(rCol, gCol, bCol, alpha).setLight(brightness); + builder.addVertex(vertices[3].x(), vertices[3].y(), vertices[3].z()).setUv(minU, maxV).setColor(rCol, gCol, bCol, alpha).setLight(brightness); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellBlockEntity.java b/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellBlockEntity.java index 7a1242b4e3..38b0c25736 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellBlockEntity.java @@ -5,16 +5,18 @@ import com.simibubi.create.AllPartialModels; import dev.engine_room.flywheel.lib.model.baked.PartialModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class HauntedBellBlockEntity extends AbstractBellBlockEntity { @@ -38,20 +40,21 @@ public class HauntedBellBlockEntity extends AbstractBellBlockEntity { public boolean ring(Level world, BlockPos pos, Direction direction) { if (isRinging && ringingTicks < RECHARGE_TICKS) return false; - HauntedBellPulser.sendPulse(world, pos, DISTANCE, false); + if (world instanceof ServerLevel serverLevel) + HauntedBellPulser.sendPulse(serverLevel, pos, DISTANCE, false); effectTicks = EFFECT_TICKS; return super.ring(world, pos, direction); } @Override - protected void write(CompoundTag compound, boolean clientPacket) { - super.write(compound, clientPacket); + protected void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.write(compound, registries, clientPacket); compound.putInt("EffectTicks", effectTicks); } @Override - protected void read(CompoundTag compound, boolean clientPacket) { - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + super.read(compound, registries, clientPacket); effectTicks = compound.getInt("EffectTicks"); } @@ -87,7 +90,7 @@ public class HauntedBellBlockEntity extends AbstractBellBlockEntity { protected void playSound(RandomSource rand) { float vol = rand.nextFloat() * 0.4F + rand.nextFloat() > 0.9F ? 0.6F : 0.0F; float pitch = 0.6F + rand.nextFloat() * 0.4F; - level.playSound(null, worldPosition, SoundEvents.SOUL_ESCAPE, SoundSource.BLOCKS, vol, pitch); + level.playSound(null, worldPosition, SoundEvents.SOUL_ESCAPE.value(), SoundSource.BLOCKS, vol, pitch); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellMovementBehaviour.java b/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellMovementBehaviour.java index 239f8b9246..01683780e5 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellMovementBehaviour.java @@ -4,6 +4,7 @@ import com.simibubi.create.content.contraptions.behaviour.BellMovementBehaviour; import com.simibubi.create.content.contraptions.behaviour.MovementContext; import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; public class HauntedBellMovementBehaviour extends BellMovementBehaviour { @@ -18,8 +19,8 @@ public class HauntedBellMovementBehaviour extends BellMovementBehaviour { @Override public void visitNewPosition(MovementContext context, BlockPos pos) { - if (!context.world.isClientSide && getRecharge(context) == 0) { - HauntedBellPulser.sendPulse(context.world, pos, DISTANCE, false); + if (!context.world.isClientSide && context.world instanceof ServerLevel serverLevel && getRecharge(context) == 0) { + HauntedBellPulser.sendPulse(serverLevel, pos, DISTANCE, false); setRecharge(context, HauntedBellBlockEntity.RECHARGE_TICKS); playSound(context); } diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellPulser.java b/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellPulser.java index 26d27b750c..cc40aea030 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellPulser.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/HauntedBellPulser.java @@ -3,17 +3,16 @@ package com.simibubi.create.content.equipment.bell; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.simibubi.create.AllBlocks; -import com.simibubi.create.AllPackets; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.IntAttached; import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.LogicalSide; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.network.PacketDistributor; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.ChunkPos; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.tick.PlayerTickEvent; import java.util.UUID; import java.util.concurrent.ExecutionException; @@ -31,38 +30,35 @@ public class HauntedBellPulser { .build(); @SubscribeEvent - public static void hauntedBellCreatesPulse(TickEvent.PlayerTickEvent event) { - if (event.phase != TickEvent.Phase.END) - return; - if (event.side != LogicalSide.SERVER) - return; - if (event.player.isSpectator()) - return; - if (!event.player.isHolding(AllBlocks.HAUNTED_BELL::isIn)) + public static void hauntedBellCreatesPulse(PlayerTickEvent.Post event) { + Player player = event.getEntity(); + + if (player.level().isClientSide()) + return; + + if (player.isSpectator()) + return; + if (!player.isHolding(AllBlocks.HAUNTED_BELL::isIn)) return; - Entity player = event.player; boolean firstPulse = false; try { IntAttached ticker = WARMUP.get(player.getUUID(), () -> IntAttached.with(WARMUP_TICKS, player)); - firstPulse = ticker.getFirst() - .intValue() == 1; + firstPulse = ticker.getFirst() == 1; ticker.decrement(); if (!ticker.isOrBelowZero()) return; - } catch (ExecutionException e) { - } + } catch (ExecutionException ignored) {} long gameTime = player.level().getGameTime(); - if (firstPulse || gameTime % RECHARGE_TICKS != 0) - sendPulse(player.level(), event.player.blockPosition(), DISTANCE, false); + if ((firstPulse || gameTime % RECHARGE_TICKS != 0) && player.level() instanceof ServerLevel serverLevel) + sendPulse(serverLevel, player.blockPosition(), DISTANCE, false); } - public static void sendPulse(Level world, BlockPos pos, int distance, boolean canOverlap) { - LevelChunk chunk = world.getChunkAt(pos); - AllPackets.getChannel().send(PacketDistributor.TRACKING_CHUNK.with(() -> chunk), - new SoulPulseEffectPacket(pos, distance, canOverlap)); + public static void sendPulse(ServerLevel world, BlockPos pos, int distance, boolean canOverlap) { + ChunkPos chunk = world.getChunkAt(pos).getPos(); + CatnipServices.NETWORK.sendToClientsTrackingChunk(world, chunk, new SoulPulseEffectPacket(pos, distance, canOverlap)); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/PeculiarBellBlockEntity.java b/src/main/java/com/simibubi/create/content/equipment/bell/PeculiarBellBlockEntity.java index 8a0259fe91..ce4b7776f0 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/PeculiarBellBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/PeculiarBellBlockEntity.java @@ -6,8 +6,8 @@ import dev.engine_room.flywheel.lib.model.baked.PartialModel; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class PeculiarBellBlockEntity extends AbstractBellBlockEntity { diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffect.java b/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffect.java index 28ddae56ec..c12f5f48e8 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffect.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffect.java @@ -11,6 +11,7 @@ import com.simibubi.create.content.equipment.bell.SoulParticle.ExpandingPerimete import net.createmod.catnip.utility.VecHelper; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.SpawnPlacementTypes; import net.minecraft.world.entity.SpawnPlacements; import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer; @@ -84,7 +85,7 @@ public class SoulPulseEffect { double dummyWidth = 0.2, dummyHeight = 0.75; double w2 = dummyWidth / 2; - return world != null && NaturalSpawner.isSpawnPositionOk(SpawnPlacements.Type.ON_GROUND, world, at, dummy) + return world != null && SpawnPlacementTypes.ON_GROUND.isSpawnPositionOk(world, at, dummy) && (ignoreLight || isDark(world, at)) && Streams .stream(world.getBlockCollisions(null, diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffectPacket.java b/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffectPacket.java index 74652139aa..b1379cbd39 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffectPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/SoulPulseEffectPacket.java @@ -1,43 +1,34 @@ package com.simibubi.create.content.equipment.bell; +import com.simibubi.create.AllPackets; import com.simibubi.create.CreateClient; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.network.NetworkEvent.Context; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SoulPulseEffectPacket extends SimplePacketBase { +public record SoulPulseEffectPacket(BlockPos pos, int distance, boolean canOverlap) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, SoulPulseEffectPacket::pos, + ByteBufCodecs.INT, SoulPulseEffectPacket::distance, + ByteBufCodecs.BOOL, SoulPulseEffectPacket::canOverlap, + SoulPulseEffectPacket::new + ); - public BlockPos pos; - public int distance; - public boolean canOverlap; - - public SoulPulseEffectPacket(BlockPos pos, int distance, boolean overlaps) { - this.pos = pos; - this.distance = distance; - this.canOverlap = overlaps; - } - - public SoulPulseEffectPacket(FriendlyByteBuf buffer) { - pos = buffer.readBlockPos(); - distance = buffer.readInt(); - canOverlap = buffer.readBoolean(); + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + CreateClient.SOUL_PULSE_EFFECT_HANDLER.addPulse(new SoulPulseEffect(pos, distance, canOverlap)); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(pos); - buffer.writeInt(distance); - buffer.writeBoolean(canOverlap); + public PacketTypeProvider getTypeProvider() { + return AllPackets.SOUL_PULSE; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - CreateClient.SOUL_PULSE_EFFECT_HANDLER.addPulse(new SoulPulseEffect(pos, distance, canOverlap)); - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java index d54451e648..05779ac9cd 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java @@ -1,43 +1,30 @@ package com.simibubi.create.content.equipment.blueprint; -import com.simibubi.create.foundation.networking.SimplePacketBase; -import net.minecraft.network.FriendlyByteBuf; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class BlueprintAssignCompleteRecipePacket extends SimplePacketBase { +public record BlueprintAssignCompleteRecipePacket(ResourceLocation recipeId) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = ResourceLocation.STREAM_CODEC.map( + BlueprintAssignCompleteRecipePacket::new, BlueprintAssignCompleteRecipePacket::recipeId + ); - private ResourceLocation recipeID; - - public BlueprintAssignCompleteRecipePacket(ResourceLocation recipeID) { - this.recipeID = recipeID; - } - - public BlueprintAssignCompleteRecipePacket(FriendlyByteBuf buffer) { - recipeID = buffer.readResourceLocation(); + @Override + public void handle(ServerPlayer player) { + if (player.containerMenu instanceof BlueprintMenu c) { + player.level() + .getRecipeManager() + .byKey(recipeId) + .ifPresent(r -> BlueprintItem.assignCompleteRecipe(c.player.level(), c.ghostInventory, r.value())); + } } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeResourceLocation(recipeID); + public PacketTypeProvider getTypeProvider() { + return AllPackets.BLUEPRINT_COMPLETE_RECIPE; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - if (player == null) - return; - if (player.containerMenu instanceof BlueprintMenu) { - BlueprintMenu c = (BlueprintMenu) player.containerMenu; - player.level() - .getRecipeManager() - .byKey(recipeID) - .ifPresent(r -> BlueprintItem.assignCompleteRecipe(c.player.level(), c.ghostInventory, r)); - } - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java index 82ad2fed9b..6a25adf524 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java @@ -3,15 +3,13 @@ package com.simibubi.create.content.equipment.blueprint; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; -import org.apache.commons.lang3.Validate; - import com.simibubi.create.AllEntityTypes; import com.simibubi.create.AllItems; -import com.simibubi.create.Create; import com.simibubi.create.content.logistics.filter.FilterItemStack; import com.simibubi.create.api.schematic.requirement.ISpecialEntityItemRequirement; import com.simibubi.create.content.schematics.requirement.ItemRequirement; @@ -27,10 +25,9 @@ import net.minecraft.core.Direction.Axis; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; @@ -42,6 +39,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityDimensions; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.decoration.HangingEntity; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -50,6 +48,7 @@ import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.inventory.TransientCraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; @@ -59,20 +58,18 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.entity.IEntityAdditionalSpawnData; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.items.IItemHandlerModifiable; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.items.wrapper.InvWrapper; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.common.CommonHooks; +import net.neoforged.neoforge.common.util.FakePlayer; +import net.neoforged.neoforge.entity.IEntityWithComplexSpawn; +import net.neoforged.neoforge.event.EventHooks; +import net.neoforged.neoforge.items.IItemHandlerModifiable; +import net.neoforged.neoforge.items.ItemStackHandler; +import net.neoforged.neoforge.items.wrapper.InvWrapper; public class BlueprintEntity extends HangingEntity - implements IEntityAdditionalSpawnData, ISpecialEntityItemRequirement, ISyncPersistentData, IInteractionChecker { + implements IEntityWithComplexSpawn, ISpecialEntityItemRequirement, ISyncPersistentData, IInteractionChecker { protected int size; protected Direction verticalOrientation; @@ -101,9 +98,7 @@ public class BlueprintEntity extends HangingEntity } @Override - public Packet getAddEntityPacket() { - return NetworkHooks.getEntitySpawningPacket(this); - } + protected void defineSynchedData(SynchedEntityData.Builder builder) {} @Override public void addAdditionalSaveData(CompoundTag p_213281_1_) { @@ -129,7 +124,7 @@ public class BlueprintEntity extends HangingEntity } protected void updateFacingWithBoundingBox(Direction facing, Direction verticalOrientation) { - Validate.notNull(facing); + Objects.requireNonNull(facing); this.direction = facing; this.verticalOrientation = verticalOrientation; if (facing.getAxis() @@ -149,21 +144,16 @@ public class BlueprintEntity extends HangingEntity } @Override - protected float getEyeHeight(Pose p_213316_1_, EntityDimensions p_213316_2_) { - return 0; + public EntityDimensions getDimensions(Pose pose) { + return super.getDimensions(pose).withEyeHeight(0); } @Override - protected void recalculateBoundingBox() { - if (this.direction == null) - return; - if (this.verticalOrientation == null) - return; - + protected AABB calculateBoundingBox(BlockPos blockPos, Direction direction) { Vec3 pos = Vec3.atLowerCornerOf(getPos()) - .add(.5, .5, .5) - .subtract(Vec3.atLowerCornerOf(direction.getNormal()) - .scale(0.46875)); + .add(.5, .5, .5) + .subtract(Vec3.atLowerCornerOf(direction.getNormal()) + .scale(0.46875)); double d1 = pos.x; double d2 = pos.y; double d3 = pos.z; @@ -172,16 +162,16 @@ public class BlueprintEntity extends HangingEntity Axis axis = direction.getAxis(); if (size == 2) pos = pos.add(Vec3.atLowerCornerOf(axis.isHorizontal() ? direction.getCounterClockWise() - .getNormal() - : verticalOrientation.getClockWise() - .getNormal()) - .scale(0.5)) - .add(Vec3 - .atLowerCornerOf(axis.isHorizontal() ? Direction.UP.getNormal() - : direction == Direction.UP ? verticalOrientation.getNormal() - : verticalOrientation.getOpposite() - .getNormal()) - .scale(0.5)); + .getNormal() + : verticalOrientation.getClockWise() + .getNormal()) + .scale(0.5)) + .add(Vec3 + .atLowerCornerOf(axis.isHorizontal() ? Direction.UP.getNormal() + : direction == Direction.UP ? verticalOrientation.getNormal() + : verticalOrientation.getOpposite() + .getNormal()) + .scale(0.5)); d1 = pos.x; d2 = pos.y; @@ -192,22 +182,29 @@ public class BlueprintEntity extends HangingEntity double d6 = (double) this.getWidth(); Direction.Axis direction$axis = this.direction.getAxis(); switch (direction$axis) { - case X: - d4 = 1.0D; - break; - case Y: - d5 = 1.0D; - break; - case Z: - d6 = 1.0D; + case X: + d4 = 1.0D; + break; + case Y: + d5 = 1.0D; + break; + case Z: + d6 = 1.0D; } d4 = d4 / 32.0D; d5 = d5 / 32.0D; d6 = d6 / 32.0D; - this.setBoundingBox(new AABB(d1 - d4, d2 - d5, d3 - d6, d1 + d4, d2 + d5, d3 + d6)); + + return new AABB(d1 - d4, d2 - d5, d3 - d6, d1 + d4, d2 + d5, d3 + d6); } + @Override + protected void recalculateBoundingBox() { + if (this.direction != null && this.verticalOrientation != null) { + recalculateBoundingBox(); + } + } @Override public void setPos(double pX, double pY, double pZ) { setPosRaw(pX, pY, pZ); @@ -249,24 +246,20 @@ public class BlueprintEntity extends HangingEntity .isEmpty(); } - @Override public int getWidth() { return 16 * size; } - @Override public int getHeight() { return 16 * size; } @Override public boolean skipAttackInteraction(Entity source) { - if (!(source instanceof Player) || level().isClientSide) + if (!(source instanceof Player player) || level().isClientSide) return super.skipAttackInteraction(source); - Player player = (Player) source; - double attrib = player.getAttribute(ForgeMod.BLOCK_REACH.get()) - .getValue() + (player.isCreative() ? 0 : -0.5F); + double attrib = player.getAttributeValue(Attributes.BLOCK_INTERACTION_RANGE) + (player.isCreative() ? 0 : -0.5F); Vec3 eyePos = source.getEyePosition(1); Vec3 look = source.getViewVector(1); @@ -327,25 +320,24 @@ public class BlueprintEntity extends HangingEntity @Override @OnlyIn(Dist.CLIENT) - public void lerpTo(double p_180426_1_, double p_180426_3_, double p_180426_5_, float p_180426_7_, float p_180426_8_, - int p_180426_9_, boolean p_180426_10_) { + public void lerpTo(double pX, double pY, double pZ, float pYRot, float pXRot, int pSteps) { BlockPos blockpos = - this.pos.offset(BlockPos.containing(p_180426_1_ - this.getX(), p_180426_3_ - this.getY(), p_180426_5_ - this.getZ())); - this.setPos((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); + this.pos.offset(BlockPos.containing(pX - this.getX(), pY - this.getY(), pZ - this.getZ())); + this.setPos(blockpos.getX(), blockpos.getY(), blockpos.getZ()); } @Override - public void writeSpawnData(FriendlyByteBuf buffer) { + public void writeSpawnData(RegistryFriendlyByteBuf registryFriendlyByteBuf) { CompoundTag compound = new CompoundTag(); addAdditionalSaveData(compound); - buffer.writeNbt(compound); - buffer.writeNbt(getPersistentData()); + registryFriendlyByteBuf.writeNbt(compound); + registryFriendlyByteBuf.writeNbt(getPersistentData()); } @Override - public void readSpawnData(FriendlyByteBuf additionalData) { - readAdditionalSaveData(additionalData.readNbt()); - getPersistentData().merge(additionalData.readNbt()); + public void readSpawnData(RegistryFriendlyByteBuf registryFriendlyByteBuf) { + readAdditionalSaveData(registryFriendlyByteBuf.readNbt()); + getPersistentData().merge(registryFriendlyByteBuf.readNbt()); } @Override @@ -363,8 +355,8 @@ public class BlueprintEntity extends HangingEntity IItemHandlerModifiable playerInv = new InvWrapper(player.getInventory()); boolean firstPass = true; int amountCrafted = 0; - ForgeHooks.setCraftingPlayer(player); - Optional recipe = Optional.empty(); + CommonHooks.setCraftingPlayer(player); + Optional> recipe = Optional.empty(); do { Map stacksTaken = new HashMap<>(); @@ -400,9 +392,9 @@ public class BlueprintEntity extends HangingEntity if (!recipe.isPresent()) recipe = level().getRecipeManager() - .getRecipeFor(RecipeType.CRAFTING, craftingInventory, level()); - ItemStack result = recipe.filter(r -> r.matches(craftingInventory, level())) - .map(r -> r.assemble(craftingInventory, level().registryAccess())) + .getRecipeFor(RecipeType.CRAFTING, craftingInventory.asCraftInput(), level()); + ItemStack result = recipe.filter(r -> r.value().matches(craftingInventory.asCraftInput(), level())) + .map(r -> r.value().assemble(craftingInventory.asCraftInput(), registryAccess())) .orElse(ItemStack.EMPTY); if (result.isEmpty()) { @@ -412,13 +404,13 @@ public class BlueprintEntity extends HangingEntity } else { amountCrafted += result.getCount(); result.onCraftedBy(player.level(), player, 1); - ForgeEventFactory.firePlayerCraftingEvent(player, result, craftingInventory); + EventHooks.firePlayerCraftingEvent(player, result, craftingInventory); NonNullList nonnulllist = level().getRecipeManager() - .getRemainingItemsFor(RecipeType.CRAFTING, craftingInventory, level()); + .getRemainingItemsFor(RecipeType.CRAFTING, craftingInventory.asCraftInput(), level()); if (firstPass) level().playSound(null, player.blockPosition(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, - .2f, 1f + Create.RANDOM.nextFloat()); + .2f, 1f + level().getRandom().nextFloat()); player.getInventory() .placeItemBackInInventory(result); for (ItemStack itemStack : nonnulllist) @@ -435,13 +427,13 @@ public class BlueprintEntity extends HangingEntity } } while (player.isShiftKeyDown()); - ForgeHooks.setCraftingPlayer(null); + CommonHooks.setCraftingPlayer(null); return InteractionResult.SUCCESS; } int i = section.index; if (!level().isClientSide && player instanceof ServerPlayer) { - NetworkHooks.openScreen((ServerPlayer) player, section, buf -> { + player.openMenu(section, buf -> { buf.writeVarInt(getId()); buf.writeVarInt(i); }); @@ -527,13 +519,13 @@ public class BlueprintEntity extends HangingEntity CompoundTag invNBT = list.getCompound(index + ""); inferredIcon = list.getBoolean("InferredIcon"); if (!invNBT.isEmpty()) - newInv.deserializeNBT(invNBT); + newInv.deserializeNBT(registryAccess(), invNBT); return newInv; } public void save(ItemStackHandler inventory) { CompoundTag list = getOrCreateRecipeCompound(); - list.put(index + "", inventory.serializeNBT()); + list.put(index + "", inventory.serializeNBT(registryAccess())); list.putBoolean("InferredIcon", inferredIcon); cachedDisplayItems = null; if (!level().isClientSide) diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java index c87e275a60..f9497b0712 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java @@ -1,41 +1,44 @@ package com.simibubi.create.content.equipment.blueprint; -import com.simibubi.create.AllItems; -import com.simibubi.create.content.logistics.filter.AttributeFilterMenu.WhitelistMode; -import com.simibubi.create.content.logistics.filter.FilterItem; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import com.simibubi.create.AllDataComponents; +import com.simibubi.create.AllItems; +import com.simibubi.create.content.logistics.filter.AttributeFilterWhitelistMode; +import com.simibubi.create.content.logistics.filter.FilterItem; +import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute; +import com.simibubi.create.content.logistics.item.filter.attribute.attributes.InTagAttribute; +import com.simibubi.create.foundation.item.ItemHelper; -import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute;import com.simibubi.create.content.logistics.item.filter.attribute.attributes.InTagAttribute; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.component.DataComponents; import net.minecraft.tags.ItemTags; -import net.minecraft.util.GsonHelper; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.decoration.HangingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Ingredient.ItemValue; import net.minecraft.world.item.crafting.Ingredient.TagValue; import net.minecraft.world.item.crafting.Ingredient.Value; import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.level.Level; -import net.minecraftforge.common.crafting.IShapedRecipe; -import net.minecraftforge.common.crafting.MultiItemValue; -import net.minecraftforge.items.ItemStackHandler; - -import java.util.Collection; +import net.neoforged.neoforge.common.crafting.CompoundIngredient; +import net.neoforged.neoforge.items.ItemStackHandler; public class BlueprintItem extends Item { - public BlueprintItem(Properties p_i48487_1_) { - super(p_i48487_1_); + public BlueprintItem(Properties properties) { + super(properties); } @Override @@ -52,10 +55,10 @@ public class BlueprintItem extends Item { Level world = ctx.getLevel(); HangingEntity hangingentity = new BlueprintEntity(world, pos, face, face.getAxis() .isHorizontal() ? Direction.DOWN : ctx.getHorizontalDirection()); - CompoundTag compoundnbt = stack.getTag(); + CustomData customData = stack.get(DataComponents.CUSTOM_DATA); - if (compoundnbt != null) - EntityType.updateCustomEntityTag(world, player, hangingentity, compoundnbt); + if (customData != null) + EntityType.updateCustomEntityTag(world, player, hangingentity, customData); if (!hangingentity.survives()) return InteractionResult.CONSUME; if (!world.isClientSide) { @@ -67,11 +70,6 @@ public class BlueprintItem extends Item { return InteractionResult.sidedSuccess(world.isClientSide); } - protected boolean canPlace(Player p_200127_1_, Direction p_200127_2_, ItemStack p_200127_3_, - BlockPos p_200127_4_) { - return p_200127_1_.mayUseItemAt(p_200127_4_, p_200127_2_, p_200127_3_); - } - public static void assignCompleteRecipe(Level level, ItemStackHandler inv, Recipe recipe) { NonNullList ingredients = recipe.getIngredients(); @@ -79,12 +77,11 @@ public class BlueprintItem extends Item { inv.setStackInSlot(i, ItemStack.EMPTY); inv.setStackInSlot(9, recipe.getResultItem(level.registryAccess())); - if (recipe instanceof IShapedRecipe) { - IShapedRecipe shapedRecipe = (IShapedRecipe) recipe; - for (int row = 0; row < shapedRecipe.getRecipeHeight(); row++) - for (int col = 0; col < shapedRecipe.getRecipeWidth(); col++) + if (recipe instanceof ShapedRecipe shapedRecipe) { + for (int row = 0; row < shapedRecipe.getHeight(); row++) + for (int col = 0; col < shapedRecipe.getWidth(); col++) inv.setStackInSlot(row * 3 + col, - convertIngredientToFilter(ingredients.get(row * shapedRecipe.getRecipeWidth() + col))); + convertIngredientToFilter(ingredients.get(row * shapedRecipe.getWidth() + col))); } else { for (int i = 0; i < ingredients.size(); i++) inv.setStackInSlot(i, convertIngredientToFilter(ingredients.get(i))); @@ -92,45 +89,41 @@ public class BlueprintItem extends Item { } private static ItemStack convertIngredientToFilter(Ingredient ingredient) { + boolean isCompoundIngredient = ingredient.getCustomIngredient() instanceof CompoundIngredient; Ingredient.Value[] acceptedItems = ingredient.values; if (acceptedItems == null || acceptedItems.length > 18) return ItemStack.EMPTY; if (acceptedItems.length == 0) return ItemStack.EMPTY; if (acceptedItems.length == 1) - return convertIItemListToFilter(acceptedItems[0]); + return convertIItemListToFilter(acceptedItems[0], isCompoundIngredient); ItemStack result = AllItems.FILTER.asStack(); ItemStackHandler filterItems = FilterItem.getFilterItems(result); for (int i = 0; i < acceptedItems.length; i++) - filterItems.setStackInSlot(i, convertIItemListToFilter(acceptedItems[i])); - result.getOrCreateTag() - .put("Items", filterItems.serializeNBT()); + filterItems.setStackInSlot(i, convertIItemListToFilter(acceptedItems[i], isCompoundIngredient)); + result.set(AllDataComponents.FILTER_ITEMS, ItemHelper.containerContentsFromHandler(filterItems)); return result; } - private static ItemStack convertIItemListToFilter(Value itemList) { + private static ItemStack convertIItemListToFilter(Value itemList, boolean isCompoundIngredient) { Collection stacks = itemList.getItems(); if (itemList instanceof ItemValue) { for (ItemStack itemStack : stacks) return itemStack; } - if (itemList instanceof TagValue) { - ResourceLocation resourcelocation = new ResourceLocation(GsonHelper.getAsString(itemList.serialize(), "tag")); + if (itemList instanceof TagValue tagValue) { ItemStack filterItem = AllItems.ATTRIBUTE_FILTER.asStack(); - filterItem.getOrCreateTag() - .putInt("WhitelistMode", WhitelistMode.WHITELIST_DISJ.ordinal()); - ListTag attributes = new ListTag(); - CompoundTag compoundNBT = ItemAttribute.saveStatic(new InTagAttribute(ItemTags.create(resourcelocation))); - compoundNBT.putBoolean("Inverted", false); - attributes.add(compoundNBT); - filterItem.getOrCreateTag() - .put("MatchedAttributes", attributes); + filterItem.set(AllDataComponents.ATTRIBUTE_FILTER_WHITELIST_MODE, AttributeFilterWhitelistMode.WHITELIST_DISJ); + List attributes = new ArrayList<>(); + ItemAttribute at = new InTagAttribute(ItemTags.create(tagValue.tag().location())); + attributes.add(new ItemAttribute.ItemAttributeEntry(at, false)); + filterItem.set(AllDataComponents.ATTRIBUTE_FILTER_MATCHED_ATTRIBUTES, attributes); return filterItem; } - if (itemList instanceof MultiItemValue) { + if (isCompoundIngredient) { ItemStack result = AllItems.FILTER.asStack(); ItemStackHandler filterItems = FilterItem.getFilterItems(result); int i = 0; @@ -139,9 +132,8 @@ public class BlueprintItem extends Item { break; filterItems.setStackInSlot(i++, itemStack); } - CompoundTag tag = result.getOrCreateTag(); - tag.put("Items", filterItems.serializeNBT()); - tag.putBoolean("RespectNBT", true); + result.set(AllDataComponents.FILTER_ITEMS, ItemHelper.containerContentsFromHandler(filterItems)); + result.set(AllDataComponents.FILTER_ITEMS_RESPECT_NBT, true); return result; } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java index ac4fa01e62..b0ada3e188 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java @@ -1,10 +1,11 @@ package com.simibubi.create.content.equipment.blueprint; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllMenuTypes; import com.simibubi.create.content.equipment.blueprint.BlueprintEntity.BlueprintSection; import com.simibubi.create.foundation.gui.menu.GhostItemMenu; import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; @@ -16,19 +17,20 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.TransientCraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.items.SlotItemHandler; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.ItemStackHandler; +import net.neoforged.neoforge.items.SlotItemHandler; import java.util.Optional; public class BlueprintMenu extends GhostItemMenu { - public BlueprintMenu(MenuType type, int id, Inventory inv, FriendlyByteBuf extraData) { + public BlueprintMenu(MenuType type, int id, Inventory inv, RegistryFriendlyByteBuf extraData) { super(type, id, inv, extraData); } @@ -67,9 +69,9 @@ public class BlueprintMenu extends GhostItemMenu { ServerPlayer serverplayerentity = (ServerPlayer) player; CraftingContainer craftingInventory = new BlueprintCraftingInventory(this, ghostInventory); - Optional optional = player.getServer() + Optional> optional = player.getServer() .getRecipeManager() - .getRecipeFor(RecipeType.CRAFTING, craftingInventory, player.getCommandSenderWorld()); + .getRecipeFor(RecipeType.CRAFTING, craftingInventory.asCraftInput(), player.getCommandSenderWorld()); if (!optional.isPresent()) { if (ghostInventory.getStackInSlot(9) @@ -84,26 +86,20 @@ public class BlueprintMenu extends GhostItemMenu { return; } - CraftingRecipe icraftingrecipe = optional.get(); - ItemStack itemstack = icraftingrecipe.assemble(craftingInventory, level.registryAccess()); + CraftingRecipe icraftingrecipe = optional.get().value(); + ItemStack itemstack = icraftingrecipe.assemble(craftingInventory.asCraftInput(), level.registryAccess()); ghostInventory.setStackInSlot(9, itemstack); contentHolder.inferredIcon = true; ItemStack toSend = itemstack.copy(); - toSend.getOrCreateTag() - .putBoolean("InferredFromRecipe", true); + toSend.set(AllDataComponents.INFERRED_FROM_RECIPE, true); serverplayerentity.connection.send(new ClientboundContainerSetSlotPacket(containerId, incrementStateId(), 36 + 9, toSend)); } @Override public void setItem(int slotId, int stateId, ItemStack stack) { if (slotId == 36 + 9) { - if (stack.hasTag()) { - contentHolder.inferredIcon = stack.getTag() - .getBoolean("InferredFromRecipe"); - stack.getTag() - .remove("InferredFromRecipe"); - } else - contentHolder.inferredIcon = false; + contentHolder.inferredIcon = stack.getOrDefault(AllDataComponents.INFERRED_FROM_RECIPE, false); + stack.remove(AllDataComponents.INFERRED_FROM_RECIPE); } super.setItem(slotId, stateId, stack); } @@ -125,7 +121,7 @@ public class BlueprintMenu extends GhostItemMenu { @Override @OnlyIn(Dist.CLIENT) - protected BlueprintSection createOnClient(FriendlyByteBuf extraData) { + protected BlueprintSection createOnClient(RegistryFriendlyByteBuf extraData) { int entityID = extraData.readVarInt(); int section = extraData.readVarInt(); Entity entityByID = Minecraft.getInstance().level.getEntity(entityID); diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java index 4f2f60f470..441bd5769f 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java @@ -8,19 +8,20 @@ import java.util.Map; import java.util.Optional; import com.mojang.blaze3d.systems.RenderSystem; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllItems; import com.simibubi.create.content.equipment.blueprint.BlueprintEntity.BlueprintCraftingInventory; import com.simibubi.create.content.equipment.blueprint.BlueprintEntity.BlueprintSection; import com.simibubi.create.content.logistics.BigItemStack; -import com.simibubi.create.content.logistics.filter.AttributeFilterMenu.WhitelistMode; +import com.simibubi.create.content.logistics.filter.AttributeFilterWhitelistMode; import com.simibubi.create.content.logistics.filter.FilterItem; import com.simibubi.create.content.logistics.filter.FilterItemStack; import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute; import com.simibubi.create.content.logistics.item.filter.attribute.attributes.InTagAttribute; import com.simibubi.create.content.logistics.packager.InventorySummary; import com.simibubi.create.content.logistics.tableCloth.BlueprintOverlayShopContext; -import com.simibubi.create.content.logistics.tableCloth.TableClothBlockEntity; import com.simibubi.create.content.logistics.tableCloth.ShoppingListItem.ShoppingList; +import com.simibubi.create.content.logistics.tableCloth.TableClothBlockEntity; import com.simibubi.create.content.trains.track.TrackPlacement.PlacementInfo; import com.simibubi.create.foundation.gui.AllGuiTextures; @@ -32,35 +33,34 @@ import net.createmod.catnip.utility.Pair; import net.createmod.catnip.utility.lang.Components; import net.createmod.ponder.utility.LevelTickHolder; import net.minecraft.ChatFormatting; +import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.LayeredDraw; import net.minecraft.client.gui.screens.inventory.tooltip.TooltipRenderUtil; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.Item; +import net.minecraft.world.item.Item.TooltipContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.TooltipFlag; 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.GameType; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult.Type; -import net.minecraftforge.client.gui.overlay.ForgeGui; -import net.minecraftforge.client.gui.overlay.IGuiOverlay; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.tags.ITag; -import net.minecraftforge.registries.tags.ITagManager; +import net.neoforged.neoforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.items.ItemStackHandler; public class BlueprintOverlayRenderer { - public static final IGuiOverlay OVERLAY = BlueprintOverlayRenderer::renderOverlay; + public static final LayeredDraw.Layer OVERLAY = BlueprintOverlayRenderer::renderOverlay; static boolean active; static boolean empty; @@ -125,7 +125,7 @@ public class BlueprintOverlayRenderer { int pavement = info.requiredPavement; while (pavement > 0) { - ingredients.add(Pair.of(ItemHandlerHelper.copyStackWithSize(pavementItem, Math.min(64, pavement)), + ingredients.add(Pair.of(pavementItem.copyWithCount(Math.min(64, pavement)), info.hasRequiredPavement)); pavement -= 64; } @@ -183,7 +183,7 @@ public class BlueprintOverlayRenderer { for (int i = 0; i < player.getInventory().items.size(); i++) { ItemStack item = player.getInventory() .getItem(i); - if (item.isEmpty() || !ItemHandlerHelper.canItemStacksStack(item, entry.stack)) + if (item.isEmpty() || !ItemStack.isSameItemSameComponents(item, entry.stack)) continue; itemsPresent += item.getCount(); } @@ -228,7 +228,7 @@ public class BlueprintOverlayRenderer { .copy()); int amountCrafted = 0; - Optional recipe = Optional.empty(); + Optional> recipe = Optional.empty(); Map craftingGrid = new HashMap<>(); ingredients.clear(); ItemStackHandler missingItems = new ItemStackHandler(64); @@ -266,9 +266,9 @@ public class BlueprintOverlayRenderer { CraftingContainer craftingInventory = new BlueprintCraftingInventory(craftingGrid); if (!recipe.isPresent()) recipe = mc.level.getRecipeManager() - .getRecipeFor(RecipeType.CRAFTING, craftingInventory, mc.level); - ItemStack resultFromRecipe = recipe.filter(r -> r.matches(craftingInventory, mc.level)) - .map(r -> r.assemble(craftingInventory, mc.level.registryAccess())) + .getRecipeFor(RecipeType.CRAFTING, craftingInventory.asCraftInput(), mc.level); + ItemStack resultFromRecipe = recipe.filter(r -> r.value().matches(craftingInventory.asCraftInput(), mc.level)) + .map(r -> r.value().assemble(craftingInventory.asCraftInput(), mc.level.registryAccess())) .orElse(ItemStack.EMPTY); if (resultFromRecipe.isEmpty()) { @@ -323,7 +323,7 @@ public class BlueprintOverlayRenderer { } } - public static void renderOverlay(ForgeGui gui, GuiGraphics graphics, float partialTicks, int width, int height) { + public static void renderOverlay(GuiGraphics guiGraphics, DeltaTracker deltaTracker) { Minecraft mc = Minecraft.getInstance(); if (mc.options.hideGui || mc.screen != null) return; @@ -342,17 +342,17 @@ public class BlueprintOverlayRenderer { w += 30; } - int x = (width - w) / 2; - int y = (int) (height - 100); + int x = (guiGraphics.guiWidth() - w) / 2; + int y = guiGraphics.guiHeight() - 100; if (shopContext != null) { - TooltipRenderUtil.renderTooltipBackground(graphics, x - 2, y + 1, w + 4, 19, 0, 0x55_000000, 0x55_000000, 0, + TooltipRenderUtil.renderTooltipBackground(guiGraphics, x - 2, y + 1, w + 4, 19, 0, 0x55_000000, 0x55_000000, 0, 0); - AllGuiTextures.TRADE_OVERLAY.render(graphics, width / 2 - 48, y - 19); + AllGuiTextures.TRADE_OVERLAY.render(guiGraphics, guiGraphics.guiWidth() / 2 - 48, y - 19); if (shopContext.purchases() > 0) { - graphics.renderItem(AllItems.SHOPPING_LIST.asStack(), width / 2 + 20, y - 20); - graphics.drawString(mc.font, Components.literal("x" + shopContext.purchases()), width / 2 + 20 + 16, + guiGraphics.renderItem(AllItems.SHOPPING_LIST.asStack(), guiGraphics.guiWidth() / 2 + 20, y - 20); + guiGraphics.drawString(mc.font, Components.literal("x" + shopContext.purchases()), guiGraphics.guiWidth() / 2 + 20 + 16, y - 20 + 4, 0xff_eeeeee, true); } } @@ -360,11 +360,11 @@ public class BlueprintOverlayRenderer { // Ingredients for (Pair pair : ingredients) { RenderSystem.enableBlend(); - (pair.getSecond() ? AllGuiTextures.HOTSLOT_ACTIVE : AllGuiTextures.HOTSLOT).render(graphics, x, y); + (pair.getSecond() ? AllGuiTextures.HOTSLOT_ACTIVE : AllGuiTextures.HOTSLOT).render(guiGraphics, x, y); ItemStack itemStack = pair.getFirst(); String count = shopContext != null && !shopContext.checkout() || pair.getSecond() ? null : ChatFormatting.GOLD.toString() + itemStack.getCount(); - drawItemStack(graphics, mc, x, y, itemStack, count); + drawItemStack(guiGraphics, mc, x, y, itemStack, count); x += 21; } @@ -375,24 +375,24 @@ public class BlueprintOverlayRenderer { x += 5; RenderSystem.enableBlend(); if (invalidShop) - AllGuiTextures.HOTSLOT_ARROW_BAD.render(graphics, x, y + 4); + AllGuiTextures.HOTSLOT_ARROW_BAD.render(guiGraphics, x, y + 4); else - AllGuiTextures.HOTSLOT_ARROW.render(graphics, x, y + 4); + AllGuiTextures.HOTSLOT_ARROW.render(guiGraphics, x, y + 4); x += 25; // Outputs if (results.isEmpty()) { - AllGuiTextures.HOTSLOT.render(graphics, x, y); + AllGuiTextures.HOTSLOT.render(guiGraphics, x, y); GuiGameElement.of(Items.BARRIER) .at(x + 3, y + 3) - .render(graphics); + .render(guiGraphics); } else { for (ItemStack result : results) { AllGuiTextures slot = resultCraftable ? AllGuiTextures.HOTSLOT_SUPER_ACTIVE : AllGuiTextures.HOTSLOT; if (!invalidShop && shopContext != null && shopContext.stockLevel() > shopContext.purchases()) slot = AllGuiTextures.HOTSLOT_ACTIVE; - slot.render(graphics, resultCraftable ? x - 1 : x, resultCraftable ? y - 1 : y); - drawItemStack(graphics, mc, x, y, result, null); + slot.render(guiGraphics, resultCraftable ? x - 1 : x, resultCraftable ? y - 1 : y); + drawItemStack(guiGraphics, mc, x, y, result, null); x += 21; } } @@ -402,16 +402,16 @@ public class BlueprintOverlayRenderer { for (boolean count : Iterate.trueAndFalse) for (int i = 0; i < results.size(); i++) { ItemStack result = results.get(i); - List tooltipLines = result.getTooltipLines(mc.player, TooltipFlag.NORMAL); + List tooltipLines = result.getTooltipLines(TooltipContext.of(mc.level), mc.player, TooltipFlag.NORMAL); if (tooltipLines.size() <= 1) continue; if (count) { cycle++; continue; } - if ((gui.getGuiTicks() / 40) % cycle != i) + if ((mc.gui.getGuiTicks() / 40) % cycle != i) continue; - graphics.renderComponentTooltip(gui.getFont(), tooltipLines, mc.getWindow() + guiGraphics.renderComponentTooltip(mc.gui.getFont(), tooltipLines, mc.getWindow() .getGuiScaledWidth(), mc.getWindow() .getGuiScaledHeight()); @@ -438,9 +438,7 @@ public class BlueprintOverlayRenderer { private static ItemStack[] getItemsMatchingFilter(ItemStack filter) { return cachedRenderedFilters.computeIfAbsent(filter, itemStack -> { - CompoundTag tag = itemStack.getOrCreateTag(); - - if (AllItems.FILTER.isIn(itemStack) && !tag.getBoolean("Blacklist")) { + if (AllItems.FILTER.isIn(itemStack) && !itemStack.getOrDefault(AllDataComponents.FILTER_ITEMS_BLACKLIST, false)) { ItemStackHandler filterItems = FilterItem.getFilterItems(itemStack); List list = new ArrayList<>(); for (int slot = 0; slot < filterItems.getSlots(); slot++) { @@ -452,24 +450,17 @@ public class BlueprintOverlayRenderer { } if (AllItems.ATTRIBUTE_FILTER.isIn(itemStack)) { - WhitelistMode whitelistMode = WhitelistMode.values()[tag.getInt("WhitelistMode")]; - ListTag attributes = tag.getList("MatchedAttributes", net.minecraft.nbt.Tag.TAG_COMPOUND); - if (whitelistMode == WhitelistMode.WHITELIST_DISJ && attributes.size() == 1) { - ItemAttribute fromNBT = ItemAttribute.loadStatic((CompoundTag) attributes.get(0)); - if (fromNBT instanceof InTagAttribute inTag) { - ITagManager tagManager = ForgeRegistries.ITEMS.tags(); - if (tagManager.isKnownTagName(inTag.tag)) { - ITag taggedItems = tagManager.getTag(inTag.tag); - if (!taggedItems.isEmpty()) { - ItemStack[] stacks = new ItemStack[taggedItems.size()]; - int i = 0; - for (Item item : taggedItems) { - stacks[i] = new ItemStack(item); - i++; - } - return stacks; - } + AttributeFilterWhitelistMode whitelistMode = itemStack.get(AllDataComponents.ATTRIBUTE_FILTER_WHITELIST_MODE); + List attributes = itemStack.get(AllDataComponents.ATTRIBUTE_FILTER_MATCHED_ATTRIBUTES); + //noinspection DataFlowIssue + if (whitelistMode == AttributeFilterWhitelistMode.WHITELIST_DISJ && attributes.size() == 1) { + ItemAttribute attribute = attributes.getFirst().attribute(); + if (attribute instanceof InTagAttribute inTag) { + List stacks = new ArrayList<>(); + for (Holder holder : BuiltInRegistries.ITEM.getTagOrEmpty(inTag.tag())) { + stacks.add(new ItemStack(holder.value())); } + return stacks.toArray(ItemStack[]::new); } } } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintScreen.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintScreen.java index b8d1b393e1..ba93df996a 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintScreen.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintScreen.java @@ -1,7 +1,6 @@ package com.simibubi.create.content.equipment.blueprint; import com.google.common.collect.ImmutableList; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllPartialModels; import com.simibubi.create.content.logistics.filter.FilterScreenPacket; import com.simibubi.create.content.logistics.filter.FilterScreenPacket.Option; @@ -9,6 +8,7 @@ import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.gui.AllIcons; import com.simibubi.create.foundation.gui.menu.AbstractSimiContainerScreen; import com.simibubi.create.foundation.gui.widget.IconButton; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.CreateLang; import net.createmod.catnip.gui.element.GuiGameElement; import net.minecraft.ChatFormatting; @@ -160,7 +160,7 @@ public class BlueprintScreen extends AbstractSimiContainerScreen protected void contentsCleared() {} protected void sendOptionUpdate(Option option) { - AllPackets.getChannel().sendToServer(new FilterScreenPacket(option)); + CatnipServices.NETWORK.sendToServer(new FilterScreenPacket(option)); } @Override diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlock.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlock.java index 77a496d4c9..61005999f7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlock.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlock.java @@ -2,7 +2,10 @@ package com.simibubi.create.content.equipment.clipboard; import java.util.List; +import org.jetbrains.annotations.NotNull; + import com.google.common.collect.ImmutableList; +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllShapes; import com.simibubi.create.content.equipment.wrench.IWrenchable; @@ -10,10 +13,10 @@ import com.simibubi.create.foundation.block.IBE; import com.simibubi.create.foundation.block.ProperWaterloggedBlock; import net.createmod.catnip.gui.ScreenOpener; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -34,18 +37,20 @@ import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.common.util.FakePlayer; public class ClipboardBlock extends FaceAttachedHorizontalDirectionalBlock implements IBE, IWrenchable, ProperWaterloggedBlock { public static final BooleanProperty WRITTEN = BooleanProperty.create("written"); + public static final MapCodec CODEC = simpleCodec(ClipboardBlock::new); + public ClipboardBlock(Properties pProperties) { super(pProperties); registerDefaultState(defaultBlockState().setValue(WATERLOGGED, false) @@ -65,8 +70,7 @@ public class ClipboardBlock extends FaceAttachedHorizontalDirectionalBlock if (stateForPlacement.getValue(FACE) != AttachFace.WALL) stateForPlacement = stateForPlacement.setValue(FACING, stateForPlacement.getValue(FACING) .getOpposite()); - return withWater(stateForPlacement, pContext).setValue(WRITTEN, pContext.getItemInHand() - .hasTag()); + return withWater(stateForPlacement, pContext).setValue(WRITTEN, !pContext.getItemInHand().isComponentsPatchEmpty()); } @Override @@ -84,16 +88,15 @@ public class ClipboardBlock extends FaceAttachedHorizontalDirectionalBlock } @Override - public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, - BlockHitResult pHit) { - if (pPlayer.isShiftKeyDown()) { - breakAndCollect(pState, pLevel, pPos, pPlayer); + protected InteractionResult useWithoutItem(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { + if (player.isShiftKeyDown()) { + breakAndCollect(state, level, pos, player); return InteractionResult.SUCCESS; } - return onBlockEntityUse(pLevel, pPos, cbe -> { - if (pLevel.isClientSide()) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> openScreen(pPlayer, cbe.dataContainer, pPos)); + return onBlockEntityUse(level, pos, cbe -> { + if (level.isClientSide()) + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> openScreen(player, cbe.dataContainer, pos)); return InteractionResult.SUCCESS; }); } @@ -122,19 +125,21 @@ public class ClipboardBlock extends FaceAttachedHorizontalDirectionalBlock } @Override - public ItemStack getCloneItemStack(BlockGetter world, BlockPos pos, BlockState state) { - if (world.getBlockEntity(pos) instanceof ClipboardBlockEntity cbe) + public ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) { + if (level.getBlockEntity(pos) instanceof ClipboardBlockEntity cbe) return cbe.dataContainer; return new ItemStack(this); } @Override - public void playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) { + public BlockState playerWillDestroy(Level pLevel, BlockPos pPos, BlockState pState, Player pPlayer) { if (!(pLevel.getBlockEntity(pPos) instanceof ClipboardBlockEntity cbe)) - return; + return pState; if (pLevel.isClientSide || pPlayer.isCreative()) - return; + return pState; Block.popResource(pLevel, pPos, cbe.dataContainer.copy()); + + return pState; } @Override @@ -168,4 +173,8 @@ public class ClipboardBlock extends FaceAttachedHorizontalDirectionalBlock return AllBlockEntityTypes.CLIPBOARD.get(); } + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockEntity.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockEntity.java index 03bc8f9b2a..8498ec78f9 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockEntity.java @@ -8,16 +8,17 @@ import com.simibubi.create.content.logistics.AddressEditBoxHelper; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ClipboardBlockEntity extends SmartBlockEntity { @@ -40,12 +41,12 @@ public class ClipboardBlockEntity extends SmartBlockEntity { notifyUpdate(); updateWrittenState(); } - + @Override public void lazyTick() { super.lazyTick(); if (level.isClientSide()) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::advertiseToAddressHelper); + CatnipServices.PLATFORM.executeOnClientOnly(() -> this::advertiseToAddressHelper); } public void updateWrittenState() { @@ -55,7 +56,7 @@ public class ClipboardBlockEntity extends SmartBlockEntity { if (level.isClientSide()) return; boolean isWritten = blockState.getValue(ClipboardBlock.WRITTEN); - boolean shouldBeWritten = dataContainer.getTag() != null; + boolean shouldBeWritten = !dataContainer.getComponentsPatch().isEmpty(); if (isWritten == shouldBeWritten) return; level.setBlockAndUpdate(worldPosition, blockState.setValue(ClipboardBlock.WRITTEN, shouldBeWritten)); @@ -65,22 +66,22 @@ public class ClipboardBlockEntity extends SmartBlockEntity { public void addBehaviours(List behaviours) {} @Override - protected void write(CompoundTag tag, boolean clientPacket) { - super.write(tag, clientPacket); - tag.put("Item", dataContainer.serializeNBT()); + protected void write(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.write(tag, registries, clientPacket); + tag.put("Item", dataContainer.saveOptional(registries)); if (clientPacket && lastEdit != null) tag.putUUID("LastEdit", lastEdit); } @Override - protected void read(CompoundTag tag, boolean clientPacket) { - super.read(tag, clientPacket); - dataContainer = ItemStack.of(tag.getCompound("Item")); + protected void read(CompoundTag tag, HolderLookup.Provider registries, boolean clientPacket) { + super.read(tag, registries, clientPacket); + dataContainer = ItemStack.parseOptional(registries, tag.getCompound("Item")); if (!AllBlocks.CLIPBOARD.isIn(dataContainer)) dataContainer = AllBlocks.CLIPBOARD.asStack(); if (clientPacket) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> readClientSide(tag)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> readClientSide(tag)); } @OnlyIn(Dist.CLIENT) @@ -95,7 +96,7 @@ public class ClipboardBlockEntity extends SmartBlockEntity { return; cs.reopenWith(dataContainer); } - + @OnlyIn(Dist.CLIENT) private void advertiseToAddressHelper() { AddressEditBoxHelper.advertiseClipboard(this); diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockItem.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockItem.java index 9f3314a2a6..992f4213af 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardBlockItem.java @@ -2,10 +2,12 @@ package com.simibubi.create.content.equipment.clipboard; import javax.annotation.Nonnull; +import com.simibubi.create.AllDataComponents; + import net.createmod.catnip.gui.ScreenOpener; +import net.createmod.catnip.platform.CatnipServices; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; @@ -16,10 +18,8 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ClipboardBlockItem extends BlockItem { @@ -45,7 +45,7 @@ public class ClipboardBlockItem extends BlockItem { return false; if (!(pLevel.getBlockEntity(pPos) instanceof ClipboardBlockEntity cbe)) return false; - cbe.dataContainer = ItemHandlerHelper.copyStackWithSize(pStack, 1); + cbe.dataContainer = pStack.copyWithCount(1); cbe.notifyUpdate(); return true; } @@ -59,10 +59,8 @@ public class ClipboardBlockItem extends BlockItem { player.getCooldowns() .addCooldown(heldItem.getItem(), 10); if (world.isClientSide) - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> openScreen(player, heldItem)); - CompoundTag tag = heldItem.getOrCreateTag(); - tag.putInt("Type", ClipboardOverrides.ClipboardType.EDITING.ordinal()); - heldItem.setTag(tag); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> openScreen(player, heldItem)); + heldItem.set(AllDataComponents.CLIPBOARD_TYPE, ClipboardOverrides.ClipboardType.EDITING); return InteractionResultHolder.success(heldItem); } @@ -74,7 +72,7 @@ public class ClipboardBlockItem extends BlockItem { } public void registerModelOverrides() { - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> ClipboardOverrides.registerModelOverridesClient(this)); + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> ClipboardOverrides.registerModelOverridesClient(this)); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardCloneable.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardCloneable.java index fcd783b900..0eca441dd9 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardCloneable.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardCloneable.java @@ -1,15 +1,16 @@ package com.simibubi.create.content.equipment.clipboard; +import org.jetbrains.annotations.NotNull; + import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.player.Player; public interface ClipboardCloneable { + String getClipboardKey(); - public String getClipboardKey(); - - public boolean writeToClipboard(CompoundTag tag, Direction side); - - public boolean readFromClipboard(CompoundTag tag, Player player, Direction side, boolean simulate); - + boolean writeToClipboard(@NotNull HolderLookup.Provider registries, CompoundTag tag, Direction side); + + boolean readFromClipboard(@NotNull HolderLookup.Provider registries, CompoundTag tag, Player player, Direction side, boolean simulate); } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEditPacket.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEditPacket.java index 3512e2fb19..6352e12fb9 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEditPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEditPacket.java @@ -1,77 +1,65 @@ package com.simibubi.create.content.equipment.clipboard; +import org.jetbrains.annotations.Nullable; + import com.simibubi.create.AllBlocks; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllDataComponents; +import com.simibubi.create.AllPackets; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.createmod.catnip.net.base.ServerboundPacketPayload; import com.simibubi.create.foundation.utility.CreateNBTProcessors; - import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -import net.minecraftforge.network.NetworkEvent.Context; -import javax.annotation.Nullable; - -public class ClipboardEditPacket extends SimplePacketBase { - - private int hotbarSlot; - private CompoundTag data; - private BlockPos targetedBlock; - - public ClipboardEditPacket(int hotbarSlot, CompoundTag data, @Nullable BlockPos targetedBlock) { - this.hotbarSlot = hotbarSlot; - this.data = data; - this.targetedBlock = targetedBlock; - } - - public ClipboardEditPacket(FriendlyByteBuf buffer) { - hotbarSlot = buffer.readVarInt(); - data = buffer.readNbt(); - if (buffer.readBoolean()) - targetedBlock = buffer.readBlockPos(); - } +// TODO - Does this even work? +// Also make sure to filter any data through CreateNBTProcessors.clipboardProcessor +public record ClipboardEditPacket(int hotbarSlot, boolean isEmpty, @Nullable BlockPos targetedBlock) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_INT, ClipboardEditPacket::hotbarSlot, + ByteBufCodecs.BOOL, ClipboardEditPacket::isEmpty, + CatnipStreamCodecBuilders.nullable(BlockPos.STREAM_CODEC), ClipboardEditPacket::targetedBlock, + ClipboardEditPacket::new + ); @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeVarInt(hotbarSlot); - buffer.writeNbt(data); - buffer.writeBoolean(targetedBlock != null); - if (targetedBlock != null) - buffer.writeBlockPos(targetedBlock); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - // Get rid of any unsafe data - data = CreateNBTProcessors.clipboardProcessor(data); - - ServerPlayer sender = context.getSender(); - - if (targetedBlock != null) { - Level world = sender.level(); - if (world == null || !world.isLoaded(targetedBlock)) - return; - if (!targetedBlock.closerThan(sender.blockPosition(), 20)) - return; - if (world.getBlockEntity(targetedBlock) instanceof ClipboardBlockEntity cbe) { - cbe.dataContainer.setTag(data.isEmpty() ? null : data); - cbe.onEditedBy(sender); - } + public void handle(ServerPlayer sender) { + if (targetedBlock != null) { + Level world = sender.level(); + if (!world.isLoaded(targetedBlock)) return; + if (!targetedBlock.closerThan(sender.blockPosition(), 20)) + return; + if (world.getBlockEntity(targetedBlock) instanceof ClipboardBlockEntity cbe) { + if (isEmpty) clearComponents(cbe.dataContainer); + cbe.onEditedBy(sender); } + return; + } - ItemStack itemStack = sender.getInventory() + ItemStack itemStack = sender.getInventory() .getItem(hotbarSlot); - if (!AllBlocks.CLIPBOARD.isIn(itemStack)) - return; - itemStack.setTag(data.isEmpty() ? null : data); - }); - - return true; + if (!AllBlocks.CLIPBOARD.isIn(itemStack)) + return; + if (isEmpty) clearComponents(itemStack); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.CLIPBOARD_EDIT; + } + + private static void clearComponents(ItemStack stack) { + stack.remove(AllDataComponents.CLIPBOARD_TYPE); + stack.remove(AllDataComponents.CLIPBOARD_PAGES); + stack.remove(AllDataComponents.CLIPBOARD_READ_ONLY); + stack.remove(AllDataComponents.CLIPBOARD_COPIED_VALUES); + stack.remove(AllDataComponents.CLIPBOARD_PREVIOUSLY_OPENED_PAGE); + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEntry.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEntry.java index c8676d4f24..b2a2a22349 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEntry.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardEntry.java @@ -3,14 +3,49 @@ package com.simibubi.create.content.equipment.clipboard; import java.util.ArrayList; import java.util.List; -import net.createmod.catnip.utility.NBTHelper; +import com.mojang.serialization.Codec; + +import com.mojang.serialization.codecs.RecordCodecBuilder; + +import com.simibubi.create.AllDataComponents; + +import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemStack; public class ClipboardEntry { + public static final Codec CODEC = RecordCodecBuilder.create(i -> i.group( + Codec.BOOL.fieldOf("checked").forGetter(c -> c.checked), + ComponentSerialization.CODEC.fieldOf("text").forGetter(c -> c.text), + ItemStack.OPTIONAL_CODEC.fieldOf("icon").forGetter(c -> c.icon), + Codec.INT.fieldOf("item_amount").forGetter(c -> c.itemAmount) + ).apply(i, (checked, text, icon, itemAmount) -> { + ClipboardEntry entry = new ClipboardEntry(checked, text.copy()); + if (!icon.isEmpty()) + entry.displayItem(icon, itemAmount); + + return entry; + })); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.BOOL, c -> c.checked, + ComponentSerialization.STREAM_CODEC, c -> c.text, + ItemStack.OPTIONAL_STREAM_CODEC, c -> c.icon, + ByteBufCodecs.INT, c -> c.itemAmount, + (checked, text, icon, itemAmount) -> { + ClipboardEntry entry = new ClipboardEntry(checked, text.copy()); + if (!icon.isEmpty()) + entry.displayItem(icon, itemAmount); + + return entry; + } + ); public boolean checked; public MutableComponent text; @@ -30,50 +65,55 @@ public class ClipboardEntry { } public static List> readAll(ItemStack clipboardItem) { - CompoundTag tag = clipboardItem.getTag(); - if (tag == null) - return new ArrayList<>(); - return NBTHelper.readCompoundList(tag.getList("Pages", Tag.TAG_COMPOUND), pageTag -> NBTHelper - .readCompoundList(pageTag.getList("Entries", Tag.TAG_COMPOUND), ClipboardEntry::readNBT)); + return clipboardItem.getOrDefault(AllDataComponents.CLIPBOARD_PAGES, new ArrayList<>()); } public static List getLastViewedEntries(ItemStack heldItem) { List> pages = ClipboardEntry.readAll(heldItem); if (pages.isEmpty()) return new ArrayList<>(); - int page = heldItem.getTag() == null ? 0 - : Math.min(heldItem.getTag() - .getInt("PreviouslyOpenedPage"), pages.size() - 1); + int page = !heldItem.has(AllDataComponents.CLIPBOARD_PREVIOUSLY_OPENED_PAGE) ? 0 + : Math.min(heldItem.getOrDefault(AllDataComponents.CLIPBOARD_PREVIOUSLY_OPENED_PAGE, 0), pages.size() - 1); List entries = pages.get(page); return entries; } public static void saveAll(List> entries, ItemStack clipboardItem) { - CompoundTag tag = clipboardItem.getOrCreateTag(); - tag.put("Pages", NBTHelper.writeCompoundList(entries, list -> { - CompoundTag pageTag = new CompoundTag(); - pageTag.put("Entries", NBTHelper.writeCompoundList(list, ClipboardEntry::writeNBT)); - return pageTag; - })); + clipboardItem.set(AllDataComponents.CLIPBOARD_PAGES, entries); } public CompoundTag writeNBT() { CompoundTag nbt = new CompoundTag(); nbt.putBoolean("Checked", checked); - nbt.putString("Text", Component.Serializer.toJson(text)); + nbt.putString("Text", Component.Serializer.toJson(text, RegistryAccess.EMPTY)); if (icon.isEmpty()) return nbt; - nbt.put("Icon", icon.serializeNBT()); + nbt.put("Icon", icon.saveOptional(RegistryAccess.EMPTY)); nbt.putInt("ItemAmount", itemAmount); return nbt; } public static ClipboardEntry readNBT(CompoundTag tag) { ClipboardEntry clipboardEntry = - new ClipboardEntry(tag.getBoolean("Checked"), Component.Serializer.fromJson(tag.getString("Text"))); + new ClipboardEntry(tag.getBoolean("Checked"), Component.Serializer.fromJson(tag.getString("Text"), RegistryAccess.EMPTY)); if (tag.contains("Icon")) - clipboardEntry.displayItem(ItemStack.of(tag.getCompound("Icon")), tag.getInt("ItemAmount")); + clipboardEntry.displayItem(ItemStack.parseOptional(RegistryAccess.EMPTY, tag.getCompound("Icon")), tag.getInt("ItemAmount")); return clipboardEntry; } + @Override + public final boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ClipboardEntry that)) return false; + + return checked == that.checked && text.equals(that.text) && icon.equals(that.icon); + } + + @Override + public int hashCode() { + int result = Boolean.hashCode(checked); + result = 31 * result + text.hashCode(); + result = 31 * result + icon.hashCode(); + return result; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardOverrides.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardOverrides.java index 5d8cf71fe4..aa9359ff7b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardOverrides.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardOverrides.java @@ -1,55 +1,70 @@ package com.simibubi.create.content.equipment.clipboard; +import org.jetbrains.annotations.NotNull; + +import com.mojang.serialization.Codec; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.Create; import com.tterrag.registrate.providers.DataGenContext; import com.tterrag.registrate.providers.RegistrateItemModelProvider; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; +import net.createmod.catnip.utility.lang.Lang; import net.minecraft.client.renderer.item.ItemProperties; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.generators.ItemModelBuilder; -import net.minecraftforge.client.model.generators.ModelFile.UncheckedModelFile; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.model.generators.ItemModelBuilder; +import net.neoforged.neoforge.client.model.generators.ModelFile.UncheckedModelFile; public class ClipboardOverrides { - public enum ClipboardType { + public enum ClipboardType implements StringRepresentable { EMPTY("empty_clipboard"), WRITTEN("clipboard"), EDITING("clipboard_and_quill"); + public static final Codec CODEC = StringRepresentable.fromValues(ClipboardType::values); + public static final StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(ClipboardType.class); + public String file; public static ResourceLocation ID = Create.asResource("clipboard_type"); - private ClipboardType(String file) { + ClipboardType(String file) { this.file = file; } + + @Override + public @NotNull String getSerializedName() { + return Lang.asId(name()); + } } public static void switchTo(ClipboardType type, ItemStack clipboardItem) { - CompoundTag tag = clipboardItem.getOrCreateTag(); - tag.putInt("Type", type.ordinal()); + clipboardItem.set(AllDataComponents.CLIPBOARD_TYPE, type); } @OnlyIn(Dist.CLIENT) public static void registerModelOverridesClient(ClipboardBlockItem item) { - ItemProperties.register(item, ClipboardType.ID, (pStack, pLevel, pEntity, pSeed) -> { - CompoundTag tag = pStack.getTag(); - return tag == null ? 0 : tag.getInt("Type"); - }); + ItemProperties.register(item, ClipboardType.ID, (pStack, pLevel, pEntity, pSeed) -> + pStack.getOrDefault(AllDataComponents.CLIPBOARD_TYPE, ClipboardType.EMPTY).ordinal() + ); } public static ItemModelBuilder addOverrideModels(DataGenContext c, RegistrateItemModelProvider p) { - ItemModelBuilder builder = p.generated(() -> c.get()); - for (int i = 0; i < ClipboardType.values().length; i++) { + ItemModelBuilder builder = p.generated(c::get); + for (ClipboardType type : ClipboardType.values()) { + int i = type.ordinal(); builder.override() - .predicate(ClipboardType.ID, i) - .model(p.getBuilder(c.getName() + "_" + i) - .parent(new UncheckedModelFile("item/generated")) - .texture("layer0", Create.asResource("item/" + ClipboardType.values()[i].file))) - .end(); + .predicate(ClipboardType.ID, i) + .model(p.getBuilder(c.getName() + "_" + i) + .parent(new UncheckedModelFile("item/generated")) + .texture("layer0", Create.asResource("item/" + type.file))) + .end(); } return builder; } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardScreen.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardScreen.java index f731491955..bec8eb13d1 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardScreen.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardScreen.java @@ -14,23 +14,25 @@ import com.google.common.collect.Lists; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; import com.simibubi.create.AllBlocks; -import com.simibubi.create.AllPackets; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.content.equipment.clipboard.ClipboardOverrides.ClipboardType; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.gui.AllIcons; import com.simibubi.create.foundation.gui.widget.IconButton; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.CreateLang; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import net.createmod.catnip.gui.AbstractSimiScreen; import net.createmod.catnip.utility.lang.Components; -import net.minecraft.SharedConstants; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.StringSplitter; @@ -44,15 +46,15 @@ import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; import net.minecraft.util.FormattedCharSequence; import net.minecraft.util.Mth; +import net.minecraft.util.StringUtil; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ClipboardScreen extends AbstractSimiScreen { @@ -93,9 +95,7 @@ public class ClipboardScreen extends AbstractSimiScreen { if (pages.isEmpty()) pages.add(new ArrayList<>()); if (clearBtn == null) { - currentPage = item.getTag() == null ? 0 - : item.getTag() - .getInt("PreviouslyOpenedPage"); + currentPage = item.getOrDefault(AllDataComponents.CLIPBOARD_PREVIOUSLY_OPENED_PAGE, 0); currentPage = Mth.clamp(currentPage, 0, pages.size() - 1); } currentEntries = pages.get(currentPage); @@ -106,8 +106,7 @@ public class ClipboardScreen extends AbstractSimiScreen { editContext = new TextFieldHelper(this::getCurrentEntryText, this::setCurrentEntryText, this::getClipboard, this::setClipboard, this::validateTextForEntry); editingIndex = startEmpty ? 0 : -1; - readonly = item.getTag() != null && item.getTag() - .getBoolean("Readonly"); + readonly = item.has(AllDataComponents.CLIPBOARD_READ_ONLY); if (readonly) editingIndex = -1; if (clearBtn != null) @@ -345,8 +344,7 @@ public class ClipboardScreen extends AbstractSimiScreen { for (int i = 0; i < pages.size(); i++) if (pages.get(i) == currentEntries) - item.getOrCreateTag() - .putInt("PreviouslyOpenedPage", i); + item.set(AllDataComponents.CLIPBOARD_PREVIOUSLY_OPENED_PAGE, i); send(); @@ -363,10 +361,7 @@ public class ClipboardScreen extends AbstractSimiScreen { private void send() { ClipboardEntry.saveAll(pages, item); ClipboardOverrides.switchTo(ClipboardType.WRITTEN, item); - if (pages.isEmpty()) - item.setTag(new CompoundTag()); - AllPackets.getChannel() - .sendToServer(new ClipboardEditPacket(targetSlot, item.getOrCreateTag(), targetedBlock)); + CatnipServices.NETWORK.sendToServer(new ClipboardEditPacket(targetSlot, pages.isEmpty(), targetedBlock)); } @Override @@ -375,8 +370,8 @@ public class ClipboardScreen extends AbstractSimiScreen { } @Override - public boolean mouseScrolled(double pMouseX, double pMouseY, double pDelta) { - changePage(pDelta < 0); + public boolean mouseScrolled(double pMouseX, double pMouseY, double pScrollX, double pScrollY) { + changePage(pScrollY < 0); return true; } @@ -404,7 +399,7 @@ public class ClipboardScreen extends AbstractSimiScreen { public boolean charTyped(char pCodePoint, int pModifiers) { if (super.charTyped(pCodePoint, pModifiers)) return true; - if (!SharedConstants.isAllowedChatCharacter(pCodePoint)) + if (!StringUtil.isAllowedChatCharacter(pCodePoint)) return false; if (editingIndex == -1) return false; @@ -547,30 +542,27 @@ public class ClipboardScreen extends AbstractSimiScreen { private void renderHighlight(Rect2i[] pSelected) { Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferbuilder = tesselator.getBuilder(); + BufferBuilder bufferbuilder = tesselator.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); RenderSystem.setShader(GameRenderer::getPositionShader); RenderSystem.setShaderColor(0.0F, 0.0F, 255.0F, 255.0F); // RenderSystem.disableTexture(); RenderSystem.enableColorLogicOp(); RenderSystem.logicOp(GlStateManager.LogicOp.OR_REVERSE); - bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION); for (Rect2i rect2i : pSelected) { int i = rect2i.getX(); int j = rect2i.getY(); int k = i + rect2i.getWidth(); int l = j + rect2i.getHeight(); - bufferbuilder.vertex((double) i, (double) l, 0.0D) - .endVertex(); - bufferbuilder.vertex((double) k, (double) l, 0.0D) - .endVertex(); - bufferbuilder.vertex((double) k, (double) j, 0.0D) - .endVertex(); - bufferbuilder.vertex((double) i, (double) j, 0.0D) - .endVertex(); + bufferbuilder.addVertex(i, l, 0); + bufferbuilder.addVertex(k, l, 0); + bufferbuilder.addVertex(k, j, 0); + bufferbuilder.addVertex(i, j, 0); } - tesselator.end(); + @Nullable MeshData meshData = bufferbuilder.build(); + if (meshData != null) + BufferUploader.drawWithShader(meshData); RenderSystem.disableColorLogicOp(); // RenderSystem.enableTexture(); } diff --git a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardValueSettingsHandler.java b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardValueSettingsHandler.java index 8fd81e694e..9f758043ff 100644 --- a/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardValueSettingsHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/clipboard/ClipboardValueSettingsHandler.java @@ -6,6 +6,7 @@ import java.util.List; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.simibubi.create.AllBlocks; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.CreateClient; import com.simibubi.create.content.equipment.clipboard.ClipboardOverrides.ClipboardType; import com.simibubi.create.content.trains.track.TrackBlockOutline; @@ -28,19 +29,25 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.RenderHighlightEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.RenderHighlightEvent.Block; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.EntityInteract; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.LeftClickBlock; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickBlock; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem; @EventBusSubscriber public class ClipboardValueSettingsHandler { @SubscribeEvent @OnlyIn(Dist.CLIENT) - public static void drawCustomBlockSelection(RenderHighlightEvent.Block event) { + public static void drawCustomBlockSelection(Block event) { Minecraft mc = Minecraft.getInstance(); BlockHitResult target = event.getTarget(); BlockPos pos = target.getBlockPos(); @@ -58,7 +65,7 @@ public class ClipboardValueSettingsHandler { if (!(smartBE instanceof ClipboardBlockEntity) && !smartBE.getAllBehaviours() .stream() .anyMatch(b -> b instanceof ClipboardCloneable cc - && cc.writeToClipboard(new CompoundTag(), target.getDirection())) + && cc.writeToClipboard(mc.level.registryAccess(), new CompoundTag(), target.getDirection())) && !(smartBE instanceof ClipboardCloneable)) return; @@ -100,21 +107,20 @@ public class ClipboardValueSettingsHandler { return; } - CompoundTag tagElement = mc.player.getMainHandItem() - .getTagElement("CopiedValues"); + CompoundTag tagElement = mc.player.getMainHandItem().get(AllDataComponents.CLIPBOARD_COPIED_VALUES); boolean canCopy = smartBE.getAllBehaviours() .stream() .anyMatch(b -> b instanceof ClipboardCloneable cc - && cc.writeToClipboard(new CompoundTag(), target.getDirection())) + && cc.writeToClipboard(mc.level.registryAccess(), new CompoundTag(), target.getDirection())) || smartBE instanceof ClipboardCloneable ccbe - && ccbe.writeToClipboard(new CompoundTag(), target.getDirection()); + && ccbe.writeToClipboard(mc.level.registryAccess(), new CompoundTag(), target.getDirection()); boolean canPaste = tagElement != null && (smartBE.getAllBehaviours() .stream() - .anyMatch(b -> b instanceof ClipboardCloneable cc && cc.readFromClipboard( + .anyMatch(b -> b instanceof ClipboardCloneable cc && cc.readFromClipboard(mc.level.registryAccess(), tagElement.getCompound(cc.getClipboardKey()), mc.player, target.getDirection(), true)) - || smartBE instanceof ClipboardCloneable ccbe && ccbe.readFromClipboard( + || smartBE instanceof ClipboardCloneable ccbe && ccbe.readFromClipboard(mc.level.registryAccess(), tagElement.getCompound(ccbe.getClipboardKey()), mc.player, target.getDirection(), true)); if (!canCopy && !canPaste) @@ -131,12 +137,12 @@ public class ClipboardValueSettingsHandler { } @SubscribeEvent - public static void rightClickToCopy(PlayerInteractEvent.RightClickBlock event) { + public static void rightClickToCopy(RightClickBlock event) { interact(event, false); } @SubscribeEvent - public static void leftClickToPaste(PlayerInteractEvent.LeftClickBlock event) { + public static void leftClickToPaste(LeftClickBlock event) { interact(event, true); } @@ -156,8 +162,17 @@ public class ClipboardValueSettingsHandler { return; if (smartBE instanceof ClipboardBlockEntity cbe) { - event.setCanceled(true); - event.setCancellationResult(InteractionResult.SUCCESS); + if (event instanceof ICancellableEvent cancellableEvent) { + cancellableEvent.setCanceled(true); + + switch (event) { + case EntityInteractSpecific e -> e.setCancellationResult(InteractionResult.SUCCESS); + case EntityInteract e -> e.setCancellationResult(InteractionResult.SUCCESS); + case RightClickBlock e -> e.setCancellationResult(InteractionResult.SUCCESS); + case RightClickItem e -> e.setCancellationResult(InteractionResult.SUCCESS); + default -> {} + } + } if (!world.isClientSide()) { List> listTo = ClipboardEntry.readAll(itemStack); @@ -203,7 +218,7 @@ public class ClipboardValueSettingsHandler { return; } - CompoundTag tag = itemStack.getTagElement("CopiedValues"); + CompoundTag tag = itemStack.get(AllDataComponents.CLIPBOARD_COPIED_VALUES); if (paste && tag == null) return; if (!paste) @@ -218,11 +233,11 @@ public class ClipboardValueSettingsHandler { String clipboardKey = cc.getClipboardKey(); if (paste) { anySuccess |= - cc.readFromClipboard(tag.getCompound(clipboardKey), player, event.getFace(), world.isClientSide()); + cc.readFromClipboard(world.registryAccess(), tag.getCompound(clipboardKey), player, event.getFace(), world.isClientSide()); continue; } CompoundTag compoundTag = new CompoundTag(); - boolean success = cc.writeToClipboard(compoundTag, event.getFace()); + boolean success = cc.writeToClipboard(world.registryAccess(), compoundTag, event.getFace()); anySuccess |= success; if (success) tag.put(clipboardKey, compoundTag); @@ -232,11 +247,11 @@ public class ClipboardValueSettingsHandler { anyValid = true; String clipboardKey = ccbe.getClipboardKey(); if (paste) { - anySuccess |= ccbe.readFromClipboard(tag.getCompound(clipboardKey), player, event.getFace(), + anySuccess |= ccbe.readFromClipboard(world.registryAccess(), tag.getCompound(clipboardKey), player, event.getFace(), world.isClientSide()); } else { CompoundTag compoundTag = new CompoundTag(); - boolean success = ccbe.writeToClipboard(compoundTag, event.getFace()); + boolean success = ccbe.writeToClipboard(world.registryAccess(), compoundTag, event.getFace()); anySuccess |= success; if (success) tag.put(clipboardKey, compoundTag); @@ -246,8 +261,9 @@ public class ClipboardValueSettingsHandler { if (!anyValid) return; - event.setCanceled(true); - event.setCancellationResult(InteractionResult.SUCCESS); + ((ICancellableEvent) event).setCanceled(true); + if (event instanceof RightClickBlock rightClickBlock) + rightClickBlock.setCancellationResult(InteractionResult.SUCCESS); if (world.isClientSide()) return; @@ -264,8 +280,7 @@ public class ClipboardValueSettingsHandler { if (!paste) { ClipboardOverrides.switchTo(ClipboardType.WRITTEN, itemStack); - itemStack.getOrCreateTag() - .put("CopiedValues", tag); + itemStack.set(AllDataComponents.CLIPBOARD_COPIED_VALUES, tag); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripInteractionPacket.java b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripInteractionPacket.java index 0fe0ea532f..95c16bfaa2 100644 --- a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripInteractionPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripInteractionPacket.java @@ -1,19 +1,26 @@ package com.simibubi.create.content.equipment.extendoGrip; -import com.simibubi.create.foundation.networking.SimplePacketBase; -import net.minecraft.network.FriendlyByteBuf; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ExtendoGripInteractionPacket extends SimplePacketBase { - - private InteractionHand interactionHand; - private int target; - private Vec3 specificPoint; +public record ExtendoGripInteractionPacket(InteractionHand hand, int target, Vec3 point) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecBuilders.nullable(CatnipStreamCodecs.HAND), ExtendoGripInteractionPacket::hand, + ByteBufCodecs.INT, ExtendoGripInteractionPacket::target, + CatnipStreamCodecBuilders.nullable(CatnipStreamCodecs.VEC3), ExtendoGripInteractionPacket::point, + ExtendoGripInteractionPacket::new + ); public ExtendoGripInteractionPacket(Entity target) { this(target, null); @@ -24,56 +31,33 @@ public class ExtendoGripInteractionPacket extends SimplePacketBase { } public ExtendoGripInteractionPacket(Entity target, InteractionHand hand, Vec3 specificPoint) { - interactionHand = hand; - this.specificPoint = specificPoint; - this.target = target.getId(); - } - - public ExtendoGripInteractionPacket(FriendlyByteBuf buffer) { - target = buffer.readInt(); - int handId = buffer.readInt(); - interactionHand = handId == -1 ? null : InteractionHand.values()[handId]; - if (buffer.readBoolean()) - specificPoint = new Vec3(buffer.readDouble(), buffer.readDouble(), buffer.readDouble()); + this(hand, target.getId(), specificPoint); } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeInt(target); - buffer.writeInt(interactionHand == null ? -1 : interactionHand.ordinal()); - buffer.writeBoolean(specificPoint != null); - if (specificPoint != null) { - buffer.writeDouble(specificPoint.x); - buffer.writeDouble(specificPoint.y); - buffer.writeDouble(specificPoint.z); + public PacketTypeProvider getTypeProvider() { + return AllPackets.EXTENDO_INTERACT; + } + + @Override + public void handle(ServerPlayer sender) { + if (sender == null) + return; + Entity entityByID = sender.level() + .getEntity(this.target); + if (entityByID != null && ExtendoGripItem.isHoldingExtendoGrip(sender)) { + double d = sender.getAttributeValue(Attributes.BLOCK_INTERACTION_RANGE); + if (!sender.hasLineOfSight(entityByID)) + d -= 3; + d *= d; + if (sender.distanceToSqr(entityByID) > d) + return; + if (this.hand == null) + sender.attack(entityByID); + else if (this.point == null) + sender.interactOn(entityByID, this.hand); + else + entityByID.interactAt(sender, this.point, this.hand); } } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer sender = context.getSender(); - if (sender == null) - return; - Entity entityByID = sender.level() - .getEntity(target); - if (entityByID != null && ExtendoGripItem.isHoldingExtendoGrip(sender)) { - double d = sender.getAttribute(ForgeMod.BLOCK_REACH.get()) - .getValue(); - if (!sender.hasLineOfSight(entityByID)) - d -= 3; - d *= d; - if (sender.distanceToSqr(entityByID) > d) - return; - if (interactionHand == null) - sender.attack(entityByID); - else if (specificPoint == null) - sender.interactOn(entityByID, interactionHand); - else - entityByID.interactAt(sender, specificPoint, interactionHand); - } - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java index 22cd008bfa..37d5776120 100644 --- a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java @@ -1,24 +1,31 @@ package com.simibubi.create.content.equipment.extendoGrip; +import java.util.function.Consumer; +import java.util.function.Supplier; + import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.simibubi.create.AllItems; -import com.simibubi.create.AllPackets; +import com.simibubi.create.Create; import com.simibubi.create.content.equipment.armor.BacktankUtil; import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; import com.simibubi.create.infrastructure.config.AllConfigs; + +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.AnimationTickHolder; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.Holder; import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.InteractionHand; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; +import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.ProjectileUtil; @@ -29,56 +36,51 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult.Type; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; -import net.minecraftforge.common.ForgeMod; -import net.minecraftforge.event.entity.living.LivingAttackEvent; -import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; -import net.minecraftforge.event.entity.living.LivingKnockBackEvent; -import net.minecraftforge.event.entity.player.AttackEntityEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.level.BlockEvent.BreakEvent; -import net.minecraftforge.event.level.BlockEvent.EntityPlaceEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; - -import java.util.UUID; -import java.util.function.Consumer; -import java.util.function.Supplier; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.event.InputEvent; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent; +import net.neoforged.neoforge.event.entity.living.LivingKnockBackEvent; +import net.neoforged.neoforge.event.entity.player.AttackEntityEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import net.neoforged.neoforge.event.level.BlockEvent.BreakEvent; +import net.neoforged.neoforge.event.level.BlockEvent.EntityPlaceEvent; +import net.neoforged.neoforge.event.tick.EntityTickEvent; @EventBusSubscriber public class ExtendoGripItem extends Item { public static final int MAX_DAMAGE = 200; public static final AttributeModifier singleRangeAttributeModifier = - new AttributeModifier(UUID.fromString("7f7dbdb2-0d0d-458a-aa40-ac7633691f66"), "Range modifier", 3, - AttributeModifier.Operation.ADDITION); + new AttributeModifier(Create.asResource("single_range_attribute_modifier"), 3, + AttributeModifier.Operation.ADD_VALUE); public static final AttributeModifier doubleRangeAttributeModifier = - new AttributeModifier(UUID.fromString("8f7dbdb2-0d0d-458a-aa40-ac7633691f66"), "Range modifier", 5, - AttributeModifier.Operation.ADDITION); + new AttributeModifier(Create.asResource("double_range_attribute_modifier"), 5, + AttributeModifier.Operation.ADD_VALUE); - private static final Supplier> rangeModifier = Suppliers.memoize(() -> + private static final Supplier, AttributeModifier>> rangeModifier = Suppliers.memoize(() -> // Holding an ExtendoGrip - ImmutableMultimap.of(ForgeMod.BLOCK_REACH.get(), singleRangeAttributeModifier)); - private static final Supplier> doubleRangeModifier = Suppliers.memoize(() -> + ImmutableMultimap.of(Attributes.BLOCK_INTERACTION_RANGE, singleRangeAttributeModifier)); + private static final Supplier, AttributeModifier>> doubleRangeModifier = Suppliers.memoize(() -> // Holding two ExtendoGrips o.O - ImmutableMultimap.of(ForgeMod.BLOCK_REACH.get(), doubleRangeAttributeModifier)); + ImmutableMultimap.of(Attributes.BLOCK_INTERACTION_RANGE, doubleRangeAttributeModifier)); private static DamageSource lastActiveDamageSource; public ExtendoGripItem(Properties properties) { - super(properties.defaultDurability(MAX_DAMAGE)); + super(properties.durability(MAX_DAMAGE)); } public static final String EXTENDO_MARKER = "createExtendo"; public static final String DUAL_EXTENDO_MARKER = "createDualExtendo"; @SubscribeEvent - public static void holdingExtendoGripIncreasesRange(LivingTickEvent event) { + public static void holdingExtendoGripIncreasesRange(EntityTickEvent.Pre event) { if (!(event.getEntity() instanceof Player)) return; @@ -147,8 +149,7 @@ public class ExtendoGripItem extends Item { return; // Modified version of GameRenderer#getMouseOver - double d0 = player.getAttribute(ForgeMod.BLOCK_REACH.get()) - .getValue(); + double d0 = player.getAttributeValue(Attributes.BLOCK_INTERACTION_RANGE); if (!player.isCreative()) d0 -= 0.5f; Vec3 Vector3d = player.getEyePosition(AnimationTickHolder.getPartialTicks()); @@ -195,17 +196,16 @@ public class ExtendoGripItem extends Item { return; if (player.level().isClientSide) return; - InteractionHand hand = InteractionHand.MAIN_HAND; + EquipmentSlot equipmentSlot = EquipmentSlot.MAINHAND; ItemStack extendo = player.getMainHandItem(); if (!AllItems.EXTENDO_GRIP.isIn(extendo)) { extendo = player.getOffhandItem(); - hand = InteractionHand.OFF_HAND; + equipmentSlot = EquipmentSlot.OFFHAND; } if (!AllItems.EXTENDO_GRIP.isIn(extendo)) return; - final InteractionHand h = hand; if (!BacktankUtil.canAbsorbDamage(player, maxUses())) - extendo.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(h)); + extendo.hurtAndBreak(1, player, equipmentSlot); } @Override @@ -228,7 +228,7 @@ public class ExtendoGripItem extends Item { } @SubscribeEvent - public static void bufferLivingAttackEvent(LivingAttackEvent event) { + public static void bufferLivingAttackEvent(LivingIncomingDamageEvent event) { // Workaround for removed patch to get the attacking entity. lastActiveDamageSource = event.getSource(); @@ -273,7 +273,7 @@ public class ExtendoGripItem extends Item { return; Player player = (Player) entity; if (isHoldingExtendoGrip(player)) - AllPackets.getChannel().sendToServer(new ExtendoGripInteractionPacket(target)); + CatnipServices.NETWORK.sendToServer(new ExtendoGripInteractionPacket(target)); } @SubscribeEvent @@ -285,20 +285,18 @@ public class ExtendoGripItem extends Item { return; Player player = (Player) entity; if (isHoldingExtendoGrip(player)) - AllPackets.getChannel().sendToServer(new ExtendoGripInteractionPacket(target, event.getHand())); + CatnipServices.NETWORK.sendToServer(new ExtendoGripInteractionPacket(target, event.getHand())); } @SubscribeEvent @OnlyIn(Dist.CLIENT) public static void notifyServerOfLongRangeSpecificInteractions(PlayerInteractEvent.EntityInteractSpecific event) { - Entity entity = event.getEntity(); + Player entity = event.getEntity(); Entity target = event.getTarget(); if (!isUncaughtClientInteraction(entity, target)) return; - Player player = (Player) entity; - if (isHoldingExtendoGrip(player)) - AllPackets.getChannel() - .sendToServer(new ExtendoGripInteractionPacket(target, event.getHand(), event.getLocalPos())); + if (isHoldingExtendoGrip(entity)) + CatnipServices.NETWORK.sendToServer(new ExtendoGripInteractionPacket(target, event.getHand(), event.getLocalPos())); } public static boolean isHoldingExtendoGrip(Player player) { diff --git a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripRenderHandler.java b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripRenderHandler.java index 346ed6d855..f05a3f056c 100644 --- a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripRenderHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripRenderHandler.java @@ -19,11 +19,11 @@ import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.event.RenderHandEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.ClientHooks; +import net.neoforged.neoforge.client.event.RenderHandEvent; @EventBusSubscriber(value = Dist.CLIENT) public class ExtendoGripRenderHandler { @@ -67,7 +67,7 @@ public class ExtendoGripRenderHandler { PoseStack ms = event.getPoseStack(); var msr = TransformStack.of(ms); AbstractClientPlayer abstractclientplayerentity = mc.player; - RenderSystem.setShaderTexture(0, abstractclientplayerentity.getSkinTextureLocation()); + RenderSystem.setShaderTexture(0, abstractclientplayerentity.getSkin().texture()); float flip = rightHand ? 1.0F : -1.0F; float swingProgress = event.getSwingProgress(); @@ -116,7 +116,7 @@ public class ExtendoGripRenderHandler { event.getPoseStack(), event.getMultiBufferSource(), event.getPackedLight()); if (!notInOffhand) { - ForgeHooksClient.handleCameraTransforms(ms, mc.getItemRenderer() + ClientHooks.handleCameraTransforms(ms, mc.getItemRenderer() .getModel(offhandItem, null, null, 0), transform, !rightHand); ms.translate(flip * -.05f, .15f, -1.2f); ms.translate(0, 0, -animation * 2.25f); diff --git a/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java b/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java index 9988290791..eda05c640e 100644 --- a/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java @@ -28,9 +28,11 @@ import net.createmod.catnip.utility.lang.Components; import net.createmod.catnip.utility.outliner.Outline; import net.createmod.catnip.utility.outliner.Outliner.OutlineEntry; import net.createmod.catnip.utility.theme.Color; +import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; import net.minecraft.client.MouseHandler; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.LayeredDraw; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -44,20 +46,17 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; -import net.minecraftforge.client.gui.overlay.ForgeGui; -import net.minecraftforge.client.gui.overlay.IGuiOverlay; public class GoggleOverlayRenderer { - public static final IGuiOverlay OVERLAY = GoggleOverlayRenderer::renderOverlay; + public static final LayeredDraw.Layer OVERLAY = GoggleOverlayRenderer::renderOverlay; private static final Map outlines = CatnipClient.OUTLINER.getOutlines(); public static int hoverTicks = 0; public static BlockPos lastHovered = null; - public static void renderOverlay(ForgeGui gui, GuiGraphics graphics, float partialTicks, int width, - int height) { + public static void renderOverlay(GuiGraphics guiGraphics, DeltaTracker deltaTracker) { Minecraft mc = Minecraft.getInstance(); if (mc.options.hideGui || mc.gameMode.getPlayerMode() == GameType.SPECTATOR) return; @@ -171,7 +170,7 @@ public class GoggleOverlayRenderer { return; } - PoseStack poseStack = graphics.pose(); + PoseStack poseStack = guiGraphics.pose(); poseStack.pushPose(); int tooltipTextWidth = 0; @@ -187,6 +186,9 @@ public class GoggleOverlayRenderer { tooltipHeight += (tooltip.size() - 1) * 10; } + int width = guiGraphics.guiWidth(); + int height = guiGraphics.guiHeight(); + CClient cfg = AllConfigs.client(); int posX = width / 2 + cfg.overlayOffsetX.get(); int posY = height / 2 + cfg.overlayOffsetY.get(); @@ -194,7 +196,7 @@ public class GoggleOverlayRenderer { posX = Math.min(posX, width - tooltipTextWidth - 20); posY = Math.min(posY, height - tooltipHeight - 20); - float fade = Mth.clamp((hoverTicks + partialTicks) / 24f, 0, 1); + float fade = Mth.clamp((hoverTicks + deltaTracker.getGameTimeDeltaPartialTick(false)) / 24f, 0, 1); Boolean useCustom = cfg.overlayCustomColor.get(); Color colorBackground = useCustom ? new Color(cfg.overlayBackgroundColor.get()) : BoxElement.COLOR_VANILLA_BACKGROUND.scaleAlpha(.75f); @@ -212,11 +214,11 @@ public class GoggleOverlayRenderer { GuiGameElement.of(item) .at(posX + 10, posY - 16, 450) - .render(graphics); + .render(guiGraphics); if (!Mods.MODERNUI.isLoaded()) { // default tooltip rendering when modernUI is not loaded - RemovedGuiUtils.drawHoveringText(graphics, tooltip, posX, posY, width, height, -1, colorBackground.getRGB(), + RemovedGuiUtils.drawHoveringText(guiGraphics, tooltip, posX, posY, width, height, -1, colorBackground.getRGB(), colorBorderTop.getRGB(), colorBorderBot.getRGB(), mc.font); poseStack.popPose(); @@ -240,12 +242,11 @@ public class GoggleOverlayRenderer { ((MouseHandlerAccessor) mouseHandler).create$setXPos(Math.round(cursorX / guiScale) * guiScale); ((MouseHandlerAccessor) mouseHandler).create$setYPos(Math.round(cursorY / guiScale) * guiScale); - RemovedGuiUtils.drawHoveringText(graphics, tooltip, posX, posY, width, height, -1, colorBackground.getRGB(), + RemovedGuiUtils.drawHoveringText(guiGraphics, tooltip, posX, posY, width, height, -1, colorBackground.getRGB(), colorBorderTop.getRGB(), colorBorderBot.getRGB(), mc.font); ((MouseHandlerAccessor) mouseHandler).create$setXPos(cursorX); ((MouseHandlerAccessor) mouseHandler).create$setYPos(cursorY); - poseStack.popPose(); } diff --git a/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesItem.java b/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesItem.java index 22d59c6bd4..4b6b35a672 100644 --- a/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesItem.java @@ -37,7 +37,7 @@ public class GogglesItem extends Item { public InteractionResultHolder use(Level worldIn, Player playerIn, InteractionHand handIn) { ItemStack itemstack = playerIn.getItemInHand(handIn); - EquipmentSlot equipmentslottype = Mob.getEquipmentSlotForItem(itemstack); + EquipmentSlot equipmentslottype = playerIn.getEquipmentSlotForItem(itemstack); ItemStack itemstack1 = playerIn.getItemBySlot(equipmentslottype); if (itemstack1.isEmpty()) { playerIn.setItemSlot(equipmentslottype, itemstack.copy()); diff --git a/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesModel.java b/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesModel.java index 974da9d6cd..2e8024b3b8 100644 --- a/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesModel.java +++ b/src/main/java/com/simibubi/create/content/equipment/goggles/GogglesModel.java @@ -4,7 +4,7 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllPartialModels; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.world.item.ItemDisplayContext; -import net.minecraftforge.client.model.BakedModelWrapper; +import net.neoforged.neoforge.client.model.BakedModelWrapper; public class GogglesModel extends BakedModelWrapper { diff --git a/src/main/java/com/simibubi/create/content/equipment/goggles/IHaveGoggleInformation.java b/src/main/java/com/simibubi/create/content/equipment/goggles/IHaveGoggleInformation.java index 9f83112e79..cdfc9a2483 100644 --- a/src/main/java/com/simibubi/create/content/equipment/goggles/IHaveGoggleInformation.java +++ b/src/main/java/com/simibubi/create/content/equipment/goggles/IHaveGoggleInformation.java @@ -9,9 +9,8 @@ import net.createmod.catnip.utility.lang.LangBuilder; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.capability.IFluidHandler; /** * Implement this interface on the {@link BlockEntity} that wants to add info to the goggle overlay @@ -28,13 +27,11 @@ public non-sealed interface IHaveGoggleInformation extends IHaveCustomOverlayIco } default boolean containedFluidTooltip(List tooltip, boolean isPlayerSneaking, - LazyOptional handler) { - Optional resolve = handler.resolve(); - if (!resolve.isPresent()) + IFluidHandler handler) { + if (handler == null) return false; - IFluidHandler tank = resolve.get(); - if (tank.getTanks() == 0) + if (handler.getTanks() == 0) return false; LangBuilder mb = CreateLang.translate("generic.unit.millibuckets"); @@ -42,8 +39,8 @@ public non-sealed interface IHaveGoggleInformation extends IHaveCustomOverlayIco .forGoggles(tooltip); boolean isEmpty = true; - for (int i = 0; i < tank.getTanks(); i++) { - FluidStack fluidStack = tank.getFluidInTank(i); + for (int i = 0; i < handler.getTanks(); i++) { + FluidStack fluidStack = handler.getFluidInTank(i); if (fluidStack.isEmpty()) continue; @@ -56,7 +53,7 @@ public non-sealed interface IHaveGoggleInformation extends IHaveCustomOverlayIco .add(mb) .style(ChatFormatting.GOLD)) .text(ChatFormatting.GRAY, " / ") - .add(CreateLang.number(tank.getTankCapacity(i)) + .add(CreateLang.number(handler.getTankCapacity(i)) .add(mb) .style(ChatFormatting.DARK_GRAY)) .forGoggles(tooltip, 1); @@ -64,7 +61,7 @@ public non-sealed interface IHaveGoggleInformation extends IHaveCustomOverlayIco isEmpty = false; } - if (tank.getTanks() > 1) { + if (handler.getTanks() > 1) { if (isEmpty) tooltip.remove(tooltip.size() - 1); return true; @@ -74,7 +71,7 @@ public non-sealed interface IHaveGoggleInformation extends IHaveCustomOverlayIco return true; CreateLang.translate("gui.goggles.fluid_container.capacity") - .add(CreateLang.number(tank.getTankCapacity(0)) + .add(CreateLang.number(handler.getTankCapacity(0)) .add(mb) .style(ChatFormatting.GOLD)) .style(ChatFormatting.GRAY) diff --git a/src/main/java/com/simibubi/create/content/equipment/hats/CreateHatArmorLayer.java b/src/main/java/com/simibubi/create/content/equipment/hats/CreateHatArmorLayer.java index 88e1349522..1fe959bb48 100644 --- a/src/main/java/com/simibubi/create/content/equipment/hats/CreateHatArmorLayer.java +++ b/src/main/java/com/simibubi/create/content/equipment/hats/CreateHatArmorLayer.java @@ -7,6 +7,7 @@ import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.content.trains.schedule.hat.TrainHatInfo; import com.simibubi.create.content.trains.schedule.hat.TrainHatInfoReloadListener; import com.simibubi.create.foundation.mixin.accessor.AgeableListModelAccessor; +import com.simibubi.create.foundation.mixin.accessor.EntityRenderDispatcherAccessor; import dev.engine_room.flywheel.lib.model.baked.PartialModel; import dev.engine_room.flywheel.lib.transform.TransformStack; @@ -93,7 +94,7 @@ public class CreateHatArmorLayer renderer : renderManager.getSkinMap() .values()) registerOn(renderer); - for (EntityRenderer renderer : renderManager.renderers.values()) + for (EntityRenderer renderer : ((EntityRenderDispatcherAccessor) renderManager).create$getRenderers().values()) registerOn(renderer); } diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java index 72786b1a3b..ac45a32e98 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java @@ -8,6 +8,7 @@ import com.simibubi.create.foundation.mixin.accessor.FallingBlockEntityAccessor; import net.createmod.catnip.utility.WorldAttached; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Holder; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; @@ -34,11 +35,11 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.IPlantable; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.event.entity.EntityTeleportEvent; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.common.SpecialPlantable; +import net.neoforged.neoforge.common.util.FakePlayer; +import net.neoforged.neoforge.common.util.TriState; +import net.neoforged.neoforge.event.EventHooks; +import net.neoforged.neoforge.event.entity.EntityTeleportEvent; import java.util.UUID; import java.util.function.BiPredicate; @@ -262,12 +263,12 @@ public class BuiltinPotatoProjectileTypes { private static Predicate setFire(int seconds) { return ray -> { ray.getEntity() - .setSecondsOnFire(seconds); + .igniteForSeconds(seconds); return false; }; } - private static Predicate potion(MobEffect effect, int level, int ticks, boolean recoverable) { + private static Predicate potion(Holder effect, int level, int ticks, boolean recoverable) { return ray -> { Entity entity = ray.getEntity(); if (entity.level().isClientSide) @@ -285,9 +286,9 @@ public class BuiltinPotatoProjectileTypes { return true; if (entity instanceof LivingEntity) { - for (Pair effect : food.getEffects()) { - if (Create.RANDOM.nextFloat() < effect.getSecond()) - applyEffect((LivingEntity) entity, new MobEffectInstance(effect.getFirst())); + for (FoodProperties.PossibleEffect effect : food.effects()) { + if (Create.RANDOM.nextFloat() < effect.probability()) + applyEffect((LivingEntity) entity, effect.effectSupplier().get()); } } return !recoverable; @@ -295,9 +296,9 @@ public class BuiltinPotatoProjectileTypes { } private static void applyEffect(LivingEntity entity, MobEffectInstance effect) { - if (effect.getEffect() + if (effect.getEffect().value() .isInstantenous()) - effect.getEffect() + effect.getEffect().value() .applyInstantenousEffect(null, null, entity, effect.getDuration(), 1.0); else entity.addEffect(effect); @@ -318,10 +319,10 @@ public class BuiltinPotatoProjectileTypes { if (!world.getBlockState(placePos) .canBeReplaced()) return false; - if (!(cropBlock.get() instanceof IPlantable)) + if (!(cropBlock.get() instanceof SpecialPlantable)) return false; BlockState blockState = world.getBlockState(hitPos); - if (!blockState.canSustainPlant(world, hitPos, face, (IPlantable) cropBlock.get())) + if (blockState.canSustainPlant(world, hitPos, face, cropBlock.get().defaultBlockState()) == TriState.FALSE) return false; world.setBlock(placePos, cropBlock.get() .defaultBlockState(), 3); @@ -330,11 +331,10 @@ public class BuiltinPotatoProjectileTypes { } private static BiPredicate plantCrop(Block cropBlock) { - return plantCrop(ForgeRegistries.BLOCKS.getDelegateOrThrow(cropBlock)); + return plantCrop(() -> cropBlock); } - private static BiPredicate placeBlockOnGround( - Supplier block) { + private static BiPredicate placeBlockOnGround(Supplier block) { return (world, ray) -> { if (world.isClientSide()) return true; @@ -369,7 +369,7 @@ public class BuiltinPotatoProjectileTypes { } private static BiPredicate placeBlockOnGround(Block block) { - return placeBlockOnGround(ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); + return placeBlockOnGround(() -> block); } private static Predicate chorusTeleport(double teleportDiameter) { @@ -395,7 +395,7 @@ public class BuiltinPotatoProjectileTypes { .nextDouble() - 0.5D) * teleportDiameter; EntityTeleportEvent.ChorusFruit event = - ForgeEventFactory.onChorusFruitTeleport(livingEntity, teleportX, teleportY, teleportZ); + EventHooks.onChorusFruitTeleport(livingEntity, teleportX, teleportY, teleportZ); if (event.isCanceled()) return false; if (livingEntity.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true)) { diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonItem.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonItem.java index e270831bf1..e408f8b7fb 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonItem.java @@ -28,14 +28,19 @@ import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction.Axis; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.Projectile; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ProjectileWeaponItem; import net.minecraft.world.item.TooltipFlag; @@ -46,9 +51,9 @@ import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmPoseItem { @@ -56,7 +61,7 @@ public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmP public static final int MAX_DAMAGE = 100; public PotatoCannonItem(Properties properties) { - super(properties.defaultDurability(MAX_DAMAGE)); + super(properties.durability(MAX_DAMAGE)); } @Override @@ -65,18 +70,18 @@ public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmP } @Override - public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) { - if (enchantment == Enchantments.POWER_ARROWS) + public boolean supportsEnchantment(ItemStack stack, Holder enchantment) { + if (enchantment.is(Enchantments.POWER)) return true; - if (enchantment == Enchantments.PUNCH_ARROWS) + if (enchantment.is(Enchantments.PUNCH)) return true; - if (enchantment == Enchantments.FLAMING_ARROWS) + if (enchantment.is(Enchantments.FLAME)) return true; - if (enchantment == Enchantments.MOB_LOOTING) + if (enchantment.is(Enchantments.LOOTING)) return true; - if (enchantment == AllEnchantments.POTATO_RECOVERY.get()) + if (enchantment.is(AllEnchantments.POTATO_RECOVERY)) return true; - return super.canApplyAtEnchantingTable(stack, enchantment); + return super.supportsEnchantment(stack, enchantment); } @Override @@ -107,6 +112,12 @@ public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmP return stack.getItem() instanceof PotatoCannonItem; } + @Override + protected void shootProjectile(LivingEntity shooter, Projectile projectile, int index, float velocity, float inaccuracy, float angle, @Nullable LivingEntity target) {} + + @Override + protected void shoot(ServerLevel level, LivingEntity shooter, InteractionHand hand, ItemStack weapon, List projectileItems, float velocity, float inaccuracy, boolean isCrit, @Nullable LivingEntity target) {} + @Override public InteractionResultHolder use(Level world, Player player, InteractionHand hand) { ItemStack stack = player.getItemInHand(hand); @@ -169,7 +180,7 @@ public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmP } if (!BacktankUtil.canAbsorbDamage(player, maxUses())) - stack.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(hand)); + stack.hurtAndBreak(1, player, LivingEntity.getSlotForHand(hand)); Integer cooldown = findAmmoInInventory(world, player, stack).flatMap(PotatoProjectileTypeManager::getTypeForStack) @@ -178,7 +189,7 @@ public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmP ShootableGadgetItemMethods.applyCooldown(player, stack, hand, this::isCannon, cooldown); ShootableGadgetItemMethods.sendPackets(player, - b -> new PotatoCannonPacket(barrelPos, lookVec.normalize(), itemStack, hand, soundPitch, b)); + b -> new PotatoCannonPacket(barrelPos, hand, b, soundPitch, lookVec.normalize(), itemStack)); return InteractionResultHolder.success(stack); }) .orElse(InteractionResultHolder.pass(stack)); @@ -214,48 +225,53 @@ public class PotatoCannonItem extends ProjectileWeaponItem implements CustomArmP @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level world, List tooltip, TooltipFlag flag) { - int power = stack.getEnchantmentLevel(Enchantments.POWER_ARROWS); - int punch = stack.getEnchantmentLevel(Enchantments.PUNCH_ARROWS); - final float additionalDamageMult = 1 + power * .2f; - final float additionalKnockback = punch * .5f; + public void appendHoverText(ItemStack stack, TooltipContext context, List tooltip, TooltipFlag flag) { + HolderLookup.Provider registries = context.registries(); + // FIXME 1.21: checkover + if (registries != null) { + HolderLookup.RegistryLookup enchantLookup = registries.lookupOrThrow(Registries.ENCHANTMENT); + int power = stack.getEnchantmentLevel(enchantLookup.get(Enchantments.POWER).orElseThrow().getDelegate()); + int punch = stack.getEnchantmentLevel(enchantLookup.get(Enchantments.PUNCH).orElseThrow().getDelegate()); + final float additionalDamageMult = 1 + power * .2f; + final float additionalKnockback = punch * .5f; - getAmmoforPreview(stack).ifPresent(ammo -> { - String _attack = "potato_cannon.ammo.attack_damage"; - String _reload = "potato_cannon.ammo.reload_ticks"; - String _knockback = "potato_cannon.ammo.knockback"; + getAmmoforPreview(stack).ifPresent(ammo -> { + String _attack = "potato_cannon.ammo.attack_damage"; + String _reload = "potato_cannon.ammo.reload_ticks"; + String _knockback = "potato_cannon.ammo.knockback"; - tooltip.add(Components.immutableEmpty()); - tooltip.add(Components.translatable(ammo.getDescriptionId()).append(Components.literal(":")) - .withStyle(ChatFormatting.GRAY)); - PotatoCannonProjectileType type = PotatoProjectileTypeManager.getTypeForStack(ammo) - .get(); - MutableComponent spacing = Components.literal(" "); - ChatFormatting green = ChatFormatting.GREEN; - ChatFormatting darkGreen = ChatFormatting.DARK_GREEN; + tooltip.add(Components.immutableEmpty()); + tooltip.add(Components.translatable(ammo.getDescriptionId()).append(Components.literal(":")) + .withStyle(ChatFormatting.GRAY)); + PotatoCannonProjectileType type = PotatoProjectileTypeManager.getTypeForStack(ammo) + .get(); + MutableComponent spacing = Components.literal(" "); + ChatFormatting green = ChatFormatting.GREEN; + ChatFormatting darkGreen = ChatFormatting.DARK_GREEN; - float damageF = type.getDamage() * additionalDamageMult; - MutableComponent damage = Components.literal( - damageF == Mth.floor(damageF) ? "" + Mth.floor(damageF) : "" + damageF); - MutableComponent reloadTicks = Components.literal("" + type.getReloadTicks()); - MutableComponent knockback = - Components.literal("" + (type.getKnockback() + additionalKnockback)); + float damageF = type.getDamage() * additionalDamageMult; + MutableComponent damage = Components.literal( + damageF == Mth.floor(damageF) ? "" + Mth.floor(damageF) : "" + damageF); + MutableComponent reloadTicks = Components.literal("" + type.getReloadTicks()); + MutableComponent knockback = + Components.literal("" + (type.getKnockback() + additionalKnockback)); - damage = damage.withStyle(additionalDamageMult > 1 ? green : darkGreen); - knockback = knockback.withStyle(additionalKnockback > 0 ? green : darkGreen); - reloadTicks = reloadTicks.withStyle(darkGreen); + damage = damage.withStyle(additionalDamageMult > 1 ? green : darkGreen); + knockback = knockback.withStyle(additionalKnockback > 0 ? green : darkGreen); + reloadTicks = reloadTicks.withStyle(darkGreen); - tooltip.add(spacing.plainCopy() - .append(CreateLang.translateDirect(_attack, damage) - .withStyle(darkGreen))); - tooltip.add(spacing.plainCopy() - .append(CreateLang.translateDirect(_reload, reloadTicks) - .withStyle(darkGreen))); - tooltip.add(spacing.plainCopy() - .append(CreateLang.translateDirect(_knockback, knockback) - .withStyle(darkGreen))); - }); - super.appendHoverText(stack, world, tooltip, flag); + tooltip.add(spacing.plainCopy() + .append(CreateLang.translateDirect(_attack, damage) + .withStyle(darkGreen))); + tooltip.add(spacing.plainCopy() + .append(CreateLang.translateDirect(_reload, reloadTicks) + .withStyle(darkGreen))); + tooltip.add(spacing.plainCopy() + .append(CreateLang.translateDirect(_knockback, knockback) + .withStyle(darkGreen))); + }); + } + super.appendHoverText(stack, context, tooltip, flag); } @Override diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonPacket.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonPacket.java index 2aa8ac9513..0332dd5779 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonPacket.java @@ -1,49 +1,42 @@ package com.simibubi.create.content.equipment.potatoCannon; +import com.simibubi.create.AllPackets; import com.simibubi.create.CreateClient; import com.simibubi.create.content.equipment.zapper.ShootGadgetPacket; import com.simibubi.create.content.equipment.zapper.ShootableGadgetRenderHandler; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class PotatoCannonPacket extends ShootGadgetPacket { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecs.VEC3, packet -> packet.location, + CatnipStreamCodecs.HAND, packet -> packet.hand, + ByteBufCodecs.BOOL, packet -> packet.self, + ByteBufCodecs.FLOAT, packet -> packet.pitch, + CatnipStreamCodecs.VEC3, packet -> packet.motion, + ItemStack.STREAM_CODEC, packet -> packet.item, + PotatoCannonPacket::new + ); - private float pitch; - private Vec3 motion; - private ItemStack item; + private final float pitch; + private final Vec3 motion; + private final ItemStack item; - public PotatoCannonPacket(Vec3 location, Vec3 motion, ItemStack item, InteractionHand hand, float pitch, boolean self) { + public PotatoCannonPacket(Vec3 location, InteractionHand hand, boolean self, float pitch, Vec3 motion, ItemStack item) { super(location, hand, self); this.motion = motion; this.item = item; this.pitch = pitch; } - public PotatoCannonPacket(FriendlyByteBuf buffer) { - super(buffer); - } - - @Override - protected void readAdditional(FriendlyByteBuf buffer) { - pitch = buffer.readFloat(); - motion = new Vec3(buffer.readFloat(), buffer.readFloat(), buffer.readFloat()); - item = buffer.readItem(); - } - - @Override - protected void writeAdditional(FriendlyByteBuf buffer) { - buffer.writeFloat(pitch); - buffer.writeFloat((float) motion.x); - buffer.writeFloat((float) motion.y); - buffer.writeFloat((float) motion.z); - buffer.writeItem(item); - } - @Override @OnlyIn(Dist.CLIENT) protected void handleAdditional() { @@ -56,4 +49,8 @@ public class PotatoCannonPacket extends ShootGadgetPacket { return CreateClient.POTATO_CANNON_RENDER_HANDLER; } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.POTATO_CANNON; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonProjectileType.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonProjectileType.java index 4ac551cdf4..06b4297e7d 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonProjectileType.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoCannonProjectileType.java @@ -4,29 +4,67 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.BiPredicate; -import java.util.function.Consumer; import java.util.function.Predicate; -import java.util.function.Supplier; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.createmod.catnip.platform.CatnipServices; -import net.minecraft.ResourceLocationException; -import net.minecraft.core.Holder; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.codecs.stream.CatnipLargerStreamCodecs; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; -import net.minecraftforge.registries.ForgeRegistries; public class PotatoCannonProjectileType { + public static Codec CODEC = RecordCodecBuilder.create(i -> i.group( + BuiltInRegistries.ITEM.byNameCodec().listOf().fieldOf("items").forGetter(p -> p.getItems()), + Codec.INT.optionalFieldOf("reload_ticks").forGetter(p -> Optional.of(p.getReloadTicks())), + Codec.INT.optionalFieldOf("damage").forGetter(p -> Optional.of(p.getDamage())), + Codec.INT.optionalFieldOf("split").forGetter(p -> Optional.of(p.getSplit())), + Codec.FLOAT.optionalFieldOf("knockback").forGetter(p -> Optional.of(p.getKnockback())), + Codec.FLOAT.optionalFieldOf("drag").forGetter(p -> Optional.of(p.getDrag())), + Codec.FLOAT.optionalFieldOf("velocity_multiplier").forGetter(p -> Optional.of(p.getVelocityMultiplier())), + Codec.FLOAT.optionalFieldOf("gravity_multiplier").forGetter(p -> Optional.of(p.getGravityMultiplier())), + Codec.FLOAT.optionalFieldOf("sound_pitch").forGetter(p -> Optional.of(p.getSoundPitch())), + Codec.BOOL.optionalFieldOf("sticky").forGetter(p -> Optional.of(p.isSticky())) + ).apply(i, (items, reloadTicks, damage, split, knockback, drag, velocityMultiplier, gravityMultiplier, soundPitch, sticky) -> { + PotatoCannonProjectileType type = new PotatoCannonProjectileType(); + type.items.addAll(items); + reloadTicks.ifPresent(r -> type.reloadTicks = r); + damage.ifPresent(r -> type.damage = r); + split.ifPresent(r -> type.split = r); + knockback.ifPresent(r -> type.knockback = r); + drag.ifPresent(r -> type.drag = r); + velocityMultiplier.ifPresent(r -> type.velocityMultiplier = r); + gravityMultiplier.ifPresent(r -> type.gravityMultiplier = r); + soundPitch.ifPresent(r -> type.soundPitch = r); + sticky.ifPresent(r -> type.sticky = r); - private List> items = new ArrayList<>(); + return type; + })); + + public static StreamCodec STREAM_CODEC = CatnipLargerStreamCodecs.composite( + ByteBufCodecs.registry(Registries.ITEM).apply(ByteBufCodecs.list()), t -> t.items, + ByteBufCodecs.INT, PotatoCannonProjectileType::getReloadTicks, + ByteBufCodecs.INT, PotatoCannonProjectileType::getDamage, + ByteBufCodecs.INT, PotatoCannonProjectileType::getSplit, + ByteBufCodecs.FLOAT, PotatoCannonProjectileType::getKnockback, + ByteBufCodecs.FLOAT, PotatoCannonProjectileType::getDrag, + ByteBufCodecs.FLOAT, PotatoCannonProjectileType::getVelocityMultiplier, + ByteBufCodecs.FLOAT, PotatoCannonProjectileType::getGravityMultiplier, + ByteBufCodecs.FLOAT, PotatoCannonProjectileType::getSoundPitch, + ByteBufCodecs.BOOL, PotatoCannonProjectileType::isSticky, + PotatoCannonProjectileType::new + ); + + private List items = new ArrayList<>(); private int reloadTicks = 10; private int damage = 1; @@ -43,10 +81,24 @@ public class PotatoCannonProjectileType { private Predicate onEntityHit = e -> false; // True if shouldn't recover projectile private BiPredicate onBlockHit = (w, ray) -> false; - protected PotatoCannonProjectileType() { + protected PotatoCannonProjectileType() {} + + public PotatoCannonProjectileType(List items, int reloadTicks, int damage, int split, float knockback, + float drag, float velocityMultiplier, float gravityMultiplier, float soundPitch, + boolean sticky) { + this.items = items; + this.reloadTicks = reloadTicks; + this.damage = damage; + this.split = split; + this.knockback = knockback; + this.drag = drag; + this.velocityMultiplier = velocityMultiplier; + this.gravityMultiplier = gravityMultiplier; + this.soundPitch = soundPitch; + this.sticky = sticky; } - public List> getItems() { + public List getItems() { return items; } @@ -102,90 +154,6 @@ public class PotatoCannonProjectileType { return onBlockHit.test(world, ray); } - public static PotatoCannonProjectileType fromJson(JsonObject object) { - PotatoCannonProjectileType type = new PotatoCannonProjectileType(); - try { - JsonElement itemsElement = object.get("items"); - if (itemsElement != null && itemsElement.isJsonArray()) { - for (JsonElement element : itemsElement.getAsJsonArray()) { - if (element.isJsonPrimitive()) { - JsonPrimitive primitive = element.getAsJsonPrimitive(); - if (primitive.isString()) { - try { - Optional> reference = ForgeRegistries.ITEMS.getDelegate(new ResourceLocation(primitive.getAsString())); - if (reference.isPresent()) { - type.items.add(reference.get()); - } - } catch (ResourceLocationException e) { - // - } - } - } - } - } - - parseJsonPrimitive(object, "reload_ticks", JsonPrimitive::isNumber, primitive -> type.reloadTicks = primitive.getAsInt()); - parseJsonPrimitive(object, "damage", JsonPrimitive::isNumber, primitive -> type.damage = primitive.getAsInt()); - parseJsonPrimitive(object, "split", JsonPrimitive::isNumber, primitive -> type.split = primitive.getAsInt()); - parseJsonPrimitive(object, "knockback", JsonPrimitive::isNumber, primitive -> type.knockback = primitive.getAsFloat()); - parseJsonPrimitive(object, "drag", JsonPrimitive::isNumber, primitive -> type.drag = primitive.getAsFloat()); - parseJsonPrimitive(object, "velocity_multiplier", JsonPrimitive::isNumber, primitive -> type.velocityMultiplier = primitive.getAsFloat()); - parseJsonPrimitive(object, "gravity_multiplier", JsonPrimitive::isNumber, primitive -> type.gravityMultiplier = primitive.getAsFloat()); - parseJsonPrimitive(object, "sound_pitch", JsonPrimitive::isNumber, primitive -> type.soundPitch = primitive.getAsFloat()); - parseJsonPrimitive(object, "sticky", JsonPrimitive::isBoolean, primitive -> type.sticky = primitive.getAsBoolean()); - } catch (Exception e) { - // - } - return type; - } - - private static void parseJsonPrimitive(JsonObject object, String key, Predicate predicate, Consumer consumer) { - JsonElement element = object.get(key); - if (element != null && element.isJsonPrimitive()) { - JsonPrimitive primitive = element.getAsJsonPrimitive(); - if (predicate.test(primitive)) { - consumer.accept(primitive); - } - } - } - - public static void toBuffer(PotatoCannonProjectileType type, FriendlyByteBuf buffer) { - buffer.writeVarInt(type.items.size()); - for (Supplier delegate : type.items) { - buffer.writeResourceLocation(CatnipServices.REGISTRIES.getKeyOrThrow(delegate.get())); - } - buffer.writeInt(type.reloadTicks); - buffer.writeInt(type.damage); - buffer.writeInt(type.split); - buffer.writeFloat(type.knockback); - buffer.writeFloat(type.drag); - buffer.writeFloat(type.velocityMultiplier); - buffer.writeFloat(type.gravityMultiplier); - buffer.writeFloat(type.soundPitch); - buffer.writeBoolean(type.sticky); - } - - public static PotatoCannonProjectileType fromBuffer(FriendlyByteBuf buffer) { - PotatoCannonProjectileType type = new PotatoCannonProjectileType(); - int size = buffer.readVarInt(); - for (int i = 0; i < size; i++) { - Optional> reference = ForgeRegistries.ITEMS.getDelegate(buffer.readResourceLocation()); - if (reference.isPresent()) { - type.items.add(reference.get()); - } - } - type.reloadTicks = buffer.readInt(); - type.damage = buffer.readInt(); - type.split = buffer.readInt(); - type.knockback = buffer.readFloat(); - type.drag = buffer.readFloat(); - type.velocityMultiplier = buffer.readFloat(); - type.gravityMultiplier = buffer.readFloat(); - type.soundPitch = buffer.readFloat(); - type.sticky = buffer.readBoolean(); - return type; - } - public static class Builder { protected ResourceLocation id; @@ -278,7 +246,7 @@ public class PotatoCannonProjectileType { public Builder addItems(ItemLike... items) { for (ItemLike provider : items) - result.items.add(ForgeRegistries.ITEMS.getDelegateOrThrow(provider.asItem())); + result.items.add(provider.asItem()); return this; } @@ -294,5 +262,4 @@ public class PotatoCannonProjectileType { } } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java index ad5685f311..7580da5fe3 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java @@ -10,14 +10,15 @@ import com.simibubi.create.foundation.particle.AirParticleData; import net.createmod.catnip.utility.VecHelper; import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; import net.minecraft.core.particles.ItemParticleOption; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.protocol.game.ClientboundGameEventPacket; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.tags.DamageTypeTags; import net.minecraft.world.damagesource.DamageSource; @@ -29,17 +30,15 @@ import net.minecraft.world.entity.boss.wither.WitherBoss; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.AbstractHurtingProjectile; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.Level; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.entity.IEntityAdditionalSpawnData; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.neoforge.entity.IEntityWithComplexSpawn; -public class PotatoProjectileEntity extends AbstractHurtingProjectile implements IEntityAdditionalSpawnData { +public class PotatoProjectileEntity extends AbstractHurtingProjectile implements IEntityWithComplexSpawn { protected PotatoCannonProjectileType type; protected ItemStack stack = ItemStack.EMPTY; @@ -73,24 +72,17 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements } public void setEnchantmentEffectsFromCannon(ItemStack cannon) { - int power = cannon.getEnchantmentLevel(Enchantments.POWER_ARROWS); - int punch = cannon.getEnchantmentLevel(Enchantments.PUNCH_ARROWS); - int flame = cannon.getEnchantmentLevel(Enchantments.FLAMING_ARROWS); - int recovery = cannon.getEnchantmentLevel(AllEnchantments.POTATO_RECOVERY.get()); + Registry enchantmentRegistry = registryAccess().registryOrThrow(Registries.ENCHANTMENT); + + int recovery = cannon.getEnchantmentLevel(enchantmentRegistry.getHolderOrThrow(AllEnchantments.POTATO_RECOVERY)); - if (power > 0) - additionalDamageMult = 1 + power * .2f; - if (punch > 0) - additionalKnockback = punch * .5f; - if (flame > 0) - setSecondsOnFire(100); if (recovery > 0) recoveryChance = .125f + recovery * .125f; } @Override public void readAdditionalSaveData(CompoundTag nbt) { - stack = ItemStack.of(nbt.getCompound("Item")); + stack = ItemStack.parseOptional(this.registryAccess(), nbt.getCompound("Item")); additionalDamageMult = nbt.getFloat("AdditionalDamage"); additionalKnockback = nbt.getFloat("AdditionalKnockback"); recoveryChance = nbt.getFloat("Recovery"); @@ -99,7 +91,7 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements @Override public void addAdditionalSaveData(CompoundTag nbt) { - nbt.put("Item", stack.serializeNBT()); + nbt.put("Item", stack.saveOptional(this.registryAccess())); nbt.putFloat("AdditionalDamage", additionalDamageMult); nbt.putFloat("AdditionalKnockback", additionalKnockback); nbt.putFloat("Recovery", recoveryChance); @@ -207,10 +199,11 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements boolean targetIsEnderman = target.getType() == EntityType.ENDERMAN; int k = target.getRemainingFireTicks(); if (this.isOnFire() && !targetIsEnderman) - target.setSecondsOnFire(5); + target.igniteForSeconds(5); boolean onServer = !level().isClientSide; - if (onServer && !target.hurt(causePotatoDamage(), damage)) { + DamageSource damageSource = causePotatoDamage(); + if (onServer && !target.hurt(damageSource, damage)) { target.setRemainingFireTicks(k); kill(); return; @@ -244,8 +237,7 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements } if (onServer && owner instanceof LivingEntity) { - EnchantmentHelper.doPostHurtEffects(livingentity, owner); - EnchantmentHelper.doPostDamageEffects((LivingEntity) owner, livingentity); + EnchantmentHelper.doPostAttackEffects((ServerLevel) level(), livingentity, damageSource); } if (livingentity != owner && livingentity instanceof Player && owner instanceof ServerPlayer @@ -254,8 +246,7 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements .send(new ClientboundGameEventPacket(ClientboundGameEventPacket.ARROW_HIT_PLAYER, 0.0F)); } - if (onServer && owner instanceof ServerPlayer) { - ServerPlayer serverplayerentity = (ServerPlayer) owner; + if (onServer && owner instanceof ServerPlayer serverplayerentity) { if (!target.isAlive() && target.getType() .getCategory() == MobCategory.MONSTER || (target instanceof Player && target != owner)) AllAdvancements.POTATO_CANNON.awardTo(serverplayerentity); @@ -271,7 +262,7 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements private void recoverItem() { if (!stack.isEmpty()) - spawnAtLocation(ItemHandlerHelper.copyStackWithSize(stack, 1)); + spawnAtLocation(stack.copyWithCount(1)); } public static void playHitSound(Level world, Vec3 location) { @@ -327,19 +318,14 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements } @Override - public Packet getAddEntityPacket() { - return NetworkHooks.getEntitySpawningPacket(this); - } - - @Override - public void writeSpawnData(FriendlyByteBuf buffer) { + public void writeSpawnData(RegistryFriendlyByteBuf buffer) { CompoundTag compound = new CompoundTag(); addAdditionalSaveData(compound); buffer.writeNbt(compound); } @Override - public void readSpawnData(FriendlyByteBuf additionalData) { + public void readSpawnData(RegistryFriendlyByteBuf additionalData) { readAdditionalSaveData(additionalData.readNbt()); } diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileRenderMode.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileRenderMode.java index 781fc4b85b..54e9fbd13d 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileRenderMode.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileRenderMode.java @@ -10,8 +10,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public interface PotatoProjectileRenderMode { diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileTypeManager.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileTypeManager.java index 09d8674bc0..260bbeeaa6 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileTypeManager.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileTypeManager.java @@ -4,16 +4,20 @@ import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.Optional; -import java.util.function.Supplier; +import java.util.Set; import com.google.gson.Gson; import com.google.gson.JsonElement; -import com.google.gson.JsonObject; +import com.mojang.serialization.JsonOps; import com.simibubi.create.AllItems; import com.simibubi.create.AllPackets; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; +import net.createmod.catnip.platform.CatnipServices; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.packs.resources.ResourceManager; @@ -21,8 +25,9 @@ import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent.Context; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; public class PotatoProjectileTypeManager { @@ -48,6 +53,10 @@ public class PotatoProjectileTypeManager { return ITEM_TO_TYPE_MAP.get(item); } + public static Set getItems() { + return ITEM_TO_TYPE_MAP.keySet(); + } + public static Optional getTypeForStack(ItemStack item) { if (item.isEmpty()) return Optional.empty(); @@ -62,44 +71,25 @@ public class PotatoProjectileTypeManager { public static void fillItemMap() { for (Map.Entry entry : BUILTIN_TYPE_MAP.entrySet()) { PotatoCannonProjectileType type = entry.getValue(); - for (Supplier delegate : type.getItems()) { - ITEM_TO_TYPE_MAP.put(delegate.get(), type); + for (Item item : type.getItems()) { + ITEM_TO_TYPE_MAP.put(item, type); } } for (Map.Entry entry : CUSTOM_TYPE_MAP.entrySet()) { PotatoCannonProjectileType type = entry.getValue(); - for (Supplier delegate : type.getItems()) { - ITEM_TO_TYPE_MAP.put(delegate.get(), type); + for (Item item : type.getItems()) { + ITEM_TO_TYPE_MAP.put(item, type); } } ITEM_TO_TYPE_MAP.remove(AllItems.POTATO_CANNON.get()); } - public static void toBuffer(FriendlyByteBuf buffer) { - buffer.writeVarInt(CUSTOM_TYPE_MAP.size()); - for (Map.Entry entry : CUSTOM_TYPE_MAP.entrySet()) { - buffer.writeResourceLocation(entry.getKey()); - PotatoCannonProjectileType.toBuffer(entry.getValue(), buffer); - } - } - - public static void fromBuffer(FriendlyByteBuf buffer) { - clear(); - - int size = buffer.readVarInt(); - for (int i = 0; i < size; i++) { - CUSTOM_TYPE_MAP.put(buffer.readResourceLocation(), PotatoCannonProjectileType.fromBuffer(buffer)); - } - - fillItemMap(); - } - public static void syncTo(ServerPlayer player) { - AllPackets.getChannel().send(PacketDistributor.PLAYER.with(() -> player), new SyncPacket()); + CatnipServices.NETWORK.sendToClient(player, new SyncPacket(CUSTOM_TYPE_MAP)); } public static void syncToAll() { - AllPackets.getChannel().send(PacketDistributor.ALL.noArg(), new SyncPacket()); + CatnipServices.NETWORK.sendToAllClients(new SyncPacket(CUSTOM_TYPE_MAP)); } public static class ReloadListener extends SimpleJsonResourceReloadListener { @@ -117,13 +107,9 @@ public class PotatoProjectileTypeManager { clear(); for (Map.Entry entry : map.entrySet()) { - JsonElement element = entry.getValue(); - if (element.isJsonObject()) { - ResourceLocation id = entry.getKey(); - JsonObject object = element.getAsJsonObject(); - PotatoCannonProjectileType type = PotatoCannonProjectileType.fromJson(object); - CUSTOM_TYPE_MAP.put(id, type); - } + PotatoCannonProjectileType.CODEC.decode(JsonOps.INSTANCE, entry.getValue()).result().ifPresent(p -> { + CUSTOM_TYPE_MAP.put(entry.getKey(), p.getFirst()); + }); } fillItemMap(); @@ -131,30 +117,30 @@ public class PotatoProjectileTypeManager { } - public static class SyncPacket extends SimplePacketBase { + public record SyncPacket(Map customTypes) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = ByteBufCodecs.map( + SyncPacket::newMap, ResourceLocation.STREAM_CODEC, PotatoCannonProjectileType.STREAM_CODEC + ).map(SyncPacket::new, SyncPacket::customTypes); - private FriendlyByteBuf buffer; + @Override + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + clear(); - public SyncPacket() { - } + CUSTOM_TYPE_MAP.putAll(customTypes); - public SyncPacket(FriendlyByteBuf buffer) { - this.buffer = buffer; + fillItemMap(); } @Override - public void write(FriendlyByteBuf buffer) { - toBuffer(buffer); + public PacketTypeProvider getTypeProvider() { + return AllPackets.SYNC_POTATO_PROJECTILE_TYPES; } - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - fromBuffer(buffer); - }); - return true; + // needed for generics + private static Map newMap(int size) { + return new HashMap<>(size); } - } } diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoRecoveryEnchantment.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoRecoveryEnchantment.java deleted file mode 100644 index 47e767ffff..0000000000 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoRecoveryEnchantment.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.simibubi.create.content.equipment.potatoCannon; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.EnchantmentCategory; - -public class PotatoRecoveryEnchantment extends Enchantment { - - public PotatoRecoveryEnchantment(Rarity p_i46731_1_, EnchantmentCategory p_i46731_2_, EquipmentSlot[] p_i46731_3_) { - super(p_i46731_1_, p_i46731_2_, p_i46731_3_); - } - - @Override - public int getMaxLevel() { - return 3; - } - - @Override - public boolean canApplyAtEnchantingTable(ItemStack stack) { - return stack.getItem() instanceof PotatoCannonItem; - } - -} diff --git a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java index c66d4c2955..f898df2c32 100644 --- a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java @@ -4,6 +4,7 @@ import java.util.function.Consumer; import javax.annotation.ParametersAreNonnullByDefault; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.foundation.item.CustomUseEffectsItem; import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; @@ -14,7 +15,6 @@ import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ItemParticleOption; import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.nbt.CompoundTag; import net.minecraft.sounds.SoundEvent; import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; @@ -32,21 +32,20 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; -import net.minecraftforge.common.ToolAction; -import net.minecraftforge.common.ToolActions; -import net.minecraftforge.common.util.FakePlayer; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.common.ItemAbilities; +import net.neoforged.neoforge.common.ItemAbility; +import net.neoforged.neoforge.common.util.FakePlayer; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class SandPaperItem extends Item implements CustomUseEffectsItem { public SandPaperItem(Properties properties) { - super(properties.defaultDurability(8)); + super(properties.durability(8)); } @Override @@ -54,8 +53,7 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { ItemStack itemstack = playerIn.getItemInHand(handIn); InteractionResultHolder FAIL = new InteractionResultHolder<>(InteractionResult.FAIL, itemstack); - if (itemstack.getOrCreateTag() - .contains("Polishing")) { + if (itemstack.has(AllDataComponents.SAND_PAPER_POLISHING)) { playerIn.startUsingItem(handIn); return new InteractionResultHolder<>(InteractionResult.PASS, itemstack); } @@ -67,17 +65,13 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { ItemStack item = itemInOtherHand.copy(); ItemStack toPolish = item.split(1); playerIn.startUsingItem(handIn); - itemstack.getOrCreateTag() - .put("Polishing", toPolish.serializeNBT()); + itemstack.set(AllDataComponents.SAND_PAPER_POLISHING, toPolish); playerIn.setItemInHand(otherHand, item); return new InteractionResultHolder<>(InteractionResult.SUCCESS, itemstack); } - HitResult raytraceresult = getPlayerPOVHitResult(worldIn, playerIn, ClipContext.Fluid.NONE); - if (!(raytraceresult instanceof BlockHitResult)) - return FAIL; - BlockHitResult ray = (BlockHitResult) raytraceresult; - Vec3 hitVec = ray.getLocation(); + BlockHitResult raytraceresult = getPlayerPOVHitResult(worldIn, playerIn, ClipContext.Fluid.NONE); + Vec3 hitVec = raytraceresult.getLocation(); AABB bb = new AABB(hitVec, hitVec).inflate(1f); ItemEntity pickUp = null; @@ -104,8 +98,7 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { playerIn.startUsingItem(handIn); if (!worldIn.isClientSide) { - itemstack.getOrCreateTag() - .put("Polishing", toPolish.serializeNBT()); + itemstack.set(AllDataComponents.SAND_PAPER_POLISHING, toPolish); if (item.isEmpty()) pickUp.discard(); else @@ -117,12 +110,11 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { @Override public ItemStack finishUsingItem(ItemStack stack, Level worldIn, LivingEntity entityLiving) { - if (!(entityLiving instanceof Player)) + if (!(entityLiving instanceof Player player)) return stack; - Player player = (Player) entityLiving; - CompoundTag tag = stack.getOrCreateTag(); - if (tag.contains("Polishing")) { - ItemStack toPolish = ItemStack.of(tag.getCompound("Polishing")); + if (stack.has(AllDataComponents.SAND_PAPER_POLISHING)) { + ItemStack toPolish = stack.get(AllDataComponents.SAND_PAPER_POLISHING); + //noinspection DataFlowIssue - toPolish won't be null as we do call .has before calling .get ItemStack polished = SandPaperPolishingRecipe.applyPolish(worldIn, entityLiving.position(), toPolish, stack); @@ -142,8 +134,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { .placeItemBackInInventory(polished); } } - tag.remove("Polishing"); - stack.hurtAndBreak(1, entityLiving, p -> p.broadcastBreakEvent(p.getUsedItemHand())); + stack.remove(AllDataComponents.SAND_PAPER_POLISHING); + stack.hurtAndBreak(1, entityLiving, LivingEntity.getSlotForHand(entityLiving.getUsedItemHand())); } return stack; @@ -159,15 +151,14 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { @Override public void releaseUsing(ItemStack stack, Level worldIn, LivingEntity entityLiving, int timeLeft) { - if (!(entityLiving instanceof Player)) + if (!(entityLiving instanceof Player player)) return; - Player player = (Player) entityLiving; - CompoundTag tag = stack.getOrCreateTag(); - if (tag.contains("Polishing")) { - ItemStack toPolish = ItemStack.of(tag.getCompound("Polishing")); + if (stack.has(AllDataComponents.SAND_PAPER_POLISHING)) { + ItemStack toPolish = stack.get(AllDataComponents.SAND_PAPER_POLISHING); + //noinspection DataFlowIssue - toPolish won't be null as we do call .has before calling .get player.getInventory() .placeItemBackInInventory(toPolish); - tag.remove("Polishing"); + stack.remove(AllDataComponents.SAND_PAPER_POLISHING); } } @@ -179,12 +170,12 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { BlockPos pos = context.getClickedPos(); BlockState state = level.getBlockState(pos); - BlockState newState = state.getToolModifiedState(context, ToolActions.AXE_SCRAPE, false); + BlockState newState = state.getToolModifiedState(context, ItemAbilities.AXE_SCRAPE, false); if (newState != null) { AllSoundEvents.SANDING_LONG.play(level, player, pos, 1, 1 + (level.random.nextFloat() * 0.5f - 1f) / 5f); level.levelEvent(player, 3005, pos, 0); // Spawn particles } else { - newState = state.getToolModifiedState(context, ToolActions.AXE_WAX_OFF, false); + newState = state.getToolModifiedState(context, ItemAbilities.AXE_WAX_OFF, false); if (newState != null) { AllSoundEvents.SANDING_LONG.play(level, player, pos, 1, 1 + (level.random.nextFloat() * 0.5f - 1f) / 5f); @@ -195,7 +186,7 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { if (newState != null) { level.setBlockAndUpdate(pos, newState); if (player != null) - stack.hurtAndBreak(1, player, p -> p.broadcastBreakEvent(p.getUsedItemHand())); + stack.hurtAndBreak(1, player, LivingEntity.getSlotForHand(player.getUsedItemHand())); return InteractionResult.sidedSuccess(level.isClientSide); } @@ -203,8 +194,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { } @Override - public boolean canPerformAction(ItemStack stack, ToolAction toolAction) { - return toolAction == ToolActions.AXE_SCRAPE || toolAction == ToolActions.AXE_WAX_OFF; + public boolean canPerformAction(ItemStack stack, ItemAbility itemAbility) { + return itemAbility == ItemAbilities.AXE_SCRAPE || itemAbility == ItemAbilities.AXE_WAX_OFF; } @Override @@ -215,9 +206,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { @Override public boolean triggerUseEffects(ItemStack stack, LivingEntity entity, int count, RandomSource random) { - CompoundTag tag = stack.getOrCreateTag(); - if (tag.contains("Polishing")) { - ItemStack polishing = ItemStack.of(tag.getCompound("Polishing")); + if (stack.has(AllDataComponents.SAND_PAPER_POLISHING)) { + ItemStack polishing = stack.get(AllDataComponents.SAND_PAPER_POLISHING); ((LivingEntityAccessor) entity).create$callSpawnItemParticles(polishing, 1); } @@ -240,7 +230,7 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { } @Override - public int getUseDuration(ItemStack stack) { + public int getUseDuration(ItemStack stack, LivingEntity entity) { return 32; } diff --git a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItemRenderer.java b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItemRenderer.java index cefe36ab52..7f757d0453 100644 --- a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItemRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItemRenderer.java @@ -2,6 +2,7 @@ package com.simibubi.create.content.equipment.sandPaper; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.foundation.item.render.CustomRenderedItemModel; import com.simibubi.create.foundation.item.render.CustomRenderedItemModelRenderer; import com.simibubi.create.foundation.item.render.PartialItemModelRenderer; @@ -11,29 +12,30 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.nbt.CompoundTag; import net.minecraft.util.Mth; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; public class SandPaperItemRenderer extends CustomRenderedItemModelRenderer { @Override protected void render(ItemStack stack, CustomRenderedItemModel model, PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, MultiBufferSource buffer, int light, int overlay) { - ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); - LocalPlayer player = Minecraft.getInstance().player; + Minecraft mc = Minecraft.getInstance(); + ItemRenderer itemRenderer = mc.getItemRenderer(); + LocalPlayer player = mc.player; + Level level = mc.level; float partialTicks = AnimationTickHolder.getPartialTicks(); boolean leftHand = transformType == ItemDisplayContext.FIRST_PERSON_LEFT_HAND; boolean firstPerson = leftHand || transformType == ItemDisplayContext.FIRST_PERSON_RIGHT_HAND; - CompoundTag tag = stack.getOrCreateTag(); - boolean jeiMode = tag.contains("JEI"); + boolean jeiMode = stack.has(AllDataComponents.SAND_PAPER_JEI); ms.pushPose(); - if (tag.contains("Polishing")) { + if (stack.has(AllDataComponents.SAND_PAPER_POLISHING)) { ms.pushPose(); if (transformType == ItemDisplayContext.GUI) { @@ -46,8 +48,8 @@ public class SandPaperItemRenderer extends CustomRenderedItemModelRenderer { // Reverse bobbing float time = (float) (!jeiMode ? player.getUseItemRemainingTicks() - : (-AnimationTickHolder.getTicks()) % stack.getUseDuration()) - partialTicks + 1.0F; - if (time / (float) stack.getUseDuration() < 0.8F) { + : (-AnimationTickHolder.getTicks()) % stack.getUseDuration(player)) - partialTicks + 1.0F; + if (time / (float) stack.getUseDuration(player) < 0.8F) { float bobbing = -Mth.abs(Mth.cos(time / 4.0F * (float) Math.PI) * 0.1F); if (transformType == ItemDisplayContext.GUI) @@ -56,7 +58,8 @@ public class SandPaperItemRenderer extends CustomRenderedItemModelRenderer { ms.translate(0.0f, bobbing, 0.0F); } - ItemStack toPolish = ItemStack.of(tag.getCompound("Polishing")); + ItemStack toPolish = stack.get(AllDataComponents.SAND_PAPER_POLISHING); + //noinspection DataFlowIssue - We call .has, toPolish won't be null itemRenderer.renderStatic(toPolish, ItemDisplayContext.NONE, light, overlay, ms, buffer, player.level(), 0); ms.popPose(); diff --git a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperPolishingRecipe.java b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperPolishingRecipe.java index ea0659deb3..0e1dca0755 100644 --- a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperPolishingRecipe.java +++ b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperPolishingRecipe.java @@ -5,26 +5,25 @@ import java.util.List; import javax.annotation.ParametersAreNonnullByDefault; import com.simibubi.create.AllRecipeTypes; -import com.simibubi.create.content.equipment.sandPaper.SandPaperPolishingRecipe.SandPaperInv; import com.simibubi.create.content.processing.recipe.ProcessingRecipe; import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeParams; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; +import net.minecraft.world.item.crafting.SingleRecipeInput; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.items.ItemStackHandler; -import net.minecraftforge.items.wrapper.RecipeWrapper; @ParametersAreNonnullByDefault -public class SandPaperPolishingRecipe extends ProcessingRecipe { +public class SandPaperPolishingRecipe extends ProcessingRecipe { public SandPaperPolishingRecipe(ProcessingRecipeParams params) { super(AllRecipeTypes.SANDPAPER_POLISHING, params); } @Override - public boolean matches(SandPaperInv inv, Level worldIn) { + public boolean matches(SingleRecipeInput inv, Level worldIn) { return ingredients.get(0) .test(inv.getItem(0)); } @@ -44,26 +43,16 @@ public class SandPaperPolishingRecipe extends ProcessingRecipe { } public static ItemStack applyPolish(Level world, Vec3 position, ItemStack stack, ItemStack sandPaperStack) { - List> matchingRecipes = getMatchingRecipes(world, stack); + List>> matchingRecipes = getMatchingRecipes(world, stack); if (!matchingRecipes.isEmpty()) - return matchingRecipes.get(0) - .assemble(new SandPaperInv(stack), world.registryAccess()) + return matchingRecipes.get(0).value() + .assemble(new SingleRecipeInput(stack), world.registryAccess()) .copy(); return stack; } - public static List> getMatchingRecipes(Level world, ItemStack stack) { + public static List>> getMatchingRecipes(Level world, ItemStack stack) { return world.getRecipeManager() - .getRecipesFor(AllRecipeTypes.SANDPAPER_POLISHING.getType(), new SandPaperInv(stack), world); + .getRecipesFor(AllRecipeTypes.SANDPAPER_POLISHING.getType(), new SingleRecipeInput(stack), world); } - - public static class SandPaperInv extends RecipeWrapper { - - public SandPaperInv(ItemStack stack) { - super(new ItemStackHandler(1)); - inv.setStackInSlot(0, stack); - } - - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/ConfigureSymmetryWandPacket.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/ConfigureSymmetryWandPacket.java index 068011bd73..e039e5b109 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/ConfigureSymmetryWandPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/ConfigureSymmetryWandPacket.java @@ -1,48 +1,35 @@ package com.simibubi.create.content.equipment.symmetryWand; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.equipment.symmetryWand.mirror.SymmetryMirror; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import com.simibubi.create.infrastructure.codec.CreateStreamCodecs; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ConfigureSymmetryWandPacket extends SimplePacketBase { +public record ConfigureSymmetryWandPacket(InteractionHand hand, SymmetryMirror mirror) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecs.HAND, ConfigureSymmetryWandPacket::hand, + SymmetryMirror.STREAM_CODEC, ConfigureSymmetryWandPacket::mirror, + ConfigureSymmetryWandPacket::new + ); - protected InteractionHand hand; - protected SymmetryMirror mirror; - - public ConfigureSymmetryWandPacket(InteractionHand hand, SymmetryMirror mirror) { - this.hand = hand; - this.mirror = mirror; - } - - public ConfigureSymmetryWandPacket(FriendlyByteBuf buffer) { - hand = buffer.readEnum(InteractionHand.class); - mirror = SymmetryMirror.fromNBT(buffer.readNbt()); + @Override + public void handle(ServerPlayer player) { + ItemStack stack = player.getItemInHand(hand); + if (stack.getItem() instanceof SymmetryWandItem) { + SymmetryWandItem.configureSettings(stack, mirror); + } } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeEnum(hand); - buffer.writeNbt(mirror.writeToNbt()); + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONFIGURE_SYMMETRY_WAND; } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - if (player == null) { - return; - } - ItemStack stack = player.getItemInHand(hand); - if (stack.getItem() instanceof SymmetryWandItem) { - SymmetryWandItem.configureSettings(stack, mirror); - } - }); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryEffectPacket.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryEffectPacket.java index c7572c4cbb..ccc6cdf225 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryEffectPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryEffectPacket.java @@ -1,55 +1,38 @@ package com.simibubi.create.content.equipment.symmetryWand; -import java.util.ArrayList; import java.util.List; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ClientboundPacketPayload; -import net.minecraft.client.Minecraft; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class SymmetryEffectPacket extends SimplePacketBase { +public record SymmetryEffectPacket(BlockPos mirror, List positions) implements ClientboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + BlockPos.STREAM_CODEC, SymmetryEffectPacket::mirror, + CatnipStreamCodecBuilders.list(BlockPos.STREAM_CODEC), SymmetryEffectPacket::positions, + SymmetryEffectPacket::new + ); - private BlockPos mirror; - private List positions; - - public SymmetryEffectPacket(BlockPos mirror, List positions) { - this.mirror = mirror; - this.positions = positions; - } - - public SymmetryEffectPacket(FriendlyByteBuf buffer) { - mirror = buffer.readBlockPos(); - int amt = buffer.readInt(); - positions = new ArrayList<>(amt); - for (int i = 0; i < amt; i++) { - positions.add(buffer.readBlockPos()); - } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.SYMMETRY_EFFECT; } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(mirror); - buffer.writeInt(positions.size()); - for (BlockPos blockPos : positions) { - buffer.writeBlockPos(blockPos); - } + @OnlyIn(Dist.CLIENT) + public void handle(LocalPlayer player) { + if (player.position().distanceTo(Vec3.atLowerCornerOf(mirror)) > 100) + return; + for (BlockPos to : positions) + SymmetryHandler.drawEffect(mirror, to); } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { - if (Minecraft.getInstance().player.position().distanceTo(Vec3.atLowerCornerOf(mirror)) > 100) - return; - for (BlockPos to : positions) - SymmetryHandler.drawEffect(mirror, to); - })); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryHandler.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryHandler.java index 3a8772ca46..57c7a29130 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryHandler.java @@ -2,6 +2,10 @@ package com.simibubi.create.content.equipment.symmetryWand; import java.util.Random; +import net.neoforged.fml.common.EventBusSubscriber; + +import net.neoforged.neoforge.client.event.ClientTickEvent; + import org.joml.Vector3f; import com.mojang.blaze3d.vertex.PoseStack; @@ -28,21 +32,17 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.RenderLevelStageEvent; -import net.minecraftforge.client.event.RenderLevelStageEvent.Stage; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.event.TickEvent.ClientTickEvent; -import net.minecraftforge.event.TickEvent.Phase; -import net.minecraftforge.event.level.BlockEvent.BreakEvent; -import net.minecraftforge.event.level.BlockEvent.EntityPlaceEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.client.event.RenderLevelStageEvent; +import net.neoforged.neoforge.client.event.RenderLevelStageEvent.Stage; +import net.neoforged.neoforge.client.model.data.ModelData; +import net.neoforged.neoforge.event.level.BlockEvent.BreakEvent; +import net.neoforged.neoforge.event.level.BlockEvent.EntityPlaceEvent; -@EventBusSubscriber(bus = Bus.FORGE) +@EventBusSubscriber public class SymmetryHandler { private static int tickCounter = 0; @@ -79,7 +79,7 @@ public class SymmetryHandler { public static void onRenderWorld(RenderLevelStageEvent event) { if (event.getStage() != Stage.AFTER_PARTICLES) return; - + Minecraft mc = Minecraft.getInstance(); LocalPlayer player = mc.player; RandomSource random = RandomSource.create(); @@ -127,9 +127,7 @@ public class SymmetryHandler { @OnlyIn(Dist.CLIENT) @SubscribeEvent - public static void onClientTick(ClientTickEvent event) { - if (event.phase == Phase.START) - return; + public static void onClientTick(ClientTickEvent.Post event) { Minecraft mc = Minecraft.getInstance(); LocalPlayer player = mc.player; diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java index 63b8a719b5..1c2b6153e4 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java @@ -10,21 +10,22 @@ import javax.annotation.Nonnull; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllItems; -import com.simibubi.create.AllPackets; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.content.contraptions.mounted.CartAssemblerBlock; import com.simibubi.create.content.equipment.symmetryWand.mirror.CrossPlaneMirror; import com.simibubi.create.content.equipment.symmetryWand.mirror.EmptyMirror; import com.simibubi.create.content.equipment.symmetryWand.mirror.PlaneMirror; import com.simibubi.create.content.equipment.symmetryWand.mirror.SymmetryMirror; import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.BlockHelper; +import com.simibubi.create.foundation.utility.DistExecutor; import com.simibubi.create.infrastructure.config.AllConfigs; import net.createmod.catnip.gui.ScreenOpener; import net.createmod.catnip.utility.Iterate; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; @@ -42,19 +43,14 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; -import net.minecraftforge.common.util.BlockSnapshot; -import net.minecraftforge.event.ForgeEventFactory; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.common.util.BlockSnapshot; +import net.neoforged.neoforge.event.EventHooks; public class SymmetryWandItem extends Item { - public static final String SYMMETRY = "symmetry"; - private static final String ENABLE = "enable"; - public SymmetryWandItem(Properties properties) { super(properties); } @@ -69,12 +65,12 @@ public class SymmetryWandItem extends Item { player.getCooldowns() .addCooldown(this, 5); ItemStack wand = player.getItemInHand(context.getHand()); - checkNBT(wand); + checkComponents(wand); // Shift -> open GUI if (player.isShiftKeyDown()) { if (player.level().isClientSide) { - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> { openWandGUI(wand, context.getHand()); }); player.getCooldowns() @@ -86,14 +82,11 @@ public class SymmetryWandItem extends Item { if (context.getLevel().isClientSide || context.getHand() != InteractionHand.MAIN_HAND) return InteractionResult.SUCCESS; - CompoundTag compound = wand.getTag() - .getCompound(SYMMETRY); pos = pos.relative(context.getClickedFace()); - SymmetryMirror previousElement = SymmetryMirror.fromNBT(compound); + SymmetryMirror previousElement = wand.get(AllDataComponents.SYMMETRY_WAND); // No Shift -> Make / Move Mirror - wand.getTag() - .putBoolean(ENABLE, true); + wand.set(AllDataComponents.SYMMETRY_WAND_ENABLE, true); Vec3 pos3d = new Vec3(pos.getX(), pos.getY(), pos.getZ()); SymmetryMirror newElement = new PlaneMirror(pos3d); @@ -103,9 +96,7 @@ public class SymmetryWandItem extends Item { ? PlaneMirror.Align.XY.ordinal() : PlaneMirror.Align.YZ.ordinal()); newElement.enable = true; - wand.getTag() - .putBoolean(ENABLE, true); - + wand.set(AllDataComponents.SYMMETRY_WAND_ENABLE, true); } else { previousElement.setPosition(pos3d); @@ -127,9 +118,7 @@ public class SymmetryWandItem extends Item { newElement = previousElement; } - compound = newElement.writeToNbt(); - wand.getTag() - .put(SYMMETRY, compound); + wand.set(AllDataComponents.SYMMETRY_WAND, newElement); player.setItemInHand(context.getHand(), wand); return InteractionResult.SUCCESS; @@ -138,24 +127,23 @@ public class SymmetryWandItem extends Item { @Override public InteractionResultHolder use(Level worldIn, Player playerIn, InteractionHand handIn) { ItemStack wand = playerIn.getItemInHand(handIn); - checkNBT(wand); + checkComponents(wand); // Shift -> Open GUI if (playerIn.isShiftKeyDown()) { if (worldIn.isClientSide) { - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> { openWandGUI(playerIn.getItemInHand(handIn), handIn); }); playerIn.getCooldowns() .addCooldown(this, 5); } - return new InteractionResultHolder(InteractionResult.SUCCESS, wand); + return new InteractionResultHolder<>(InteractionResult.SUCCESS, wand); } // No Shift -> Clear Mirror - wand.getTag() - .putBoolean(ENABLE, false); - return new InteractionResultHolder(InteractionResult.SUCCESS, wand); + wand.set(AllDataComponents.SYMMETRY_WAND_ENABLE, false); + return new InteractionResultHolder<>(InteractionResult.SUCCESS, wand); } @OnlyIn(Dist.CLIENT) @@ -163,36 +151,31 @@ public class SymmetryWandItem extends Item { ScreenOpener.open(new SymmetryWandScreen(wand, hand)); } - private static void checkNBT(ItemStack wand) { - if (!wand.hasTag() || !wand.getTag() - .contains(SYMMETRY)) { - wand.setTag(new CompoundTag()); - wand.getTag() - .put(SYMMETRY, new EmptyMirror(new Vec3(0, 0, 0)).writeToNbt()); - wand.getTag() - .putBoolean(ENABLE, false); + private static void checkComponents(ItemStack wand) { + if (!wand.has(AllDataComponents.SYMMETRY_WAND)) { + wand.set(AllDataComponents.SYMMETRY_WAND, new EmptyMirror(new Vec3(0, 0, 0))); + wand.set(AllDataComponents.SYMMETRY_WAND_ENABLE, false); } } public static boolean isEnabled(ItemStack stack) { - checkNBT(stack); - CompoundTag tag = stack.getTag(); - return tag.getBoolean(ENABLE) && !tag.getBoolean("Simulate"); + checkComponents(stack); + return stack.getOrDefault(AllDataComponents.SYMMETRY_WAND_ENABLE, false) && + !stack.getOrDefault(AllDataComponents.SYMMETRY_WAND_SIMULATE, false); } public static SymmetryMirror getMirror(ItemStack stack) { - checkNBT(stack); - return SymmetryMirror.fromNBT(stack.getTag() - .getCompound(SYMMETRY)); + checkComponents(stack); + return stack.get(AllDataComponents.SYMMETRY_WAND); } public static void configureSettings(ItemStack stack, SymmetryMirror mirror) { - checkNBT(stack); - stack.getTag().put(SYMMETRY, mirror.writeToNbt()); + checkComponents(stack); + stack.set(AllDataComponents.SYMMETRY_WAND, mirror); } public static void apply(Level world, ItemStack wand, Player player, BlockPos pos, BlockState block) { - checkNBT(wand); + checkComponents(wand); if (!isEnabled(wand)) return; if (!BlockItem.BY_BLOCK.containsKey(block.getBlock())) @@ -200,8 +183,7 @@ public class SymmetryWandItem extends Item { Map blockSet = new HashMap<>(); blockSet.put(pos, block); - SymmetryMirror symmetry = SymmetryMirror.fromNBT((CompoundTag) wand.getTag() - .getCompound(SYMMETRY)); + SymmetryMirror symmetry = wand.get(AllDataComponents.SYMMETRY_WAND); Vec3 mirrorPos = symmetry.getPosition(); if (mirrorPos.distanceTo(Vec3.atLowerCornerOf(pos)) > AllConfigs.server().equipment.maxSymmetryWandRange.get()) @@ -253,21 +235,19 @@ public class SymmetryWandItem extends Item { world.setBlock(position, ifluidstate.createLegacyBlock(), Block.UPDATE_KNOWN_SHAPE); world.setBlockAndUpdate(position, blockState); - CompoundTag wandNbt = wand.getOrCreateTag(); - wandNbt.putBoolean("Simulate", true); - boolean placeInterrupted = ForgeEventFactory.onBlockPlace(player, blocksnapshot, Direction.UP); - wandNbt.putBoolean("Simulate", false); + wand.set(AllDataComponents.SYMMETRY_WAND_SIMULATE, true); + boolean placeInterrupted = EventHooks.onBlockPlace(player, blocksnapshot, Direction.UP); + wand.set(AllDataComponents.SYMMETRY_WAND_SIMULATE, false); if (placeInterrupted) { - blocksnapshot.restore(true, false); + blocksnapshot.restore(Block.UPDATE_CLIENTS); continue; } targets.add(position); } } - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player), - new SymmetryEffectPacket(to, targets)); + CatnipServices.NETWORK.sendToClientsTrackingAndSelf(player, new SymmetryEffectPacket(to, targets)); } private static boolean isHoldingBlock(Player player, BlockState block) { @@ -278,14 +258,13 @@ public class SymmetryWandItem extends Item { public static void remove(Level world, ItemStack wand, Player player, BlockPos pos) { BlockState air = Blocks.AIR.defaultBlockState(); BlockState ogBlock = world.getBlockState(pos); - checkNBT(wand); + checkComponents(wand); if (!isEnabled(wand)) return; Map blockSet = new HashMap<>(); blockSet.put(pos, air); - SymmetryMirror symmetry = SymmetryMirror.fromNBT((CompoundTag) wand.getTag() - .getCompound(SYMMETRY)); + SymmetryMirror symmetry = wand.get(AllDataComponents.SYMMETRY_WAND); Vec3 mirrorPos = symmetry.getPosition(); if (mirrorPos.distanceTo(Vec3.atLowerCornerOf(pos)) > AllConfigs.server().equipment.maxSymmetryWandRange.get()) @@ -321,8 +300,7 @@ public class SymmetryWandItem extends Item { } } - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> player), - new SymmetryEffectPacket(to, targets)); + CatnipServices.NETWORK.sendToClientsTrackingAndSelf(player, new SymmetryEffectPacket(to, targets)); } @Override @@ -330,7 +308,7 @@ public class SymmetryWandItem extends Item { public void initializeClient(Consumer consumer) { consumer.accept(SimpleCustomRenderer.create(this, new SymmetryWandItemRenderer())); } - + public static boolean presentInHotbar(Player player) { Inventory inv = player.getInventory(); for (int i = 0; i < Inventory.getSelectionSize(); i++) diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandScreen.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandScreen.java index 890d4fd5c6..038d9f8f04 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandScreen.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandScreen.java @@ -1,10 +1,11 @@ package com.simibubi.create.content.equipment.symmetryWand; +import net.createmod.catnip.platform.CatnipServices; + import org.joml.Vector3f; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; -import com.simibubi.create.AllPackets; import com.simibubi.create.content.equipment.symmetryWand.mirror.CrossPlaneMirror; import com.simibubi.create.content.equipment.symmetryWand.mirror.EmptyMirror; import com.simibubi.create.content.equipment.symmetryWand.mirror.PlaneMirror; @@ -153,7 +154,7 @@ public class SymmetryWandScreen extends AbstractSimiScreen { @Override public void removed() { SymmetryWandItem.configureSettings(wand, currentElement); - AllPackets.getChannel().sendToServer(new ConfigureSymmetryWandPacket(hand, currentElement)); + CatnipServices.NETWORK.sendToServer(new ConfigureSymmetryWandPacket(hand, currentElement)); } } diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/CrossPlaneMirror.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/CrossPlaneMirror.java index 4363f2d843..657f93bf19 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/CrossPlaneMirror.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/CrossPlaneMirror.java @@ -16,8 +16,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.StringRepresentable; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class CrossPlaneMirror extends SymmetryMirror { diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/EmptyMirror.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/EmptyMirror.java index 85d79136af..01d0ddf651 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/EmptyMirror.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/EmptyMirror.java @@ -12,8 +12,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.StringRepresentable; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class EmptyMirror extends SymmetryMirror { diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/PlaneMirror.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/PlaneMirror.java index ffd1133d32..4e7785d6bd 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/PlaneMirror.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/PlaneMirror.java @@ -16,8 +16,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.StringRepresentable; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class PlaneMirror extends SymmetryMirror { diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/SymmetryMirror.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/SymmetryMirror.java index a67ba5dcff..9f6862063b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/SymmetryMirror.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/SymmetryMirror.java @@ -3,18 +3,22 @@ package com.simibubi.create.content.equipment.symmetryWand.mirror; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; import com.simibubi.create.foundation.utility.CreateLang; import dev.engine_room.flywheel.lib.model.baked.PartialModel; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.FloatTag; -import net.minecraft.nbt.ListTag; import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.util.StringRepresentable; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; @@ -23,16 +27,30 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.DirectionProperty; import net.minecraft.world.level.block.state.properties.Property; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public abstract class SymmetryMirror { - public static final String EMPTY = "empty"; public static final String PLANE = "plane"; public static final String CROSS_PLANE = "cross_plane"; public static final String TRIPLE_PLANE = "triple_plane"; + public static final Codec CODEC = RecordCodecBuilder.create(i -> i.group( + Codec.INT.fieldOf("orientationIndex").forGetter(SymmetryMirror::getOrientationIndex), + Vec3.CODEC.fieldOf("position").forGetter(SymmetryMirror::getPosition), + Codec.STRING.fieldOf("type").forGetter(SymmetryMirror::typeName), + Codec.BOOL.fieldOf("enable").forGetter(m -> m.enable) + ).apply(i, SymmetryMirror::create)); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.INT, SymmetryMirror::getOrientationIndex, + CatnipStreamCodecs.VEC3, SymmetryMirror::getPosition, + ByteBufCodecs.STRING_UTF8, SymmetryMirror::typeName, + ByteBufCodecs.BOOL, m -> m.enable, + SymmetryMirror::create + ); + protected Vec3 position; protected StringRepresentable orientation; protected int orientationIndex; @@ -49,6 +67,20 @@ public abstract class SymmetryMirror { CreateLang.translateDirect("symmetry.mirror.triplePlane")); } + private static SymmetryMirror create(Integer orientationIndex, Vec3 position, String type, Boolean enable) { + SymmetryMirror element = switch (type) { + case PLANE -> new PlaneMirror(position); + case CROSS_PLANE -> new CrossPlaneMirror(position); + case TRIPLE_PLANE -> new TriplePlaneMirror(position); + default -> new EmptyMirror(position); + }; + + element.setOrientation(orientationIndex); + element.enable = enable; + + return element; + } + public StringRepresentable getOrientation() { return orientation; } @@ -87,52 +119,6 @@ public abstract class SymmetryMirror { public void applyModelTransform(PoseStack ms) {} - private static final String $ORIENTATION = "direction"; - private static final String $POSITION = "pos"; - private static final String $TYPE = "type"; - private static final String $ENABLE = "enable"; - - public CompoundTag writeToNbt() { - CompoundTag nbt = new CompoundTag(); - nbt.putInt($ORIENTATION, orientationIndex); - - ListTag floatList = new ListTag(); - floatList.add(FloatTag.valueOf((float) position.x)); - floatList.add(FloatTag.valueOf((float) position.y)); - floatList.add(FloatTag.valueOf((float) position.z)); - nbt.put($POSITION, floatList); - nbt.putString($TYPE, typeName()); - nbt.putBoolean($ENABLE, enable); - - return nbt; - } - - public static SymmetryMirror fromNBT(CompoundTag nbt) { - ListTag floatList = nbt.getList($POSITION, 5); - Vec3 pos = new Vec3(floatList.getFloat(0), floatList.getFloat(1), floatList.getFloat(2)); - SymmetryMirror element; - - switch (nbt.getString($TYPE)) { - case PLANE: - element = new PlaneMirror(pos); - break; - case CROSS_PLANE: - element = new CrossPlaneMirror(pos); - break; - case TRIPLE_PLANE: - element = new TriplePlaneMirror(pos); - break; - default: - element = new EmptyMirror(pos); - break; - } - - element.setOrientation(nbt.getInt($ORIENTATION)); - element.enable = nbt.getBoolean($ENABLE); - - return element; - } - protected Vec3 getDiff(BlockPos position) { return this.position.scale(-1) .add(position.getX(), position.getY(), position.getZ()); @@ -213,4 +199,20 @@ public abstract class SymmetryMirror { public abstract List getAlignToolTips(); + @Override + public final boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof SymmetryMirror that)) return false; + + return getOrientationIndex() == that.getOrientationIndex() && enable == that.enable && Objects.equals(getPosition(), that.getPosition()) && Objects.equals(getOrientation(), that.getOrientation()); + } + + @Override + public int hashCode() { + int result = Objects.hashCode(getPosition()); + result = 31 * result + Objects.hashCode(getOrientation()); + result = 31 * result + getOrientationIndex(); + result = 31 * result + Boolean.hashCode(enable); + return result; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/TriplePlaneMirror.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/TriplePlaneMirror.java index 9c8a814380..28ed63f39c 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/TriplePlaneMirror.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/mirror/TriplePlaneMirror.java @@ -14,8 +14,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.util.StringRepresentable; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class TriplePlaneMirror extends SymmetryMirror { diff --git a/src/main/java/com/simibubi/create/content/equipment/tool/AllToolMaterials.java b/src/main/java/com/simibubi/create/content/equipment/tool/AllToolMaterials.java index eb9e7021fa..5c218b8b45 100644 --- a/src/main/java/com/simibubi/create/content/equipment/tool/AllToolMaterials.java +++ b/src/main/java/com/simibubi/create/content/equipment/tool/AllToolMaterials.java @@ -2,28 +2,31 @@ package com.simibubi.create.content.equipment.tool; import java.util.function.Supplier; +import org.jetbrains.annotations.NotNull; + import com.simibubi.create.AllItems; import com.simibubi.create.Create; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Tier; import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.block.Block; public enum AllToolMaterials implements Tier { - CARDBOARD(Create.asResource("cardboard") .toString(), 200, 1, 2, 1, () -> Ingredient.of(AllItems.CARDBOARD.asItem())) - ; - public String name; + public final String name; - private int uses; - private float speed; - private float damageBonus; - private int enchantValue; - private Supplier repairMaterial; + private final int uses; + private final float speed; + private final float damageBonus; + private final int enchantValue; + private final Supplier repairMaterial; - private AllToolMaterials(String name, int uses, float speed, float damageBonus, int enchantValue, + AllToolMaterials(String name, int uses, float speed, float damageBonus, int enchantValue, Supplier repairMaterial) { this.name = name; this.uses = uses; @@ -49,8 +52,8 @@ public enum AllToolMaterials implements Tier { } @Override - public int getLevel() { - return 0; + public @NotNull TagKey getIncorrectBlocksForDrops() { + return BlockTags.INCORRECT_FOR_WOODEN_TOOL; } @Override @@ -59,8 +62,7 @@ public enum AllToolMaterials implements Tier { } @Override - public Ingredient getRepairIngredient() { + public @NotNull Ingredient getRepairIngredient() { return repairMaterial.get(); } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/tool/CardboardSwordItem.java b/src/main/java/com/simibubi/create/content/equipment/tool/CardboardSwordItem.java index ccda5e4d21..8621e9240b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/tool/CardboardSwordItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/tool/CardboardSwordItem.java @@ -2,14 +2,15 @@ package com.simibubi.create.content.equipment.tool; import java.util.function.Consumer; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.simibubi.create.AllItems; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; +import net.createmod.catnip.platform.CatnipServices; +import net.minecraft.core.Holder; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; @@ -22,43 +23,36 @@ import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.monster.Spider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.ItemStack.TooltipPart; -import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.SwordItem; +import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; -import net.minecraftforge.event.entity.living.LivingAttackEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock.Action; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.LogicalSide; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.network.PacketDistributor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.LogicalSide; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.event.entity.player.AttackEntityEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; @EventBusSubscriber public class CardboardSwordItem extends SwordItem { public CardboardSwordItem(Properties pProperties) { - super(AllToolMaterials.CARDBOARD, 3, 1f, pProperties); + super(AllToolMaterials.CARDBOARD, pProperties); } @Override public int getBurnTime(ItemStack itemStack, @Nullable RecipeType recipeType) { return 1000; } - - @Override - public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) { - return enchantment == Enchantments.KNOCKBACK; - } @Override - public int getDefaultTooltipHideFlags(@NotNull ItemStack stack) { - return TooltipPart.MODIFIERS.getMask(); + public boolean supportsEnchantment(ItemStack stack, Holder enchantment) { + return enchantment == Enchantments.KNOCKBACK; } @Override @@ -68,11 +62,11 @@ public class CardboardSwordItem extends SwordItem { } @SubscribeEvent - public static void cardboardSwordsMakeNoiseOnClick(LeftClickBlock event) { + public static void cardboardSwordsMakeNoiseOnClick(PlayerInteractEvent.LeftClickBlock event) { ItemStack itemStack = event.getItemStack(); if (!AllItems.CARDBOARD_SWORD.isIn(itemStack)) return; - if (event.getAction() != Action.START) + if (event.getAction() != PlayerInteractEvent.LeftClickBlock.Action.START) return; if (event.getSide() == LogicalSide.CLIENT) AllSoundEvents.CARDBOARD_SWORD.playAt(event.getLevel(), event.getPos(), 0.5f, 1.85f, false); @@ -80,47 +74,48 @@ public class CardboardSwordItem extends SwordItem { AllSoundEvents.CARDBOARD_SWORD.play(event.getLevel(), event.getEntity(), event.getPos(), 0.5f, 1.85f); } - @SubscribeEvent - public static void cardboardSwordsCannotHurtYou(LivingAttackEvent event) { - Entity attacker = event.getSource() - .getEntity(); - LivingEntity target = event.getEntity(); - if (target == null || target instanceof Spider) + // We set priority to highest just so we catch this before anyone does anything else + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void cardboardSwordsCannotHurtYou(AttackEntityEvent event) { + Player attacker = event.getEntity(); + if (!(event.getTarget() instanceof LivingEntity target) || target == null || target instanceof Spider) return; - if (!(attacker instanceof LivingEntity livingAttacker - && AllItems.CARDBOARD_SWORD.isIn(livingAttacker.getItemInHand(InteractionHand.MAIN_HAND)))) + ItemStack stack = attacker.getItemInHand(InteractionHand.MAIN_HAND); + if (!(AllItems.CARDBOARD_SWORD.isIn(stack))) return; + // Previously this was listening to LivingEntityAttackEvent, but that got merged, and so if we cancel this event + // onLeftClickEntity won't be called, so lets just call it manually over here + stack.getItem().onLeftClickEntity(stack, attacker, target); event.setCanceled(true); // Reference player.attack() // This section replicates knockback behaviour without hurting the target - double knockbackStrength = livingAttacker.getAttributeValue(Attributes.ATTACK_KNOCKBACK) + 2; - knockbackStrength += EnchantmentHelper.getKnockbackBonus(livingAttacker); - if (livingAttacker.isSprinting() - && (!(livingAttacker instanceof Player p) || p.getAttackStrengthScale(0.5f) > 0.9f)) + float knockbackStrength = (float) (attacker.getAttributeValue(Attributes.ATTACK_KNOCKBACK) + 2); + if (attacker.level() instanceof ServerLevel serverLevel) + knockbackStrength = EnchantmentHelper.modifyKnockback(serverLevel, stack, target, serverLevel.damageSources().playerAttack(attacker), knockbackStrength); + if (attacker.isSprinting() && attacker.getAttackStrengthScale(0.5f) > 0.9f) ++knockbackStrength; if (knockbackStrength <= 0) return; - float yRot = livingAttacker.getYRot(); + float yRot = attacker.getYRot(); knockback(target, knockbackStrength, yRot); boolean targetIsPlayer = target instanceof Player; MobCategory targetType = target.getClassification(false); if (target instanceof ServerPlayer sp) - AllPackets.getChannel() - .send(PacketDistributor.PLAYER.with(() -> sp), new KnockbackPacket(yRot, (float) knockbackStrength)); + CatnipServices.NETWORK.sendToClient(sp, new KnockbackPacket(yRot, (float) knockbackStrength)); if ((targetType == MobCategory.MISC || targetType == MobCategory.CREATURE) && !targetIsPlayer) target.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 60, 9, true, false, false)); - livingAttacker.setDeltaMovement(livingAttacker.getDeltaMovement() + attacker.setDeltaMovement(attacker.getDeltaMovement() .multiply(0.6D, 1.0D, 0.6D)); - livingAttacker.setSprinting(false); + attacker.setSprinting(false); } public static void knockback(LivingEntity target, double knockbackStrength, float yRot) { diff --git a/src/main/java/com/simibubi/create/content/equipment/tool/KnockbackPacket.java b/src/main/java/com/simibubi/create/content/equipment/tool/KnockbackPacket.java index 733df927f1..9adba1730c 100644 --- a/src/main/java/com/simibubi/create/content/equipment/tool/KnockbackPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/tool/KnockbackPacket.java @@ -1,43 +1,28 @@ package com.simibubi.create.content.equipment.tool; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; -import net.minecraft.client.Minecraft; +import io.netty.buffer.ByteBuf; +import net.createmod.catnip.net.base.ClientboundPacketPayload; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.network.NetworkEvent.Context; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; -public class KnockbackPacket extends SimplePacketBase { +public record KnockbackPacket(float yRot, float strength) implements ClientboundPacketPayload { + public static StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.FLOAT, KnockbackPacket::yRot, + ByteBufCodecs.FLOAT, KnockbackPacket::strength, + KnockbackPacket::new + ); - private float yRot; - private float strength; - - public KnockbackPacket(float yRot, float strength) { - this.yRot = yRot; - this.strength = strength; - } - - public KnockbackPacket(FriendlyByteBuf buffer) { - strength = buffer.readFloat(); - yRot = buffer.readFloat(); + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.KNOCKBACK; } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeFloat(strength); - buffer.writeFloat(yRot); + public void handle(LocalPlayer player) { + if (player != null) + CardboardSwordItem.knockback(player, strength, yRot); } - - @Override - @OnlyIn(Dist.CLIENT) - public boolean handle(Context context) { - LocalPlayer player = Minecraft.getInstance().player; - if (player == null) - return true; - CardboardSwordItem.knockback(player, strength, yRot); - return true; - } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ItemReturnInvWrapper.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ItemReturnInvWrapper.java index 24bcc11fda..d457213b9e 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ItemReturnInvWrapper.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ItemReturnInvWrapper.java @@ -2,7 +2,7 @@ package com.simibubi.create.content.equipment.toolbox; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.wrapper.PlayerMainInvWrapper; +import net.neoforged.neoforge.items.wrapper.PlayerMainInvWrapper; /** * For inserting items into a players' inventory anywhere except the hotbar diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/RadialToolboxMenu.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/RadialToolboxMenu.java index 17468ad483..208d960ed0 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/RadialToolboxMenu.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/RadialToolboxMenu.java @@ -12,9 +12,9 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllKeys; -import com.simibubi.create.AllPackets; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.gui.AllIcons; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.CreateLang; import dev.engine_room.flywheel.lib.transform.TransformStack; @@ -213,11 +213,11 @@ public class RadialToolboxMenu extends AbstractSimiScreen { } @Override - public void renderBackground(GuiGraphics graphics) { + public void renderBackground(GuiGraphics pGuiGraphics, int pMouseX, int pMouseY, float pPartialTick) { Color color = BACKGROUND_COLOR .scaleAlpha(Math.min(1, (ticksOpen + AnimationTickHolder.getPartialTicks()) / 20f)); - graphics.fillGradient(0, 0, this.width, this.height, color.getRGB(), color.getRGB()); + pGuiGraphics.fillGradient(0, 0, this.width, this.height, color.getRGB(), color.getRGB()); } @Override @@ -236,9 +236,9 @@ public class RadialToolboxMenu extends AbstractSimiScreen { if (state == State.DETACH) return; else if (state == State.SELECT_BOX) - toolboxes.forEach(be -> AllPackets.getChannel().sendToServer(new ToolboxDisposeAllPacket(be.getBlockPos()))); + toolboxes.forEach(be -> CatnipServices.NETWORK.sendToServer(new ToolboxDisposeAllPacket(be.getBlockPos()))); else - AllPackets.getChannel().sendToServer(new ToolboxDisposeAllPacket(selectedBox.getBlockPos())); + CatnipServices.NETWORK.sendToServer(new ToolboxDisposeAllPacket(selectedBox.getBlockPos())); return; } @@ -247,13 +247,13 @@ public class RadialToolboxMenu extends AbstractSimiScreen { if (state == State.DETACH) { if (selected == UNEQUIP) - AllPackets.getChannel().sendToServer( + CatnipServices.NETWORK.sendToServer( new ToolboxEquipPacket(null, selected, minecraft.player.getInventory().selected)); return; } if (selected == UNEQUIP) - AllPackets.getChannel().sendToServer(new ToolboxEquipPacket(selectedBox.getBlockPos(), selected, + CatnipServices.NETWORK.sendToServer(new ToolboxEquipPacket(selectedBox.getBlockPos(), selected, minecraft.player.getInventory().selected)); if (selected < 0) @@ -266,19 +266,19 @@ public class RadialToolboxMenu extends AbstractSimiScreen { .isEmpty()) return; - AllPackets.getChannel().sendToServer(new ToolboxEquipPacket(selectedBox.getBlockPos(), selected, + CatnipServices.NETWORK.sendToServer(new ToolboxEquipPacket(selectedBox.getBlockPos(), selected, minecraft.player.getInventory().selected)); } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double delta) { + public boolean mouseScrolled(double pMouseX, double pMouseY, double pScrollX, double pScrollY) { Window window = getMinecraft().getWindow(); - double hoveredX = mouseX - window.getGuiScaledWidth() / 2; - double hoveredY = mouseY - window.getGuiScaledHeight() / 2; + double hoveredX = pMouseY - window.getGuiScaledWidth() / 2; + double hoveredY = pMouseY - window.getGuiScaledHeight() / 2; double distance = hoveredX * hoveredX + hoveredY * hoveredY; if (distance <= 150) { scrollMode = true; - scrollSlot = (((int) (scrollSlot - delta)) + 8) % 8; + scrollSlot = (((int) (scrollSlot - pScrollY)) + 8) % 8; for (int i = 0; i < 10; i++) { if (state == State.SELECT_ITEM || state == State.SELECT_ITEM_UNEQUIP) { @@ -296,13 +296,13 @@ public class RadialToolboxMenu extends AbstractSimiScreen { if (state == State.DETACH) break; - scrollSlot -= Mth.sign(delta); + scrollSlot -= Mth.sign(pScrollY); scrollSlot = (scrollSlot + 8) % 8; } return true; } - return super.mouseScrolled(mouseX, mouseY, delta); + return super.mouseScrolled(pMouseX, pMouseY, pScrollX, pScrollY); } @Override @@ -339,7 +339,7 @@ public class RadialToolboxMenu extends AbstractSimiScreen { if (state == State.SELECT_ITEM_UNEQUIP && selected == UNEQUIP) { if (toolboxes.size() > 1) { - AllPackets.getChannel().sendToServer(new ToolboxEquipPacket(selectedBox.getBlockPos(), selected, + CatnipServices.NETWORK.sendToServer(new ToolboxEquipPacket(selectedBox.getBlockPos(), selected, minecraft.player.getInventory().selected)); state = State.SELECT_BOX; return true; diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlock.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlock.java index 613ae91533..0ce6c0c314 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlock.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlock.java @@ -4,28 +4,35 @@ import static net.minecraft.world.level.block.state.properties.BlockStatePropert import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +import com.mojang.serialization.MapCodec; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllBlocks; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllShapes; import com.simibubi.create.foundation.block.IBE; +import com.simibubi.create.foundation.mixin.accessor.ItemStackHandlerAccessor; import com.simibubi.create.foundation.utility.BlockHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; +import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemContainerContents; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.SimpleWaterloggedBlock; @@ -38,13 +45,14 @@ import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.common.util.FakePlayer; -import net.minecraftforge.network.NetworkHooks; +import net.neoforged.neoforge.common.util.FakePlayer; public class ToolboxBlock extends HorizontalDirectionalBlock implements SimpleWaterloggedBlock, IBE { protected final DyeColor color; + public static final MapCodec CODEC = simpleCodec(p -> new ToolboxBlock(p, DyeColor.WHITE)); + public ToolboxBlock(Properties properties, DyeColor color) { super(properties); this.color = color; @@ -70,11 +78,10 @@ public class ToolboxBlock extends HorizontalDirectionalBlock implements SimpleWa if (stack == null) return; withBlockEntityDo(worldIn, pos, be -> { - CompoundTag orCreateTag = stack.getOrCreateTag(); - be.readInventory(orCreateTag.getCompound("Inventory")); - if (orCreateTag.contains("UniqueId")) - be.setUniqueId(orCreateTag.getUUID("UniqueId")); - if (stack.hasCustomHoverName()) + be.readInventory(stack.getOrDefault(AllDataComponents.TOOLBOX_INVENTORY, ItemContainerContents.EMPTY)); + if (stack.has(AllDataComponents.TOOLBOX_UUID)) + be.setUniqueId(stack.get(AllDataComponents.TOOLBOX_UUID)); + if (stack.has(DataComponents.CUSTOM_NAME)) be.setCustomName(stack.getHoverName()); }); } @@ -101,19 +108,18 @@ public class ToolboxBlock extends HorizontalDirectionalBlock implements SimpleWa } @Override - public ItemStack getCloneItemStack(BlockGetter world, BlockPos pos, BlockState state) { + public ItemStack getCloneItemStack(LevelReader level, BlockPos pos, BlockState state) { ItemStack item = new ItemStack(this); - Optional blockEntityOptional = getBlockEntityOptional(world, pos); - CompoundTag tag = item.getOrCreateTag(); + Optional blockEntityOptional = getBlockEntityOptional(level, pos); - CompoundTag inv = blockEntityOptional.map(tb -> tb.inventory.serializeNBT()) - .orElse(new CompoundTag()); - tag.put("Inventory", inv); + NonNullList stacks = blockEntityOptional.map(tb -> ((ItemStackHandlerAccessor) tb.inventory).create$getStacks()) + .orElse(NonNullList.create()); + item.set(AllDataComponents.TOOLBOX_INVENTORY, ItemContainerContents.fromItems(stacks)); - blockEntityOptional.map(tb -> tb.getUniqueId()) - .ifPresent(uid -> tag.putUUID("UniqueId", uid)); + blockEntityOptional.map(ToolboxBlockEntity::getUniqueId) + .ifPresent(uid -> item.set(AllDataComponents.TOOLBOX_UUID, uid)); blockEntityOptional.map(ToolboxBlockEntity::getCustomName) - .ifPresent(item::setHoverName); + .ifPresent(name -> item.set(DataComponents.CUSTOM_NAME, name)); return item; } @@ -131,31 +137,28 @@ public class ToolboxBlock extends HorizontalDirectionalBlock implements SimpleWa } @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { - + protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) { if (player == null || player.isCrouching()) - return InteractionResult.PASS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; - ItemStack stack = player.getItemInHand(hand); DyeColor color = DyeColor.getColor(stack); if (color != null && color != this.color) { - if (world.isClientSide) - return InteractionResult.SUCCESS; + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; BlockState newState = BlockHelper.copyProperties(state, AllBlocks.TOOLBOXES.get(color) .getDefaultState()); - world.setBlockAndUpdate(pos, newState); - return InteractionResult.SUCCESS; + level.setBlockAndUpdate(pos, newState); + return ItemInteractionResult.SUCCESS; } if (player instanceof FakePlayer) - return InteractionResult.PASS; - if (world.isClientSide) - return InteractionResult.SUCCESS; + return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; + if (level.isClientSide) + return ItemInteractionResult.SUCCESS; - withBlockEntityDo(world, pos, - toolbox -> NetworkHooks.openScreen((ServerPlayer) player, toolbox, toolbox::sendToMenu)); - return InteractionResult.SUCCESS; + withBlockEntityDo(level, pos, + toolbox -> player.openMenu(toolbox, toolbox::sendToMenu)); + return ItemInteractionResult.SUCCESS; } @Override @@ -171,7 +174,7 @@ public class ToolboxBlock extends HorizontalDirectionalBlock implements SimpleWa public Class getBlockEntityClass() { return ToolboxBlockEntity.class; } - + @Override public BlockEntityType getBlockEntityType() { return AllBlockEntityTypes.TOOLBOX.get(); @@ -186,4 +189,8 @@ public class ToolboxBlock extends HorizontalDirectionalBlock implements SimpleWa .get()); } + @Override + protected @NotNull MapCodec codec() { + return CODEC; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java index 90542b1968..4de9584947 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java @@ -10,17 +10,20 @@ import java.util.Set; import java.util.UUID; import java.util.WeakHashMap; +import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllBlocks; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import com.simibubi.create.foundation.blockEntity.behaviour.animatedContainer.AnimatedContainerBehaviour; +import com.simibubi.create.foundation.item.ItemHelper; import com.simibubi.create.foundation.utility.ResetableLazy; import net.createmod.catnip.utility.VecHelper; import net.createmod.catnip.utility.animation.LerpedFloat; import net.createmod.catnip.utility.animation.LerpedFloat.Chaser; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; @@ -33,13 +36,12 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemContainerContents; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.capabilities.Capabilities; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider, Nameable { @@ -51,7 +53,6 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider UUID uniqueId; ToolboxInventory inventory; - LazyOptional inventoryProvider; ResetableLazy colorProvider; Map> connectedPlayers; @@ -64,7 +65,6 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider super(type, pos, state); connectedPlayers = new HashMap<>(); inventory = new ToolboxInventory(this); - inventoryProvider = LazyOptional.of(() -> inventory); colorProvider = ResetableLazy.of(() -> { BlockState blockState = getBlockState(); if (blockState != null && blockState.getBlock() instanceof ToolboxBlock) @@ -74,6 +74,14 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider setLazyTickRate(10); } + public static void registerCapabilities(RegisterCapabilitiesEvent event) { + event.registerBlockEntity( + Capabilities.ItemHandler.BLOCK, + AllBlockEntityTypes.TOOLBOX.get(), + (be, context) -> be.inventory + ); + } + public DyeColor getColor() { return colorProvider.get(); } @@ -148,7 +156,7 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider } int count = playerStack.getCount(); - int targetAmount = (referenceItem.getMaxStackSize() + 1) / 2; + int targetAmount = (referenceItem.getOrDefault(DataComponents.MAX_STACK_SIZE, 64) + 1) / 2; if (count < targetAmount) { int amountToReplenish = targetAmount - count; @@ -167,13 +175,13 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider update = true; ItemStack template = playerStack.isEmpty() ? extracted : playerStack; playerInv.setItem(hotbarSlot, - ItemHandlerHelper.copyStackWithSize(template, count + extracted.getCount())); + template.copyWithCount(count + extracted.getCount())); } } if (count > targetAmount) { int amountToDeposit = count - targetAmount; - ItemStack toDistribute = ItemHandlerHelper.copyStackWithSize(playerStack, amountToDeposit); + ItemStack toDistribute = playerStack.copyWithCount(amountToDeposit); if (isOpenInContainer(player)) { int deposited = amountToDeposit - inventory.distributeToCompartment(toDistribute, slot, true) @@ -190,7 +198,7 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider if (deposited > 0) { update = true; playerInv.setItem(hotbarSlot, - ItemHandlerHelper.copyStackWithSize(playerStack, count - deposited)); + playerStack.copyWithCount(count - deposited)); } } } @@ -277,33 +285,26 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider } @Override - public LazyOptional getCapability(Capability cap, Direction side) { - if (isItemHandlerCap(cap)) - return inventoryProvider.cast(); - return super.getCapability(cap, side); - } - - @Override - protected void read(CompoundTag compound, boolean clientPacket) { - inventory.deserializeNBT(compound.getCompound("Inventory")); - super.read(compound, clientPacket); + protected void read(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { + inventory.deserializeNBT(registries, compound.getCompound("Inventory")); + super.read(compound, registries, clientPacket); if (compound.contains("UniqueId", 11)) this.uniqueId = compound.getUUID("UniqueId"); if (compound.contains("CustomName", 8)) - this.customName = Component.Serializer.fromJson(compound.getString("CustomName")); + this.customName = Component.Serializer.fromJson(compound.getString("CustomName"), registries); } @Override - protected void write(CompoundTag compound, boolean clientPacket) { + protected void write(CompoundTag compound, HolderLookup.Provider registries, boolean clientPacket) { if (uniqueId == null) uniqueId = UUID.randomUUID(); - compound.put("Inventory", inventory.serializeNBT()); + compound.put("Inventory", inventory.serializeNBT(registries)); compound.putUUID("UniqueId", uniqueId); if (customName != null) - compound.putString("CustomName", Component.Serializer.toJson(customName)); - super.write(compound, clientPacket); + compound.putString("CustomName", Component.Serializer.toJson(customName, registries)); + super.write(compound, registries, clientPacket); } @Override @@ -331,8 +332,8 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider map.put(player, hotbarSlot); } - public void readInventory(CompoundTag compound) { - inventory.deserializeNBT(compound); + public void readInventory(ItemContainerContents contents) { + ItemHelper.fillItemStackHandler(contents, inventory); } public void setUniqueId(UUID uniqueId) { diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java index 1890dadb04..df2e395e0d 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java @@ -2,76 +2,64 @@ package com.simibubi.create.content.equipment.toolbox; import org.apache.commons.lang3.mutable.MutableBoolean; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ToolboxDisposeAllPacket extends SimplePacketBase { +public record ToolboxDisposeAllPacket(BlockPos toolboxPos) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = BlockPos.STREAM_CODEC.map( + ToolboxDisposeAllPacket::new, ToolboxDisposeAllPacket::toolboxPos + ); - private BlockPos toolboxPos; - - public ToolboxDisposeAllPacket(BlockPos toolboxPos) { - this.toolboxPos = toolboxPos; - } - - public ToolboxDisposeAllPacket(FriendlyByteBuf buffer) { - toolboxPos = buffer.readBlockPos(); + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.TOOLBOX_DISPOSE_ALL; } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBlockPos(toolboxPos); - } + public void handle(ServerPlayer player) { + Level world = player.level(); + BlockEntity blockEntity = world.getBlockEntity(toolboxPos); - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - Level world = player.level(); - BlockEntity blockEntity = world.getBlockEntity(toolboxPos); - - double maxRange = ToolboxHandler.getMaxRange(player); - if (player.distanceToSqr(toolboxPos.getX() + 0.5, toolboxPos.getY(), toolboxPos.getZ() + 0.5) > maxRange + double maxRange = ToolboxHandler.getMaxRange(player); + if (player.distanceToSqr(toolboxPos.getX() + 0.5, toolboxPos.getY(), toolboxPos.getZ() + 0.5) > maxRange * maxRange) - return; - if (!(blockEntity instanceof ToolboxBlockEntity)) - return; - ToolboxBlockEntity toolbox = (ToolboxBlockEntity) blockEntity; + return; + if (!(blockEntity instanceof ToolboxBlockEntity toolbox)) + return; - CompoundTag compound = player.getPersistentData() + CompoundTag compound = player.getPersistentData() .getCompound("CreateToolboxData"); - MutableBoolean sendData = new MutableBoolean(false); + MutableBoolean sendData = new MutableBoolean(false); - toolbox.inventory.inLimitedMode(inventory -> { - for (int i = 0; i < 36; i++) { - String key = String.valueOf(i); - if (compound.contains(key) && NbtUtils.readBlockPos(compound.getCompound(key) - .getCompound("Pos")) + toolbox.inventory.inLimitedMode(inventory -> { + for (int i = 0; i < 36; i++) { + String key = String.valueOf(i); + if (compound.contains(key) && NbtUtils.readBlockPos(compound.getCompound(key),"Pos").orElseThrow() .equals(toolboxPos)) { - ToolboxHandler.unequip(player, i, true); - sendData.setTrue(); - } - - ItemStack itemStack = player.getInventory().getItem(i); - ItemStack remainder = ItemHandlerHelper.insertItemStacked(toolbox.inventory, itemStack, false); - if (remainder.getCount() != itemStack.getCount()) - player.getInventory().setItem(i, remainder); + ToolboxHandler.unequip(player, i, true); + sendData.setTrue(); } - }); - - if (sendData.booleanValue()) - ToolboxHandler.syncData(player); - }); - return true; - } + ItemStack itemStack = player.getInventory().getItem(i); + ItemStack remainder = ItemHandlerHelper.insertItemStacked(toolbox.inventory, itemStack, false); + if (remainder.getCount() != itemStack.getCount()) + player.getInventory().setItem(i, remainder); + } + }); + + if (sendData.booleanValue()) + ToolboxHandler.syncData(player); + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDyeingRecipe.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDyeingRecipe.java index d9a336ea95..d7df2c73b7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDyeingRecipe.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDyeingRecipe.java @@ -3,31 +3,33 @@ package com.simibubi.create.content.equipment.toolbox; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllRecipeTypes; +import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingBookCategory; +import net.minecraft.world.item.crafting.CraftingInput; import net.minecraft.world.item.crafting.CustomRecipe; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; -import net.minecraftforge.common.Tags; +import net.neoforged.neoforge.common.Tags; public class ToolboxDyeingRecipe extends CustomRecipe { - public ToolboxDyeingRecipe(ResourceLocation rl, CraftingBookCategory category) { - super(rl, category); + public ToolboxDyeingRecipe(CraftingBookCategory category) { + super(category); } @Override - public boolean matches(CraftingContainer inventory, Level world) { + public boolean matches(CraftingInput input, Level level) { int toolboxes = 0; int dyes = 0; - for (int i = 0; i < inventory.getContainerSize(); ++i) { - ItemStack stack = inventory.getItem(i); + for (int i = 0; i < input.size(); ++i) { + ItemStack stack = input.getItem(i); if (!stack.isEmpty()) { if (Block.byItem(stack.getItem()) instanceof ToolboxBlock) { ++toolboxes; @@ -47,12 +49,12 @@ public class ToolboxDyeingRecipe extends CustomRecipe { } @Override - public ItemStack assemble(CraftingContainer inventory, RegistryAccess pRegistryAccess) { + public ItemStack assemble(CraftingInput input, HolderLookup.Provider registries) { ItemStack toolbox = ItemStack.EMPTY; DyeColor color = DyeColor.BROWN; - for (int i = 0; i < inventory.getContainerSize(); ++i) { - ItemStack stack = inventory.getItem(i); + for (int i = 0; i < input.size(); ++i) { + ItemStack stack = input.getItem(i); if (!stack.isEmpty()) { if (Block.byItem(stack.getItem()) instanceof ToolboxBlock) { toolbox = stack; @@ -67,9 +69,8 @@ public class ToolboxDyeingRecipe extends CustomRecipe { ItemStack dyedToolbox = AllBlocks.TOOLBOXES.get(color) .asStack(); - if (toolbox.hasTag()) { - dyedToolbox.setTag(toolbox.getTag() - .copy()); + if (!toolbox.isComponentsPatchEmpty()) { + dyedToolbox.applyComponents(toolbox.getComponentsPatch()); } return dyedToolbox; diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java index a63c4befaf..ebaf394ffc 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java @@ -1,105 +1,87 @@ package com.simibubi.create.content.equipment.toolbox; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import com.simibubi.create.AllPackets; +import net.createmod.catnip.net.base.ServerboundPacketPayload; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.items.ItemHandlerHelper; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public class ToolboxEquipPacket extends SimplePacketBase { +public record ToolboxEquipPacket(BlockPos toolboxPos, int slot, int hotbarSlot) implements ServerboundPacketPayload { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecBuilders.nullable(BlockPos.STREAM_CODEC), ToolboxEquipPacket::toolboxPos, + ByteBufCodecs.VAR_INT, ToolboxEquipPacket::slot, + ByteBufCodecs.VAR_INT, ToolboxEquipPacket::hotbarSlot, + ToolboxEquipPacket::new + ); - private BlockPos toolboxPos; - private int slot; - private int hotbarSlot; - - public ToolboxEquipPacket(BlockPos toolboxPos, int slot, int hotbarSlot) { - this.toolboxPos = toolboxPos; - this.slot = slot; - this.hotbarSlot = hotbarSlot; - } - - public ToolboxEquipPacket(FriendlyByteBuf buffer) { - if (buffer.readBoolean()) - toolboxPos = buffer.readBlockPos(); - slot = buffer.readVarInt(); - hotbarSlot = buffer.readVarInt(); + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.TOOLBOX_EQUIP; } @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeBoolean(toolboxPos != null); - if (toolboxPos != null) - buffer.writeBlockPos(toolboxPos); - buffer.writeVarInt(slot); - buffer.writeVarInt(hotbarSlot); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - Level world = player.level(); - - if (toolboxPos == null) { - ToolboxHandler.unequip(player, hotbarSlot, false); - ToolboxHandler.syncData(player); - return; - } - - BlockEntity blockEntity = world.getBlockEntity(toolboxPos); - - double maxRange = ToolboxHandler.getMaxRange(player); - if (player.distanceToSqr(toolboxPos.getX() + 0.5, toolboxPos.getY(), toolboxPos.getZ() + 0.5) > maxRange - * maxRange) - return; - if (!(blockEntity instanceof ToolboxBlockEntity)) - return; + public void handle(ServerPlayer player) { + Level world = player.level(); + if (toolboxPos == null) { ToolboxHandler.unequip(player, hotbarSlot, false); + ToolboxHandler.syncData(player); + return; + } - if (slot < 0 || slot >= 8) { - ToolboxHandler.syncData(player); - return; - } + BlockEntity blockEntity = world.getBlockEntity(toolboxPos); - ToolboxBlockEntity toolboxBlockEntity = (ToolboxBlockEntity) blockEntity; + double maxRange = ToolboxHandler.getMaxRange(player); + if (player.distanceToSqr(toolboxPos.getX() + 0.5, toolboxPos.getY(), toolboxPos.getZ() + 0.5) > maxRange + * maxRange) + return; + if (!(blockEntity instanceof ToolboxBlockEntity toolboxBlockEntity)) + return; - ItemStack playerStack = player.getInventory().getItem(hotbarSlot); - if (!playerStack.isEmpty() && !ToolboxInventory.canItemsShareCompartment(playerStack, + ToolboxHandler.unequip(player, hotbarSlot, false); + + if (slot < 0 || slot >= 8) { + ToolboxHandler.syncData(player); + return; + } + + ItemStack playerStack = player.getInventory().getItem(hotbarSlot); + if (!playerStack.isEmpty() && !ToolboxInventory.canItemsShareCompartment(playerStack, toolboxBlockEntity.inventory.filters.get(slot))) { - toolboxBlockEntity.inventory.inLimitedMode(inventory -> { - ItemStack remainder = ItemHandlerHelper.insertItemStacked(inventory, playerStack, false); - if (!remainder.isEmpty()) - remainder = ItemHandlerHelper.insertItemStacked(new ItemReturnInvWrapper(player.getInventory()), + toolboxBlockEntity.inventory.inLimitedMode(inventory -> { + ItemStack remainder = ItemHandlerHelper.insertItemStacked(inventory, playerStack, false); + if (!remainder.isEmpty()) + remainder = ItemHandlerHelper.insertItemStacked(new ItemReturnInvWrapper(player.getInventory()), remainder, false); - if (remainder.getCount() != playerStack.getCount()) - player.getInventory().setItem(hotbarSlot, remainder); - }); - } + if (remainder.getCount() != playerStack.getCount()) + player.getInventory().setItem(hotbarSlot, remainder); + }); + } - CompoundTag compound = player.getPersistentData() + CompoundTag compound = player.getPersistentData() .getCompound("CreateToolboxData"); - String key = String.valueOf(hotbarSlot); + String key = String.valueOf(hotbarSlot); - CompoundTag data = new CompoundTag(); - data.putInt("Slot", slot); - data.put("Pos", NbtUtils.writeBlockPos(toolboxPos)); - compound.put(key, data); + CompoundTag data = new CompoundTag(); + data.putInt("Slot", slot); + data.put("Pos", NbtUtils.writeBlockPos(toolboxPos)); + compound.put(key, data); - player.getPersistentData() + player.getPersistentData() .put("CreateToolboxData", compound); - toolboxBlockEntity.connectPlayer(slot, player, hotbarSlot); - ToolboxHandler.syncData(player); - }); - return true; + toolboxBlockEntity.connectPlayer(slot, player, hotbarSlot); + ToolboxHandler.syncData(player); } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java index a3242cbaa6..41f5e505ed 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java @@ -4,10 +4,10 @@ import java.util.List; import java.util.WeakHashMap; import java.util.stream.Collectors; -import com.simibubi.create.AllPackets; import com.simibubi.create.foundation.networking.ISyncPersistentData.PersistentDataPacket; import com.simibubi.create.infrastructure.config.AllConfigs; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.WorldAttached; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; @@ -20,7 +20,6 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.PacketDistributor; public class ToolboxHandler { @@ -63,7 +62,7 @@ public class ToolboxHandler { continue; CompoundTag data = compound.getCompound(key); - BlockPos pos = NbtUtils.readBlockPos(data.getCompound("Pos")); + BlockPos pos = NbtUtils.readBlockPos(data, "Pos").orElseThrow(); int slot = data.getInt("Slot"); if (!world.isLoaded(pos)) @@ -97,7 +96,7 @@ public class ToolboxHandler { } public static void syncData(Player player) { - AllPackets.getChannel().send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), + CatnipServices.NETWORK.sendToClient((ServerPlayer) player, new PersistentDataPacket(player)); } @@ -124,12 +123,11 @@ public class ToolboxHandler { return; CompoundTag prevData = compound.getCompound(key); - BlockPos prevPos = NbtUtils.readBlockPos(prevData.getCompound("Pos")); + BlockPos prevPos = NbtUtils.readBlockPos(prevData, "Pos").orElseThrow(); int prevSlot = prevData.getInt("Slot"); BlockEntity prevBlockEntity = world.getBlockEntity(prevPos); - if (prevBlockEntity instanceof ToolboxBlockEntity) { - ToolboxBlockEntity toolbox = (ToolboxBlockEntity) prevBlockEntity; + if (prevBlockEntity instanceof ToolboxBlockEntity toolbox) { toolbox.unequip(prevSlot, player, hotbarSlot, keepItems || !ToolboxHandler.withinRange(player, toolbox)); } compound.remove(key); diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandlerClient.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandlerClient.java index 8a42bbb9f2..3f147409f2 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandlerClient.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandlerClient.java @@ -12,12 +12,14 @@ import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllKeys; -import com.simibubi.create.AllPackets; import com.simibubi.create.foundation.gui.AllGuiTextures; import net.createmod.catnip.gui.ScreenOpener; +import net.createmod.catnip.platform.CatnipServices; +import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.LayeredDraw; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; @@ -32,12 +34,10 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; -import net.minecraftforge.client.gui.overlay.ForgeGui; -import net.minecraftforge.client.gui.overlay.IGuiOverlay; public class ToolboxHandlerClient { - public static final IGuiOverlay OVERLAY = ToolboxHandlerClient::renderOverlay; + public static final LayeredDraw.Layer OVERLAY = ToolboxHandlerClient::renderOverlay; static int COOLDOWN = 0; @@ -91,7 +91,7 @@ public class ToolboxHandlerClient { if (!ItemStack.matches(inSlot, result)) continue; - AllPackets.getChannel().sendToServer( + CatnipServices.NETWORK.sendToServer( new ToolboxEquipPacket(toolboxBlockEntity.getBlockPos(), comp, player.getInventory().selected)); return true; } @@ -125,8 +125,7 @@ public class ToolboxHandlerClient { boolean equipped = compound.contains(slotKey); if (equipped) { - BlockPos pos = NbtUtils.readBlockPos(compound.getCompound(slotKey) - .getCompound("Pos")); + BlockPos pos = NbtUtils.readBlockPos(compound.getCompound(slotKey), "Pos").orElseThrow(); double max = ToolboxHandler.getMaxRange(player); boolean canReachToolbox = ToolboxHandler.distance(player.position(), pos) < max * max; @@ -155,7 +154,9 @@ public class ToolboxHandlerClient { ScreenOpener.open(new RadialToolboxMenu(toolboxes, RadialToolboxMenu.State.SELECT_BOX, null)); } - public static void renderOverlay(ForgeGui gui, GuiGraphics graphics, float partialTicks, int width, int height) { + public static void renderOverlay(GuiGraphics guiGraphics, DeltaTracker deltaTracker) { + int width = guiGraphics.guiWidth(); + int height = guiGraphics.guiHeight(); Minecraft mc = Minecraft.getInstance(); if (mc.options.hideGui || mc.gameMode.getPlayerMode() == GameType.SPECTATOR) return; @@ -175,21 +176,20 @@ public class ToolboxHandlerClient { if (compound.isEmpty()) return; - PoseStack poseStack = graphics.pose(); + PoseStack poseStack = guiGraphics.pose(); poseStack.pushPose(); for (int slot = 0; slot < 9; slot++) { String key = String.valueOf(slot); if (!compound.contains(key)) continue; - BlockPos pos = NbtUtils.readBlockPos(compound.getCompound(key) - .getCompound("Pos")); + BlockPos pos = NbtUtils.readBlockPos(compound.getCompound(key), "Pos").orElseThrow(); double max = ToolboxHandler.getMaxRange(player); boolean selected = player.getInventory().selected == slot; int offset = selected ? 1 : 0; AllGuiTextures texture = ToolboxHandler.distance(player.position(), pos) < max * max ? selected ? TOOLBELT_SELECTED_ON : TOOLBELT_HOTBAR_ON : selected ? TOOLBELT_SELECTED_OFF : TOOLBELT_HOTBAR_OFF; - texture.render(graphics, x + 20 * slot - offset, y + offset); + texture.render(guiGraphics, x + 20 * slot - offset, y + offset); } poseStack.popPose(); } diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxInventory.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxInventory.java index d391f50239..c477cf71d2 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxInventory.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxInventory.java @@ -6,14 +6,18 @@ import java.util.function.Consumer; import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllItems; import net.createmod.catnip.utility.NBTHelper; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.component.DataComponents; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.ItemHandlerHelper; -import net.minecraftforge.items.ItemStackHandler; +import net.neoforged.neoforge.items.ItemStackHandler; public class ToolboxInventory extends ItemStackHandler { @@ -50,7 +54,7 @@ public class ToolboxInventory extends ItemStackHandler { ItemStack stackInSlot = getStackInSlot(compartment * STACKS_PER_COMPARTMENT + i); totalCount += stackInSlot.getCount(); if (!shouldBeEmpty) - shouldBeEmpty = stackInSlot.isEmpty() || stackInSlot.getCount() != stackInSlot.getMaxStackSize(); + shouldBeEmpty = stackInSlot.isEmpty() || stackInSlot.getCount() != stackInSlot.getOrDefault(DataComponents.MAX_STACK_SIZE, 64); else if (!stackInSlot.isEmpty()) { valid = false; sample = stackInSlot; @@ -77,7 +81,7 @@ public class ToolboxInventory extends ItemStackHandler { } else { for (int i = 0; i < STACKS_PER_COMPARTMENT; i++) { ItemStack copy = totalCount <= 0 ? ItemStack.EMPTY - : ItemHandlerHelper.copyStackWithSize(sample, Math.min(totalCount, sample.getMaxStackSize())); + : sample.copyWithCount(Math.min(totalCount, sample.getOrDefault(DataComponents.MAX_STACK_SIZE, 64))); setStackInSlot(compartment * STACKS_PER_COMPARTMENT + i, copy); totalCount -= copy.getCount(); } @@ -108,19 +112,19 @@ public class ToolboxInventory extends ItemStackHandler { int compartment = slot / STACKS_PER_COMPARTMENT; if (!stack.isEmpty() && filters.get(compartment) .isEmpty()) { - filters.set(compartment, ItemHandlerHelper.copyStackWithSize(stack, 1)); + filters.set(compartment, stack.copyWithCount(1)); notifyUpdate(); } } @Override - public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { + public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) { ItemStack insertItem = super.insertItem(slot, stack, simulate); if (insertItem.getCount() != stack.getCount()) { int compartment = slot / STACKS_PER_COMPARTMENT; if (!stack.isEmpty() && filters.get(compartment) .isEmpty()) { - filters.set(compartment, ItemHandlerHelper.copyStackWithSize(stack, 1)); + filters.set(compartment, stack.copyWithCount(1)); notifyUpdate(); } } @@ -128,9 +132,9 @@ public class ToolboxInventory extends ItemStackHandler { } @Override - public CompoundTag serializeNBT() { - CompoundTag compound = super.serializeNBT(); - compound.put("Compartments", NBTHelper.writeItemList(filters)); + public @NotNull CompoundTag serializeNBT(@NotNull HolderLookup.Provider registries) { + CompoundTag compound = super.serializeNBT(registries); + compound.put("Compartments", NBTHelper.writeItemList(filters, registries)); return compound; } @@ -143,14 +147,14 @@ public class ToolboxInventory extends ItemStackHandler { } @Override - public void deserializeNBT(CompoundTag nbt) { - filters = NBTHelper.readItemList(nbt.getList("Compartments", Tag.TAG_COMPOUND)); + public void deserializeNBT(@NotNull HolderLookup.Provider registries, CompoundTag nbt) { + filters = NBTHelper.readItemList(nbt.getList("Compartments", Tag.TAG_COMPOUND), registries); if (filters.size() != 8) { filters.clear(); for (int i = 0; i < 8; i++) filters.add(ItemStack.EMPTY); } - super.deserializeNBT(nbt); + super.deserializeNBT(registries, nbt); } public ItemStack distributeToCompartment(@Nonnull ItemStack stack, int compartment, boolean simulate) { @@ -184,18 +188,18 @@ public class ToolboxInventory extends ItemStackHandler { if (!extracted.isEmpty()) lastValid = extracted; if (remaining == 0) - return ItemHandlerHelper.copyStackWithSize(lastValid, amount); + return lastValid.copyWithCount(amount); } if (remaining == amount) return ItemStack.EMPTY; - return ItemHandlerHelper.copyStackWithSize(lastValid, amount - remaining); + return lastValid.copyWithCount(amount - remaining); } public static ItemStack cleanItemNBT(ItemStack stack) { if (AllItems.BELT_CONNECTOR.isIn(stack)) - stack.removeTagKey("FirstPulley"); + stack.remove(AllDataComponents.BELT_FIRST_SHAFT); return stack; } @@ -204,7 +208,7 @@ public class ToolboxInventory extends ItemStackHandler { return stack1.getItem() == stack2.getItem(); if (AllItems.BELT_CONNECTOR.isIn(stack1) && AllItems.BELT_CONNECTOR.isIn(stack2)) return true; - return ItemHandlerHelper.canItemStacksStack(stack1, stack2); + return ItemStack.isSameItemSameComponents(stack1, stack2); } private void notifyUpdate() { diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java index f7db862c84..9bd3c797ff 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java @@ -12,6 +12,7 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ClickType; @@ -19,11 +20,11 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.items.SlotItemHandler; +import net.neoforged.neoforge.items.SlotItemHandler; public class ToolboxMenu extends MenuBase { - public ToolboxMenu(MenuType type, int id, Inventory inv, FriendlyByteBuf extraData) { + public ToolboxMenu(MenuType type, int id, Inventory inv, RegistryFriendlyByteBuf extraData) { super(type, id, inv, extraData); } @@ -38,15 +39,14 @@ public class ToolboxMenu extends MenuBase { } @Override - protected ToolboxBlockEntity createOnClient(FriendlyByteBuf extraData) { + protected ToolboxBlockEntity createOnClient(RegistryFriendlyByteBuf extraData) { BlockPos readBlockPos = extraData.readBlockPos(); CompoundTag readNbt = extraData.readNbt(); ClientLevel world = Minecraft.getInstance().level; BlockEntity blockEntity = world.getBlockEntity(readBlockPos); - if (blockEntity instanceof ToolboxBlockEntity) { - ToolboxBlockEntity toolbox = (ToolboxBlockEntity) blockEntity; - toolbox.readClient(readNbt); + if (blockEntity instanceof ToolboxBlockEntity toolbox) { + toolbox.readClient(readNbt, extraData.registryAccess()); return toolbox; } diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxScreen.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxScreen.java index 97c8120e61..3de37be46c 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxScreen.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxScreen.java @@ -7,12 +7,12 @@ import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllBlocks; -import com.simibubi.create.AllPackets; import com.simibubi.create.AllPartialModels; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.gui.AllIcons; import com.simibubi.create.foundation.gui.menu.AbstractSimiContainerScreen; import com.simibubi.create.foundation.gui.widget.IconButton; +import net.createmod.catnip.platform.CatnipServices; import com.simibubi.create.foundation.utility.CreateLang; import dev.engine_room.flywheel.lib.transform.TransformStack; @@ -60,7 +60,7 @@ public class ToolboxScreen extends AbstractSimiContainerScreen { disposeButton = new IconButton(leftPos + 30 + 81, topPos + 69, AllIcons.I_TOOLBOX); disposeButton.withCallback(() -> { - AllPackets.getChannel().sendToServer(new ToolboxDisposeAllPacket(menu.contentHolder.getBlockPos())); + CatnipServices.NETWORK.sendToServer(new ToolboxDisposeAllPacket(menu.contentHolder.getBlockPos())); }); disposeButton.setToolTip(CreateLang.translateDirect("toolbox.depositBox")); addRenderableWidget(disposeButton); diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxSlot.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxSlot.java index a87c215943..d8c204abc8 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxSlot.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxSlot.java @@ -1,7 +1,7 @@ package com.simibubi.create.content.equipment.toolbox; -import net.minecraftforge.items.IItemHandler; -import net.minecraftforge.items.SlotItemHandler; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.SlotItemHandler; public class ToolboxSlot extends SlotItemHandler { @@ -11,7 +11,7 @@ public class ToolboxSlot extends SlotItemHandler { super(itemHandler, index, xPosition, yPosition); this.toolboxMenu = menu; } - + @Override public boolean isActive() { return !toolboxMenu.renderPass && super.isActive(); diff --git a/src/main/java/com/simibubi/create/content/equipment/wrench/IWrenchable.java b/src/main/java/com/simibubi/create/content/equipment/wrench/IWrenchable.java index 877b7f815c..261da7083b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/wrench/IWrenchable.java +++ b/src/main/java/com/simibubi/create/content/equipment/wrench/IWrenchable.java @@ -20,8 +20,8 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.level.BlockEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.level.BlockEvent; public interface IWrenchable { @@ -54,7 +54,7 @@ public interface IWrenchable { return InteractionResult.SUCCESS; BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(world, pos, world.getBlockState(pos), player); - MinecraftForge.EVENT_BUS.post(event); + NeoForge.EVENT_BUS.post(event); if (event.isCanceled()) return InteractionResult.SUCCESS; diff --git a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java index b9d6bb3bbe..aa3489007e 100644 --- a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java @@ -10,10 +10,10 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; @EventBusSubscriber public class WrenchEventHandler { diff --git a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java index cfdf6b45c4..4b0e50e7f7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java @@ -22,10 +22,10 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; -import net.minecraftforge.event.entity.player.AttackEntityEvent; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.event.entity.player.AttackEntityEvent; public class WrenchItem extends Item { diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ConfigureZapperPacket.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ConfigureZapperPacket.java index 6b90d8b2c7..6dfdf88b9e 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ConfigureZapperPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ConfigureZapperPacket.java @@ -1,47 +1,28 @@ package com.simibubi.create.content.equipment.zapper; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ServerboundPacketPayload; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public abstract class ConfigureZapperPacket extends SimplePacketBase { - - protected InteractionHand hand; - protected PlacementPatterns pattern; +public abstract class ConfigureZapperPacket implements ServerboundPacketPayload { + protected final InteractionHand hand; + protected final PlacementPatterns pattern; public ConfigureZapperPacket(InteractionHand hand, PlacementPatterns pattern) { this.hand = hand; this.pattern = pattern; } - public ConfigureZapperPacket(FriendlyByteBuf buffer) { - hand = buffer.readEnum(InteractionHand.class); - pattern = buffer.readEnum(PlacementPatterns.class); - } - @Override - public void write(FriendlyByteBuf buffer) { - buffer.writeEnum(hand); - buffer.writeEnum(pattern); - } - - @Override - public boolean handle(Context context) { - context.enqueueWork(() -> { - ServerPlayer player = context.getSender(); - if (player == null) { - return; - } - ItemStack stack = player.getItemInHand(hand); - if (stack.getItem() instanceof ZapperItem) { - configureZapper(stack); - } - }); - return true; + public void handle(ServerPlayer player) { + ItemStack stack = player.getItemInHand(hand); + if (stack.getItem() instanceof ZapperItem) { + configureZapper(stack); + } } public abstract void configureZapper(ItemStack stack); diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/PlacementPatterns.java b/src/main/java/com/simibubi/create/content/equipment/zapper/PlacementPatterns.java index 5f482639da..bf30fadbd5 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/PlacementPatterns.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/PlacementPatterns.java @@ -5,15 +5,23 @@ import java.util.Random; import java.util.function.Predicate; import com.google.common.base.Predicates; +import com.mojang.serialization.Codec; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.foundation.gui.AllIcons; import net.createmod.catnip.utility.lang.Lang; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.ItemStack; -public enum PlacementPatterns { +import io.netty.buffer.ByteBuf; +import org.jetbrains.annotations.NotNull; + +public enum PlacementPatterns implements StringRepresentable { Solid(AllIcons.I_PATTERN_SOLID), Checkered(AllIcons.I_PATTERN_CHECKERED), InverseCheckered(AllIcons.I_PATTERN_CHECKERED_INVERSED), @@ -21,6 +29,9 @@ public enum PlacementPatterns { Chance50(AllIcons.I_PATTERN_CHANCE_50), Chance75(AllIcons.I_PATTERN_CHANCE_75); + public static final Codec CODEC = StringRepresentable.fromValues(PlacementPatterns::values); + public static final StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(PlacementPatterns.class); + public final String translationKey; public final AllIcons icon; @@ -30,9 +41,7 @@ public enum PlacementPatterns { } public static void applyPattern(List blocksIn, ItemStack stack) { - CompoundTag tag = stack.getTag(); - PlacementPatterns pattern = - !tag.contains("Pattern") ? Solid : valueOf(tag.getString("Pattern")); + PlacementPatterns pattern = stack.getOrDefault(AllDataComponents.PLACEMENT_PATTERN, Solid); Random r = new Random(); Predicate filter = Predicates.alwaysFalse(); @@ -60,4 +69,8 @@ public enum PlacementPatterns { blocksIn.removeIf(filter); } + @Override + public @NotNull String getSerializedName() { + return Lang.asId(name()); + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ShootGadgetPacket.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ShootGadgetPacket.java index 8b624b98a7..eb4a8f6f68 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ShootGadgetPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ShootGadgetPacket.java @@ -1,21 +1,21 @@ package com.simibubi.create.content.equipment.zapper; -import com.simibubi.create.foundation.networking.SimplePacketBase; +import net.createmod.catnip.net.base.ClientboundPacketPayload; import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.network.NetworkEvent.Context; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.network.handling.IPayloadContext; -public abstract class ShootGadgetPacket extends SimplePacketBase { - - public Vec3 location; - public InteractionHand hand; - public boolean self; +public abstract class ShootGadgetPacket implements ClientboundPacketPayload { + protected final Vec3 location; + protected final InteractionHand hand; + protected final boolean self; public ShootGadgetPacket(Vec3 location, InteractionHand hand, boolean self) { this.location = location; @@ -23,26 +23,6 @@ public abstract class ShootGadgetPacket extends SimplePacketBase { this.self = self; } - public ShootGadgetPacket(FriendlyByteBuf buffer) { - hand = buffer.readBoolean() ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND; - self = buffer.readBoolean(); - location = new Vec3(buffer.readDouble(), buffer.readDouble(), buffer.readDouble()); - readAdditional(buffer); - } - - public final void write(FriendlyByteBuf buffer) { - buffer.writeBoolean(hand == InteractionHand.MAIN_HAND); - buffer.writeBoolean(self); - buffer.writeDouble(location.x); - buffer.writeDouble(location.y); - buffer.writeDouble(location.z); - writeAdditional(buffer); - } - - protected abstract void readAdditional(FriendlyByteBuf buffer); - - protected abstract void writeAdditional(FriendlyByteBuf buffer); - @OnlyIn(Dist.CLIENT) protected abstract void handleAdditional(); @@ -51,24 +31,20 @@ public abstract class ShootGadgetPacket extends SimplePacketBase { @Override @OnlyIn(Dist.CLIENT) - public boolean handle(Context context) { - context.enqueueWork(() -> { - Entity renderViewEntity = Minecraft.getInstance() + public void handle(LocalPlayer player) { + Entity renderViewEntity = Minecraft.getInstance() .getCameraEntity(); - if (renderViewEntity == null) - return; - if (renderViewEntity.position() + if (renderViewEntity == null) + return; + if (renderViewEntity.position() .distanceTo(location) > 100) - return; + return; - ShootableGadgetRenderHandler handler = getHandler(); - handleAdditional(); - if (self) - handler.shoot(hand, location); - else - handler.playSound(hand, location); - }); - return true; + ShootableGadgetRenderHandler handler = getHandler(); + handleAdditional(); + if (self) + handler.shoot(hand, location); + else + handler.playSound(hand, location); } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetItemMethods.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetItemMethods.java index d03ff7a432..577acf4062 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetItemMethods.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetItemMethods.java @@ -3,15 +3,17 @@ package com.simibubi.create.content.equipment.zapper; import java.util.function.Function; import java.util.function.Predicate; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllPackets; +import net.createmod.catnip.platform.CatnipServices; + import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.network.PacketDistributor; public class ShootableGadgetItemMethods { @@ -29,13 +31,12 @@ public class ShootableGadgetItemMethods { public static void sendPackets(Player player, Function factory) { if (!(player instanceof ServerPlayer)) return; - AllPackets.getChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> player), factory.apply(false)); - AllPackets.getChannel().send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), factory.apply(true)); + CatnipServices.NETWORK.sendToClientsTrackingEntity(player, factory.apply(false)); + CatnipServices.NETWORK.sendToClient((ServerPlayer) player, factory.apply(true)); } public static boolean shouldSwap(Player player, ItemStack item, InteractionHand hand, Predicate predicate) { - boolean isSwap = item.getTag() - .contains("_Swap"); + boolean isSwap = item.has(AllDataComponents.SHAPER_SWAP); boolean mainHand = hand == InteractionHand.MAIN_HAND; boolean gunInOtherHand = predicate.test(player.getItemInHand(mainHand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND)); @@ -43,15 +44,11 @@ public class ShootableGadgetItemMethods { if (mainHand && isSwap && gunInOtherHand) return true; if (mainHand && !isSwap && gunInOtherHand) - item.getTag() - .putBoolean("_Swap", true); + item.set(AllDataComponents.SHAPER_SWAP, true); if (!mainHand && isSwap) - item.getTag() - .remove("_Swap"); + item.remove(AllDataComponents.SHAPER_SWAP); if (!mainHand && gunInOtherHand) - player.getItemInHand(InteractionHand.MAIN_HAND) - .getTag() - .remove("_Swap"); + player.getItemInHand(InteractionHand.MAIN_HAND).remove(AllDataComponents.SHAPER_SWAP); player.startUsingItem(hand); return false; } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetRenderHandler.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetRenderHandler.java index a5c77c2482..4cef100fa7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetRenderHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ShootableGadgetRenderHandler.java @@ -16,8 +16,8 @@ import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.client.event.RenderHandEvent; -import net.minecraftforge.eventbus.api.IEventBus; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.RenderHandEvent; public abstract class ShootableGadgetRenderHandler { @@ -97,7 +97,7 @@ public abstract class ShootableGadgetRenderHandler { // Render arm ms.pushPose(); - RenderSystem.setShaderTexture(0, player.getSkinTextureLocation()); + RenderSystem.setShaderTexture(0, player.getSkin().texture()); float flip = rightHand ? 1.0F : -1.0F; float f1 = Mth.sqrt(event.getSwingProgress()); diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperBeamPacket.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperBeamPacket.java index e4b79c0f04..e6cd3cd4bb 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperBeamPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperBeamPacket.java @@ -1,39 +1,34 @@ package com.simibubi.create.content.equipment.zapper; +import com.simibubi.create.AllPackets; import com.simibubi.create.CreateClient; import com.simibubi.create.content.equipment.zapper.ZapperRenderHandler.LaserBeam; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.InteractionHand; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public class ZapperBeamPacket extends ShootGadgetPacket { + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + CatnipStreamCodecs.VEC3, packet -> packet.location, + CatnipStreamCodecs.HAND, packet -> packet.hand, + ByteBufCodecs.BOOL, packet -> packet.self, + CatnipStreamCodecs.VEC3, packet -> packet.target, + ZapperBeamPacket::new + ); - public Vec3 target; + private final Vec3 target; - public ZapperBeamPacket(Vec3 start, Vec3 target, InteractionHand hand, boolean self) { + public ZapperBeamPacket(Vec3 start, InteractionHand hand, boolean self, Vec3 target) { super(start, hand, self); this.target = target; } - public ZapperBeamPacket(FriendlyByteBuf buffer) { - super(buffer); - } - - @Override - protected void readAdditional(FriendlyByteBuf buffer) { - target = new Vec3(buffer.readDouble(), buffer.readDouble(), buffer.readDouble()); - } - - @Override - protected void writeAdditional(FriendlyByteBuf buffer) { - buffer.writeDouble(target.x); - buffer.writeDouble(target.y); - buffer.writeDouble(target.z); - } - @Override @OnlyIn(Dist.CLIENT) protected ShootableGadgetRenderHandler getHandler() { @@ -46,4 +41,8 @@ public class ZapperBeamPacket extends ShootGadgetPacket { CreateClient.ZAPPER_RENDER_HANDLER.addBeam(new LaserBeam(location, target)); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.BEAM_EFFECT; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperInteractionHandler.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperInteractionHandler.java index 9a930b0f75..459e575bee 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperInteractionHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperInteractionHandler.java @@ -2,15 +2,13 @@ package com.simibubi.create.content.equipment.zapper; import java.util.Objects; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.AllTags.AllBlockTags; import com.simibubi.create.foundation.utility.BlockHelper; import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ClipContext; @@ -22,9 +20,9 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.StairsShape; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.common.EventBusSubscriber; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; @EventBusSubscriber public class ZapperInteractionHandler { @@ -36,7 +34,6 @@ public class ZapperInteractionHandler { ItemStack heldItem = event.getEntity() .getMainHandItem(); if (heldItem.getItem() instanceof ZapperItem && trySelect(heldItem, event.getEntity())) { - event.setCancellationResult(InteractionResult.FAIL); event.setCanceled(true); } } @@ -81,23 +78,22 @@ public class ZapperInteractionHandler { CompoundTag data = null; BlockEntity blockEntity = player.level().getBlockEntity(pos); if (blockEntity != null) { - data = blockEntity.saveWithFullMetadata(); + data = blockEntity.saveWithFullMetadata(player.registryAccess()); data.remove("x"); data.remove("y"); data.remove("z"); data.remove("id"); } - CompoundTag tag = stack.getOrCreateTag(); - if (tag.contains("BlockUsed") && NbtUtils.readBlockState(player.level().holderLookup(Registries.BLOCK), stack.getTag() - .getCompound("BlockUsed")) == newState && Objects.equals(data, tag.get("BlockData"))) { + + if (stack.has(AllDataComponents.SHAPER_BLOCK_USED) && stack.get(AllDataComponents.SHAPER_BLOCK_USED) == newState && Objects.equals(data, stack.get(AllDataComponents.SHAPER_BLOCK_DATA))) { return false; } - tag.put("BlockUsed", NbtUtils.writeBlockState(newState)); + stack.set(AllDataComponents.SHAPER_BLOCK_USED, newState); if (data == null) - tag.remove("BlockData"); + stack.remove(AllDataComponents.SHAPER_BLOCK_DATA); else - tag.put("BlockData", data); + stack.set(AllDataComponents.SHAPER_BLOCK_DATA, data); AllSoundEvents.CONFIRM.playOnServer(player.level(), player.blockPosition()); return true; diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItem.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItem.java index 2fa55b7cbd..a42a5d2d03 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItem.java @@ -6,6 +6,7 @@ import javax.annotation.Nonnull; import org.jetbrains.annotations.Nullable; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.AllTags.AllBlockTags; import com.simibubi.create.CreateClient; @@ -13,17 +14,13 @@ import com.simibubi.create.foundation.item.CustomArmPoseItem; import com.simibubi.create.foundation.utility.BlockHelper; import com.simibubi.create.foundation.utility.CreateLang; -import net.createmod.catnip.utility.NBTHelper; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.NBTProcessors; import net.minecraft.ChatFormatting; import net.minecraft.client.model.HumanoidModel.ArmPose; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.InteractionHand; @@ -45,9 +42,8 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fml.DistExecutor; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; public abstract class ZapperItem extends Item implements CustomArmPoseItem { @@ -57,31 +53,19 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { @Override @OnlyIn(Dist.CLIENT) - public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { - if (stack.hasTag() && stack.getTag() - .contains("BlockUsed")) { - MutableComponent usedBlock = NbtUtils.readBlockState(worldIn.holderLookup(Registries.BLOCK), stack.getTag() - .getCompound("BlockUsed")) - .getBlock() - .getName(); - tooltip.add(CreateLang.translateDirect("terrainzapper.usingBlock", - usedBlock.withStyle(ChatFormatting.GRAY)) + public void appendHoverText(ItemStack stack, TooltipContext context, List tooltip, TooltipFlag flagIn) { + if (stack.has(AllDataComponents.SHAPER_BLOCK_USED)) { + MutableComponent usedBlock = stack.get(AllDataComponents.SHAPER_BLOCK_USED).getBlock().getName(); + tooltip.add(CreateLang.translateDirect("terrainzapper.usingBlock", usedBlock.withStyle(ChatFormatting.GRAY)) .withStyle(ChatFormatting.DARK_GRAY)); } } - @SuppressWarnings("deprecation") @Override public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) { boolean differentBlock = false; - if (oldStack.hasTag() && newStack.hasTag() && oldStack.getTag() - .contains("BlockUsed") - && newStack.getTag() - .contains("BlockUsed")) - differentBlock = NbtUtils.readBlockState(BuiltInRegistries.BLOCK.asLookup(), oldStack.getTag() - .getCompound("BlockUsed")) != NbtUtils.readBlockState(BuiltInRegistries.BLOCK.asLookup(), - newStack.getTag() - .getCompound("BlockUsed")); + if (oldStack.has(AllDataComponents.SHAPER_BLOCK_USED) && newStack.has(AllDataComponents.SHAPER_BLOCK_USED)) + differentBlock = oldStack.get(AllDataComponents.SHAPER_BLOCK_USED) != newStack.get(AllDataComponents.SHAPER_BLOCK_USED); return slotChanged || !isZapper(newStack) || differentBlock; } @@ -96,7 +80,7 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { if (context.getPlayer() != null && context.getPlayer() .isShiftKeyDown()) { if (context.getLevel().isClientSide) { - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> { openHandgunGUI(context.getItemInHand(), context.getHand()); }); context.getPlayer() @@ -112,13 +96,12 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { @Override public InteractionResultHolder use(Level world, Player player, InteractionHand hand) { ItemStack item = player.getItemInHand(hand); - CompoundTag nbt = item.getOrCreateTag(); boolean mainHand = hand == InteractionHand.MAIN_HAND; // Shift -> Open GUI if (player.isShiftKeyDown()) { if (world.isClientSide) { - DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { + CatnipServices.PLATFORM.executeOnClientOnly(() -> () -> { openHandgunGUI(item, hand); }); player.getCooldowns() @@ -140,12 +123,12 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { } BlockState stateToUse = Blocks.AIR.defaultBlockState(); - if (nbt.contains("BlockUsed")) - stateToUse = NbtUtils.readBlockState(world.holderLookup(Registries.BLOCK), nbt.getCompound("BlockUsed")); + if (item.has(AllDataComponents.SHAPER_BLOCK_USED)) + stateToUse = item.get(AllDataComponents.SHAPER_BLOCK_USED); stateToUse = BlockHelper.setZeroAge(stateToUse); CompoundTag data = null; - if (AllBlockTags.SAFE_NBT.matches(stateToUse) && nbt.contains("BlockData", Tag.TAG_COMPOUND)) { - data = nbt.getCompound("BlockData"); + if (AllBlockTags.SAFE_NBT.matches(stateToUse) && item.has(AllDataComponents.SHAPER_BLOCK_DATA)) { + data = item.get(AllDataComponents.SHAPER_BLOCK_DATA); } // Raytrace - Find the target @@ -177,15 +160,14 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { if (activate(world, player, item, stateToUse, raytrace, data)) { ShootableGadgetItemMethods.applyCooldown(player, item, hand, this::isZapper, getCooldownDelay(item)); ShootableGadgetItemMethods.sendPackets(player, - b -> new ZapperBeamPacket(barrelPos, raytrace.getLocation(), hand, b)); + b -> new ZapperBeamPacket(barrelPos, hand, b, raytrace.getLocation())); } return new InteractionResultHolder<>(InteractionResult.SUCCESS, item); } public Component validateUsage(ItemStack item) { - CompoundTag tag = item.getOrCreateTag(); - if (!canActivateWithoutSelectedBlock(item) && !tag.contains("BlockUsed")) + if (!canActivateWithoutSelectedBlock(item) && !item.has(AllDataComponents.SHAPER_BLOCK_USED)) return CreateLang.translateDirect("terrainzapper.leftClickToSet"); return null; } @@ -228,11 +210,6 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { return null; } - public static void configureSettings(ItemStack stack, PlacementPatterns pattern) { - CompoundTag nbt = stack.getOrCreateTag(); - NBTHelper.writeEnum(nbt, "Pattern", pattern); - } - public static void setBlockEntityData(Level world, BlockPos pos, BlockState state, CompoundTag data, Player player) { if (data != null && AllBlockTags.SAFE_NBT.matches(state)) { BlockEntity blockEntity = world.getBlockEntity(pos); @@ -243,7 +220,7 @@ public abstract class ZapperItem extends Item implements CustomArmPoseItem { data.putInt("x", pos.getX()); data.putInt("y", pos.getY()); data.putInt("z", pos.getZ()); - blockEntity.load(data); + blockEntity.loadWithComponents(data, world.registryAccess()); } } } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItemRenderer.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItemRenderer.java index c017fa6fac..0a1c9bf643 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItemRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperItemRenderer.java @@ -1,6 +1,7 @@ package com.simibubi.create.content.equipment.zapper; import com.mojang.blaze3d.vertex.PoseStack; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.CreateClient; import com.simibubi.create.foundation.item.render.CustomRenderedItemModel; import com.simibubi.create.foundation.item.render.CustomRenderedItemModelRenderer; @@ -23,15 +24,13 @@ public abstract class ZapperItemRenderer extends CustomRenderedItemModelRenderer protected void render(ItemStack stack, CustomRenderedItemModel model, PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, MultiBufferSource buffer, int light, int overlay) { // Block indicator - if (transformType == ItemDisplayContext.GUI && stack.hasTag() && stack.getTag() - .contains("BlockUsed")) + if (transformType == ItemDisplayContext.GUI && stack.has(AllDataComponents.SHAPER_BLOCK_USED)) renderBlockUsed(stack, ms, buffer, light, overlay); } @SuppressWarnings("deprecation") private void renderBlockUsed(ItemStack stack, PoseStack ms, MultiBufferSource buffer, int light, int overlay) { - BlockState state = NbtUtils.readBlockState(BuiltInRegistries.BLOCK.asLookup(), stack.getTag() - .getCompound("BlockUsed")); + BlockState state = stack.get(AllDataComponents.SHAPER_BLOCK_USED); ms.pushPose(); ms.translate(-0.3F, -0.45F, -0.0F); diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperLog.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperLog.java index d5d5fa88c6..05a3512704 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperLog.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperLog.java @@ -17,14 +17,14 @@ public class ZapperLog { /* * Undo and redo operations applied by tools what information is necessary? - * + * * For survival mode: does undo have the required blocks - * + * * For creative mode: what data did removed TEs have - * + * * When undo: remove added blocks (added -> air) replace replaced blocks (added * -> before) add removed blocks (air -> before) - * + * */ public void record(Level world, List positions) { @@ -36,7 +36,7 @@ public class ZapperLog { List blocks = positions.stream().map(pos -> { BlockEntity blockEntity = world.getBlockEntity(pos); - return new StructureBlockInfo(pos, world.getBlockState(pos), blockEntity == null ? null : blockEntity.saveWithFullMetadata()); + return new StructureBlockInfo(pos, world.getBlockState(pos), blockEntity == null ? null : blockEntity.saveWithFullMetadata(world.registryAccess())); }).collect(Collectors.toList()); log.add(0, blocks); diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperScreen.java b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperScreen.java index 24936ff892..686fb6b244 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperScreen.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/ZapperScreen.java @@ -1,10 +1,11 @@ package com.simibubi.create.content.equipment.zapper; -import java.util.Vector; +import java.util.ArrayList; +import java.util.List; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; -import com.simibubi.create.AllPackets; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.foundation.gui.AllGuiTextures; import com.simibubi.create.foundation.gui.AllIcons; import com.simibubi.create.foundation.gui.widget.IconButton; @@ -12,12 +13,9 @@ import com.simibubi.create.foundation.utility.CreateLang; import net.createmod.catnip.gui.AbstractSimiScreen; import net.createmod.catnip.gui.element.GuiGameElement; -import net.createmod.catnip.utility.NBTHelper; +import net.createmod.catnip.platform.CatnipServices; import net.createmod.catnip.utility.lang.Components; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; @@ -35,7 +33,7 @@ public abstract class ZapperScreen extends AbstractSimiScreen { protected float animationProgress; protected Component title; - protected Vector patternButtons = new Vector<>(6); + protected List patternButtons = new ArrayList<>(6); private IconButton confirmButton; protected int brightColor; protected int fontColor; @@ -50,8 +48,7 @@ public abstract class ZapperScreen extends AbstractSimiScreen { brightColor = 0xFEFEFE; fontColor = AllGuiTextures.FONT_COLOR; - CompoundTag nbt = zapper.getOrCreateTag(); - currentPattern = NBTHelper.readEnum(nbt, "Pattern", PlacementPatterns.class); + currentPattern = zapper.getOrDefault(AllDataComponents.PLACEMENT_PATTERN, PlacementPatterns.Solid); } @Override @@ -67,9 +64,7 @@ public abstract class ZapperScreen extends AbstractSimiScreen { confirmButton = new IconButton(x + background.getWidth() - 33, y + background.getHeight() - 24, AllIcons.I_CONFIRM); - confirmButton.withCallback(() -> { - onClose(); - }); + confirmButton.withCallback(this::onClose); addRenderableWidget(confirmButton); patternButtons.clear(); @@ -119,7 +114,7 @@ public abstract class ZapperScreen extends AbstractSimiScreen { public void removed() { ConfigureZapperPacket packet = getConfigurationPacket(); packet.configureZapper(zapper); - AllPackets.getChannel().sendToServer(packet); + CatnipServices.NETWORK.sendToServer(packet); } protected void renderZapper(GuiGraphics graphics, int x, int y) { @@ -129,7 +124,6 @@ public abstract class ZapperScreen extends AbstractSimiScreen { .render(graphics); } - @SuppressWarnings("deprecation") protected void renderBlock(GuiGraphics graphics, int x, int y) { PoseStack ms = graphics.pose(); ms.pushPose(); @@ -138,11 +132,7 @@ public abstract class ZapperScreen extends AbstractSimiScreen { ms.mulPose(Axis.YP.rotationDegrees(-45f)); ms.scale(20, 20, 20); - BlockState state = Blocks.AIR.defaultBlockState(); - if (zapper.hasTag() && zapper.getTag() - .contains("BlockUsed")) - state = NbtUtils.readBlockState(BuiltInRegistries.BLOCK.asLookup(), zapper.getTag() - .getCompound("BlockUsed")); + BlockState state = zapper.getOrDefault(AllDataComponents.SHAPER_BLOCK_USED, Blocks.AIR.defaultBlockState());; GuiGameElement.of(state) .render(graphics); diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/ConfigureWorldshaperPacket.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/ConfigureWorldshaperPacket.java index 4830a0ee52..f16a4f2444 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/ConfigureWorldshaperPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/ConfigureWorldshaperPacket.java @@ -1,22 +1,40 @@ package com.simibubi.create.content.equipment.zapper.terrainzapper; +import com.simibubi.create.AllPackets; import com.simibubi.create.content.equipment.zapper.ConfigureZapperPacket; import com.simibubi.create.content.equipment.zapper.PlacementPatterns; -import net.minecraft.network.FriendlyByteBuf; +import net.createmod.catnip.codecs.stream.CatnipLargerStreamCodecs; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecs; +import io.netty.buffer.ByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; public class ConfigureWorldshaperPacket extends ConfigureZapperPacket { + public static final StreamCodec STREAM_CODEC = CatnipLargerStreamCodecs.composite( + CatnipStreamCodecs.HAND, packet -> packet.hand, + PlacementPatterns.STREAM_CODEC, packet -> packet.pattern, + TerrainBrushes.STREAM_CODEC, packet -> packet.brush, + ByteBufCodecs.VAR_INT, packet -> packet.brushParamX, + ByteBufCodecs.VAR_INT, packet -> packet.brushParamY, + ByteBufCodecs.VAR_INT, packet -> packet.brushParamZ, + TerrainTools.STREAM_CODEC, packet -> packet.tool, + PlacementOptions.STREAM_CODEC, packet -> packet.placement, + ConfigureWorldshaperPacket::new + ); - protected TerrainBrushes brush; - protected int brushParamX; - protected int brushParamY; - protected int brushParamZ; - protected TerrainTools tool; - protected PlacementOptions placement; + private final TerrainBrushes brush; + private final int brushParamX; + private final int brushParamY; + private final int brushParamZ; + private final TerrainTools tool; + private final PlacementOptions placement; - public ConfigureWorldshaperPacket(InteractionHand hand, PlacementPatterns pattern, TerrainBrushes brush, int brushParamX, int brushParamY, int brushParamZ, TerrainTools tool, PlacementOptions placement) { + public ConfigureWorldshaperPacket(InteractionHand hand, PlacementPatterns pattern, TerrainBrushes brush, + int brushParamX, int brushParamY, int brushParamZ, + TerrainTools tool, PlacementOptions placement) { super(hand, pattern); this.brush = brush; this.brushParamX = brushParamX; @@ -26,30 +44,13 @@ public class ConfigureWorldshaperPacket extends ConfigureZapperPacket { this.placement = placement; } - public ConfigureWorldshaperPacket(FriendlyByteBuf buffer) { - super(buffer); - brush = buffer.readEnum(TerrainBrushes.class); - brushParamX = buffer.readVarInt(); - brushParamY = buffer.readVarInt(); - brushParamZ = buffer.readVarInt(); - tool = buffer.readEnum(TerrainTools.class); - placement = buffer.readEnum(PlacementOptions.class); - } - - @Override - public void write(FriendlyByteBuf buffer) { - super.write(buffer); - buffer.writeEnum(brush); - buffer.writeVarInt(brushParamX); - buffer.writeVarInt(brushParamY); - buffer.writeVarInt(brushParamZ); - buffer.writeEnum(tool); - buffer.writeEnum(placement); - } - @Override public void configureZapper(ItemStack stack) { WorldshaperItem.configureSettings(stack, pattern, brush, brushParamX, brushParamY, brushParamZ, tool, placement); } + @Override + public PacketTypeProvider getTypeProvider() { + return AllPackets.CONFIGURE_WORLDSHAPER; + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/PlacementOptions.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/PlacementOptions.java index 090a1849a1..ad984dc2ca 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/PlacementOptions.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/PlacementOptions.java @@ -1,21 +1,38 @@ package com.simibubi.create.content.equipment.zapper.terrainzapper; +import com.mojang.serialization.Codec; import com.simibubi.create.foundation.gui.AllIcons; import net.createmod.catnip.utility.lang.Lang; -public enum PlacementOptions { +import com.simibubi.create.infrastructure.codec.CreateStreamCodecs; +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.util.StringRepresentable; + +import io.netty.buffer.ByteBuf; + +import org.jetbrains.annotations.NotNull; + +public enum PlacementOptions implements StringRepresentable { Merged(AllIcons.I_CENTERED), Attached(AllIcons.I_ATTACHED), Inserted(AllIcons.I_INSERTED); - public String translationKey; - public AllIcons icon; + public static final Codec CODEC = StringRepresentable.fromValues(PlacementOptions::values); + public static final StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(PlacementOptions.class); - private PlacementOptions(AllIcons icon) { + public final String translationKey; + public final AllIcons icon; + + PlacementOptions(AllIcons icon) { this.translationKey = Lang.asId(name()); this.icon = icon; } + @Override + public @NotNull String getSerializedName() { + return Lang.asId(name()); + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainBrushes.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainBrushes.java index 11b4a17191..2f48fe927c 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainBrushes.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainBrushes.java @@ -1,18 +1,28 @@ package com.simibubi.create.content.equipment.zapper.terrainzapper; -public enum TerrainBrushes { - +import org.jetbrains.annotations.NotNull; + +import com.mojang.serialization.Codec; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; +import io.netty.buffer.ByteBuf; +import net.createmod.catnip.utility.lang.Lang; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.util.StringRepresentable; + +public enum TerrainBrushes implements StringRepresentable { Cuboid(new CuboidBrush()), Sphere(new SphereBrush()), Cylinder(new CylinderBrush()), Surface(new DynamicBrush(true)), - Cluster(new DynamicBrush(false)), - - ; - + Cluster(new DynamicBrush(false)); + + public static final Codec CODEC = StringRepresentable.fromValues(TerrainBrushes::values); + public static final StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(TerrainBrushes.class); + private Brush brush; - private TerrainBrushes(Brush brush) { + TerrainBrushes(Brush brush) { this.brush = brush; } @@ -20,4 +30,8 @@ public enum TerrainBrushes { return brush; } + @Override + public @NotNull String getSerializedName() { + return Lang.asId(name()); + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainTools.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainTools.java index 4b3422b9b3..2987a17a99 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainTools.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/TerrainTools.java @@ -4,37 +4,50 @@ import java.util.List; import javax.annotation.Nullable; +import com.mojang.serialization.Codec; import com.simibubi.create.content.equipment.zapper.ZapperItem; import com.simibubi.create.foundation.gui.AllIcons; import net.createmod.catnip.utility.lang.Lang; + +import net.createmod.catnip.codecs.stream.CatnipStreamCodecBuilders; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.util.StringRepresentable; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; -public enum TerrainTools { +import io.netty.buffer.ByteBuf; +import org.jetbrains.annotations.NotNull; + +public enum TerrainTools implements StringRepresentable { Fill(AllIcons.I_FILL), Place(AllIcons.I_PLACE), Replace(AllIcons.I_REPLACE), Clear(AllIcons.I_CLEAR), Overlay(AllIcons.I_OVERLAY), - Flatten(AllIcons.I_FLATTEN), - - ; + Flatten(AllIcons.I_FLATTEN); + public static final Codec CODEC = StringRepresentable.fromValues(TerrainTools::values); + public static final StreamCodec STREAM_CODEC = CatnipStreamCodecBuilders.ofEnum(TerrainTools.class); public String translationKey; public AllIcons icon; - private TerrainTools(AllIcons icon) { + TerrainTools(AllIcons icon) { this.translationKey = Lang.asId(name()); this.icon = icon; } + @Override + public @NotNull String getSerializedName() { + return Lang.asId(name()); + } + public boolean requiresSelectedBlock() { return this != Clear && this != Flatten; } @@ -94,5 +107,4 @@ public enum TerrainTools { public static boolean isReplaceable(BlockState toReplace) { return toReplace.canBeReplaced(); } - } diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperItem.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperItem.java index 79fdc24dfc..55619abba7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperItem.java @@ -4,16 +4,15 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.content.equipment.zapper.PlacementPatterns; import com.simibubi.create.content.equipment.zapper.ZapperItem; import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; import com.simibubi.create.foundation.utility.CreateLang; import net.createmod.catnip.gui.ScreenOpener; -import net.createmod.catnip.utility.NBTHelper; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -21,9 +20,9 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.api.distmarker.OnlyIn; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; public class WorldshaperItem extends ZapperItem { @@ -49,16 +48,14 @@ public class WorldshaperItem extends ZapperItem { @Override public Component validateUsage(ItemStack item) { - if (!item.getOrCreateTag() - .contains("BrushParams")) + if (!item.has(AllDataComponents.SHAPER_BRUSH_PARAMS)) return CreateLang.translateDirect("terrainzapper.shiftRightClickToSet"); return super.validateUsage(item); } @Override protected boolean canActivateWithoutSelectedBlock(ItemStack stack) { - CompoundTag tag = stack.getOrCreateTag(); - TerrainTools tool = NBTHelper.readEnum(tag, "Tool", TerrainTools.class); + TerrainTools tool = stack.getOrDefault(AllDataComponents.SHAPER_TOOL, TerrainTools.Fill); return !tool.requiresSelectedBlock(); } @@ -69,12 +66,10 @@ public class WorldshaperItem extends ZapperItem { BlockPos targetPos = raytrace.getBlockPos(); List affectedPositions = new ArrayList<>(); - CompoundTag tag = stack.getOrCreateTag(); - Brush brush = NBTHelper.readEnum(tag, "Brush", TerrainBrushes.class) - .get(); - BlockPos params = NbtUtils.readBlockPos(tag.getCompound("BrushParams")); - PlacementOptions option = NBTHelper.readEnum(tag, "Placement", PlacementOptions.class); - TerrainTools tool = NBTHelper.readEnum(tag, "Tool", TerrainTools.class); + Brush brush = stack.getOrDefault(AllDataComponents.SHAPER_BRUSH, TerrainBrushes.Cuboid).get(); + BlockPos params = stack.get(AllDataComponents.SHAPER_BRUSH_PARAMS); + PlacementOptions option = stack.getOrDefault(AllDataComponents.SHAPER_PLACEMENT_OPTIONS, PlacementOptions.Merged); + TerrainTools tool = stack.getOrDefault(AllDataComponents.SHAPER_TOOL, TerrainTools.Fill); brush.set(params.getX(), params.getY(), params.getZ()); targetPos = targetPos.offset(brush.getOffset(player.getLookAngle(), raytrace.getDirection(), option)); @@ -88,12 +83,11 @@ public class WorldshaperItem extends ZapperItem { public static void configureSettings(ItemStack stack, PlacementPatterns pattern, TerrainBrushes brush, int brushParamX, int brushParamY, int brushParamZ, TerrainTools tool, PlacementOptions placement) { - ZapperItem.configureSettings(stack, pattern); - CompoundTag nbt = stack.getOrCreateTag(); - NBTHelper.writeEnum(nbt, "Brush", brush); - nbt.put("BrushParams", NbtUtils.writeBlockPos(new BlockPos(brushParamX, brushParamY, brushParamZ))); - NBTHelper.writeEnum(nbt, "Tool", tool); - NBTHelper.writeEnum(nbt, "Placement", placement); + stack.set(AllDataComponents.PLACEMENT_PATTERN, pattern); + stack.set(AllDataComponents.SHAPER_BRUSH, brush); + stack.set(AllDataComponents.SHAPER_BRUSH_PARAMS, new BlockPos(brushParamX, brushParamY, brushParamZ)); + stack.set(AllDataComponents.SHAPER_TOOL, tool); + stack.set(AllDataComponents.SHAPER_PLACEMENT_OPTIONS, placement); } @Override diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperRenderHandler.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperRenderHandler.java index 07de94f09b..8dd5525c73 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperRenderHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperRenderHandler.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.function.Supplier; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.AllItems; import com.simibubi.create.AllSpecialTextures; @@ -46,33 +47,30 @@ public class WorldshaperRenderHandler { boolean zapperInOff = AllItems.WORLDSHAPER.isIn(heldOff); if (zapperInMain) { - CompoundTag tag = heldMain.getOrCreateTag(); - if (!tag.contains("_Swap") || !zapperInOff) { - createBrushOutline(tag, player, heldMain); + if (!heldMain.has(AllDataComponents.SHAPER_SWAP) || !zapperInOff) { + createBrushOutline(player, heldMain); return; } } if (zapperInOff) { - CompoundTag tag = heldOff.getOrCreateTag(); - createBrushOutline(tag, player, heldOff); + createBrushOutline(player, heldOff); return; } renderedPositions = null; } - public static void createBrushOutline(CompoundTag tag, LocalPlayer player, ItemStack zapper) { - if (!tag.contains("BrushParams")) { + public static void createBrushOutline(LocalPlayer player, ItemStack zapper) { + if (!zapper.has(AllDataComponents.SHAPER_BRUSH_PARAMS)) { renderedPositions = null; return; } - Brush brush = NBTHelper.readEnum(tag, "Brush", TerrainBrushes.class) - .get(); - PlacementOptions placement = NBTHelper.readEnum(tag, "Placement", PlacementOptions.class); - TerrainTools tool = NBTHelper.readEnum(tag, "Tool", TerrainTools.class); - BlockPos params = NbtUtils.readBlockPos(tag.getCompound("BrushParams")); + Brush brush = zapper.getOrDefault(AllDataComponents.SHAPER_BRUSH, TerrainBrushes.Cuboid).get(); + PlacementOptions placement = zapper.getOrDefault(AllDataComponents.SHAPER_PLACEMENT_OPTIONS, PlacementOptions.Merged); + TerrainTools tool = zapper.getOrDefault(AllDataComponents.SHAPER_TOOL, TerrainTools.Fill); + BlockPos params = zapper.get(AllDataComponents.SHAPER_BRUSH_PARAMS); brush.set(params.getX(), params.getY(), params.getZ()); Vec3 start = player.position() diff --git a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperScreen.java b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperScreen.java index 72a42ff23c..9a829d1783 100644 --- a/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperScreen.java +++ b/src/main/java/com/simibubi/create/content/equipment/zapper/terrainzapper/WorldshaperScreen.java @@ -1,8 +1,9 @@ package com.simibubi.create.content.equipment.zapper.terrainzapper; +import java.util.ArrayList; import java.util.List; -import java.util.Vector; +import com.simibubi.create.AllDataComponents; import com.simibubi.create.content.equipment.zapper.ConfigureZapperPacket; import com.simibubi.create.content.equipment.zapper.ZapperScreen; import com.simibubi.create.foundation.gui.AllGuiTextures; @@ -15,13 +16,9 @@ import com.simibubi.create.foundation.gui.widget.ScrollInput; import com.simibubi.create.foundation.gui.widget.SelectionScrollInput; import com.simibubi.create.foundation.utility.CreateLang; -import net.createmod.catnip.utility.NBTHelper; import net.createmod.catnip.utility.lang.Components; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; @@ -33,13 +30,13 @@ public class WorldshaperScreen extends ZapperScreen { protected final List brushOptions = CreateLang.translatedOptions("gui.terrainzapper.brush", "cuboid", "sphere", "cylinder", "surface", "cluster"); - protected Vector toolButtons; - protected Vector placementButtons; + protected List toolButtons; + protected List placementButtons; protected ScrollInput brushInput; protected Label brushLabel; - protected Vector brushParams = new Vector<>(3); - protected Vector