diff --git a/buildSrc/build.gradle.kts b/build-logic/build.gradle.kts similarity index 59% rename from buildSrc/build.gradle.kts rename to build-logic/build.gradle.kts index f277a4f59..7ded3026e 100644 --- a/buildSrc/build.gradle.kts +++ b/build-logic/build.gradle.kts @@ -3,26 +3,7 @@ } repositories { - maven { - name = "PaperMC" - url = uri("https://repo.papermc.io/repository/maven-public/") - content { - includeGroupAndSubgroups("io.papermc") - } - } - maven { - name = "NeoForged Maven" - url = uri("https://maven.neoforged.net/releases") - content { - includeGroupAndSubgroups("net.neoforged") - } - } - mavenCentral() gradlePluginPortal() - maven { - name = "Fabric" - url = uri("https://maven.fabricmc.net/") - } maven { name = "EngineHub Repository" url = uri("https://maven.enginehub.org/repo/") @@ -36,11 +17,8 @@ implementation(libs.japicmp) implementation(libs.shadow) implementation(libs.jfrog.buildinfo) - implementation(libs.neoGradle.userdev) - implementation(libs.fabric.loom) - implementation(libs.fabric.mixin) - implementation(libs.codecov) implementation(libs.paperweight) + implementation(libs.gson) constraints { val asmVersion = "[${libs.versions.minimumAsm.get()},)" implementation("org.ow2.asm:asm:$asmVersion") { diff --git a/buildSrc/settings.gradle.kts b/build-logic/settings.gradle.kts similarity index 100% rename from buildSrc/settings.gradle.kts rename to build-logic/settings.gradle.kts diff --git a/build-logic/src/main/kotlin/buildlogic.adapter.gradle.kts b/build-logic/src/main/kotlin/buildlogic.adapter.gradle.kts new file mode 100644 index 000000000..58fce0a23 --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.adapter.gradle.kts @@ -0,0 +1,26 @@ +import buildlogic.stringyLibs +import buildlogic.getVersion + +plugins { + `java-library` + id("buildlogic.common") + id("buildlogic.common-java") + id("io.papermc.paperweight.userdev") +} + +configure { + banSlf4j = false +} + +dependencies { + "implementation"(project(":worldedit-bukkit")) + constraints { + "remapper"("net.fabricmc:tiny-remapper:[${stringyLibs.getVersion("minimumTinyRemapper")},)") { + because("Need remapper to support Java 21") + } + } +} + +tasks.named("assemble") { + dependsOn("reobfJar") +} diff --git a/build-logic/src/main/kotlin/buildlogic.artifactory-root.gradle.kts b/build-logic/src/main/kotlin/buildlogic.artifactory-root.gradle.kts new file mode 100644 index 000000000..c3b4f8310 --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.artifactory-root.gradle.kts @@ -0,0 +1,35 @@ +import org.gradle.api.Project +import org.gradle.kotlin.dsl.configure +import org.gradle.kotlin.dsl.named +import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention +import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask + +plugins { + id("com.jfrog.artifactory") +} + +val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl" +val ARTIFACTORY_USER = "artifactory_user" +val ARTIFACTORY_PASSWORD = "artifactory_password" + +if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost" +if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest" +if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = "" + +configure { + setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}") + clientConfig.publisher.run { + repoKey = when { + "${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local" + else -> "libs-release-local" + } + username = "${project.property(ARTIFACTORY_USER)}" + password = "${project.property(ARTIFACTORY_PASSWORD)}" + isMaven = true + isIvy = false + } +} + +tasks.named("artifactoryPublish") { + isSkip = true +} diff --git a/build-logic/src/main/kotlin/buildlogic.artifactory-sub.gradle.kts b/build-logic/src/main/kotlin/buildlogic.artifactory-sub.gradle.kts new file mode 100644 index 000000000..966409761 --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.artifactory-sub.gradle.kts @@ -0,0 +1,10 @@ +plugins { + id("com.jfrog.artifactory") +} + +// Artifactory eagerly evaluates publications, so this must run after all changes to artifacts are done +afterEvaluate { + tasks.named("artifactoryPublish") { + publications("maven") + } +} diff --git a/build-logic/src/main/kotlin/buildlogic.common-java.gradle.kts b/build-logic/src/main/kotlin/buildlogic.common-java.gradle.kts new file mode 100644 index 000000000..48387042f --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.common-java.gradle.kts @@ -0,0 +1,82 @@ +import buildlogic.stringyLibs +import buildlogic.getLibrary + +plugins { + id("eclipse") + id("idea") + id("checkstyle") + id("buildlogic.common") +} + +val commonJava = extensions.create("commonJava") +commonJava.banSlf4j.convention(true) + +tasks + .withType() + .matching { it.name == "compileJava" || it.name == "compileTestJava" } + .configureEach { + // TODO: re-enable this-escape when ANTLR suppresses it properly + val disabledLint = listOf( + "processing", "path", "fallthrough", "serial", "overloads", "this-escape", + ) + options.release.set(21) + options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" }) + options.isDeprecation = true + options.encoding = "UTF-8" + options.compilerArgs.add("-parameters") + options.compilerArgs.add("-Werror") + } + +configure { + configFile = rootProject.file("config/checkstyle/checkstyle.xml") + toolVersion = "9.1" +} + +tasks.withType().configureEach { + useJUnitPlatform() +} + +dependencies { + "compileOnly"(stringyLibs.getLibrary("jsr305")) + "testImplementation"(platform(stringyLibs.getLibrary("junit-bom"))) + "testImplementation"(stringyLibs.getLibrary("junit-jupiter-api")) + "testImplementation"(stringyLibs.getLibrary("junit-jupiter-params")) + "testImplementation"(platform(stringyLibs.getLibrary("mockito-bom"))) + "testImplementation"(stringyLibs.getLibrary("mockito-core")) + "testImplementation"(stringyLibs.getLibrary("mockito-junit-jupiter")) + "testRuntimeOnly"(stringyLibs.getLibrary("junit-jupiter-engine")) +} + +// Java 8 turns on doclint which we fail +tasks.withType().configureEach { + options.encoding = "UTF-8" + (options as StandardJavadocDocletOptions).apply { + addBooleanOption("Werror", true) + addBooleanOption("Xdoclint:all", true) + addBooleanOption("Xdoclint:-missing", true) + tags( + "apiNote:a:API Note:", + "implSpec:a:Implementation Requirements:", + "implNote:a:Implementation Note:" + ) + } +} + +configure { + withJavadocJar() + withSourcesJar() +} + +configurations["compileClasspath"].apply { + resolutionStrategy.componentSelection { + withModule("org.slf4j:slf4j-api") { + if (commonJava.banSlf4j.get()) { + reject("No SLF4J allowed on compile classpath") + } + } + } +} + +tasks.named("check").configure { + dependsOn("checkstyleMain", "checkstyleTest") +} diff --git a/build-logic/src/main/kotlin/buildlogic.common.gradle.kts b/build-logic/src/main/kotlin/buildlogic.common.gradle.kts new file mode 100644 index 000000000..91006dfea --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.common.gradle.kts @@ -0,0 +1,68 @@ +import buildlogic.getLibrary +import buildlogic.stringyLibs +import org.gradle.plugins.ide.idea.model.IdeaModel + +plugins { + id("org.cadixdev.licenser") +} + +group = rootProject.group +version = rootProject.version + +repositories { + maven { + name = "EngineHub" + url = uri("https://maven.enginehub.org/repo/") + } +} + +configurations.all { + resolutionStrategy { + cacheChangingModulesFor(1, TimeUnit.DAYS) + } +} + +plugins.withId("java") { + the().toolchain { + languageVersion.set(JavaLanguageVersion.of(21)) + } +} + +dependencies { + for (conf in listOf("implementation", "api")) { + if (!configurations.names.contains(conf)) { + continue + } + add(conf, platform(stringyLibs.getLibrary("log4j-bom")).map { + val dep = create(it) + dep.because("Mojang provides Log4j") + dep + }) + constraints { + add(conf, stringyLibs.getLibrary("guava")) { + because("Mojang provides Guava") + } + add(conf, stringyLibs.getLibrary("gson")) { + because("Mojang provides Gson") + } + add(conf, stringyLibs.getLibrary("fastutil")) { + because("Mojang provides FastUtil") + } + } + } +} + +license { + header(rootProject.file("HEADER.txt")) + include("**/*.java") + include("**/*.kt") +} + +plugins.withId("idea") { + configure { + module { + isDownloadSources = true + isDownloadJavadoc = true + } + } +} diff --git a/build-logic/src/main/kotlin/buildlogic.core-and-platform.gradle.kts b/build-logic/src/main/kotlin/buildlogic.core-and-platform.gradle.kts new file mode 100644 index 000000000..ce369ccec --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.core-and-platform.gradle.kts @@ -0,0 +1,23 @@ +plugins { + id("java") + id("maven-publish") + id("buildlogic.common-java") + id("buildlogic.artifactory-sub") +} + +ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}" + +publishing { + publications { + register("maven") { + versionMapping { + usage("java-api") { + fromResolutionOf("runtimeClasspath") + } + usage("java-runtime") { + fromResolutionResult() + } + } + } + } +} diff --git a/build-logic/src/main/kotlin/buildlogic.libs.gradle.kts b/build-logic/src/main/kotlin/buildlogic.libs.gradle.kts new file mode 100644 index 000000000..653c7d09c --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.libs.gradle.kts @@ -0,0 +1,180 @@ +plugins { + id("java-base") + id("maven-publish") + id("com.github.johnrengelman.shadow") + id("com.jfrog.artifactory") + id("buildlogic.common") + id("buildlogic.artifactory-sub") +} + +// A horrible hack because `softwareComponentFactory` has to be gotten via plugin +// gradle why +internal open class LibsConfigPluginHack @Inject constructor( + private val softwareComponentFactory: SoftwareComponentFactory +) : Plugin { + override fun apply(project: Project) { + val libsComponents = softwareComponentFactory.adhoc("libs") + project.components.add(libsComponents) + } +} + +configurations { + create("shade") +} + +group = "${rootProject.group}.worldedit-libs" + +val relocations = mapOf( + "net.kyori.text" to "com.sk89q.worldedit.util.formatting.text", + "net.kyori.minecraft" to "com.sk89q.worldedit.util.kyori", +) + +tasks.register("jar") { + configurations = listOf(project.configurations["shade"]) + archiveClassifier.set("") + + // Yeet module-info's + exclude("module-info.class") + + dependencies { + exclude(dependency("com.google.guava:guava")) + exclude(dependency("com.google.code.gson:gson")) + exclude(dependency("com.google.errorprone:error_prone_annotations")) + exclude(dependency("com.google.guava:failureaccess")) + exclude(dependency("org.checkerframework:checker-qual")) + exclude(dependency("org.jetbrains:annotations")) + exclude(dependency("org.apache.logging.log4j:log4j-api")) + exclude(dependency("com.google.code.findbugs:jsr305")) + exclude { + it.moduleGroup == "org.jetbrains.kotlin" + } + } + + relocations.forEach { (from, to) -> + relocate(from, to) + } +} +val altConfigFiles = { artifactType: String -> + val deps = configurations["shade"].incoming.dependencies + .filterIsInstance() + .map { it.copy() } + .map { dependency -> + val category = dependency.attributes.getAttribute(Category.CATEGORY_ATTRIBUTE)?.name + if (category == Category.REGULAR_PLATFORM || category == Category.ENFORCED_PLATFORM) { + return@map dependency + } + try { + dependency.artifact { + name = dependency.name + type = artifactType + extension = "jar" + classifier = artifactType + } + } catch (e: Exception) { + throw RuntimeException("Failed to add artifact to dependency: $dependency", e) + } + dependency + } + + files(configurations.detachedConfiguration(*deps.toTypedArray()) + .resolvedConfiguration.lenientConfiguration.artifacts + .filter { it.classifier == artifactType } + .map { zipTree(it.file) }) +} +tasks.register("sourcesJar") { + from({ + altConfigFiles("sources") + }) + + // Yeet module-info's + exclude("module-info.java") + + relocations.forEach { (from, to) -> + val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)") + val textPattern = Regex.fromLiteral(from) + eachFile { + filter { + it.replaceFirst(textPattern, to) + } + path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2") + } + } + archiveClassifier.set("sources") +} + +tasks.named("assemble").configure { + dependsOn("jar", "sourcesJar") +} + +project.apply() + +val libsComponent = project.components["libs"] as AdhocComponentWithVariants + +val apiElements = project.configurations.register("apiElements") { + isVisible = false + description = "API elements for libs" + isCanBeResolved = false + isCanBeConsumed = true + attributes { + attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API)) + attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY)) + attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED)) + attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR)) + attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 16) + } + outgoing.artifact(tasks.named("jar")) +} + +val runtimeElements = project.configurations.register("runtimeElements") { + isVisible = false + description = "Runtime elements for libs" + isCanBeResolved = false + isCanBeConsumed = true + attributes { + attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME)) + attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY)) + attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED)) + attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR)) + attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 16) + } + outgoing.artifact(tasks.named("jar")) +} + +val sourcesElements = project.configurations.register("sourcesElements") { + isVisible = false + description = "Source elements for libs" + isCanBeResolved = false + isCanBeConsumed = true + attributes { + attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME)) + attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION)) + attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED)) + attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES)) + } + outgoing.artifact(tasks.named("sourcesJar")) +} + +libsComponent.addVariantsFromConfiguration(apiElements.get()) { + mapToMavenScope("compile") +} + +libsComponent.addVariantsFromConfiguration(runtimeElements.get()) { + mapToMavenScope("runtime") +} + +libsComponent.addVariantsFromConfiguration(sourcesElements.get()) { + mapToMavenScope("runtime") +} + +configure { + publications { + register("maven") { + from(libsComponent) + } + } +} + +if (project != project(":worldedit-libs:core")) { + evaluationDependsOn(":worldedit-libs:core") + configurations["shade"].shouldResolveConsistentlyWith(project(":worldedit-libs:core").configurations["shade"]) +} diff --git a/build-logic/src/main/kotlin/buildlogic.platform.gradle.kts b/build-logic/src/main/kotlin/buildlogic.platform.gradle.kts new file mode 100644 index 000000000..259794771 --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic.platform.gradle.kts @@ -0,0 +1,53 @@ +plugins { + id("com.github.johnrengelman.shadow") + id("buildlogic.core-and-platform") +} + +val platform = extensions.create("platform") +platform.includeClasspath.convention(false) +platform.extraAttributes.convention(mapOf()) + +tasks.named("shadowJar") { + archiveClassifier.set("dist") + dependencies { + include(project(":worldedit-libs:core")) + include(project(":worldedit-libs:${project.name.replace("worldedit-", "")}")) + include(project(":worldedit-core")) + exclude("com.google.code.findbugs:jsr305") + } + exclude("GradleStart**") + exclude(".cache") + exclude("LICENSE*") + exclude("META-INF/maven/**") + minimize() +} +val javaComponent = components["java"] as AdhocComponentWithVariants +// I don't think we want this published (it's the shadow jar) +javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) { + skip() +} + +afterEvaluate { + tasks.named("jar") { + val kind = platform.kind.get() + val includeClasspath = platform.includeClasspath.get() + val extraAttributes = platform.extraAttributes.get() + + val version = project(":worldedit-core").version + inputs.property("version", version) + val attributes = mutableMapOf( + "Implementation-Version" to version, + "WorldEdit-Version" to version, + "WorldEdit-Kind" to kind.name, + "Main-Class" to kind.mainClass + ) + if (includeClasspath) { + attributes["Class-Path"] = listOf("truezip", "truevfs", "js") + .map { "$it.jar" } + .flatMap { listOf(it, "WorldEdit/$it") } + .joinToString(separator = " ") + } + attributes.putAll(extraAttributes) + manifest.attributes(attributes) + } +} diff --git a/build-logic/src/main/kotlin/buildlogic/CommonJavaExtension.kt b/build-logic/src/main/kotlin/buildlogic/CommonJavaExtension.kt new file mode 100644 index 000000000..8631f5379 --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic/CommonJavaExtension.kt @@ -0,0 +1,7 @@ +package buildlogic + +import org.gradle.api.provider.Property + +interface CommonJavaExtension { + val banSlf4j: Property +} diff --git a/buildSrc/src/main/kotlin/GradleExtras.kt b/build-logic/src/main/kotlin/buildlogic/GradleExtras.kt similarity index 98% rename from buildSrc/src/main/kotlin/GradleExtras.kt rename to build-logic/src/main/kotlin/buildlogic/GradleExtras.kt index e6d1fa3c6..77b0059db 100644 --- a/buildSrc/src/main/kotlin/GradleExtras.kt +++ b/build-logic/src/main/kotlin/buildlogic/GradleExtras.kt @@ -1,3 +1,5 @@ +package buildlogic + import org.gradle.api.Project import org.gradle.api.artifacts.MinimalExternalModuleDependency import org.gradle.api.artifacts.VersionCatalog diff --git a/build-logic/src/main/kotlin/buildlogic/PlatformExtension.kt b/build-logic/src/main/kotlin/buildlogic/PlatformExtension.kt new file mode 100644 index 000000000..d27a3e495 --- /dev/null +++ b/build-logic/src/main/kotlin/buildlogic/PlatformExtension.kt @@ -0,0 +1,19 @@ +package buildlogic + +import org.gradle.api.provider.MapProperty +import org.gradle.api.provider.Property + +interface PlatformExtension { + val kind: Property + val includeClasspath: Property + val extraAttributes: MapProperty +} + +sealed class WorldEditKind( + val name: String, + val mainClass: String = "com.sk89q.worldedit.internal.util.InfoEntryPoint" +) { + class Standalone(mainClass: String) : WorldEditKind("STANDALONE", mainClass) + object Mod : WorldEditKind("MOD") + object Plugin : WorldEditKind("PLUGIN") +} diff --git a/buildSrc/src/main/kotlin/japicmp/accept/AbstractAcceptingRule.kt b/build-logic/src/main/kotlin/japicmp/accept/AbstractAcceptingRule.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/AbstractAcceptingRule.kt rename to build-logic/src/main/kotlin/japicmp/accept/AbstractAcceptingRule.kt diff --git a/buildSrc/src/main/kotlin/japicmp/accept/AcceptedRegressionsRulePostProcess.kt b/build-logic/src/main/kotlin/japicmp/accept/AcceptedRegressionsRulePostProcess.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/AcceptedRegressionsRulePostProcess.kt rename to build-logic/src/main/kotlin/japicmp/accept/AcceptedRegressionsRulePostProcess.kt diff --git a/buildSrc/src/main/kotlin/japicmp/accept/AcceptingSetupRule.kt b/build-logic/src/main/kotlin/japicmp/accept/AcceptingSetupRule.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/AcceptingSetupRule.kt rename to build-logic/src/main/kotlin/japicmp/accept/AcceptingSetupRule.kt diff --git a/buildSrc/src/main/kotlin/japicmp/accept/BinaryCompatRule.kt b/build-logic/src/main/kotlin/japicmp/accept/BinaryCompatRule.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/BinaryCompatRule.kt rename to build-logic/src/main/kotlin/japicmp/accept/BinaryCompatRule.kt diff --git a/buildSrc/src/main/kotlin/japicmp/accept/ChangeParams.kt b/build-logic/src/main/kotlin/japicmp/accept/ChangeParams.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/ChangeParams.kt rename to build-logic/src/main/kotlin/japicmp/accept/ChangeParams.kt diff --git a/buildSrc/src/main/kotlin/japicmp/accept/LICENSE.md b/build-logic/src/main/kotlin/japicmp/accept/LICENSE.md similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/LICENSE.md rename to build-logic/src/main/kotlin/japicmp/accept/LICENSE.md diff --git a/buildSrc/src/main/kotlin/japicmp/accept/apichanges.kt b/build-logic/src/main/kotlin/japicmp/accept/apichanges.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/apichanges.kt rename to build-logic/src/main/kotlin/japicmp/accept/apichanges.kt diff --git a/buildSrc/src/main/kotlin/japicmp/accept/userdata.kt b/build-logic/src/main/kotlin/japicmp/accept/userdata.kt similarity index 100% rename from buildSrc/src/main/kotlin/japicmp/accept/userdata.kt rename to build-logic/src/main/kotlin/japicmp/accept/userdata.kt diff --git a/build.gradle.kts b/build.gradle.kts index 939ab6097..0f5d6e564 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,21 +1,25 @@ import org.ajoberstar.grgit.Grgit -// needed for fabric to know where FF executor is.... buildscript { repositories { - mavenCentral() + maven { + name = "EngineHub" + url = uri("https://maven.enginehub.org/repo/") + } maven { name = "Fabric" url = uri("https://maven.fabricmc.net/") } } dependencies { - classpath(libs.fabric.loom) + // needed for fabric to know where FF executor is.... } } plugins { - id("org.enginehub.codecov") + alias(libs.plugins.codecov) jacoco + id("buildlogic.common") + id("buildlogic.artifactory-root") } if (!project.hasProperty("gitCommitHash")) { @@ -29,23 +33,6 @@ } } -logger.lifecycle(""" -******************************************* - You are building WorldEdit! - - If you encounter trouble: - 1) Read COMPILING.md if you haven't yet - 2) Try running 'build' in a separate Gradle run - 3) Use gradlew and not gradle - 4) If you still need help, ask on Discord! https://discord.gg/enginehub - - Output files will be in [subproject]/build/libs -******************************************* -""") - -applyCommonConfiguration() -applyRootArtifactoryConfig() - val totalReport = tasks.register("jacocoTotalReport") { for (proj in subprojects) { proj.apply(plugin = "jacoco") diff --git a/buildSrc/src/main/kotlin/AdapterConfig.kt b/buildSrc/src/main/kotlin/AdapterConfig.kt deleted file mode 100644 index 240a623d2..000000000 --- a/buildSrc/src/main/kotlin/AdapterConfig.kt +++ /dev/null @@ -1,29 +0,0 @@ -import org.gradle.api.Project -import org.gradle.kotlin.dsl.apply -import org.gradle.kotlin.dsl.dependencies - -// For specific version pinning, see -// https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ -fun Project.applyPaperweightAdapterConfiguration(javaRelease: Int = 21) { - applyCommonConfiguration() - apply(plugin = "java-library") - applyCommonJavaConfiguration( - sourcesJar = true, - javaRelease = javaRelease, - banSlf4j = false, - ) - apply(plugin = "io.papermc.paperweight.userdev") - - dependencies { - "implementation"(project(":worldedit-bukkit")) - constraints { - "remapper"("net.fabricmc:tiny-remapper:[${stringyLibs.getVersion("minimumTinyRemapper")},)") { - because("Need remapper to support Java 21") - } - } - } - - tasks.named("assemble") { - dependsOn("reobfJar") - } -} diff --git a/buildSrc/src/main/kotlin/ArtifactoryConfig.kt b/buildSrc/src/main/kotlin/ArtifactoryConfig.kt deleted file mode 100644 index fade87454..000000000 --- a/buildSrc/src/main/kotlin/ArtifactoryConfig.kt +++ /dev/null @@ -1,43 +0,0 @@ -import org.gradle.api.Project -import org.gradle.kotlin.dsl.apply -import org.gradle.kotlin.dsl.configure -import org.gradle.kotlin.dsl.named -import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention -import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask - -private const val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl" -private const val ARTIFACTORY_USER = "artifactory_user" -private const val ARTIFACTORY_PASSWORD = "artifactory_password" - -fun Project.applyRootArtifactoryConfig() { - if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost" - if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest" - if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = "" - - apply(plugin = "com.jfrog.artifactory") - configure { - setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}") - clientConfig.publisher.run { - repoKey = when { - "${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local" - else -> "libs-release-local" - } - username = "${project.property(ARTIFACTORY_USER)}" - password = "${project.property(ARTIFACTORY_PASSWORD)}" - isMaven = true - isIvy = false - } - } - tasks.named("artifactoryPublish") { - isSkip = true - } -} - -fun Project.applyCommonArtifactoryConfig() { - // Artifactory eagerly evaluates publications, so this must run after all changes to artifacts are done - afterEvaluate { - tasks.named("artifactoryPublish") { - publications("maven") - } - } -} diff --git a/buildSrc/src/main/kotlin/CommonConfig.kt b/buildSrc/src/main/kotlin/CommonConfig.kt deleted file mode 100644 index f3354f170..000000000 --- a/buildSrc/src/main/kotlin/CommonConfig.kt +++ /dev/null @@ -1,82 +0,0 @@ -import groovy.lang.Closure -import org.cadixdev.gradle.licenser.LicenseExtension -import org.gradle.api.Project -import org.gradle.api.artifacts.Dependency -import org.gradle.api.artifacts.ExternalModuleDependency -import org.gradle.api.plugins.JavaPluginExtension -import org.gradle.jvm.toolchain.JavaLanguageVersion -import org.gradle.kotlin.dsl.* -import org.gradle.plugins.ide.idea.model.IdeaModel -import java.util.concurrent.TimeUnit - -fun Project.applyCommonConfiguration() { - group = rootProject.group - version = rootProject.version - - repositories { - mavenCentral { - mavenContent { - releasesOnly() - } - } - maven { url = uri("https://maven.enginehub.org/repo/") } - maven { - url = uri("https://oss.sonatype.org/content/repositories/snapshots/") - mavenContent { - snapshotsOnly() - } - } - } - - configurations.all { - resolutionStrategy { - cacheChangingModulesFor(1, TimeUnit.DAYS) - } - } - - plugins.withId("java") { - the().toolchain { - languageVersion.set(JavaLanguageVersion.of(21)) - } - } - - dependencies { - for (conf in listOf("implementation", "api")) { - if (!configurations.names.contains(conf)) { - continue - } - add(conf, platform(stringyLibs.getLibrary("log4j-bom")).map { - val dep = create(it) - dep.because("Mojang provides Log4j") - dep - }) - constraints { - add(conf, stringyLibs.getLibrary("guava")) { - because("Mojang provides Guava") - } - add(conf, stringyLibs.getLibrary("gson")) { - because("Mojang provides Gson") - } - add(conf, stringyLibs.getLibrary("fastutil")) { - because("Mojang provides FastUtil") - } - } - } - } - - apply(plugin = "org.cadixdev.licenser") - configure { - header(rootProject.file("HEADER.txt")) - include("**/*.java") - include("**/*.kt") - } - - plugins.withId("idea") { - configure { - module { - isDownloadSources = true - isDownloadJavadoc = true - } - } - } -} diff --git a/buildSrc/src/main/kotlin/CommonJavaConfig.kt b/buildSrc/src/main/kotlin/CommonJavaConfig.kt deleted file mode 100644 index 3c58b86ea..000000000 --- a/buildSrc/src/main/kotlin/CommonJavaConfig.kt +++ /dev/null @@ -1,91 +0,0 @@ -import org.gradle.api.Project -import org.gradle.api.plugins.JavaPluginExtension -import org.gradle.api.plugins.quality.CheckstyleExtension -import org.gradle.api.tasks.compile.JavaCompile -import org.gradle.api.tasks.javadoc.Javadoc -import org.gradle.api.tasks.testing.Test -import org.gradle.external.javadoc.StandardJavadocDocletOptions -import org.gradle.kotlin.dsl.apply -import org.gradle.kotlin.dsl.configure -import org.gradle.kotlin.dsl.dependencies -import org.gradle.kotlin.dsl.get -import org.gradle.kotlin.dsl.withType - -fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, javaRelease: Int = 17, banSlf4j: Boolean = true) { - applyCommonConfiguration() - apply(plugin = "eclipse") - apply(plugin = "idea") - apply(plugin = "checkstyle") - - tasks - .withType() - .matching { it.name == "compileJava" || it.name == "compileTestJava" } - .configureEach { - // TODO: re-enable this-escape when ANTLR suppresses it properly - val disabledLint = listOf( - "processing", "path", "fallthrough", "serial", "overloads", "this-escape", - ) - options.release.set(javaRelease) - options.compilerArgs.addAll(listOf("-Xlint:all") + disabledLint.map { "-Xlint:-$it" }) - options.isDeprecation = true - options.encoding = "UTF-8" - options.compilerArgs.add("-parameters") - options.compilerArgs.add("-Werror") - } - - configure { - configFile = rootProject.file("config/checkstyle/checkstyle.xml") - toolVersion = "9.1" - } - - tasks.withType().configureEach { - useJUnitPlatform() - } - - dependencies { - "compileOnly"(stringyLibs.getLibrary("jsr305")) - "testImplementation"(platform(stringyLibs.getLibrary("junit-bom"))) - "testImplementation"(stringyLibs.getLibrary("junit-jupiter-api")) - "testImplementation"(stringyLibs.getLibrary("junit-jupiter-params")) - "testImplementation"(platform(stringyLibs.getLibrary("mockito-bom"))) - "testImplementation"(stringyLibs.getLibrary("mockito-core")) - "testImplementation"(stringyLibs.getLibrary("mockito-junit-jupiter")) - "testRuntimeOnly"(stringyLibs.getLibrary("junit-jupiter-engine")) - } - - // Java 8 turns on doclint which we fail - tasks.withType().configureEach { - options.encoding = "UTF-8" - (options as StandardJavadocDocletOptions).apply { - addBooleanOption("Werror", true) - addBooleanOption("Xdoclint:all", true) - addBooleanOption("Xdoclint:-missing", true) - tags( - "apiNote:a:API Note:", - "implSpec:a:Implementation Requirements:", - "implNote:a:Implementation Note:" - ) - } - } - - configure { - withJavadocJar() - if (sourcesJar) { - withSourcesJar() - } - } - - if (banSlf4j) { - configurations["compileClasspath"].apply { - resolutionStrategy.componentSelection { - withModule("org.slf4j:slf4j-api") { - reject("No SLF4J allowed on compile classpath") - } - } - } - } - - tasks.named("check").configure { - dependsOn("checkstyleMain", "checkstyleTest") - } -} diff --git a/buildSrc/src/main/kotlin/LibsConfig.kt b/buildSrc/src/main/kotlin/LibsConfig.kt deleted file mode 100644 index 90caecaba..000000000 --- a/buildSrc/src/main/kotlin/LibsConfig.kt +++ /dev/null @@ -1,214 +0,0 @@ -import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar -import org.gradle.api.Plugin -import org.gradle.api.Project -import org.gradle.api.artifacts.ExternalModuleDependency -import org.gradle.api.artifacts.ModuleDependency -import org.gradle.api.attributes.Bundling -import org.gradle.api.attributes.Category -import org.gradle.api.attributes.DocsType -import org.gradle.api.attributes.LibraryElements -import org.gradle.api.attributes.Usage -import org.gradle.api.attributes.java.TargetJvmVersion -import org.gradle.api.component.AdhocComponentWithVariants -import org.gradle.api.component.SoftwareComponentFactory -import org.gradle.api.publish.PublishingExtension -import org.gradle.api.publish.maven.MavenPublication -import org.gradle.api.tasks.bundling.Jar -import org.gradle.kotlin.dsl.apply -import org.gradle.kotlin.dsl.configure -import org.gradle.kotlin.dsl.exclude -import org.gradle.kotlin.dsl.get -import org.gradle.kotlin.dsl.invoke -import org.gradle.kotlin.dsl.named -import org.gradle.kotlin.dsl.register -import javax.inject.Inject - -fun Project.applyLibrariesConfiguration() { - applyCommonConfiguration() - apply(plugin = "java-base") - apply(plugin = "maven-publish") - apply(plugin = "com.github.johnrengelman.shadow") - apply(plugin = "com.jfrog.artifactory") - - configurations { - create("shade") - } - - group = "${rootProject.group}.worldedit-libs" - - val relocations = mapOf( - "net.kyori.text" to "com.sk89q.worldedit.util.formatting.text", - "net.kyori.minecraft" to "com.sk89q.worldedit.util.kyori", - ) - - tasks.register("jar") { - configurations = listOf(project.configurations["shade"]) - archiveClassifier.set("") - - // Yeet module-info's - exclude("module-info.class") - - dependencies { - exclude(dependency("com.google.guava:guava")) - exclude(dependency("com.google.code.gson:gson")) - exclude(dependency("com.google.errorprone:error_prone_annotations")) - exclude(dependency("com.google.guava:failureaccess")) - exclude(dependency("org.checkerframework:checker-qual")) - exclude(dependency("org.jetbrains:annotations")) - exclude(dependency("org.apache.logging.log4j:log4j-api")) - exclude(dependency("com.google.code.findbugs:jsr305")) - exclude { - it.moduleGroup == "org.jetbrains.kotlin" - } - } - - relocations.forEach { (from, to) -> - relocate(from, to) - } - } - val altConfigFiles = { artifactType: String -> - val deps = configurations["shade"].incoming.dependencies - .filterIsInstance() - .map { it.copy() } - .map { dependency -> - val category = dependency.attributes.getAttribute(Category.CATEGORY_ATTRIBUTE)?.name - if (category == Category.REGULAR_PLATFORM || category == Category.ENFORCED_PLATFORM) { - return@map dependency - } - try { - dependency.artifact { - name = dependency.name - type = artifactType - extension = "jar" - classifier = artifactType - } - } catch (e: Exception) { - throw RuntimeException("Failed to add artifact to dependency: $dependency", e) - } - dependency - } - - files(configurations.detachedConfiguration(*deps.toTypedArray()) - .resolvedConfiguration.lenientConfiguration.artifacts - .filter { it.classifier == artifactType } - .map { zipTree(it.file) }) - } - tasks.register("sourcesJar") { - from({ - altConfigFiles("sources") - }) - - // Yeet module-info's - exclude("module-info.java") - - relocations.forEach { (from, to) -> - val filePattern = Regex("(.*)${from.replace('.', '/')}((?:/|$).*)") - val textPattern = Regex.fromLiteral(from) - eachFile { - filter { - it.replaceFirst(textPattern, to) - } - path = path.replaceFirst(filePattern, "$1${to.replace('.', '/')}$2") - } - } - archiveClassifier.set("sources") - } - - tasks.named("assemble").configure { - dependsOn("jar", "sourcesJar") - } - - project.apply() - - val libsComponent = project.components["libs"] as AdhocComponentWithVariants - - val apiElements = project.configurations.register("apiElements") { - isVisible = false - description = "API elements for libs" - isCanBeResolved = false - isCanBeConsumed = true - attributes { - attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_API)) - attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY)) - attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED)) - attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR)) - attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 16) - } - outgoing.artifact(tasks.named("jar")) - } - - val runtimeElements = project.configurations.register("runtimeElements") { - isVisible = false - description = "Runtime elements for libs" - isCanBeResolved = false - isCanBeConsumed = true - attributes { - attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME)) - attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.LIBRARY)) - attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED)) - attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements.JAR)) - attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, 16) - } - outgoing.artifact(tasks.named("jar")) - } - - val sourcesElements = project.configurations.register("sourcesElements") { - isVisible = false - description = "Source elements for libs" - isCanBeResolved = false - isCanBeConsumed = true - attributes { - attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage.JAVA_RUNTIME)) - attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category.DOCUMENTATION)) - attribute(Bundling.BUNDLING_ATTRIBUTE, project.objects.named(Bundling.SHADOWED)) - attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.objects.named(DocsType.SOURCES)) - } - outgoing.artifact(tasks.named("sourcesJar")) - } - - libsComponent.addVariantsFromConfiguration(apiElements.get()) { - mapToMavenScope("compile") - } - - libsComponent.addVariantsFromConfiguration(runtimeElements.get()) { - mapToMavenScope("runtime") - } - - libsComponent.addVariantsFromConfiguration(sourcesElements.get()) { - mapToMavenScope("runtime") - } - - configure { - publications { - register("maven") { - from(libsComponent) - } - } - } - - applyCommonArtifactoryConfig() -} - -// A horrible hack because `softwareComponentFactory` has to be gotten via plugin -// gradle why -internal open class LibsConfigPluginHack @Inject constructor( - private val softwareComponentFactory: SoftwareComponentFactory -) : Plugin { - override fun apply(project: Project) { - val libsComponents = softwareComponentFactory.adhoc("libs") - project.components.add(libsComponents) - } -} - -fun Project.constrainDependenciesToLibsCore() { - evaluationDependsOn(":worldedit-libs:core") - val coreDeps = project(":worldedit-libs:core").configurations["shade"].dependencies - .filterIsInstance() - dependencies.constraints { - for (coreDep in coreDeps) { - add("shade", "${coreDep.group}:${coreDep.name}:${coreDep.version}") { - because("libs should align with libs:core") - } - } - } -} diff --git a/buildSrc/src/main/kotlin/PlatformConfig.kt b/buildSrc/src/main/kotlin/PlatformConfig.kt deleted file mode 100644 index 38f68d010..000000000 --- a/buildSrc/src/main/kotlin/PlatformConfig.kt +++ /dev/null @@ -1,98 +0,0 @@ -import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar -import org.gradle.api.Project -import org.gradle.api.component.AdhocComponentWithVariants -import org.gradle.api.publish.PublishingExtension -import org.gradle.api.publish.maven.MavenPublication -import org.gradle.api.tasks.bundling.Jar -import org.gradle.kotlin.dsl.apply -import org.gradle.kotlin.dsl.configure -import org.gradle.kotlin.dsl.get -import org.gradle.kotlin.dsl.named -import org.gradle.kotlin.dsl.register -import kotlin.collections.set - -fun Project.applyPlatformAndCoreConfiguration(javaRelease: Int = 21) { - applyCommonConfiguration() - apply(plugin = "java") - apply(plugin = "maven-publish") - apply(plugin = "com.jfrog.artifactory") - applyCommonJavaConfiguration( - sourcesJar = name in setOf("worldedit-core", "worldedit-bukkit", "worldedit-fabric"), - javaRelease = javaRelease, - banSlf4j = name !in setOf("worldedit-fabric", "worldedit-neoforge", "worldedit-sponge"), - ) - - ext["internalVersion"] = "$version+${rootProject.ext["gitCommitHash"]}" - - configure { - publications { - register("maven") { - versionMapping { - usage("java-api") { - fromResolutionOf("runtimeClasspath") - } - usage("java-runtime") { - fromResolutionResult() - } - } - } - } - } - - applyCommonArtifactoryConfig() -} - -fun Project.applyShadowConfiguration() { - apply(plugin = "com.github.johnrengelman.shadow") - tasks.named("shadowJar") { - archiveClassifier.set("dist") - dependencies { - include(project(":worldedit-libs:core")) - include(project(":worldedit-libs:${project.name.replace("worldedit-", "")}")) - include(project(":worldedit-core")) - exclude("com.google.code.findbugs:jsr305") - } - exclude("GradleStart**") - exclude(".cache") - exclude("LICENSE*") - exclude("META-INF/maven/**") - minimize() - } - val javaComponent = components["java"] as AdhocComponentWithVariants - // I don't think we want this published (it's the shadow jar) - javaComponent.withVariantsFromConfiguration(configurations["shadowRuntimeElements"]) { - skip() - } -} - -private val CLASSPATH = listOf("truezip", "truevfs", "js") - .map { "$it.jar" } - .flatMap { listOf(it, "WorldEdit/$it") } - .joinToString(separator = " ") - -sealed class WorldEditKind( - val name: String, - val mainClass: String = "com.sk89q.worldedit.internal.util.InfoEntryPoint" -) { - class Standalone(mainClass: String) : WorldEditKind("STANDALONE", mainClass) - object Mod : WorldEditKind("MOD") - object Plugin : WorldEditKind("PLUGIN") -} - -fun Project.addJarManifest(kind: WorldEditKind, includeClasspath: Boolean = false, extraAttributes: Map = mapOf()) { - tasks.named("jar") { - val version = project(":worldedit-core").version - inputs.property("version", version) - val attributes = mutableMapOf( - "Implementation-Version" to version, - "WorldEdit-Version" to version, - "WorldEdit-Kind" to kind.name, - "Main-Class" to kind.mainClass - ) - if (includeClasspath) { - attributes["Class-Path"] = CLASSPATH - } - attributes.putAll(extraAttributes) - manifest.attributes(attributes) - } -} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d5400084c..561dc4236 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,6 +1,9 @@ -[versions] -neoGradle = "7.0.107" +[plugins] +codecov = "org.enginehub.codecov:0.2.0" +neogradle-userdev = "net.neoforged.gradle.userdev:7.0.107" +fabric-loom = "fabric-loom:1.6.9" +[versions] kyoriText = "3.0.4" piston = "0.5.10" autoValue = "1.10.4" @@ -29,10 +32,8 @@ japicmp = "me.champeau.gradle:japicmp-gradle-plugin:0.4.2" shadow = "com.github.johnrengelman:shadow:8.1.1" jfrog-buildinfo = "org.jfrog.buildinfo:build-info-extractor-gradle:5.2.0" -fabric-loom = "net.fabricmc:fabric-loom:1.6.9" fabric-mixin = "net.fabricmc:sponge-mixin:0.13.3+mixin.0.8.5" -codecov = "org.enginehub.gradle:gradle-codecov-plugin:0.2.0" paperweight = "io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin:1.6.0" linBus-bom = "org.enginehub.lin-bus:lin-bus-bom:0.1.0-SNAPSHOT" @@ -89,10 +90,6 @@ fastutil = "it.unimi.dsi:fastutil:8.5.12!!" # may not be the same as the ones in the latest Bukkit API. snakeyaml = "org.yaml:snakeyaml:2.0" -[libraries.neoGradle-userdev] -module = "net.neoforged.gradle:userdev" -version.ref = "neoGradle" - [libraries.kyoriText-api] module = "net.kyori:text-api" version.ref = "kyoriText" diff --git a/settings.gradle.kts b/settings.gradle.kts index b5dc75541..4929a2ddf 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,10 +1,9 @@ pluginManagement { repositories { - mavenCentral() gradlePluginPortal() maven { - name = "Fabric" - url = uri("https://maven.fabricmc.net/") + name = "EngineHub" + url = uri("https://maven.enginehub.org/repo/") } } } @@ -12,8 +11,24 @@ id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" } +logger.lifecycle(""" +******************************************* + You are building WorldEdit! + + If you encounter trouble: + 1) Read COMPILING.md if you haven't yet + 2) Try running 'build' in a separate Gradle run + 3) Use gradlew and not gradle + 4) If you still need help, ask on Discord! https://discord.gg/enginehub + + Output files will be in [subproject]/build/libs +******************************************* +""") + rootProject.name = "worldedit" +includeBuild("build-logic") + include("worldedit-libs") listOf("1.19.4", "1.20", "1.20.2", "1.20.4", "1.20.5").forEach { diff --git a/verification/build.gradle.kts b/verification/build.gradle.kts index 0024ee1b1..e17ef62c8 100644 --- a/verification/build.gradle.kts +++ b/verification/build.gradle.kts @@ -74,6 +74,19 @@ (this as? ModuleDependency)?.isTransitive = false } ) + val resolvedOldJar = files({ + try { + conf.resolvedConfiguration.rethrowFailure() + conf + } catch (e: ResolveException) { + if (e.cause is ModuleVersionNotFoundException) { + logger.warn("Skipping check for $projectFragment API compatibility because there is no jar to compare against") + setOf() + } else { + throw e + } + } + }) val checkApi = tasks.register("check${capitalizedFragment}ApiCompatibility") { group = "API Compatibility" description = "Check API compatibility for $capitalizedFragment API" @@ -89,20 +102,10 @@ onlyIf { // Only check if we have a jar to compare against - try { - conf.resolvedConfiguration.rethrowFailure() - true - } catch (e: ResolveException) { - if (e.cause is ModuleVersionNotFoundException) { - it.logger.warn("Skipping check for $projectFragment API compatibility because there is no jar to compare against") - false - } else { - throw e - } - } + !resolvedOldJar.isEmpty } - oldClasspath.from(conf) + oldClasspath.from(resolvedOldJar) newClasspath.from(proj.tasks.named("jar")) onlyModified.set(false) failOnModification.set(false) // report does the failing (so we can accept) diff --git a/worldedit-bukkit/adapters/adapter-1.18.2/build.gradle.kts b/worldedit-bukkit/adapters/adapter-1.18.2/build.gradle.kts deleted file mode 100644 index 7bb1cc7e9..000000000 --- a/worldedit-bukkit/adapters/adapter-1.18.2/build.gradle.kts +++ /dev/null @@ -1,8 +0,0 @@ -import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension - -applyPaperweightAdapterConfiguration() - -dependencies { - // https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ - the().paperDevBundle("1.18.2-R0.1-20220920.010157-167") -} diff --git a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightAdapter.java b/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightAdapter.java deleted file mode 100644 index da5fc9c5d..000000000 --- a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightAdapter.java +++ /dev/null @@ -1,1061 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.bukkit.adapter.impl.v1_18_R2; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.Futures; -import com.mojang.datafixers.util.Either; -import com.mojang.serialization.Lifecycle; -import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseItem; -import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; -import com.sk89q.worldedit.bukkit.adapter.Refraction; -import com.sk89q.worldedit.entity.BaseEntity; -import com.sk89q.worldedit.extension.platform.Watchdog; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.internal.Constants; -import com.sk89q.worldedit.internal.block.BlockStateIdAccess; -import com.sk89q.worldedit.internal.wna.WorldNativeAccess; -import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.registry.state.BooleanProperty; -import com.sk89q.worldedit.registry.state.DirectionalProperty; -import com.sk89q.worldedit.registry.state.EnumProperty; -import com.sk89q.worldedit.registry.state.IntegerProperty; -import com.sk89q.worldedit.registry.state.Property; -import com.sk89q.worldedit.util.Direction; -import com.sk89q.worldedit.util.SideEffect; -import com.sk89q.worldedit.util.concurrency.LazyReference; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; -import com.sk89q.worldedit.util.io.file.SafeFiles; -import com.sk89q.worldedit.world.DataFixer; -import com.sk89q.worldedit.world.RegenOptions; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.biome.BiomeTypes; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.entity.EntityTypes; -import com.sk89q.worldedit.world.item.ItemType; -import net.minecraft.Util; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.nbt.ByteArrayTag; -import net.minecraft.nbt.ByteTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.EndTag; -import net.minecraft.nbt.FloatTag; -import net.minecraft.nbt.IntArrayTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.LongArrayTag; -import net.minecraft.nbt.LongTag; -import net.minecraft.nbt.ShortTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; -import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; -import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.dedicated.DedicatedServer; -import net.minecraft.server.level.ChunkHolder; -import net.minecraft.server.level.ServerChunkCache; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.progress.ChunkProgressListener; -import net.minecraft.util.StringRepresentable; -import net.minecraft.util.thread.BlockableEventLoop; -import net.minecraft.world.Clearable; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.LevelSettings; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.StructureBlockEntity; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.DirectionProperty; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkStatus; -import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.PrimaryLevelData; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.Vec3; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.World.Environment; -import org.bukkit.block.data.BlockData; -import org.bukkit.craftbukkit.v1_18_R2.CraftServer; -import org.bukkit.craftbukkit.v1_18_R2.CraftWorld; -import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData; -import org.bukkit.craftbukkit.v1_18_R2.entity.CraftEntity; -import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer; -import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftItemStack; -import org.bukkit.craftbukkit.v1_18_R2.util.CraftMagicNumbers; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; -import org.bukkit.generator.ChunkGenerator; -import org.enginehub.linbus.common.LinTagId; -import org.enginehub.linbus.tree.LinByteArrayTag; -import org.enginehub.linbus.tree.LinByteTag; -import org.enginehub.linbus.tree.LinCompoundTag; -import org.enginehub.linbus.tree.LinDoubleTag; -import org.enginehub.linbus.tree.LinEndTag; -import org.enginehub.linbus.tree.LinFloatTag; -import org.enginehub.linbus.tree.LinIntArrayTag; -import org.enginehub.linbus.tree.LinIntTag; -import org.enginehub.linbus.tree.LinListTag; -import org.enginehub.linbus.tree.LinLongArrayTag; -import org.enginehub.linbus.tree.LinLongTag; -import org.enginehub.linbus.tree.LinShortTag; -import org.enginehub.linbus.tree.LinStringTag; -import org.enginehub.linbus.tree.LinTag; -import org.enginehub.linbus.tree.LinTagType; -import org.spigotmc.SpigotConfig; -import org.spigotmc.WatchdogThread; - -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.OptionalInt; -import java.util.OptionalLong; -import java.util.Set; -import java.util.TreeMap; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ForkJoinPool; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -public final class PaperweightAdapter implements BukkitImplAdapter { - - private final Logger logger = Logger.getLogger(getClass().getCanonicalName()); - - private final Field serverWorldsField; - private final Method getChunkFutureMethod; - private final Field chunkProviderExecutorField; - private final Watchdog watchdog; - - // ------------------------------------------------------------------------ - // Code that may break between versions of Minecraft - // ------------------------------------------------------------------------ - - public PaperweightAdapter() throws NoSuchFieldException, NoSuchMethodException { - // A simple test - CraftServer.class.cast(Bukkit.getServer()); - - int dataVersion = CraftMagicNumbers.INSTANCE.getDataVersion(); - if (dataVersion != 2975) { - throw new UnsupportedClassVersionError("Not 1.18.2!"); - } - - serverWorldsField = CraftServer.class.getDeclaredField("worlds"); - serverWorldsField.setAccessible(true); - - getChunkFutureMethod = ServerChunkCache.class.getDeclaredMethod( - Refraction.pickName("getChunkFutureMainThread", "c"), - int.class, int.class, ChunkStatus.class, boolean.class - ); - getChunkFutureMethod.setAccessible(true); - - chunkProviderExecutorField = ServerChunkCache.class.getDeclaredField( - Refraction.pickName("mainThreadProcessor", "g") - ); - chunkProviderExecutorField.setAccessible(true); - - new PaperweightDataConverters(CraftMagicNumbers.INSTANCE.getDataVersion(), this).build(ForkJoinPool.commonPool()); - - Watchdog watchdog; - try { - Class.forName("org.spigotmc.WatchdogThread"); - watchdog = new SpigotWatchdog(); - } catch (ClassNotFoundException | NoSuchFieldException e) { - try { - watchdog = new MojangWatchdog(((CraftServer) Bukkit.getServer()).getServer()); - } catch (NoSuchFieldException ex) { - watchdog = null; - } - } - this.watchdog = watchdog; - - try { - Class.forName("org.spigotmc.SpigotConfig"); - SpigotConfig.config.set("world-settings.worldeditregentempworld.verbose", false); - } catch (ClassNotFoundException ignored) { - } - } - - @Override - public DataFixer getDataFixer() { - return PaperweightDataConverters.INSTANCE; - } - - /** - * Read the given NBT data into the given tile entity. - * - * @param tileEntity the tile entity - * @param tag the tag - */ - static void readTagIntoTileEntity(CompoundTag tag, BlockEntity tileEntity) { - tileEntity.load(tag); - tileEntity.setChanged(); - } - - /** - * Get the ID string of the given entity. - * - * @param entity the entity - * @return the entity ID - */ - private static String getEntityId(Entity entity) { - return EntityType.getKey(entity.getType()).toString(); - } - - /** - * Create an entity using the given entity ID. - * - * @param id the entity ID - * @param world the world - * @return an entity or null - */ - @Nullable - private static Entity createEntityFromId(String id, net.minecraft.world.level.Level world) { - return EntityType.byString(id).map(t -> t.create(world)).orElse(null); - } - - /** - * Write the given NBT data into the given entity. - * - * @param entity the entity - * @param tag the tag - */ - private static void readTagIntoEntity(CompoundTag tag, Entity entity) { - entity.load(tag); - } - - /** - * Write the entity's NBT data to the given tag. - * - * @param entity the entity - * @param tag the tag - */ - private static void readEntityIntoTag(Entity entity, CompoundTag tag) { - entity.save(tag); - } - - private static Block getBlockFromType(BlockType blockType) { - return Registry.BLOCK.get(ResourceLocation.tryParse(blockType.id())); - } - - private static Item getItemFromType(ItemType itemType) { - return Registry.ITEM.get(ResourceLocation.tryParse(itemType.id())); - } - - @Override - public OptionalInt getInternalBlockStateId(BlockData data) { - net.minecraft.world.level.block.state.BlockState state = ((CraftBlockData) data).getState(); - int combinedId = Block.getId(state); - return combinedId == 0 && state.getBlock() != Blocks.AIR ? OptionalInt.empty() : OptionalInt.of(combinedId); - } - - @Override - public OptionalInt getInternalBlockStateId(BlockState state) { - Block mcBlock = getBlockFromType(state.getBlockType()); - net.minecraft.world.level.block.state.BlockState newState = mcBlock.defaultBlockState(); - Map, Object> states = state.getStates(); - newState = applyProperties(mcBlock.getStateDefinition(), newState, states); - final int combinedId = Block.getId(newState); - return combinedId == 0 && state.getBlockType() != BlockTypes.AIR ? OptionalInt.empty() : OptionalInt.of(combinedId); - } - - @Override - public BlockState getBlock(Location location) { - checkNotNull(location); - - CraftWorld craftWorld = ((CraftWorld) location.getWorld()); - int x = location.getBlockX(); - int y = location.getBlockY(); - int z = location.getBlockZ(); - - final ServerLevel handle = craftWorld.getHandle(); - LevelChunk chunk = handle.getChunk(x >> 4, z >> 4); - final BlockPos blockPos = new BlockPos(x, y, z); - final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(blockPos); - int internalId = Block.getId(blockData); - BlockState state = BlockStateIdAccess.getBlockStateById(internalId); - if (state == null) { - org.bukkit.block.Block bukkitBlock = location.getBlock(); - state = BukkitAdapter.adapt(bukkitBlock.getBlockData()); - } - - return state; - } - - @Override - public BaseBlock getFullBlock(Location location) { - BlockState state = getBlock(location); - - CraftWorld craftWorld = ((CraftWorld) location.getWorld()); - int x = location.getBlockX(); - int y = location.getBlockY(); - int z = location.getBlockZ(); - - final ServerLevel handle = craftWorld.getHandle(); - LevelChunk chunk = handle.getChunk(x >> 4, z >> 4); - final BlockPos blockPos = new BlockPos(x, y, z); - - // Read the NBT data - BlockEntity te = chunk.getBlockEntity(blockPos); - if (te != null) { - CompoundTag tag = te.saveWithId(); - return state.toBaseBlock(LazyReference.from(() -> (LinCompoundTag) toNative(tag))); - } - - return state.toBaseBlock(); - } - - private static final HashMap> biomeTypeToNMSCache = new HashMap<>(); - private static final HashMap, BiomeType> biomeTypeFromNMSCache = new HashMap<>(); - - @Override - public BiomeType getBiome(Location location) { - checkNotNull(location); - - CraftWorld craftWorld = ((CraftWorld) location.getWorld()); - int x = location.getBlockX(); - int y = location.getBlockY(); - int z = location.getBlockZ(); - - final ServerLevel handle = craftWorld.getHandle(); - LevelChunk chunk = handle.getChunk(x >> 4, z >> 4); - - return biomeTypeFromNMSCache.computeIfAbsent(chunk.getNoiseBiome(x >> 2, y >> 2, z >> 2), b -> BiomeType.REGISTRY.get(b.unwrapKey().get().location().toString())); - } - - @Override - public void setBiome(Location location, BiomeType biome) { - checkNotNull(location); - checkNotNull(biome); - - CraftWorld craftWorld = ((CraftWorld) location.getWorld()); - int x = location.getBlockX(); - int y = location.getBlockY(); - int z = location.getBlockZ(); - - final ServerLevel handle = craftWorld.getHandle(); - LevelChunk chunk = handle.getChunk(x >> 4, z >> 4); - chunk.setBiome(x >> 2, y >> 2, z >> 2, biomeTypeToNMSCache.computeIfAbsent(biome, b -> ((CraftServer) Bukkit.getServer()).getServer().registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getHolderOrThrow(ResourceKey.create(Registry.BIOME_REGISTRY, new ResourceLocation(b.id()))))); - chunk.setUnsaved(true); - } - - @Override - public WorldNativeAccess createWorldNativeAccess(World world) { - return new PaperweightWorldNativeAccess(this, - new WeakReference<>(((CraftWorld) world).getHandle())); - } - - private static net.minecraft.core.Direction adapt(Direction face) { - switch (face) { - case NORTH: - return net.minecraft.core.Direction.NORTH; - case SOUTH: - return net.minecraft.core.Direction.SOUTH; - case WEST: - return net.minecraft.core.Direction.WEST; - case EAST: - return net.minecraft.core.Direction.EAST; - case DOWN: - return net.minecraft.core.Direction.DOWN; - case UP: - default: - return net.minecraft.core.Direction.UP; - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private net.minecraft.world.level.block.state.BlockState applyProperties( - StateDefinition stateContainer, - net.minecraft.world.level.block.state.BlockState newState, - Map, Object> states - ) { - for (Map.Entry, Object> state : states.entrySet()) { - net.minecraft.world.level.block.state.properties.Property property = - stateContainer.getProperty(state.getKey().getName()); - Comparable value = (Comparable) state.getValue(); - // we may need to adapt this value, depending on the source prop - if (property instanceof DirectionProperty) { - Direction dir = (Direction) value; - value = adapt(dir); - } else if (property instanceof net.minecraft.world.level.block.state.properties.EnumProperty) { - String enumName = (String) value; - value = ((net.minecraft.world.level.block.state.properties.EnumProperty) property) - .getValue(enumName).orElseThrow(() -> - new IllegalStateException( - "Enum property " + property.getName() + " does not contain " + enumName - ) - ); - } - - newState = newState.setValue( - (net.minecraft.world.level.block.state.properties.Property) property, - (Comparable) value - ); - } - return newState; - } - - @Override - public BaseEntity getEntity(org.bukkit.entity.Entity entity) { - checkNotNull(entity); - - CraftEntity craftEntity = ((CraftEntity) entity); - Entity mcEntity = craftEntity.getHandle(); - - // Do not allow creating of passenger entity snapshots, passengers are included in the vehicle entity - if (mcEntity.isPassenger()) { - return null; - } - - String id = getEntityId(mcEntity); - - CompoundTag tag = new CompoundTag(); - readEntityIntoTag(mcEntity, tag); - return new BaseEntity( - EntityTypes.get(id), - LazyReference.from(() -> (LinCompoundTag) toNative(tag)) - ); - } - - @Nullable - @Override - public org.bukkit.entity.Entity createEntity(Location location, BaseEntity state) { - checkNotNull(location); - checkNotNull(state); - - CraftWorld craftWorld = ((CraftWorld) location.getWorld()); - ServerLevel worldServer = craftWorld.getHandle(); - - String entityId = state.getType().id(); - - LinCompoundTag nativeTag = state.getNbt(); - CompoundTag tag; - if (nativeTag != null) { - tag = (CompoundTag) fromNative(nativeTag); - removeUnwantedEntityTagsRecursively(tag); - } else { - tag = new CompoundTag(); - } - - tag.putString("id", entityId); - - Entity createdEntity = EntityType.loadEntityRecursive(tag, craftWorld.getHandle(), (loadedEntity) -> { - loadedEntity.absMoveTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); - return loadedEntity; - }); - - if (createdEntity != null) { - worldServer.addFreshEntityWithPassengers(createdEntity, SpawnReason.CUSTOM); - return createdEntity.getBukkitEntity(); - } else { - return null; - } - } - - // This removes all unwanted tags from the main entity and all its passengers - private void removeUnwantedEntityTagsRecursively(CompoundTag tag) { - for (String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) { - tag.remove(name); - } - - // Adapted from net.minecraft.world.entity.EntityType#loadEntityRecursive - if (tag.contains("Passengers", LinTagId.LIST.id())) { - ListTag nbttaglist = tag.getList("Passengers", LinTagId.COMPOUND.id()); - - for (int i = 0; i < nbttaglist.size(); ++i) { - removeUnwantedEntityTagsRecursively(nbttaglist.getCompound(i)); - } - } - } - - @Override - public Component getRichBlockName(BlockType blockType) { - return TranslatableComponent.of(getBlockFromType(blockType).getDescriptionId()); - } - - @Override - public Component getRichItemName(ItemType itemType) { - return TranslatableComponent.of(getItemFromType(itemType).getDescriptionId()); - } - - @Override - public Component getRichItemName(BaseItemStack itemStack) { - return TranslatableComponent.of(CraftItemStack.asNMSCopy(BukkitAdapter.adapt(itemStack)).getDescriptionId()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static final LoadingCache> PROPERTY_CACHE = CacheBuilder.newBuilder().build(new CacheLoader>() { - @Override - public Property load(net.minecraft.world.level.block.state.properties.Property state) throws Exception { - if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) { - return new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues())); - } else if (state instanceof DirectionProperty) { - return new DirectionalProperty(state.getName(), - (List) state.getPossibleValues().stream().map(e -> Direction.valueOf(((StringRepresentable) e).getSerializedName().toUpperCase(Locale.ROOT))).toList()); - } else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) { - return new EnumProperty(state.getName(), - (List) state.getPossibleValues().stream().map(e -> ((StringRepresentable) e).getSerializedName()).toList()); - } else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) { - return new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues())); - } else { - throw new IllegalArgumentException("WorldEdit needs an update to support " + state.getClass().getSimpleName()); - } - } - }); - - @SuppressWarnings({ "rawtypes" }) - @Override - public Map> getProperties(BlockType blockType) { - Map> properties = new TreeMap<>(); - Block block = getBlockFromType(blockType); - StateDefinition blockStateList = - block.getStateDefinition(); - for (net.minecraft.world.level.block.state.properties.Property state : blockStateList.getProperties()) { - Property property = PROPERTY_CACHE.getUnchecked(state); - properties.put(property.getName(), property); - } - return properties; - } - - @Override - public void sendFakeNBT(Player player, BlockVector3 pos, LinCompoundTag nbtData) { - ((CraftPlayer) player).getHandle().networkManager.send(ClientboundBlockEntityDataPacket.create( - new StructureBlockEntity( - new BlockPos(pos.x(), pos.y(), pos.z()), - Blocks.STRUCTURE_BLOCK.defaultBlockState() - ), - __ -> (CompoundTag) fromNative(nbtData) - )); - } - - @Override - public void sendFakeOP(Player player) { - ((CraftPlayer) player).getHandle().networkManager.send(new ClientboundEntityEventPacket( - ((CraftPlayer) player).getHandle(), (byte) 28 - )); - } - - @Override - public org.bukkit.inventory.ItemStack adapt(BaseItemStack item) { - ItemStack stack = new ItemStack(Registry.ITEM.get(ResourceLocation.tryParse(item.getType().id())), item.getAmount()); - stack.setTag(((CompoundTag) fromNative(item.getNbt()))); - return CraftItemStack.asCraftMirror(stack); - } - - @Override - public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) { - final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack); - final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount()); - weStack.setNbtReference(LazyReference.from(() -> (LinCompoundTag) toNative(nmsStack.getTag()))); - return weStack; - } - - private final LoadingCache fakePlayers - = CacheBuilder.newBuilder().weakKeys().softValues().build(CacheLoader.from(PaperweightFakePlayer::new)); - - @Override - public boolean simulateItemUse(World world, BlockVector3 position, BaseItem item, Direction face) { - CraftWorld craftWorld = (CraftWorld) world; - ServerLevel worldServer = craftWorld.getHandle(); - ItemStack stack = CraftItemStack.asNMSCopy(BukkitAdapter.adapt(item instanceof BaseItemStack - ? ((BaseItemStack) item) : new BaseItemStack(item.getType(), item.getNbtReference(), 1))); - stack.setTag((CompoundTag) fromNative(item.getNbt())); - - PaperweightFakePlayer fakePlayer; - try { - fakePlayer = fakePlayers.get(worldServer); - } catch (ExecutionException ignored) { - return false; - } - fakePlayer.setItemInHand(InteractionHand.MAIN_HAND, stack); - fakePlayer.absMoveTo(position.x(), position.y(), position.z(), - (float) face.toVector().toYaw(), (float) face.toVector().toPitch()); - - final BlockPos blockPos = new BlockPos(position.x(), position.y(), position.z()); - final Vec3 blockVec = Vec3.atLowerCornerOf(blockPos); - final net.minecraft.core.Direction enumFacing = adapt(face); - BlockHitResult rayTrace = new BlockHitResult(blockVec, enumFacing, blockPos, false); - UseOnContext context = new UseOnContext(fakePlayer, InteractionHand.MAIN_HAND, rayTrace); - InteractionResult result = stack.useOn(context, InteractionHand.MAIN_HAND); - if (result != InteractionResult.SUCCESS) { - if (worldServer.getBlockState(blockPos).use(worldServer, fakePlayer, InteractionHand.MAIN_HAND, rayTrace).consumesAction()) { - result = InteractionResult.SUCCESS; - } else { - result = stack.getItem().use(worldServer, fakePlayer, InteractionHand.MAIN_HAND).getResult(); - } - } - - return result == InteractionResult.SUCCESS; - } - - @Override - public boolean canPlaceAt(World world, BlockVector3 position, BlockState blockState) { - int internalId = BlockStateIdAccess.getBlockStateId(blockState); - net.minecraft.world.level.block.state.BlockState blockData = Block.stateById(internalId); - return blockData.canSurvive(((CraftWorld) world).getHandle(), new BlockPos(position.x(), position.y(), position.z())); - } - - @Override - public boolean regenerate(World bukkitWorld, Region region, Extent extent, RegenOptions options) { - try { - doRegen(bukkitWorld, region, extent, options); - } catch (Exception e) { - throw new IllegalStateException("Regen failed.", e); - } - - return true; - } - - private void doRegen(World bukkitWorld, Region region, Extent extent, RegenOptions options) throws Exception { - Environment env = bukkitWorld.getEnvironment(); - ChunkGenerator gen = bukkitWorld.getGenerator(); - - Path tempDir = Files.createTempDirectory("WorldEditWorldGen"); - LevelStorageSource levelStorage = LevelStorageSource.createDefault(tempDir); - ResourceKey worldDimKey = getWorldDimKey(env); - try (LevelStorageSource.LevelStorageAccess session = levelStorage.createAccess("worldeditregentempworld", worldDimKey)) { - ServerLevel originalWorld = ((CraftWorld) bukkitWorld).getHandle(); - PrimaryLevelData levelProperties = (PrimaryLevelData) originalWorld.getServer() - .getWorldData().overworldData(); - WorldGenSettings originalOpts = levelProperties.worldGenSettings(); - - long seed = options.getSeed().orElse(originalWorld.getSeed()); - WorldGenSettings newOpts = options.getSeed().isPresent() - ? originalOpts.withSeed(levelProperties.isHardcore(), OptionalLong.of(seed)) - : originalOpts; - - LevelSettings newWorldSettings = new LevelSettings( - "worldeditregentempworld", - levelProperties.settings.gameType(), - levelProperties.settings.hardcore(), - levelProperties.settings.difficulty(), - levelProperties.settings.allowCommands(), - levelProperties.settings.gameRules(), - levelProperties.settings.getDataPackConfig() - ); - PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, Lifecycle.stable()); - - ServerLevel freshWorld = new ServerLevel( - originalWorld.getServer(), - originalWorld.getServer().executor, - session, newWorldData, - originalWorld.dimension(), - originalWorld.dimensionTypeRegistration(), - new NoOpWorldLoadListener(), - newOpts.dimensions().get(worldDimKey).generator(), - originalWorld.isDebug(), - seed, - ImmutableList.of(), - false, - env, gen, - bukkitWorld.getBiomeProvider() - ); - try { - regenForWorld(region, extent, freshWorld, options); - } finally { - freshWorld.getChunkSource().close(false); - } - } finally { - try { - @SuppressWarnings("unchecked") - Map map = (Map) serverWorldsField.get(Bukkit.getServer()); - map.remove("worldeditregentempworld"); - } catch (IllegalAccessException ignored) { - } - SafeFiles.tryHardToDeleteDir(tempDir); - } - } - - private BiomeType adapt(ServerLevel serverWorld, Biome origBiome) { - ResourceLocation key = serverWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(origBiome); - if (key == null) { - return null; - } - return BiomeTypes.get(key.toString()); - } - - @SuppressWarnings("unchecked") - private void regenForWorld(Region region, Extent extent, ServerLevel serverWorld, RegenOptions options) throws WorldEditException { - List> chunkLoadings = submitChunkLoadTasks(region, serverWorld); - BlockableEventLoop executor; - try { - executor = (BlockableEventLoop) chunkProviderExecutorField.get(serverWorld.getChunkSource()); - } catch (IllegalAccessException e) { - throw new IllegalStateException("Couldn't get executor for chunk loading.", e); - } - executor.managedBlock(() -> { - // bail out early if a future fails - if (chunkLoadings.stream().anyMatch(ftr -> - ftr.isDone() && Futures.getUnchecked(ftr) == null - )) { - return false; - } - return chunkLoadings.stream().allMatch(CompletableFuture::isDone); - }); - Map chunks = new HashMap<>(); - for (CompletableFuture future : chunkLoadings) { - @Nullable - ChunkAccess chunk = future.getNow(null); - checkState(chunk != null, "Failed to generate a chunk, regen failed."); - chunks.put(chunk.getPos(), chunk); - } - - for (BlockVector3 vec : region) { - BlockPos pos = new BlockPos(vec.x(), vec.y(), vec.z()); - ChunkAccess chunk = chunks.get(new ChunkPos(pos)); - final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(pos); - int internalId = Block.getId(blockData); - BlockStateHolder state = BlockStateIdAccess.getBlockStateById(internalId); - Objects.requireNonNull(state); - BlockEntity blockEntity = chunk.getBlockEntity(pos); - if (blockEntity != null) { - CompoundTag tag = blockEntity.saveWithId(); - state = state.toBaseBlock(LazyReference.from(() -> (LinCompoundTag) toNative(tag))); - } - extent.setBlock(vec, state.toBaseBlock()); - if (options.shouldRegenBiomes()) { - Biome origBiome = chunk.getNoiseBiome(vec.x(), vec.y(), vec.z()).value(); - BiomeType adaptedBiome = adapt(serverWorld, origBiome); - if (adaptedBiome != null) { - extent.setBiome(vec, adaptedBiome); - } - } - } - } - - @SuppressWarnings("unchecked") - private List> submitChunkLoadTasks(Region region, ServerLevel serverWorld) { - ServerChunkCache chunkManager = serverWorld.getChunkSource(); - List> chunkLoadings = new ArrayList<>(); - // Pre-gen all the chunks - for (BlockVector2 chunk : region.getChunks()) { - try { - //noinspection unchecked - chunkLoadings.add( - ((CompletableFuture>) - getChunkFutureMethod.invoke(chunkManager, chunk.x(), chunk.z(), ChunkStatus.FEATURES, true)) - .thenApply(either -> either.left().orElse(null)) - ); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new IllegalStateException("Couldn't load chunk for regen.", e); - } - } - return chunkLoadings; - } - - private ResourceKey getWorldDimKey(Environment env) { - switch (env) { - case NETHER: - return LevelStem.NETHER; - case THE_END: - return LevelStem.END; - case NORMAL: - default: - return LevelStem.OVERWORLD; - } - } - - private static final Set SUPPORTED_SIDE_EFFECTS = Sets.immutableEnumSet( - SideEffect.NEIGHBORS, - SideEffect.LIGHTING, - SideEffect.VALIDATION, - SideEffect.ENTITY_AI, - SideEffect.EVENTS, - SideEffect.UPDATE - ); - - @Override - public Set getSupportedSideEffects() { - return SUPPORTED_SIDE_EFFECTS; - } - - @Override - public boolean clearContainerBlockContents(World world, BlockVector3 pt) { - ServerLevel originalWorld = ((CraftWorld) world).getHandle(); - - BlockEntity entity = originalWorld.getBlockEntity(new BlockPos(pt.x(), pt.y(), pt.z())); - if (entity instanceof Clearable) { - ((Clearable) entity).clearContent(); - return true; - } - return false; - } - - @Override - public void initializeRegistries() { - DedicatedServer server = ((CraftServer) Bukkit.getServer()).getServer(); - // Biomes - for (ResourceLocation name : server.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).keySet()) { - if (BiomeType.REGISTRY.get(name.toString()) == null) { - BiomeType.REGISTRY.register(name.toString(), new BiomeType(name.toString())); - } - } - } - - // ------------------------------------------------------------------------ - // Code that is less likely to break - // ------------------------------------------------------------------------ - - /** - * Converts from a non-native NMS NBT structure to a native WorldEdit NBT - * structure. - * - * @param foreign non-native NMS NBT structure - * @return native WorldEdit NBT structure - */ - LinTag toNative(Tag foreign) { - if (foreign == null) { - return null; - } - if (foreign instanceof CompoundTag compoundTag) { - LinCompoundTag.Builder builder = LinCompoundTag.builder(); - for (var entry : compoundTag.tags.entrySet()) { - builder.put(entry.getKey(), toNative(entry.getValue())); - } - return builder.build(); - } else if (foreign instanceof ByteTag byteTag) { - return LinByteTag.of(byteTag.getAsByte()); - } else if (foreign instanceof ByteArrayTag byteArrayTag) { - return LinByteArrayTag.of(byteArrayTag.getAsByteArray()); - } else if (foreign instanceof DoubleTag doubleTag) { - return LinDoubleTag.of(doubleTag.getAsDouble()); - } else if (foreign instanceof FloatTag floatTag) { - return LinFloatTag.of(floatTag.getAsFloat()); - } else if (foreign instanceof IntTag intTag) { - return LinIntTag.of(intTag.getAsInt()); - } else if (foreign instanceof IntArrayTag intArrayTag) { - return LinIntArrayTag.of(intArrayTag.getAsIntArray()); - } else if (foreign instanceof LongArrayTag longArrayTag) { - return LinLongArrayTag.of(longArrayTag.getAsLongArray()); - } else if (foreign instanceof ListTag listTag) { - try { - return toNativeList(listTag); - } catch (Throwable e) { - logger.log(Level.WARNING, "Failed to convert net.minecraft.nbt.ListTag", e); - return LinListTag.empty(LinTagType.endTag()); - } - } else if (foreign instanceof LongTag longTag) { - return LinLongTag.of(longTag.getAsLong()); - } else if (foreign instanceof ShortTag shortTag) { - return LinShortTag.of(shortTag.getAsShort()); - } else if (foreign instanceof StringTag stringTag) { - return LinStringTag.of(stringTag.getAsString()); - } else if (foreign instanceof EndTag) { - return LinEndTag.instance(); - } else { - throw new IllegalArgumentException("Don't know how to make native " + foreign.getClass().getCanonicalName()); - } - } - - /** - * Convert a foreign NBT list tag into a native WorldEdit one. - * - * @param foreign the foreign tag - * @return the converted tag - * @throws SecurityException on error - * @throws IllegalArgumentException on error - */ - private LinListTag toNativeList(ListTag foreign) throws SecurityException, IllegalArgumentException { - LinListTag.Builder> builder = LinListTag.builder( - LinTagType.fromId(LinTagId.fromId(foreign.getElementType())) - ); - - for (Tag tag : foreign) { - builder.add(toNative(tag)); - } - - return builder.build(); - } - - /** - * Converts a WorldEdit-native NBT structure to a NMS structure. - * - * @param foreign structure to convert - * @return non-native structure - */ - Tag fromNative(LinTag foreign) { - if (foreign == null) { - return null; - } - if (foreign instanceof LinCompoundTag compoundTag) { - CompoundTag tag = new CompoundTag(); - for (var entry : compoundTag.value().entrySet()) { - tag.put(entry.getKey(), fromNative(entry.getValue())); - } - return tag; - } else if (foreign instanceof LinByteTag byteTag) { - return ByteTag.valueOf(byteTag.valueAsByte()); - } else if (foreign instanceof LinByteArrayTag byteArrayTag) { - return new ByteArrayTag(byteArrayTag.value()); - } else if (foreign instanceof LinDoubleTag doubleTag) { - return DoubleTag.valueOf(doubleTag.valueAsDouble()); - } else if (foreign instanceof LinFloatTag floatTag) { - return FloatTag.valueOf(floatTag.valueAsFloat()); - } else if (foreign instanceof LinIntTag intTag) { - return IntTag.valueOf(intTag.valueAsInt()); - } else if (foreign instanceof LinIntArrayTag intArrayTag) { - return new IntArrayTag(intArrayTag.value()); - } else if (foreign instanceof LinLongArrayTag longArrayTag) { - return new LongArrayTag(longArrayTag.value()); - } else if (foreign instanceof LinListTag listTag) { - ListTag tag = new ListTag(); - for (var t : listTag.value()) { - tag.add(fromNative(t)); - } - return tag; - } else if (foreign instanceof LinLongTag longTag) { - return LongTag.valueOf(longTag.valueAsLong()); - } else if (foreign instanceof LinShortTag shortTag) { - return ShortTag.valueOf(shortTag.valueAsShort()); - } else if (foreign instanceof LinStringTag stringTag) { - return StringTag.valueOf(stringTag.value()); - } else if (foreign instanceof LinEndTag) { - return EndTag.INSTANCE; - } else { - throw new IllegalArgumentException("Don't know how to make NMS " + foreign.getClass().getCanonicalName()); - } - } - - @Override - public boolean supportsWatchdog() { - return watchdog != null; - } - - @Override - public void tickWatchdog() { - watchdog.tick(); - } - - private class SpigotWatchdog implements Watchdog { - private final Field instanceField; - private final Field lastTickField; - - SpigotWatchdog() throws NoSuchFieldException { - Field instanceField = WatchdogThread.class.getDeclaredField("instance"); - instanceField.setAccessible(true); - this.instanceField = instanceField; - - Field lastTickField = WatchdogThread.class.getDeclaredField("lastTick"); - lastTickField.setAccessible(true); - this.lastTickField = lastTickField; - } - - @Override - public void tick() { - try { - WatchdogThread instance = (WatchdogThread) this.instanceField.get(null); - if ((long) lastTickField.get(instance) != 0) { - WatchdogThread.tick(); - } - } catch (IllegalAccessException e) { - logger.log(Level.WARNING, "Failed to tick watchdog", e); - } - } - } - - private static class MojangWatchdog implements Watchdog { - private final DedicatedServer server; - private final Field tickField; - - MojangWatchdog(DedicatedServer server) throws NoSuchFieldException { - this.server = server; - Field tickField = MinecraftServer.class.getDeclaredField( - Refraction.pickName("nextTickTime", "ao") - ); - tickField.setAccessible(true); - this.tickField = tickField; - } - - @Override - public void tick() { - try { - tickField.set(server, Util.getMillis()); - } catch (IllegalAccessException ignored) { - } - } - } - - private static class NoOpWorldLoadListener implements ChunkProgressListener { - @Override - public void updateSpawnPos(ChunkPos spawnPos) { - } - - @Override - public void onStatusChange(ChunkPos pos, @org.jetbrains.annotations.Nullable ChunkStatus status) { - } - - @Override - public void start() { - } - - @Override - public void stop() { - } - - @Override - public void setChunkRadius(int radius) { - } - } -} diff --git a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightDataConverters.java b/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightDataConverters.java deleted file mode 100644 index 78d4e2fa4..000000000 --- a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightDataConverters.java +++ /dev/null @@ -1,2800 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.bukkit.adapter.impl.v1_18_R2; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.mojang.datafixers.DSL.TypeReference; -import com.mojang.datafixers.DataFixer; -import com.mojang.datafixers.DataFixerBuilder; -import com.mojang.datafixers.schemas.Schema; -import com.mojang.serialization.Dynamic; -import net.minecraft.core.Direction; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.FloatTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; -import net.minecraft.util.StringUtil; -import net.minecraft.util.datafix.DataFixers; -import net.minecraft.util.datafix.fixes.References; -import net.minecraft.world.item.DyeColor; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.enginehub.linbus.tree.LinCompoundTag; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Executor; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -/** - * Handles converting all Pre 1.13.2 data using the Legacy DataFix System (ported to 1.13.2) - * - * We register a DFU Fixer per Legacy Data Version and apply the fixes using legacy strategy - * which is safer, faster and cleaner code. - * - * The pre DFU code did not fail when the Source version was unknown. - * - * This class also provides util methods for converting compounds to wrap the update call to - * receive the source version in the compound - */ -@SuppressWarnings({ "rawtypes", "unchecked" }) -class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.worldedit.world.DataFixer { - - @SuppressWarnings("unchecked") - @Override - public T fixUp(FixType type, T original, int srcVer) { - if (type == FixTypes.CHUNK) { - return (T) fixChunk((LinCompoundTag) original, srcVer); - } else if (type == FixTypes.BLOCK_ENTITY) { - return (T) fixBlockEntity((LinCompoundTag) original, srcVer); - } else if (type == FixTypes.ENTITY) { - return (T) fixEntity((LinCompoundTag) original, srcVer); - } else if (type == FixTypes.BLOCK_STATE) { - return (T) fixBlockState((String) original, srcVer); - } else if (type == FixTypes.ITEM_TYPE) { - return (T) fixItemType((String) original, srcVer); - } else if (type == FixTypes.BIOME) { - return (T) fixBiome((String) original, srcVer); - } - return original; - } - - private LinCompoundTag fixChunk(LinCompoundTag originalChunk, int srcVer) { - CompoundTag tag = (CompoundTag) adapter.fromNative(originalChunk); - CompoundTag fixed = convert(LegacyType.CHUNK, tag, srcVer); - return (LinCompoundTag) adapter.toNative(fixed); - } - - private LinCompoundTag fixBlockEntity(LinCompoundTag origTileEnt, int srcVer) { - CompoundTag tag = (CompoundTag) adapter.fromNative(origTileEnt); - CompoundTag fixed = convert(LegacyType.BLOCK_ENTITY, tag, srcVer); - return (LinCompoundTag) adapter.toNative(fixed); - } - - private LinCompoundTag fixEntity(LinCompoundTag origEnt, int srcVer) { - CompoundTag tag = (CompoundTag) adapter.fromNative(origEnt); - CompoundTag fixed = convert(LegacyType.ENTITY, tag, srcVer); - return (LinCompoundTag) adapter.toNative(fixed); - } - - private String fixBlockState(String blockState, int srcVer) { - CompoundTag stateNBT = stateToNBT(blockState); - Dynamic dynamic = new Dynamic<>(OPS_NBT, stateNBT); - CompoundTag fixed = (CompoundTag) INSTANCE.fixer.update(References.BLOCK_STATE, dynamic, srcVer, DATA_VERSION).getValue(); - return nbtToState(fixed); - } - - private String nbtToState(CompoundTag tagCompound) { - StringBuilder sb = new StringBuilder(); - sb.append(tagCompound.getString("Name")); - if (tagCompound.contains("Properties", 10)) { - sb.append('['); - CompoundTag props = tagCompound.getCompound("Properties"); - sb.append(props.getAllKeys().stream().map(k -> k + "=" + props.getString(k).replace("\"", "")).collect(Collectors.joining(","))); - sb.append(']'); - } - return sb.toString(); - } - - private static CompoundTag stateToNBT(String blockState) { - int propIdx = blockState.indexOf('['); - CompoundTag tag = new CompoundTag(); - if (propIdx < 0) { - tag.putString("Name", blockState); - } else { - tag.putString("Name", blockState.substring(0, propIdx)); - CompoundTag propTag = new CompoundTag(); - String props = blockState.substring(propIdx + 1, blockState.length() - 1); - String[] propArr = props.split(","); - for (String pair : propArr) { - final String[] split = pair.split("="); - propTag.putString(split[0], split[1]); - } - tag.put("Properties", propTag); - } - return tag; - } - - private String fixBiome(String key, int srcVer) { - return fixName(key, srcVer, References.BIOME); - } - - private String fixItemType(String key, int srcVer) { - return fixName(key, srcVer, References.ITEM_NAME); - } - - private static String fixName(String key, int srcVer, TypeReference type) { - return INSTANCE.fixer.update(type, new Dynamic<>(OPS_NBT, StringTag.valueOf(key)), srcVer, DATA_VERSION) - .getValue().getAsString(); - } - - private final PaperweightAdapter adapter; - - private static final NbtOps OPS_NBT = NbtOps.INSTANCE; - private static final int LEGACY_VERSION = 1343; - private static int DATA_VERSION; - static PaperweightDataConverters INSTANCE; - - private final Map> converters = new EnumMap<>(LegacyType.class); - private final Map> inspectors = new EnumMap<>(LegacyType.class); - - // Set on build - private DataFixer fixer; - private static final Map DFU_TO_LEGACY = new HashMap<>(); - - public enum LegacyType { - LEVEL(References.LEVEL), - PLAYER(References.PLAYER), - CHUNK(References.CHUNK), - BLOCK_ENTITY(References.BLOCK_ENTITY), - ENTITY(References.ENTITY), - ITEM_INSTANCE(References.ITEM_STACK), - OPTIONS(References.OPTIONS), - STRUCTURE(References.STRUCTURE); - - private final TypeReference type; - - LegacyType(TypeReference type) { - this.type = type; - DFU_TO_LEGACY.put(type.typeName(), this); - } - - public TypeReference getDFUType() { - return type; - } - } - - PaperweightDataConverters(int dataVersion, PaperweightAdapter adapter) { - super(dataVersion); - DATA_VERSION = dataVersion; - INSTANCE = this; - this.adapter = adapter; - registerConverters(); - registerInspectors(); - } - - - // Called after fixers are built and ready for FIXING - @Override - public DataFixer build(final Executor executor) { - return this.fixer = new WrappedDataFixer(DataFixers.getDataFixer()); - } - - @SuppressWarnings("unchecked") - private class WrappedDataFixer implements DataFixer { - private final DataFixer realFixer; - - WrappedDataFixer(DataFixer realFixer) { - this.realFixer = realFixer; - } - - @Override - public Dynamic update(TypeReference type, Dynamic dynamic, int sourceVer, int targetVer) { - LegacyType legacyType = DFU_TO_LEGACY.get(type.typeName()); - if (sourceVer < LEGACY_VERSION && legacyType != null) { - CompoundTag cmp = (CompoundTag) dynamic.getValue(); - int desiredVersion = Math.min(targetVer, LEGACY_VERSION); - - cmp = convert(legacyType, cmp, sourceVer, desiredVersion); - sourceVer = desiredVersion; - dynamic = new Dynamic(OPS_NBT, cmp); - } - return realFixer.update(type, dynamic, sourceVer, targetVer); - } - - private CompoundTag convert(LegacyType type, CompoundTag cmp, int sourceVer, int desiredVersion) { - List converters = PaperweightDataConverters.this.converters.get(type); - if (converters != null && !converters.isEmpty()) { - for (DataConverter converter : converters) { - int dataVersion = converter.getDataVersion(); - if (dataVersion > sourceVer && dataVersion <= desiredVersion) { - cmp = converter.convert(cmp); - } - } - } - - List inspectors = PaperweightDataConverters.this.inspectors.get(type); - if (inspectors != null && !inspectors.isEmpty()) { - for (DataInspector inspector : inspectors) { - cmp = inspector.inspect(cmp, sourceVer, desiredVersion); - } - } - - return cmp; - } - - @Override - public Schema getSchema(int i) { - return realFixer.getSchema(i); - } - } - - public static CompoundTag convert(LegacyType type, CompoundTag cmp) { - return convert(type.getDFUType(), cmp); - } - - public static CompoundTag convert(LegacyType type, CompoundTag cmp, int sourceVer) { - return convert(type.getDFUType(), cmp, sourceVer); - } - - public static CompoundTag convert(LegacyType type, CompoundTag cmp, int sourceVer, int targetVer) { - return convert(type.getDFUType(), cmp, sourceVer, targetVer); - } - - public static CompoundTag convert(TypeReference type, CompoundTag cmp) { - int i = cmp.contains("DataVersion", 99) ? cmp.getInt("DataVersion") : -1; - return convert(type, cmp, i); - } - - public static CompoundTag convert(TypeReference type, CompoundTag cmp, int sourceVer) { - return convert(type, cmp, sourceVer, DATA_VERSION); - } - - public static CompoundTag convert(TypeReference type, CompoundTag cmp, int sourceVer, int targetVer) { - if (sourceVer >= targetVer) { - return cmp; - } - return (CompoundTag) INSTANCE.fixer.update(type, new Dynamic<>(OPS_NBT, cmp), sourceVer, targetVer).getValue(); - } - - - public interface DataInspector { - CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer); - } - - public interface DataConverter { - - int getDataVersion(); - - CompoundTag convert(CompoundTag cmp); - } - - - private void registerInspector(LegacyType type, DataInspector inspector) { - this.inspectors.computeIfAbsent(type, k -> new ArrayList<>()).add(inspector); - } - - private void registerConverter(LegacyType type, DataConverter converter) { - int version = converter.getDataVersion(); - - List list = this.converters.computeIfAbsent(type, k -> new ArrayList<>()); - if (!list.isEmpty() && list.get(list.size() - 1).getDataVersion() > version) { - for (int j = 0; j < list.size(); ++j) { - if (list.get(j).getDataVersion() > version) { - list.add(j, converter); - break; - } - } - } else { - list.add(converter); - } - } - - private void registerInspectors() { - registerEntityItemList("EntityHorseDonkey", "SaddleItem", "Items"); - registerEntityItemList("EntityHorseMule", "Items"); - registerEntityItemList("EntityMinecartChest", "Items"); - registerEntityItemList("EntityMinecartHopper", "Items"); - registerEntityItemList("EntityVillager", "Inventory"); - registerEntityItemListEquipment("EntityArmorStand"); - registerEntityItemListEquipment("EntityBat"); - registerEntityItemListEquipment("EntityBlaze"); - registerEntityItemListEquipment("EntityCaveSpider"); - registerEntityItemListEquipment("EntityChicken"); - registerEntityItemListEquipment("EntityCow"); - registerEntityItemListEquipment("EntityCreeper"); - registerEntityItemListEquipment("EntityEnderDragon"); - registerEntityItemListEquipment("EntityEnderman"); - registerEntityItemListEquipment("EntityEndermite"); - registerEntityItemListEquipment("EntityEvoker"); - registerEntityItemListEquipment("EntityGhast"); - registerEntityItemListEquipment("EntityGiantZombie"); - registerEntityItemListEquipment("EntityGuardian"); - registerEntityItemListEquipment("EntityGuardianElder"); - registerEntityItemListEquipment("EntityHorse"); - registerEntityItemListEquipment("EntityHorseDonkey"); - registerEntityItemListEquipment("EntityHorseMule"); - registerEntityItemListEquipment("EntityHorseSkeleton"); - registerEntityItemListEquipment("EntityHorseZombie"); - registerEntityItemListEquipment("EntityIronGolem"); - registerEntityItemListEquipment("EntityMagmaCube"); - registerEntityItemListEquipment("EntityMushroomCow"); - registerEntityItemListEquipment("EntityOcelot"); - registerEntityItemListEquipment("EntityPig"); - registerEntityItemListEquipment("EntityPigZombie"); - registerEntityItemListEquipment("EntityRabbit"); - registerEntityItemListEquipment("EntitySheep"); - registerEntityItemListEquipment("EntityShulker"); - registerEntityItemListEquipment("EntitySilverfish"); - registerEntityItemListEquipment("EntitySkeleton"); - registerEntityItemListEquipment("EntitySkeletonStray"); - registerEntityItemListEquipment("EntitySkeletonWither"); - registerEntityItemListEquipment("EntitySlime"); - registerEntityItemListEquipment("EntitySnowman"); - registerEntityItemListEquipment("EntitySpider"); - registerEntityItemListEquipment("EntitySquid"); - registerEntityItemListEquipment("EntityVex"); - registerEntityItemListEquipment("EntityVillager"); - registerEntityItemListEquipment("EntityVindicator"); - registerEntityItemListEquipment("EntityWitch"); - registerEntityItemListEquipment("EntityWither"); - registerEntityItemListEquipment("EntityWolf"); - registerEntityItemListEquipment("EntityZombie"); - registerEntityItemListEquipment("EntityZombieHusk"); - registerEntityItemListEquipment("EntityZombieVillager"); - registerEntityItemSingle("EntityFireworks", "FireworksItem"); - registerEntityItemSingle("EntityHorse", "ArmorItem"); - registerEntityItemSingle("EntityHorse", "SaddleItem"); - registerEntityItemSingle("EntityHorseMule", "SaddleItem"); - registerEntityItemSingle("EntityHorseSkeleton", "SaddleItem"); - registerEntityItemSingle("EntityHorseZombie", "SaddleItem"); - registerEntityItemSingle("EntityItem", "Item"); - registerEntityItemSingle("EntityItemFrame", "Item"); - registerEntityItemSingle("EntityPotion", "Potion"); - - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItem("TileEntityRecordPlayer", "RecordItem")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityBrewingStand", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityChest", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityDispenser", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityDropper", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityFurnace", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityHopper", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorItemList("TileEntityShulkerBox", "Items")); - registerInspector(LegacyType.BLOCK_ENTITY, new DataInspectorMobSpawnerMobs()); - registerInspector(LegacyType.CHUNK, new DataInspectorChunks()); - registerInspector(LegacyType.ENTITY, new DataInspectorCommandBlock()); - registerInspector(LegacyType.ENTITY, new DataInspectorEntityPassengers()); - registerInspector(LegacyType.ENTITY, new DataInspectorMobSpawnerMinecart()); - registerInspector(LegacyType.ENTITY, new DataInspectorVillagers()); - registerInspector(LegacyType.ITEM_INSTANCE, new DataInspectorBlockEntity()); - registerInspector(LegacyType.ITEM_INSTANCE, new DataInspectorEntity()); - registerInspector(LegacyType.LEVEL, new DataInspectorLevelPlayer()); - registerInspector(LegacyType.PLAYER, new DataInspectorPlayer()); - registerInspector(LegacyType.PLAYER, new DataInspectorPlayerVehicle()); - registerInspector(LegacyType.STRUCTURE, new DataInspectorStructure()); - } - - private void registerConverters() { - registerConverter(LegacyType.ENTITY, new DataConverterEquipment()); - registerConverter(LegacyType.BLOCK_ENTITY, new DataConverterSignText()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterMaterialId()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterPotionId()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterSpawnEgg()); - registerConverter(LegacyType.ENTITY, new DataConverterMinecart()); - registerConverter(LegacyType.BLOCK_ENTITY, new DataConverterMobSpawner()); - registerConverter(LegacyType.ENTITY, new DataConverterUUID()); - registerConverter(LegacyType.ENTITY, new DataConverterHealth()); - registerConverter(LegacyType.ENTITY, new DataConverterSaddle()); - registerConverter(LegacyType.ENTITY, new DataConverterHanging()); - registerConverter(LegacyType.ENTITY, new DataConverterDropChances()); - registerConverter(LegacyType.ENTITY, new DataConverterRiding()); - registerConverter(LegacyType.ENTITY, new DataConverterArmorStand()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterBook()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterCookedFish()); - registerConverter(LegacyType.ENTITY, new DataConverterZombie()); - registerConverter(LegacyType.OPTIONS, new DataConverterVBO()); - registerConverter(LegacyType.ENTITY, new DataConverterGuardian()); - registerConverter(LegacyType.ENTITY, new DataConverterSkeleton()); - registerConverter(LegacyType.ENTITY, new DataConverterZombieType()); - registerConverter(LegacyType.ENTITY, new DataConverterHorse()); - registerConverter(LegacyType.BLOCK_ENTITY, new DataConverterTileEntity()); - registerConverter(LegacyType.ENTITY, new DataConverterEntity()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterBanner()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterPotionWater()); - registerConverter(LegacyType.ENTITY, new DataConverterShulker()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterShulkerBoxItem()); - registerConverter(LegacyType.BLOCK_ENTITY, new DataConverterShulkerBoxBlock()); - registerConverter(LegacyType.OPTIONS, new DataConverterLang()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterTotem()); - registerConverter(LegacyType.CHUNK, new DataConverterBedBlock()); - registerConverter(LegacyType.ITEM_INSTANCE, new DataConverterBedItem()); - } - - private void registerEntityItemList(String type, String... keys) { - registerInspector(LegacyType.ENTITY, new DataInspectorItemList(type, keys)); - } - - private void registerEntityItemSingle(String type, String key) { - registerInspector(LegacyType.ENTITY, new DataInspectorItem(type, key)); - } - - private void registerEntityItemListEquipment(String type) { - registerEntityItemList(type, "ArmorItems", "HandItems"); - } - - private static final Map OLD_ID_TO_KEY_MAP = new HashMap<>(); - - static { - final Map map = OLD_ID_TO_KEY_MAP; - map.put("EntityItem", new ResourceLocation("item")); - map.put("EntityExperienceOrb", new ResourceLocation("xp_orb")); - map.put("EntityAreaEffectCloud", new ResourceLocation("area_effect_cloud")); - map.put("EntityGuardianElder", new ResourceLocation("elder_guardian")); - map.put("EntitySkeletonWither", new ResourceLocation("wither_skeleton")); - map.put("EntitySkeletonStray", new ResourceLocation("stray")); - map.put("EntityEgg", new ResourceLocation("egg")); - map.put("EntityLeash", new ResourceLocation("leash_knot")); - map.put("EntityPainting", new ResourceLocation("painting")); - map.put("EntityTippedArrow", new ResourceLocation("arrow")); - map.put("EntitySnowball", new ResourceLocation("snowball")); - map.put("EntityLargeFireball", new ResourceLocation("fireball")); - map.put("EntitySmallFireball", new ResourceLocation("small_fireball")); - map.put("EntityEnderPearl", new ResourceLocation("ender_pearl")); - map.put("EntityEnderSignal", new ResourceLocation("eye_of_ender_signal")); - map.put("EntityPotion", new ResourceLocation("potion")); - map.put("EntityThrownExpBottle", new ResourceLocation("xp_bottle")); - map.put("EntityItemFrame", new ResourceLocation("item_frame")); - map.put("EntityWitherSkull", new ResourceLocation("wither_skull")); - map.put("EntityTNTPrimed", new ResourceLocation("tnt")); - map.put("EntityFallingBlock", new ResourceLocation("falling_block")); - map.put("EntityFireworks", new ResourceLocation("fireworks_rocket")); - map.put("EntityZombieHusk", new ResourceLocation("husk")); - map.put("EntitySpectralArrow", new ResourceLocation("spectral_arrow")); - map.put("EntityShulkerBullet", new ResourceLocation("shulker_bullet")); - map.put("EntityDragonFireball", new ResourceLocation("dragon_fireball")); - map.put("EntityZombieVillager", new ResourceLocation("zombie_villager")); - map.put("EntityHorseSkeleton", new ResourceLocation("skeleton_horse")); - map.put("EntityHorseZombie", new ResourceLocation("zombie_horse")); - map.put("EntityArmorStand", new ResourceLocation("armor_stand")); - map.put("EntityHorseDonkey", new ResourceLocation("donkey")); - map.put("EntityHorseMule", new ResourceLocation("mule")); - map.put("EntityEvokerFangs", new ResourceLocation("evocation_fangs")); - map.put("EntityEvoker", new ResourceLocation("evocation_illager")); - map.put("EntityVex", new ResourceLocation("vex")); - map.put("EntityVindicator", new ResourceLocation("vindication_illager")); - map.put("EntityIllagerIllusioner", new ResourceLocation("illusion_illager")); - map.put("EntityMinecartCommandBlock", new ResourceLocation("commandblock_minecart")); - map.put("EntityBoat", new ResourceLocation("boat")); - map.put("EntityMinecartRideable", new ResourceLocation("minecart")); - map.put("EntityMinecartChest", new ResourceLocation("chest_minecart")); - map.put("EntityMinecartFurnace", new ResourceLocation("furnace_minecart")); - map.put("EntityMinecartTNT", new ResourceLocation("tnt_minecart")); - map.put("EntityMinecartHopper", new ResourceLocation("hopper_minecart")); - map.put("EntityMinecartMobSpawner", new ResourceLocation("spawner_minecart")); - map.put("EntityCreeper", new ResourceLocation("creeper")); - map.put("EntitySkeleton", new ResourceLocation("skeleton")); - map.put("EntitySpider", new ResourceLocation("spider")); - map.put("EntityGiantZombie", new ResourceLocation("giant")); - map.put("EntityZombie", new ResourceLocation("zombie")); - map.put("EntitySlime", new ResourceLocation("slime")); - map.put("EntityGhast", new ResourceLocation("ghast")); - map.put("EntityPigZombie", new ResourceLocation("zombie_pigman")); - map.put("EntityEnderman", new ResourceLocation("enderman")); - map.put("EntityCaveSpider", new ResourceLocation("cave_spider")); - map.put("EntitySilverfish", new ResourceLocation("silverfish")); - map.put("EntityBlaze", new ResourceLocation("blaze")); - map.put("EntityMagmaCube", new ResourceLocation("magma_cube")); - map.put("EntityEnderDragon", new ResourceLocation("ender_dragon")); - map.put("EntityWither", new ResourceLocation("wither")); - map.put("EntityBat", new ResourceLocation("bat")); - map.put("EntityWitch", new ResourceLocation("witch")); - map.put("EntityEndermite", new ResourceLocation("endermite")); - map.put("EntityGuardian", new ResourceLocation("guardian")); - map.put("EntityShulker", new ResourceLocation("shulker")); - map.put("EntityPig", new ResourceLocation("pig")); - map.put("EntitySheep", new ResourceLocation("sheep")); - map.put("EntityCow", new ResourceLocation("cow")); - map.put("EntityChicken", new ResourceLocation("chicken")); - map.put("EntitySquid", new ResourceLocation("squid")); - map.put("EntityWolf", new ResourceLocation("wolf")); - map.put("EntityMushroomCow", new ResourceLocation("mooshroom")); - map.put("EntitySnowman", new ResourceLocation("snowman")); - map.put("EntityOcelot", new ResourceLocation("ocelot")); - map.put("EntityIronGolem", new ResourceLocation("villager_golem")); - map.put("EntityHorse", new ResourceLocation("horse")); - map.put("EntityRabbit", new ResourceLocation("rabbit")); - map.put("EntityPolarBear", new ResourceLocation("polar_bear")); - map.put("EntityLlama", new ResourceLocation("llama")); - map.put("EntityLlamaSpit", new ResourceLocation("llama_spit")); - map.put("EntityParrot", new ResourceLocation("parrot")); - map.put("EntityVillager", new ResourceLocation("villager")); - map.put("EntityEnderCrystal", new ResourceLocation("ender_crystal")); - map.put("TileEntityFurnace", new ResourceLocation("furnace")); - map.put("TileEntityChest", new ResourceLocation("chest")); - map.put("TileEntityEnderChest", new ResourceLocation("ender_chest")); - map.put("TileEntityRecordPlayer", new ResourceLocation("jukebox")); - map.put("TileEntityDispenser", new ResourceLocation("dispenser")); - map.put("TileEntityDropper", new ResourceLocation("dropper")); - map.put("TileEntitySign", new ResourceLocation("sign")); - map.put("TileEntityMobSpawner", new ResourceLocation("mob_spawner")); - map.put("TileEntityNote", new ResourceLocation("noteblock")); - map.put("TileEntityPiston", new ResourceLocation("piston")); - map.put("TileEntityBrewingStand", new ResourceLocation("brewing_stand")); - map.put("TileEntityEnchantTable", new ResourceLocation("enchanting_table")); - map.put("TileEntityEnderPortal", new ResourceLocation("end_portal")); - map.put("TileEntityBeacon", new ResourceLocation("beacon")); - map.put("TileEntitySkull", new ResourceLocation("skull")); - map.put("TileEntityLightDetector", new ResourceLocation("daylight_detector")); - map.put("TileEntityHopper", new ResourceLocation("hopper")); - map.put("TileEntityComparator", new ResourceLocation("comparator")); - map.put("TileEntityFlowerPot", new ResourceLocation("flower_pot")); - map.put("TileEntityBanner", new ResourceLocation("banner")); - map.put("TileEntityStructure", new ResourceLocation("structure_block")); - map.put("TileEntityEndGateway", new ResourceLocation("end_gateway")); - map.put("TileEntityCommand", new ResourceLocation("command_block")); - map.put("TileEntityShulkerBox", new ResourceLocation("shulker_box")); - map.put("TileEntityBed", new ResourceLocation("bed")); - } - - private static ResourceLocation getKey(String type) { - final ResourceLocation key = OLD_ID_TO_KEY_MAP.get(type); - if (key == null) { - throw new IllegalArgumentException("Unknown mapping for " + type); - } - return key; - } - - private static void convertCompound(LegacyType type, CompoundTag cmp, String key, int sourceVer, int targetVer) { - cmp.put(key, convert(type, cmp.getCompound(key), sourceVer, targetVer)); - } - - private static void convertItem(CompoundTag nbttagcompound, String key, int sourceVer, int targetVer) { - if (nbttagcompound.contains(key, 10)) { - convertCompound(LegacyType.ITEM_INSTANCE, nbttagcompound, key, sourceVer, targetVer); - } - } - - private static void convertItems(CompoundTag nbttagcompound, String key, int sourceVer, int targetVer) { - if (nbttagcompound.contains(key, 9)) { - ListTag nbttaglist = nbttagcompound.getList(key, 10); - - for (int j = 0; j < nbttaglist.size(); ++j) { - nbttaglist.set(j, convert(LegacyType.ITEM_INSTANCE, nbttaglist.getCompound(j), sourceVer, targetVer)); - } - } - - } - - private static class DataConverterEquipment implements DataConverter { - - DataConverterEquipment() { - } - - public int getDataVersion() { - return 100; - } - - public CompoundTag convert(CompoundTag cmp) { - ListTag nbttaglist = cmp.getList("Equipment", 10); - ListTag nbttaglist1; - - if (!nbttaglist.isEmpty() && !cmp.contains("HandItems", 10)) { - nbttaglist1 = new ListTag(); - nbttaglist1.add(nbttaglist.get(0)); - nbttaglist1.add(new CompoundTag()); - cmp.put("HandItems", nbttaglist1); - } - - if (nbttaglist.size() > 1 && !cmp.contains("ArmorItem", 10)) { - nbttaglist1 = new ListTag(); - nbttaglist1.add(nbttaglist.get(1)); - nbttaglist1.add(nbttaglist.get(2)); - nbttaglist1.add(nbttaglist.get(3)); - nbttaglist1.add(nbttaglist.get(4)); - cmp.put("ArmorItems", nbttaglist1); - } - - cmp.remove("Equipment"); - if (cmp.contains("DropChances", 9)) { - nbttaglist1 = cmp.getList("DropChances", 5); - ListTag nbttaglist2; - - if (!cmp.contains("HandDropChances", 10)) { - nbttaglist2 = new ListTag(); - nbttaglist2.add(FloatTag.valueOf(nbttaglist1.getFloat(0))); - nbttaglist2.add(FloatTag.valueOf(0.0F)); - cmp.put("HandDropChances", nbttaglist2); - } - - if (!cmp.contains("ArmorDropChances", 10)) { - nbttaglist2 = new ListTag(); - nbttaglist2.add(FloatTag.valueOf(nbttaglist1.getFloat(1))); - nbttaglist2.add(FloatTag.valueOf(nbttaglist1.getFloat(2))); - nbttaglist2.add(FloatTag.valueOf(nbttaglist1.getFloat(3))); - nbttaglist2.add(FloatTag.valueOf(nbttaglist1.getFloat(4))); - cmp.put("ArmorDropChances", nbttaglist2); - } - - cmp.remove("DropChances"); - } - - return cmp; - } - } - - private static class DataInspectorBlockEntity implements DataInspector { - - private static final Map b = Maps.newHashMap(); - private static final Map c = Maps.newHashMap(); - - DataInspectorBlockEntity() { - } - - @Nullable - private static String convertEntityId(int i, String s) { - String key = new ResourceLocation(s).toString(); - if (i < 515 && DataInspectorBlockEntity.b.containsKey(key)) { - return DataInspectorBlockEntity.b.get(key); - } else { - return DataInspectorBlockEntity.c.get(key); - } - } - - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (!cmp.contains("tag", 10)) { - return cmp; - } else { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - - if (nbttagcompound1.contains("BlockEntityTag", 10)) { - CompoundTag nbttagcompound2 = nbttagcompound1.getCompound("BlockEntityTag"); - String s = cmp.getString("id"); - String s1 = convertEntityId(sourceVer, s); - boolean flag; - - if (s1 == null) { - // CraftBukkit - Remove unnecessary warning (occurs when deserializing a Shulker Box item) - // DataInspectorBlockEntity.a.warn("Unable to resolve BlockEntity for ItemInstance: {}", s); - flag = false; - } else { - flag = !nbttagcompound2.contains("id"); - nbttagcompound2.putString("id", s1); - } - - convert(LegacyType.BLOCK_ENTITY, nbttagcompound2, sourceVer, targetVer); - if (flag) { - nbttagcompound2.remove("id"); - } - } - - return cmp; - } - } - - static { - Map map = DataInspectorBlockEntity.b; - - map.put("minecraft:furnace", "Furnace"); - map.put("minecraft:lit_furnace", "Furnace"); - map.put("minecraft:chest", "Chest"); - map.put("minecraft:trapped_chest", "Chest"); - map.put("minecraft:ender_chest", "EnderChest"); - map.put("minecraft:jukebox", "RecordPlayer"); - map.put("minecraft:dispenser", "Trap"); - map.put("minecraft:dropper", "Dropper"); - map.put("minecraft:sign", "Sign"); - map.put("minecraft:mob_spawner", "MobSpawner"); - map.put("minecraft:noteblock", "Music"); - map.put("minecraft:brewing_stand", "Cauldron"); - map.put("minecraft:enhanting_table", "EnchantTable"); - map.put("minecraft:command_block", "CommandBlock"); - map.put("minecraft:beacon", "Beacon"); - map.put("minecraft:skull", "Skull"); - map.put("minecraft:daylight_detector", "DLDetector"); - map.put("minecraft:hopper", "Hopper"); - map.put("minecraft:banner", "Banner"); - map.put("minecraft:flower_pot", "FlowerPot"); - map.put("minecraft:repeating_command_block", "CommandBlock"); - map.put("minecraft:chain_command_block", "CommandBlock"); - map.put("minecraft:standing_sign", "Sign"); - map.put("minecraft:wall_sign", "Sign"); - map.put("minecraft:piston_head", "Piston"); - map.put("minecraft:daylight_detector_inverted", "DLDetector"); - map.put("minecraft:unpowered_comparator", "Comparator"); - map.put("minecraft:powered_comparator", "Comparator"); - map.put("minecraft:wall_banner", "Banner"); - map.put("minecraft:standing_banner", "Banner"); - map.put("minecraft:structure_block", "Structure"); - map.put("minecraft:end_portal", "Airportal"); - map.put("minecraft:end_gateway", "EndGateway"); - map.put("minecraft:shield", "Shield"); - map = DataInspectorBlockEntity.c; - map.put("minecraft:furnace", "minecraft:furnace"); - map.put("minecraft:lit_furnace", "minecraft:furnace"); - map.put("minecraft:chest", "minecraft:chest"); - map.put("minecraft:trapped_chest", "minecraft:chest"); - map.put("minecraft:ender_chest", "minecraft:enderchest"); - map.put("minecraft:jukebox", "minecraft:jukebox"); - map.put("minecraft:dispenser", "minecraft:dispenser"); - map.put("minecraft:dropper", "minecraft:dropper"); - map.put("minecraft:sign", "minecraft:sign"); - map.put("minecraft:mob_spawner", "minecraft:mob_spawner"); - map.put("minecraft:noteblock", "minecraft:noteblock"); - map.put("minecraft:brewing_stand", "minecraft:brewing_stand"); - map.put("minecraft:enhanting_table", "minecraft:enchanting_table"); - map.put("minecraft:command_block", "minecraft:command_block"); - map.put("minecraft:beacon", "minecraft:beacon"); - map.put("minecraft:skull", "minecraft:skull"); - map.put("minecraft:daylight_detector", "minecraft:daylight_detector"); - map.put("minecraft:hopper", "minecraft:hopper"); - map.put("minecraft:banner", "minecraft:banner"); - map.put("minecraft:flower_pot", "minecraft:flower_pot"); - map.put("minecraft:repeating_command_block", "minecraft:command_block"); - map.put("minecraft:chain_command_block", "minecraft:command_block"); - map.put("minecraft:shulker_box", "minecraft:shulker_box"); - map.put("minecraft:white_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:orange_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:magenta_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:light_blue_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:yellow_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:lime_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:pink_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:gray_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:silver_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:cyan_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:purple_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:blue_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:brown_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:green_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:red_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:black_shulker_box", "minecraft:shulker_box"); - map.put("minecraft:bed", "minecraft:bed"); - map.put("minecraft:standing_sign", "minecraft:sign"); - map.put("minecraft:wall_sign", "minecraft:sign"); - map.put("minecraft:piston_head", "minecraft:piston"); - map.put("minecraft:daylight_detector_inverted", "minecraft:daylight_detector"); - map.put("minecraft:unpowered_comparator", "minecraft:comparator"); - map.put("minecraft:powered_comparator", "minecraft:comparator"); - map.put("minecraft:wall_banner", "minecraft:banner"); - map.put("minecraft:standing_banner", "minecraft:banner"); - map.put("minecraft:structure_block", "minecraft:structure_block"); - map.put("minecraft:end_portal", "minecraft:end_portal"); - map.put("minecraft:end_gateway", "minecraft:end_gateway"); - map.put("minecraft:shield", "minecraft:shield"); - } - } - - private static class DataInspectorEntity implements DataInspector { - - private static final Logger a = LogManager.getLogger(PaperweightDataConverters.class); - - DataInspectorEntity() { - } - - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - - if (nbttagcompound1.contains("EntityTag", 10)) { - CompoundTag nbttagcompound2 = nbttagcompound1.getCompound("EntityTag"); - String s = cmp.getString("id"); - String s1; - - if ("minecraft:armor_stand".equals(s)) { - s1 = sourceVer < 515 ? "ArmorStand" : "minecraft:armor_stand"; - } else { - if (!"minecraft:spawn_egg".equals(s)) { - return cmp; - } - - s1 = nbttagcompound2.getString("id"); - } - - boolean flag; - - flag = !nbttagcompound2.contains("id", 8); - nbttagcompound2.putString("id", s1); - - convert(LegacyType.ENTITY, nbttagcompound2, sourceVer, targetVer); - if (flag) { - nbttagcompound2.remove("id"); - } - } - - return cmp; - } - } - - - private abstract static class DataInspectorTagged implements DataInspector { - - private final ResourceLocation key; - - DataInspectorTagged(String type) { - this.key = getKey(type); - } - - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (this.key.equals(new ResourceLocation(cmp.getString("id")))) { - cmp = this.inspectChecked(cmp, sourceVer, targetVer); - } - - return cmp; - } - - abstract CompoundTag inspectChecked(CompoundTag nbttagcompound, int sourceVer, int targetVer); - } - - private static class DataInspectorItemList extends DataInspectorTagged { - - private final String[] keys; - - DataInspectorItemList(String oclass, String... astring) { - super(oclass); - this.keys = astring; - } - - CompoundTag inspectChecked(CompoundTag nbttagcompound, int sourceVer, int targetVer) { - for (String s : this.keys) { - PaperweightDataConverters.convertItems(nbttagcompound, s, sourceVer, targetVer); - } - - return nbttagcompound; - } - } - - private static class DataInspectorItem extends DataInspectorTagged { - - private final String[] keys; - - DataInspectorItem(String oclass, String... astring) { - super(oclass); - this.keys = astring; - } - - CompoundTag inspectChecked(CompoundTag nbttagcompound, int sourceVer, int targetVer) { - for (String key : this.keys) { - PaperweightDataConverters.convertItem(nbttagcompound, key, sourceVer, targetVer); - } - - return nbttagcompound; - } - } - - private static class DataConverterMaterialId implements DataConverter { - - private static final String[] materials = new String[2268]; - - DataConverterMaterialId() { - } - - public int getDataVersion() { - return 102; - } - - public CompoundTag convert(CompoundTag cmp) { - if (cmp.contains("id", 99)) { - short short0 = cmp.getShort("id"); - - if (short0 > 0 && short0 < materials.length && materials[short0] != null) { - cmp.putString("id", materials[short0]); - } - } - - return cmp; - } - - static { - materials[1] = "minecraft:stone"; - materials[2] = "minecraft:grass"; - materials[3] = "minecraft:dirt"; - materials[4] = "minecraft:cobblestone"; - materials[5] = "minecraft:planks"; - materials[6] = "minecraft:sapling"; - materials[7] = "minecraft:bedrock"; - materials[8] = "minecraft:flowing_water"; - materials[9] = "minecraft:water"; - materials[10] = "minecraft:flowing_lava"; - materials[11] = "minecraft:lava"; - materials[12] = "minecraft:sand"; - materials[13] = "minecraft:gravel"; - materials[14] = "minecraft:gold_ore"; - materials[15] = "minecraft:iron_ore"; - materials[16] = "minecraft:coal_ore"; - materials[17] = "minecraft:log"; - materials[18] = "minecraft:leaves"; - materials[19] = "minecraft:sponge"; - materials[20] = "minecraft:glass"; - materials[21] = "minecraft:lapis_ore"; - materials[22] = "minecraft:lapis_block"; - materials[23] = "minecraft:dispenser"; - materials[24] = "minecraft:sandstone"; - materials[25] = "minecraft:noteblock"; - materials[27] = "minecraft:golden_rail"; - materials[28] = "minecraft:detector_rail"; - materials[29] = "minecraft:sticky_piston"; - materials[30] = "minecraft:web"; - materials[31] = "minecraft:tallgrass"; - materials[32] = "minecraft:deadbush"; - materials[33] = "minecraft:piston"; - materials[35] = "minecraft:wool"; - materials[37] = "minecraft:yellow_flower"; - materials[38] = "minecraft:red_flower"; - materials[39] = "minecraft:brown_mushroom"; - materials[40] = "minecraft:red_mushroom"; - materials[41] = "minecraft:gold_block"; - materials[42] = "minecraft:iron_block"; - materials[43] = "minecraft:double_stone_slab"; - materials[44] = "minecraft:stone_slab"; - materials[45] = "minecraft:brick_block"; - materials[46] = "minecraft:tnt"; - materials[47] = "minecraft:bookshelf"; - materials[48] = "minecraft:mossy_cobblestone"; - materials[49] = "minecraft:obsidian"; - materials[50] = "minecraft:torch"; - materials[51] = "minecraft:fire"; - materials[52] = "minecraft:mob_spawner"; - materials[53] = "minecraft:oak_stairs"; - materials[54] = "minecraft:chest"; - materials[56] = "minecraft:diamond_ore"; - materials[57] = "minecraft:diamond_block"; - materials[58] = "minecraft:crafting_table"; - materials[60] = "minecraft:farmland"; - materials[61] = "minecraft:furnace"; - materials[62] = "minecraft:lit_furnace"; - materials[65] = "minecraft:ladder"; - materials[66] = "minecraft:rail"; - materials[67] = "minecraft:stone_stairs"; - materials[69] = "minecraft:lever"; - materials[70] = "minecraft:stone_pressure_plate"; - materials[72] = "minecraft:wooden_pressure_plate"; - materials[73] = "minecraft:redstone_ore"; - materials[76] = "minecraft:redstone_torch"; - materials[77] = "minecraft:stone_button"; - materials[78] = "minecraft:snow_layer"; - materials[79] = "minecraft:ice"; - materials[80] = "minecraft:snow"; - materials[81] = "minecraft:cactus"; - materials[82] = "minecraft:clay"; - materials[84] = "minecraft:jukebox"; - materials[85] = "minecraft:fence"; - materials[86] = "minecraft:pumpkin"; - materials[87] = "minecraft:netherrack"; - materials[88] = "minecraft:soul_sand"; - materials[89] = "minecraft:glowstone"; - materials[90] = "minecraft:portal"; - materials[91] = "minecraft:lit_pumpkin"; - materials[95] = "minecraft:stained_glass"; - materials[96] = "minecraft:trapdoor"; - materials[97] = "minecraft:monster_egg"; - materials[98] = "minecraft:stonebrick"; - materials[99] = "minecraft:brown_mushroom_block"; - materials[100] = "minecraft:red_mushroom_block"; - materials[101] = "minecraft:iron_bars"; - materials[102] = "minecraft:glass_pane"; - materials[103] = "minecraft:melon_block"; - materials[106] = "minecraft:vine"; - materials[107] = "minecraft:fence_gate"; - materials[108] = "minecraft:brick_stairs"; - materials[109] = "minecraft:stone_brick_stairs"; - materials[110] = "minecraft:mycelium"; - materials[111] = "minecraft:waterlily"; - materials[112] = "minecraft:nether_brick"; - materials[113] = "minecraft:nether_brick_fence"; - materials[114] = "minecraft:nether_brick_stairs"; - materials[116] = "minecraft:enchanting_table"; - materials[119] = "minecraft:end_portal"; - materials[120] = "minecraft:end_portal_frame"; - materials[121] = "minecraft:end_stone"; - materials[122] = "minecraft:dragon_egg"; - materials[123] = "minecraft:redstone_lamp"; - materials[125] = "minecraft:double_wooden_slab"; - materials[126] = "minecraft:wooden_slab"; - materials[127] = "minecraft:cocoa"; - materials[128] = "minecraft:sandstone_stairs"; - materials[129] = "minecraft:emerald_ore"; - materials[130] = "minecraft:ender_chest"; - materials[131] = "minecraft:tripwire_hook"; - materials[133] = "minecraft:emerald_block"; - materials[134] = "minecraft:spruce_stairs"; - materials[135] = "minecraft:birch_stairs"; - materials[136] = "minecraft:jungle_stairs"; - materials[137] = "minecraft:command_block"; - materials[138] = "minecraft:beacon"; - materials[139] = "minecraft:cobblestone_wall"; - materials[141] = "minecraft:carrots"; - materials[142] = "minecraft:potatoes"; - materials[143] = "minecraft:wooden_button"; - materials[145] = "minecraft:anvil"; - materials[146] = "minecraft:trapped_chest"; - materials[147] = "minecraft:light_weighted_pressure_plate"; - materials[148] = "minecraft:heavy_weighted_pressure_plate"; - materials[151] = "minecraft:daylight_detector"; - materials[152] = "minecraft:redstone_block"; - materials[153] = "minecraft:quartz_ore"; - materials[154] = "minecraft:hopper"; - materials[155] = "minecraft:quartz_block"; - materials[156] = "minecraft:quartz_stairs"; - materials[157] = "minecraft:activator_rail"; - materials[158] = "minecraft:dropper"; - materials[159] = "minecraft:stained_hardened_clay"; - materials[160] = "minecraft:stained_glass_pane"; - materials[161] = "minecraft:leaves2"; - materials[162] = "minecraft:log2"; - materials[163] = "minecraft:acacia_stairs"; - materials[164] = "minecraft:dark_oak_stairs"; - materials[170] = "minecraft:hay_block"; - materials[171] = "minecraft:carpet"; - materials[172] = "minecraft:hardened_clay"; - materials[173] = "minecraft:coal_block"; - materials[174] = "minecraft:packed_ice"; - materials[175] = "minecraft:double_plant"; - materials[256] = "minecraft:iron_shovel"; - materials[257] = "minecraft:iron_pickaxe"; - materials[258] = "minecraft:iron_axe"; - materials[259] = "minecraft:flint_and_steel"; - materials[260] = "minecraft:apple"; - materials[261] = "minecraft:bow"; - materials[262] = "minecraft:arrow"; - materials[263] = "minecraft:coal"; - materials[264] = "minecraft:diamond"; - materials[265] = "minecraft:iron_ingot"; - materials[266] = "minecraft:gold_ingot"; - materials[267] = "minecraft:iron_sword"; - materials[268] = "minecraft:wooden_sword"; - materials[269] = "minecraft:wooden_shovel"; - materials[270] = "minecraft:wooden_pickaxe"; - materials[271] = "minecraft:wooden_axe"; - materials[272] = "minecraft:stone_sword"; - materials[273] = "minecraft:stone_shovel"; - materials[274] = "minecraft:stone_pickaxe"; - materials[275] = "minecraft:stone_axe"; - materials[276] = "minecraft:diamond_sword"; - materials[277] = "minecraft:diamond_shovel"; - materials[278] = "minecraft:diamond_pickaxe"; - materials[279] = "minecraft:diamond_axe"; - materials[280] = "minecraft:stick"; - materials[281] = "minecraft:bowl"; - materials[282] = "minecraft:mushroom_stew"; - materials[283] = "minecraft:golden_sword"; - materials[284] = "minecraft:golden_shovel"; - materials[285] = "minecraft:golden_pickaxe"; - materials[286] = "minecraft:golden_axe"; - materials[287] = "minecraft:string"; - materials[288] = "minecraft:feather"; - materials[289] = "minecraft:gunpowder"; - materials[290] = "minecraft:wooden_hoe"; - materials[291] = "minecraft:stone_hoe"; - materials[292] = "minecraft:iron_hoe"; - materials[293] = "minecraft:diamond_hoe"; - materials[294] = "minecraft:golden_hoe"; - materials[295] = "minecraft:wheat_seeds"; - materials[296] = "minecraft:wheat"; - materials[297] = "minecraft:bread"; - materials[298] = "minecraft:leather_helmet"; - materials[299] = "minecraft:leather_chestplate"; - materials[300] = "minecraft:leather_leggings"; - materials[301] = "minecraft:leather_boots"; - materials[302] = "minecraft:chainmail_helmet"; - materials[303] = "minecraft:chainmail_chestplate"; - materials[304] = "minecraft:chainmail_leggings"; - materials[305] = "minecraft:chainmail_boots"; - materials[306] = "minecraft:iron_helmet"; - materials[307] = "minecraft:iron_chestplate"; - materials[308] = "minecraft:iron_leggings"; - materials[309] = "minecraft:iron_boots"; - materials[310] = "minecraft:diamond_helmet"; - materials[311] = "minecraft:diamond_chestplate"; - materials[312] = "minecraft:diamond_leggings"; - materials[313] = "minecraft:diamond_boots"; - materials[314] = "minecraft:golden_helmet"; - materials[315] = "minecraft:golden_chestplate"; - materials[316] = "minecraft:golden_leggings"; - materials[317] = "minecraft:golden_boots"; - materials[318] = "minecraft:flint"; - materials[319] = "minecraft:porkchop"; - materials[320] = "minecraft:cooked_porkchop"; - materials[321] = "minecraft:painting"; - materials[322] = "minecraft:golden_apple"; - materials[323] = "minecraft:sign"; - materials[324] = "minecraft:wooden_door"; - materials[325] = "minecraft:bucket"; - materials[326] = "minecraft:water_bucket"; - materials[327] = "minecraft:lava_bucket"; - materials[328] = "minecraft:minecart"; - materials[329] = "minecraft:saddle"; - materials[330] = "minecraft:iron_door"; - materials[331] = "minecraft:redstone"; - materials[332] = "minecraft:snowball"; - materials[333] = "minecraft:boat"; - materials[334] = "minecraft:leather"; - materials[335] = "minecraft:milk_bucket"; - materials[336] = "minecraft:brick"; - materials[337] = "minecraft:clay_ball"; - materials[338] = "minecraft:reeds"; - materials[339] = "minecraft:paper"; - materials[340] = "minecraft:book"; - materials[341] = "minecraft:slime_ball"; - materials[342] = "minecraft:chest_minecart"; - materials[343] = "minecraft:furnace_minecart"; - materials[344] = "minecraft:egg"; - materials[345] = "minecraft:compass"; - materials[346] = "minecraft:fishing_rod"; - materials[347] = "minecraft:clock"; - materials[348] = "minecraft:glowstone_dust"; - materials[349] = "minecraft:fish"; - materials[350] = "minecraft:cooked_fish"; // Paper - cooked_fished -> cooked_fish - materials[351] = "minecraft:dye"; - materials[352] = "minecraft:bone"; - materials[353] = "minecraft:sugar"; - materials[354] = "minecraft:cake"; - materials[355] = "minecraft:bed"; - materials[356] = "minecraft:repeater"; - materials[357] = "minecraft:cookie"; - materials[358] = "minecraft:filled_map"; - materials[359] = "minecraft:shears"; - materials[360] = "minecraft:melon"; - materials[361] = "minecraft:pumpkin_seeds"; - materials[362] = "minecraft:melon_seeds"; - materials[363] = "minecraft:beef"; - materials[364] = "minecraft:cooked_beef"; - materials[365] = "minecraft:chicken"; - materials[366] = "minecraft:cooked_chicken"; - materials[367] = "minecraft:rotten_flesh"; - materials[368] = "minecraft:ender_pearl"; - materials[369] = "minecraft:blaze_rod"; - materials[370] = "minecraft:ghast_tear"; - materials[371] = "minecraft:gold_nugget"; - materials[372] = "minecraft:nether_wart"; - materials[373] = "minecraft:potion"; - materials[374] = "minecraft:glass_bottle"; - materials[375] = "minecraft:spider_eye"; - materials[376] = "minecraft:fermented_spider_eye"; - materials[377] = "minecraft:blaze_powder"; - materials[378] = "minecraft:magma_cream"; - materials[379] = "minecraft:brewing_stand"; - materials[380] = "minecraft:cauldron"; - materials[381] = "minecraft:ender_eye"; - materials[382] = "minecraft:speckled_melon"; - materials[383] = "minecraft:spawn_egg"; - materials[384] = "minecraft:experience_bottle"; - materials[385] = "minecraft:fire_charge"; - materials[386] = "minecraft:writable_book"; - materials[387] = "minecraft:written_book"; - materials[388] = "minecraft:emerald"; - materials[389] = "minecraft:item_frame"; - materials[390] = "minecraft:flower_pot"; - materials[391] = "minecraft:carrot"; - materials[392] = "minecraft:potato"; - materials[393] = "minecraft:baked_potato"; - materials[394] = "minecraft:poisonous_potato"; - materials[395] = "minecraft:map"; - materials[396] = "minecraft:golden_carrot"; - materials[397] = "minecraft:skull"; - materials[398] = "minecraft:carrot_on_a_stick"; - materials[399] = "minecraft:nether_star"; - materials[400] = "minecraft:pumpkin_pie"; - materials[401] = "minecraft:fireworks"; - materials[402] = "minecraft:firework_charge"; - materials[403] = "minecraft:enchanted_book"; - materials[404] = "minecraft:comparator"; - materials[405] = "minecraft:netherbrick"; - materials[406] = "minecraft:quartz"; - materials[407] = "minecraft:tnt_minecart"; - materials[408] = "minecraft:hopper_minecart"; - materials[417] = "minecraft:iron_horse_armor"; - materials[418] = "minecraft:golden_horse_armor"; - materials[419] = "minecraft:diamond_horse_armor"; - materials[420] = "minecraft:lead"; - materials[421] = "minecraft:name_tag"; - materials[422] = "minecraft:command_block_minecart"; - materials[2256] = "minecraft:record_13"; - materials[2257] = "minecraft:record_cat"; - materials[2258] = "minecraft:record_blocks"; - materials[2259] = "minecraft:record_chirp"; - materials[2260] = "minecraft:record_far"; - materials[2261] = "minecraft:record_mall"; - materials[2262] = "minecraft:record_mellohi"; - materials[2263] = "minecraft:record_stal"; - materials[2264] = "minecraft:record_strad"; - materials[2265] = "minecraft:record_ward"; - materials[2266] = "minecraft:record_11"; - materials[2267] = "minecraft:record_wait"; - // Paper start - materials[409] = "minecraft:prismarine_shard"; - materials[410] = "minecraft:prismarine_crystals"; - materials[411] = "minecraft:rabbit"; - materials[412] = "minecraft:cooked_rabbit"; - materials[413] = "minecraft:rabbit_stew"; - materials[414] = "minecraft:rabbit_foot"; - materials[415] = "minecraft:rabbit_hide"; - materials[416] = "minecraft:armor_stand"; - materials[423] = "minecraft:mutton"; - materials[424] = "minecraft:cooked_mutton"; - materials[425] = "minecraft:banner"; - materials[426] = "minecraft:end_crystal"; - materials[427] = "minecraft:spruce_door"; - materials[428] = "minecraft:birch_door"; - materials[429] = "minecraft:jungle_door"; - materials[430] = "minecraft:acacia_door"; - materials[431] = "minecraft:dark_oak_door"; - materials[432] = "minecraft:chorus_fruit"; - materials[433] = "minecraft:chorus_fruit_popped"; - materials[434] = "minecraft:beetroot"; - materials[435] = "minecraft:beetroot_seeds"; - materials[436] = "minecraft:beetroot_soup"; - materials[437] = "minecraft:dragon_breath"; - materials[438] = "minecraft:splash_potion"; - materials[439] = "minecraft:spectral_arrow"; - materials[440] = "minecraft:tipped_arrow"; - materials[441] = "minecraft:lingering_potion"; - materials[442] = "minecraft:shield"; - materials[443] = "minecraft:elytra"; - materials[444] = "minecraft:spruce_boat"; - materials[445] = "minecraft:birch_boat"; - materials[446] = "minecraft:jungle_boat"; - materials[447] = "minecraft:acacia_boat"; - materials[448] = "minecraft:dark_oak_boat"; - materials[449] = "minecraft:totem_of_undying"; - materials[450] = "minecraft:shulker_shell"; - materials[452] = "minecraft:iron_nugget"; - materials[453] = "minecraft:knowledge_book"; - // Paper end - } - } - - private static class DataConverterArmorStand implements DataConverter { - - DataConverterArmorStand() { - } - - public int getDataVersion() { - return 147; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("ArmorStand".equals(cmp.getString("id")) && cmp.getBoolean("Silent") && !cmp.getBoolean("Marker")) { - cmp.remove("Silent"); - } - - return cmp; - } - } - - private static class DataConverterBanner implements DataConverter { - - DataConverterBanner() { - } - - public int getDataVersion() { - return 804; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:banner".equals(cmp.getString("id")) && cmp.contains("tag", 10)) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - - if (nbttagcompound1.contains("BlockEntityTag", 10)) { - CompoundTag nbttagcompound2 = nbttagcompound1.getCompound("BlockEntityTag"); - - if (nbttagcompound2.contains("Base", 99)) { - cmp.putShort("Damage", (short) (nbttagcompound2.getShort("Base") & 15)); - if (nbttagcompound1.contains("display", 10)) { - CompoundTag nbttagcompound3 = nbttagcompound1.getCompound("display"); - - if (nbttagcompound3.contains("Lore", 9)) { - ListTag nbttaglist = nbttagcompound3.getList("Lore", 8); - - if (nbttaglist.size() == 1 && "(+NBT)".equals(nbttaglist.getString(0))) { - return cmp; - } - } - } - - nbttagcompound2.remove("Base"); - if (nbttagcompound2.isEmpty()) { - nbttagcompound1.remove("BlockEntityTag"); - } - - if (nbttagcompound1.isEmpty()) { - cmp.remove("tag"); - } - } - } - } - - return cmp; - } - } - - private static class DataConverterPotionId implements DataConverter { - - private static final String[] potions = new String[128]; - - DataConverterPotionId() { - } - - public int getDataVersion() { - return 102; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:potion".equals(cmp.getString("id"))) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - short short0 = cmp.getShort("Damage"); - - if (!nbttagcompound1.contains("Potion", 8)) { - String s = DataConverterPotionId.potions[short0 & 127]; - - nbttagcompound1.putString("Potion", s == null ? "minecraft:water" : s); - cmp.put("tag", nbttagcompound1); - if ((short0 & 16384) == 16384) { - cmp.putString("id", "minecraft:splash_potion"); - } - } - - if (short0 != 0) { - cmp.putShort("Damage", (short) 0); - } - } - - return cmp; - } - - static { - DataConverterPotionId.potions[0] = "minecraft:water"; - DataConverterPotionId.potions[1] = "minecraft:regeneration"; - DataConverterPotionId.potions[2] = "minecraft:swiftness"; - DataConverterPotionId.potions[3] = "minecraft:fire_resistance"; - DataConverterPotionId.potions[4] = "minecraft:poison"; - DataConverterPotionId.potions[5] = "minecraft:healing"; - DataConverterPotionId.potions[6] = "minecraft:night_vision"; - DataConverterPotionId.potions[7] = null; - DataConverterPotionId.potions[8] = "minecraft:weakness"; - DataConverterPotionId.potions[9] = "minecraft:strength"; - DataConverterPotionId.potions[10] = "minecraft:slowness"; - DataConverterPotionId.potions[11] = "minecraft:leaping"; - DataConverterPotionId.potions[12] = "minecraft:harming"; - DataConverterPotionId.potions[13] = "minecraft:water_breathing"; - DataConverterPotionId.potions[14] = "minecraft:invisibility"; - DataConverterPotionId.potions[15] = null; - DataConverterPotionId.potions[16] = "minecraft:awkward"; - DataConverterPotionId.potions[17] = "minecraft:regeneration"; - DataConverterPotionId.potions[18] = "minecraft:swiftness"; - DataConverterPotionId.potions[19] = "minecraft:fire_resistance"; - DataConverterPotionId.potions[20] = "minecraft:poison"; - DataConverterPotionId.potions[21] = "minecraft:healing"; - DataConverterPotionId.potions[22] = "minecraft:night_vision"; - DataConverterPotionId.potions[23] = null; - DataConverterPotionId.potions[24] = "minecraft:weakness"; - DataConverterPotionId.potions[25] = "minecraft:strength"; - DataConverterPotionId.potions[26] = "minecraft:slowness"; - DataConverterPotionId.potions[27] = "minecraft:leaping"; - DataConverterPotionId.potions[28] = "minecraft:harming"; - DataConverterPotionId.potions[29] = "minecraft:water_breathing"; - DataConverterPotionId.potions[30] = "minecraft:invisibility"; - DataConverterPotionId.potions[31] = null; - DataConverterPotionId.potions[32] = "minecraft:thick"; - DataConverterPotionId.potions[33] = "minecraft:strong_regeneration"; - DataConverterPotionId.potions[34] = "minecraft:strong_swiftness"; - DataConverterPotionId.potions[35] = "minecraft:fire_resistance"; - DataConverterPotionId.potions[36] = "minecraft:strong_poison"; - DataConverterPotionId.potions[37] = "minecraft:strong_healing"; - DataConverterPotionId.potions[38] = "minecraft:night_vision"; - DataConverterPotionId.potions[39] = null; - DataConverterPotionId.potions[40] = "minecraft:weakness"; - DataConverterPotionId.potions[41] = "minecraft:strong_strength"; - DataConverterPotionId.potions[42] = "minecraft:slowness"; - DataConverterPotionId.potions[43] = "minecraft:strong_leaping"; - DataConverterPotionId.potions[44] = "minecraft:strong_harming"; - DataConverterPotionId.potions[45] = "minecraft:water_breathing"; - DataConverterPotionId.potions[46] = "minecraft:invisibility"; - DataConverterPotionId.potions[47] = null; - DataConverterPotionId.potions[48] = null; - DataConverterPotionId.potions[49] = "minecraft:strong_regeneration"; - DataConverterPotionId.potions[50] = "minecraft:strong_swiftness"; - DataConverterPotionId.potions[51] = "minecraft:fire_resistance"; - DataConverterPotionId.potions[52] = "minecraft:strong_poison"; - DataConverterPotionId.potions[53] = "minecraft:strong_healing"; - DataConverterPotionId.potions[54] = "minecraft:night_vision"; - DataConverterPotionId.potions[55] = null; - DataConverterPotionId.potions[56] = "minecraft:weakness"; - DataConverterPotionId.potions[57] = "minecraft:strong_strength"; - DataConverterPotionId.potions[58] = "minecraft:slowness"; - DataConverterPotionId.potions[59] = "minecraft:strong_leaping"; - DataConverterPotionId.potions[60] = "minecraft:strong_harming"; - DataConverterPotionId.potions[61] = "minecraft:water_breathing"; - DataConverterPotionId.potions[62] = "minecraft:invisibility"; - DataConverterPotionId.potions[63] = null; - DataConverterPotionId.potions[64] = "minecraft:mundane"; - DataConverterPotionId.potions[65] = "minecraft:long_regeneration"; - DataConverterPotionId.potions[66] = "minecraft:long_swiftness"; - DataConverterPotionId.potions[67] = "minecraft:long_fire_resistance"; - DataConverterPotionId.potions[68] = "minecraft:long_poison"; - DataConverterPotionId.potions[69] = "minecraft:healing"; - DataConverterPotionId.potions[70] = "minecraft:long_night_vision"; - DataConverterPotionId.potions[71] = null; - DataConverterPotionId.potions[72] = "minecraft:long_weakness"; - DataConverterPotionId.potions[73] = "minecraft:long_strength"; - DataConverterPotionId.potions[74] = "minecraft:long_slowness"; - DataConverterPotionId.potions[75] = "minecraft:long_leaping"; - DataConverterPotionId.potions[76] = "minecraft:harming"; - DataConverterPotionId.potions[77] = "minecraft:long_water_breathing"; - DataConverterPotionId.potions[78] = "minecraft:long_invisibility"; - DataConverterPotionId.potions[79] = null; - DataConverterPotionId.potions[80] = "minecraft:awkward"; - DataConverterPotionId.potions[81] = "minecraft:long_regeneration"; - DataConverterPotionId.potions[82] = "minecraft:long_swiftness"; - DataConverterPotionId.potions[83] = "minecraft:long_fire_resistance"; - DataConverterPotionId.potions[84] = "minecraft:long_poison"; - DataConverterPotionId.potions[85] = "minecraft:healing"; - DataConverterPotionId.potions[86] = "minecraft:long_night_vision"; - DataConverterPotionId.potions[87] = null; - DataConverterPotionId.potions[88] = "minecraft:long_weakness"; - DataConverterPotionId.potions[89] = "minecraft:long_strength"; - DataConverterPotionId.potions[90] = "minecraft:long_slowness"; - DataConverterPotionId.potions[91] = "minecraft:long_leaping"; - DataConverterPotionId.potions[92] = "minecraft:harming"; - DataConverterPotionId.potions[93] = "minecraft:long_water_breathing"; - DataConverterPotionId.potions[94] = "minecraft:long_invisibility"; - DataConverterPotionId.potions[95] = null; - DataConverterPotionId.potions[96] = "minecraft:thick"; - DataConverterPotionId.potions[97] = "minecraft:regeneration"; - DataConverterPotionId.potions[98] = "minecraft:swiftness"; - DataConverterPotionId.potions[99] = "minecraft:long_fire_resistance"; - DataConverterPotionId.potions[100] = "minecraft:poison"; - DataConverterPotionId.potions[101] = "minecraft:strong_healing"; - DataConverterPotionId.potions[102] = "minecraft:long_night_vision"; - DataConverterPotionId.potions[103] = null; - DataConverterPotionId.potions[104] = "minecraft:long_weakness"; - DataConverterPotionId.potions[105] = "minecraft:strength"; - DataConverterPotionId.potions[106] = "minecraft:long_slowness"; - DataConverterPotionId.potions[107] = "minecraft:leaping"; - DataConverterPotionId.potions[108] = "minecraft:strong_harming"; - DataConverterPotionId.potions[109] = "minecraft:long_water_breathing"; - DataConverterPotionId.potions[110] = "minecraft:long_invisibility"; - DataConverterPotionId.potions[111] = null; - DataConverterPotionId.potions[112] = null; - DataConverterPotionId.potions[113] = "minecraft:regeneration"; - DataConverterPotionId.potions[114] = "minecraft:swiftness"; - DataConverterPotionId.potions[115] = "minecraft:long_fire_resistance"; - DataConverterPotionId.potions[116] = "minecraft:poison"; - DataConverterPotionId.potions[117] = "minecraft:strong_healing"; - DataConverterPotionId.potions[118] = "minecraft:long_night_vision"; - DataConverterPotionId.potions[119] = null; - DataConverterPotionId.potions[120] = "minecraft:long_weakness"; - DataConverterPotionId.potions[121] = "minecraft:strength"; - DataConverterPotionId.potions[122] = "minecraft:long_slowness"; - DataConverterPotionId.potions[123] = "minecraft:leaping"; - DataConverterPotionId.potions[124] = "minecraft:strong_harming"; - DataConverterPotionId.potions[125] = "minecraft:long_water_breathing"; - DataConverterPotionId.potions[126] = "minecraft:long_invisibility"; - DataConverterPotionId.potions[127] = null; - } - } - - private static class DataConverterSpawnEgg implements DataConverter { - - private static final String[] eggs = new String[256]; - - DataConverterSpawnEgg() { - } - - public int getDataVersion() { - return 105; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:spawn_egg".equals(cmp.getString("id"))) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - CompoundTag nbttagcompound2 = nbttagcompound1.getCompound("EntityTag"); - short short0 = cmp.getShort("Damage"); - - if (!nbttagcompound2.contains("id", 8)) { - String s = DataConverterSpawnEgg.eggs[short0 & 255]; - - if (s != null) { - nbttagcompound2.putString("id", s); - nbttagcompound1.put("EntityTag", nbttagcompound2); - cmp.put("tag", nbttagcompound1); - } - } - - if (short0 != 0) { - cmp.putShort("Damage", (short) 0); - } - } - - return cmp; - } - - static { - - DataConverterSpawnEgg.eggs[1] = "Item"; - DataConverterSpawnEgg.eggs[2] = "XPOrb"; - DataConverterSpawnEgg.eggs[7] = "ThrownEgg"; - DataConverterSpawnEgg.eggs[8] = "LeashKnot"; - DataConverterSpawnEgg.eggs[9] = "Painting"; - DataConverterSpawnEgg.eggs[10] = "Arrow"; - DataConverterSpawnEgg.eggs[11] = "Snowball"; - DataConverterSpawnEgg.eggs[12] = "Fireball"; - DataConverterSpawnEgg.eggs[13] = "SmallFireball"; - DataConverterSpawnEgg.eggs[14] = "ThrownEnderpearl"; - DataConverterSpawnEgg.eggs[15] = "EyeOfEnderSignal"; - DataConverterSpawnEgg.eggs[16] = "ThrownPotion"; - DataConverterSpawnEgg.eggs[17] = "ThrownExpBottle"; - DataConverterSpawnEgg.eggs[18] = "ItemFrame"; - DataConverterSpawnEgg.eggs[19] = "WitherSkull"; - DataConverterSpawnEgg.eggs[20] = "PrimedTnt"; - DataConverterSpawnEgg.eggs[21] = "FallingSand"; - DataConverterSpawnEgg.eggs[22] = "FireworksRocketEntity"; - DataConverterSpawnEgg.eggs[23] = "TippedArrow"; - DataConverterSpawnEgg.eggs[24] = "SpectralArrow"; - DataConverterSpawnEgg.eggs[25] = "ShulkerBullet"; - DataConverterSpawnEgg.eggs[26] = "DragonFireball"; - DataConverterSpawnEgg.eggs[30] = "ArmorStand"; - DataConverterSpawnEgg.eggs[41] = "Boat"; - DataConverterSpawnEgg.eggs[42] = "MinecartRideable"; - DataConverterSpawnEgg.eggs[43] = "MinecartChest"; - DataConverterSpawnEgg.eggs[44] = "MinecartFurnace"; - DataConverterSpawnEgg.eggs[45] = "MinecartTNT"; - DataConverterSpawnEgg.eggs[46] = "MinecartHopper"; - DataConverterSpawnEgg.eggs[47] = "MinecartSpawner"; - DataConverterSpawnEgg.eggs[40] = "MinecartCommandBlock"; - DataConverterSpawnEgg.eggs[48] = "Mob"; - DataConverterSpawnEgg.eggs[49] = "Monster"; - DataConverterSpawnEgg.eggs[50] = "Creeper"; - DataConverterSpawnEgg.eggs[51] = "Skeleton"; - DataConverterSpawnEgg.eggs[52] = "Spider"; - DataConverterSpawnEgg.eggs[53] = "Giant"; - DataConverterSpawnEgg.eggs[54] = "Zombie"; - DataConverterSpawnEgg.eggs[55] = "Slime"; - DataConverterSpawnEgg.eggs[56] = "Ghast"; - DataConverterSpawnEgg.eggs[57] = "PigZombie"; - DataConverterSpawnEgg.eggs[58] = "Enderman"; - DataConverterSpawnEgg.eggs[59] = "CaveSpider"; - DataConverterSpawnEgg.eggs[60] = "Silverfish"; - DataConverterSpawnEgg.eggs[61] = "Blaze"; - DataConverterSpawnEgg.eggs[62] = "LavaSlime"; - DataConverterSpawnEgg.eggs[63] = "EnderDragon"; - DataConverterSpawnEgg.eggs[64] = "WitherBoss"; - DataConverterSpawnEgg.eggs[65] = "Bat"; - DataConverterSpawnEgg.eggs[66] = "Witch"; - DataConverterSpawnEgg.eggs[67] = "Endermite"; - DataConverterSpawnEgg.eggs[68] = "Guardian"; - DataConverterSpawnEgg.eggs[69] = "Shulker"; - DataConverterSpawnEgg.eggs[90] = "Pig"; - DataConverterSpawnEgg.eggs[91] = "Sheep"; - DataConverterSpawnEgg.eggs[92] = "Cow"; - DataConverterSpawnEgg.eggs[93] = "Chicken"; - DataConverterSpawnEgg.eggs[94] = "Squid"; - DataConverterSpawnEgg.eggs[95] = "Wolf"; - DataConverterSpawnEgg.eggs[96] = "MushroomCow"; - DataConverterSpawnEgg.eggs[97] = "SnowMan"; - DataConverterSpawnEgg.eggs[98] = "Ozelot"; - DataConverterSpawnEgg.eggs[99] = "VillagerGolem"; - DataConverterSpawnEgg.eggs[100] = "EntityHorse"; - DataConverterSpawnEgg.eggs[101] = "Rabbit"; - DataConverterSpawnEgg.eggs[120] = "Villager"; - DataConverterSpawnEgg.eggs[200] = "EnderCrystal"; - } - } - - private static class DataConverterMinecart implements DataConverter { - - private static final List a = Lists.newArrayList("MinecartRideable", "MinecartChest", "MinecartFurnace", "MinecartTNT", "MinecartSpawner", "MinecartHopper", "MinecartCommandBlock"); - - DataConverterMinecart() { - } - - public int getDataVersion() { - return 106; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("Minecart".equals(cmp.getString("id"))) { - String s = "MinecartRideable"; - int i = cmp.getInt("Type"); - - if (i > 0 && i < DataConverterMinecart.a.size()) { - s = DataConverterMinecart.a.get(i); - } - - cmp.putString("id", s); - cmp.remove("Type"); - } - - return cmp; - } - } - - private static class DataConverterMobSpawner implements DataConverter { - - DataConverterMobSpawner() { - } - - public int getDataVersion() { - return 107; - } - - public CompoundTag convert(CompoundTag cmp) { - if (!"MobSpawner".equals(cmp.getString("id"))) { - return cmp; - } else { - if (cmp.contains("EntityId", 8)) { - String s = cmp.getString("EntityId"); - CompoundTag nbttagcompound1 = cmp.getCompound("SpawnData"); - - nbttagcompound1.putString("id", s.isEmpty() ? "Pig" : s); - cmp.put("SpawnData", nbttagcompound1); - cmp.remove("EntityId"); - } - - if (cmp.contains("SpawnPotentials", 9)) { - ListTag nbttaglist = cmp.getList("SpawnPotentials", 10); - - for (int i = 0; i < nbttaglist.size(); ++i) { - CompoundTag nbttagcompound2 = nbttaglist.getCompound(i); - - if (nbttagcompound2.contains("Type", 8)) { - CompoundTag nbttagcompound3 = nbttagcompound2.getCompound("Properties"); - - nbttagcompound3.putString("id", nbttagcompound2.getString("Type")); - nbttagcompound2.put("Entity", nbttagcompound3); - nbttagcompound2.remove("Type"); - nbttagcompound2.remove("Properties"); - } - } - } - - return cmp; - } - } - } - - private static class DataConverterUUID implements DataConverter { - - DataConverterUUID() { - } - - public int getDataVersion() { - return 108; - } - - public CompoundTag convert(CompoundTag cmp) { - if (cmp.contains("UUID", 8)) { - cmp.putUUID("UUID", UUID.fromString(cmp.getString("UUID"))); - } - - return cmp; - } - } - - private static class DataConverterHealth implements DataConverter { - - private static final Set a = Sets.newHashSet("ArmorStand", "Bat", "Blaze", "CaveSpider", "Chicken", "Cow", "Creeper", "EnderDragon", "Enderman", "Endermite", "EntityHorse", "Ghast", "Giant", "Guardian", "LavaSlime", "MushroomCow", "Ozelot", "Pig", "PigZombie", "Rabbit", "Sheep", "Shulker", "Silverfish", "Skeleton", "Slime", "SnowMan", "Spider", "Squid", "Villager", "VillagerGolem", "Witch", "WitherBoss", "Wolf", "Zombie"); - - DataConverterHealth() { - } - - public int getDataVersion() { - return 109; - } - - public CompoundTag convert(CompoundTag cmp) { - if (DataConverterHealth.a.contains(cmp.getString("id"))) { - float f; - - if (cmp.contains("HealF", 99)) { - f = cmp.getFloat("HealF"); - cmp.remove("HealF"); - } else { - if (!cmp.contains("Health", 99)) { - return cmp; - } - - f = cmp.getFloat("Health"); - } - - cmp.putFloat("Health", f); - } - - return cmp; - } - } - - private static class DataConverterSaddle implements DataConverter { - - DataConverterSaddle() { - } - - public int getDataVersion() { - return 110; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("EntityHorse".equals(cmp.getString("id")) && !cmp.contains("SaddleItem", 10) && cmp.getBoolean("Saddle")) { - CompoundTag nbttagcompound1 = new CompoundTag(); - - nbttagcompound1.putString("id", "minecraft:saddle"); - nbttagcompound1.putByte("Count", (byte) 1); - nbttagcompound1.putShort("Damage", (short) 0); - cmp.put("SaddleItem", nbttagcompound1); - cmp.remove("Saddle"); - } - - return cmp; - } - } - - private static class DataConverterHanging implements DataConverter { - - DataConverterHanging() { - } - - public int getDataVersion() { - return 111; - } - - public CompoundTag convert(CompoundTag cmp) { - String s = cmp.getString("id"); - boolean flag = "Painting".equals(s); - boolean flag1 = "ItemFrame".equals(s); - - if ((flag || flag1) && !cmp.contains("Facing", 99)) { - Direction enumdirection; - - if (cmp.contains("Direction", 99)) { - enumdirection = Direction.from2DDataValue(cmp.getByte("Direction")); - cmp.putInt("TileX", cmp.getInt("TileX") + enumdirection.getStepX()); - cmp.putInt("TileY", cmp.getInt("TileY") + enumdirection.getStepY()); - cmp.putInt("TileZ", cmp.getInt("TileZ") + enumdirection.getStepZ()); - cmp.remove("Direction"); - if (flag1 && cmp.contains("ItemRotation", 99)) { - cmp.putByte("ItemRotation", (byte) (cmp.getByte("ItemRotation") * 2)); - } - } else { - enumdirection = Direction.from2DDataValue(cmp.getByte("Dir")); - cmp.remove("Dir"); - } - - cmp.putByte("Facing", (byte) enumdirection.get2DDataValue()); - } - - return cmp; - } - } - - private static class DataConverterDropChances implements DataConverter { - - DataConverterDropChances() { - } - - public int getDataVersion() { - return 113; - } - - public CompoundTag convert(CompoundTag cmp) { - ListTag nbttaglist; - - if (cmp.contains("HandDropChances", 9)) { - nbttaglist = cmp.getList("HandDropChances", 5); - if (nbttaglist.size() == 2 && nbttaglist.getFloat(0) == 0.0F && nbttaglist.getFloat(1) == 0.0F) { - cmp.remove("HandDropChances"); - } - } - - if (cmp.contains("ArmorDropChances", 9)) { - nbttaglist = cmp.getList("ArmorDropChances", 5); - if (nbttaglist.size() == 4 && nbttaglist.getFloat(0) == 0.0F && nbttaglist.getFloat(1) == 0.0F && nbttaglist.getFloat(2) == 0.0F && nbttaglist.getFloat(3) == 0.0F) { - cmp.remove("ArmorDropChances"); - } - } - - return cmp; - } - } - - private static class DataConverterRiding implements DataConverter { - - DataConverterRiding() { - } - - public int getDataVersion() { - return 135; - } - - public CompoundTag convert(CompoundTag cmp) { - while (cmp.contains("Riding", 10)) { - CompoundTag nbttagcompound1 = this.b(cmp); - - this.convert(cmp, nbttagcompound1); - cmp = nbttagcompound1; - } - - return cmp; - } - - protected void convert(CompoundTag nbttagcompound, CompoundTag nbttagcompound1) { - ListTag nbttaglist = new ListTag(); - - nbttaglist.add(nbttagcompound); - nbttagcompound1.put("Passengers", nbttaglist); - } - - protected CompoundTag b(CompoundTag nbttagcompound) { - CompoundTag nbttagcompound1 = nbttagcompound.getCompound("Riding"); - - nbttagcompound.remove("Riding"); - return nbttagcompound1; - } - } - - private static class DataConverterBook implements DataConverter { - - DataConverterBook() { - } - - public int getDataVersion() { - return 165; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:written_book".equals(cmp.getString("id"))) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - - if (nbttagcompound1.contains("pages", 9)) { - ListTag nbttaglist = nbttagcompound1.getList("pages", 8); - - for (int i = 0; i < nbttaglist.size(); ++i) { - String s = nbttaglist.getString(i); - Component object = null; - - if (!"null".equals(s) && !StringUtil.isNullOrEmpty(s)) { - if ((s.charAt(0) != 34 || s.charAt(s.length() - 1) != 34) && (s.charAt(0) != 123 || s.charAt(s.length() - 1) != 125)) { - object = new TextComponent(s); - } else { - try { - object = GsonHelper.fromJson(DataConverterSignText.a, s, Component.class, true); - if (object == null) { - object = new TextComponent(""); - } - } catch (JsonParseException jsonparseexception) { - ; - } - - if (object == null) { - try { - object = Component.Serializer.fromJson(s); - } catch (JsonParseException jsonparseexception1) { - ; - } - } - - if (object == null) { - try { - object = Component.Serializer.fromJsonLenient(s); - } catch (JsonParseException jsonparseexception2) { - ; - } - } - - if (object == null) { - object = new TextComponent(s); - } - } - } else { - object = new TextComponent(""); - } - - nbttaglist.set(i, StringTag.valueOf(Component.Serializer.toJson(object))); - } - - nbttagcompound1.put("pages", nbttaglist); - } - } - - return cmp; - } - } - - private static class DataConverterCookedFish implements DataConverter { - - private static final ResourceLocation a = new ResourceLocation("cooked_fished"); - - DataConverterCookedFish() { - } - - public int getDataVersion() { - return 502; - } - - public CompoundTag convert(CompoundTag cmp) { - if (cmp.contains("id", 8) && DataConverterCookedFish.a.equals(new ResourceLocation(cmp.getString("id")))) { - cmp.putString("id", "minecraft:cooked_fish"); - } - - return cmp; - } - } - - private static class DataConverterZombie implements DataConverter { - - private static final Random a = new Random(); - - DataConverterZombie() { - } - - public int getDataVersion() { - return 502; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("Zombie".equals(cmp.getString("id")) && cmp.getBoolean("IsVillager")) { - if (!cmp.contains("ZombieType", 99)) { - int i = -1; - - if (cmp.contains("VillagerProfession", 99)) { - try { - i = this.convert(cmp.getInt("VillagerProfession")); - } catch (RuntimeException runtimeexception) { - ; - } - } - - if (i == -1) { - i = this.convert(DataConverterZombie.a.nextInt(6)); - } - - cmp.putInt("ZombieType", i); - } - - cmp.remove("IsVillager"); - } - - return cmp; - } - - private int convert(int i) { - return i >= 0 && i < 6 ? i : -1; - } - } - - private static class DataConverterVBO implements DataConverter { - - DataConverterVBO() { - } - - public int getDataVersion() { - return 505; - } - - public CompoundTag convert(CompoundTag cmp) { - cmp.putString("useVbo", "true"); - return cmp; - } - } - - private static class DataConverterGuardian implements DataConverter { - - DataConverterGuardian() { - } - - public int getDataVersion() { - return 700; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("Guardian".equals(cmp.getString("id"))) { - if (cmp.getBoolean("Elder")) { - cmp.putString("id", "ElderGuardian"); - } - - cmp.remove("Elder"); - } - - return cmp; - } - } - - private static class DataConverterSkeleton implements DataConverter { - - DataConverterSkeleton() { - } - - public int getDataVersion() { - return 701; - } - - public CompoundTag convert(CompoundTag cmp) { - String s = cmp.getString("id"); - - if ("Skeleton".equals(s)) { - int i = cmp.getInt("SkeletonType"); - - if (i == 1) { - cmp.putString("id", "WitherSkeleton"); - } else if (i == 2) { - cmp.putString("id", "Stray"); - } - - cmp.remove("SkeletonType"); - } - - return cmp; - } - } - - private static class DataConverterZombieType implements DataConverter { - - DataConverterZombieType() { - } - - public int getDataVersion() { - return 702; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("Zombie".equals(cmp.getString("id"))) { - int i = cmp.getInt("ZombieType"); - - switch (i) { - case 0: - default: - break; - - case 1: - case 2: - case 3: - case 4: - case 5: - cmp.putString("id", "ZombieVillager"); - cmp.putInt("Profession", i - 1); - break; - - case 6: - cmp.putString("id", "Husk"); - } - - cmp.remove("ZombieType"); - } - - return cmp; - } - } - - private static class DataConverterHorse implements DataConverter { - - DataConverterHorse() { - } - - public int getDataVersion() { - return 703; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("EntityHorse".equals(cmp.getString("id"))) { - int i = cmp.getInt("Type"); - - switch (i) { - case 0: - default: - cmp.putString("id", "Horse"); - break; - - case 1: - cmp.putString("id", "Donkey"); - break; - - case 2: - cmp.putString("id", "Mule"); - break; - - case 3: - cmp.putString("id", "ZombieHorse"); - break; - - case 4: - cmp.putString("id", "SkeletonHorse"); - } - - cmp.remove("Type"); - } - - return cmp; - } - } - - private static class DataConverterTileEntity implements DataConverter { - - private static final Map a = Maps.newHashMap(); - - DataConverterTileEntity() { - } - - public int getDataVersion() { - return 704; - } - - public CompoundTag convert(CompoundTag cmp) { - String s = DataConverterTileEntity.a.get(cmp.getString("id")); - - if (s != null) { - cmp.putString("id", s); - } - - return cmp; - } - - static { - DataConverterTileEntity.a.put("Airportal", "minecraft:end_portal"); - DataConverterTileEntity.a.put("Banner", "minecraft:banner"); - DataConverterTileEntity.a.put("Beacon", "minecraft:beacon"); - DataConverterTileEntity.a.put("Cauldron", "minecraft:brewing_stand"); - DataConverterTileEntity.a.put("Chest", "minecraft:chest"); - DataConverterTileEntity.a.put("Comparator", "minecraft:comparator"); - DataConverterTileEntity.a.put("Control", "minecraft:command_block"); - DataConverterTileEntity.a.put("DLDetector", "minecraft:daylight_detector"); - DataConverterTileEntity.a.put("Dropper", "minecraft:dropper"); - DataConverterTileEntity.a.put("EnchantTable", "minecraft:enchanting_table"); - DataConverterTileEntity.a.put("EndGateway", "minecraft:end_gateway"); - DataConverterTileEntity.a.put("EnderChest", "minecraft:ender_chest"); - DataConverterTileEntity.a.put("FlowerPot", "minecraft:flower_pot"); - DataConverterTileEntity.a.put("Furnace", "minecraft:furnace"); - DataConverterTileEntity.a.put("Hopper", "minecraft:hopper"); - DataConverterTileEntity.a.put("MobSpawner", "minecraft:mob_spawner"); - DataConverterTileEntity.a.put("Music", "minecraft:noteblock"); - DataConverterTileEntity.a.put("Piston", "minecraft:piston"); - DataConverterTileEntity.a.put("RecordPlayer", "minecraft:jukebox"); - DataConverterTileEntity.a.put("Sign", "minecraft:sign"); - DataConverterTileEntity.a.put("Skull", "minecraft:skull"); - DataConverterTileEntity.a.put("Structure", "minecraft:structure_block"); - DataConverterTileEntity.a.put("Trap", "minecraft:dispenser"); - } - } - - private static class DataConverterEntity implements DataConverter { - - private static final Map a = Maps.newHashMap(); - - DataConverterEntity() { - } - - public int getDataVersion() { - return 704; - } - - public CompoundTag convert(CompoundTag cmp) { - String s = DataConverterEntity.a.get(cmp.getString("id")); - - if (s != null) { - cmp.putString("id", s); - } - - return cmp; - } - - static { - DataConverterEntity.a.put("AreaEffectCloud", "minecraft:area_effect_cloud"); - DataConverterEntity.a.put("ArmorStand", "minecraft:armor_stand"); - DataConverterEntity.a.put("Arrow", "minecraft:arrow"); - DataConverterEntity.a.put("Bat", "minecraft:bat"); - DataConverterEntity.a.put("Blaze", "minecraft:blaze"); - DataConverterEntity.a.put("Boat", "minecraft:boat"); - DataConverterEntity.a.put("CaveSpider", "minecraft:cave_spider"); - DataConverterEntity.a.put("Chicken", "minecraft:chicken"); - DataConverterEntity.a.put("Cow", "minecraft:cow"); - DataConverterEntity.a.put("Creeper", "minecraft:creeper"); - DataConverterEntity.a.put("Donkey", "minecraft:donkey"); - DataConverterEntity.a.put("DragonFireball", "minecraft:dragon_fireball"); - DataConverterEntity.a.put("ElderGuardian", "minecraft:elder_guardian"); - DataConverterEntity.a.put("EnderCrystal", "minecraft:ender_crystal"); - DataConverterEntity.a.put("EnderDragon", "minecraft:ender_dragon"); - DataConverterEntity.a.put("Enderman", "minecraft:enderman"); - DataConverterEntity.a.put("Endermite", "minecraft:endermite"); - DataConverterEntity.a.put("EyeOfEnderSignal", "minecraft:eye_of_ender_signal"); - DataConverterEntity.a.put("FallingSand", "minecraft:falling_block"); - DataConverterEntity.a.put("Fireball", "minecraft:fireball"); - DataConverterEntity.a.put("FireworksRocketEntity", "minecraft:fireworks_rocket"); - DataConverterEntity.a.put("Ghast", "minecraft:ghast"); - DataConverterEntity.a.put("Giant", "minecraft:giant"); - DataConverterEntity.a.put("Guardian", "minecraft:guardian"); - DataConverterEntity.a.put("Horse", "minecraft:horse"); - DataConverterEntity.a.put("Husk", "minecraft:husk"); - DataConverterEntity.a.put("Item", "minecraft:item"); - DataConverterEntity.a.put("ItemFrame", "minecraft:item_frame"); - DataConverterEntity.a.put("LavaSlime", "minecraft:magma_cube"); - DataConverterEntity.a.put("LeashKnot", "minecraft:leash_knot"); - DataConverterEntity.a.put("MinecartChest", "minecraft:chest_minecart"); - DataConverterEntity.a.put("MinecartCommandBlock", "minecraft:commandblock_minecart"); - DataConverterEntity.a.put("MinecartFurnace", "minecraft:furnace_minecart"); - DataConverterEntity.a.put("MinecartHopper", "minecraft:hopper_minecart"); - DataConverterEntity.a.put("MinecartRideable", "minecraft:minecart"); - DataConverterEntity.a.put("MinecartSpawner", "minecraft:spawner_minecart"); - DataConverterEntity.a.put("MinecartTNT", "minecraft:tnt_minecart"); - DataConverterEntity.a.put("Mule", "minecraft:mule"); - DataConverterEntity.a.put("MushroomCow", "minecraft:mooshroom"); - DataConverterEntity.a.put("Ozelot", "minecraft:ocelot"); - DataConverterEntity.a.put("Painting", "minecraft:painting"); - DataConverterEntity.a.put("Pig", "minecraft:pig"); - DataConverterEntity.a.put("PigZombie", "minecraft:zombie_pigman"); - DataConverterEntity.a.put("PolarBear", "minecraft:polar_bear"); - DataConverterEntity.a.put("PrimedTnt", "minecraft:tnt"); - DataConverterEntity.a.put("Rabbit", "minecraft:rabbit"); - DataConverterEntity.a.put("Sheep", "minecraft:sheep"); - DataConverterEntity.a.put("Shulker", "minecraft:shulker"); - DataConverterEntity.a.put("ShulkerBullet", "minecraft:shulker_bullet"); - DataConverterEntity.a.put("Silverfish", "minecraft:silverfish"); - DataConverterEntity.a.put("Skeleton", "minecraft:skeleton"); - DataConverterEntity.a.put("SkeletonHorse", "minecraft:skeleton_horse"); - DataConverterEntity.a.put("Slime", "minecraft:slime"); - DataConverterEntity.a.put("SmallFireball", "minecraft:small_fireball"); - DataConverterEntity.a.put("SnowMan", "minecraft:snowman"); - DataConverterEntity.a.put("Snowball", "minecraft:snowball"); - DataConverterEntity.a.put("SpectralArrow", "minecraft:spectral_arrow"); - DataConverterEntity.a.put("Spider", "minecraft:spider"); - DataConverterEntity.a.put("Squid", "minecraft:squid"); - DataConverterEntity.a.put("Stray", "minecraft:stray"); - DataConverterEntity.a.put("ThrownEgg", "minecraft:egg"); - DataConverterEntity.a.put("ThrownEnderpearl", "minecraft:ender_pearl"); - DataConverterEntity.a.put("ThrownExpBottle", "minecraft:xp_bottle"); - DataConverterEntity.a.put("ThrownPotion", "minecraft:potion"); - DataConverterEntity.a.put("Villager", "minecraft:villager"); - DataConverterEntity.a.put("VillagerGolem", "minecraft:villager_golem"); - DataConverterEntity.a.put("Witch", "minecraft:witch"); - DataConverterEntity.a.put("WitherBoss", "minecraft:wither"); - DataConverterEntity.a.put("WitherSkeleton", "minecraft:wither_skeleton"); - DataConverterEntity.a.put("WitherSkull", "minecraft:wither_skull"); - DataConverterEntity.a.put("Wolf", "minecraft:wolf"); - DataConverterEntity.a.put("XPOrb", "minecraft:xp_orb"); - DataConverterEntity.a.put("Zombie", "minecraft:zombie"); - DataConverterEntity.a.put("ZombieHorse", "minecraft:zombie_horse"); - DataConverterEntity.a.put("ZombieVillager", "minecraft:zombie_villager"); - } - } - - private static class DataConverterPotionWater implements DataConverter { - - DataConverterPotionWater() { - } - - public int getDataVersion() { - return 806; - } - - public CompoundTag convert(CompoundTag cmp) { - String s = cmp.getString("id"); - - if ("minecraft:potion".equals(s) || "minecraft:splash_potion".equals(s) || "minecraft:lingering_potion".equals(s) || "minecraft:tipped_arrow".equals(s)) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - - if (!nbttagcompound1.contains("Potion", 8)) { - nbttagcompound1.putString("Potion", "minecraft:water"); - } - - if (!cmp.contains("tag", 10)) { - cmp.put("tag", nbttagcompound1); - } - } - - return cmp; - } - } - - private static class DataConverterShulker implements DataConverter { - - DataConverterShulker() { - } - - public int getDataVersion() { - return 808; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:shulker".equals(cmp.getString("id")) && !cmp.contains("Color", 99)) { - cmp.putByte("Color", (byte) 10); - } - - return cmp; - } - } - - private static class DataConverterShulkerBoxItem implements DataConverter { - - public static final String[] a = new String[] { "minecraft:white_shulker_box", "minecraft:orange_shulker_box", "minecraft:magenta_shulker_box", "minecraft:light_blue_shulker_box", "minecraft:yellow_shulker_box", "minecraft:lime_shulker_box", "minecraft:pink_shulker_box", "minecraft:gray_shulker_box", "minecraft:silver_shulker_box", "minecraft:cyan_shulker_box", "minecraft:purple_shulker_box", "minecraft:blue_shulker_box", "minecraft:brown_shulker_box", "minecraft:green_shulker_box", "minecraft:red_shulker_box", "minecraft:black_shulker_box" }; - - DataConverterShulkerBoxItem() { - } - - public int getDataVersion() { - return 813; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:shulker_box".equals(cmp.getString("id")) && cmp.contains("tag", 10)) { - CompoundTag nbttagcompound1 = cmp.getCompound("tag"); - - if (nbttagcompound1.contains("BlockEntityTag", 10)) { - CompoundTag nbttagcompound2 = nbttagcompound1.getCompound("BlockEntityTag"); - - if (nbttagcompound2.getList("Items", 10).isEmpty()) { - nbttagcompound2.remove("Items"); - } - - int i = nbttagcompound2.getInt("Color"); - - nbttagcompound2.remove("Color"); - if (nbttagcompound2.isEmpty()) { - nbttagcompound1.remove("BlockEntityTag"); - } - - if (nbttagcompound1.isEmpty()) { - cmp.remove("tag"); - } - - cmp.putString("id", DataConverterShulkerBoxItem.a[i % 16]); - } - } - - return cmp; - } - } - - private static class DataConverterShulkerBoxBlock implements DataConverter { - - DataConverterShulkerBoxBlock() { - } - - public int getDataVersion() { - return 813; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:shulker".equals(cmp.getString("id"))) { - cmp.remove("Color"); - } - - return cmp; - } - } - - private static class DataConverterLang implements DataConverter { - - DataConverterLang() { - } - - public int getDataVersion() { - return 816; - } - - public CompoundTag convert(CompoundTag cmp) { - if (cmp.contains("lang", 8)) { - cmp.putString("lang", cmp.getString("lang").toLowerCase(Locale.ROOT)); - } - - return cmp; - } - } - - private static class DataConverterTotem implements DataConverter { - - DataConverterTotem() { - } - - public int getDataVersion() { - return 820; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:totem".equals(cmp.getString("id"))) { - cmp.putString("id", "minecraft:totem_of_undying"); - } - - return cmp; - } - } - - private static class DataConverterBedBlock implements DataConverter { - - private static final Logger a = LogManager.getLogger(PaperweightDataConverters.class); - - DataConverterBedBlock() { - } - - public int getDataVersion() { - return 1125; - } - - public CompoundTag convert(CompoundTag cmp) { - try { - CompoundTag nbttagcompound1 = cmp.getCompound("Level"); - int i = nbttagcompound1.getInt("xPos"); - int j = nbttagcompound1.getInt("zPos"); - ListTag nbttaglist = nbttagcompound1.getList("TileEntities", 10); - ListTag nbttaglist1 = nbttagcompound1.getList("Sections", 10); - - for (int k = 0; k < nbttaglist1.size(); ++k) { - CompoundTag nbttagcompound2 = nbttaglist1.getCompound(k); - byte b0 = nbttagcompound2.getByte("Y"); - byte[] abyte = nbttagcompound2.getByteArray("Blocks"); - - for (int l = 0; l < abyte.length; ++l) { - if (416 == (abyte[l] & 255) << 4) { - int i1 = l & 15; - int j1 = l >> 8 & 15; - int k1 = l >> 4 & 15; - CompoundTag nbttagcompound3 = new CompoundTag(); - - nbttagcompound3.putString("id", "bed"); - nbttagcompound3.putInt("x", i1 + (i << 4)); - nbttagcompound3.putInt("y", j1 + (b0 << 4)); - nbttagcompound3.putInt("z", k1 + (j << 4)); - nbttaglist.add(nbttagcompound3); - } - } - } - } catch (Exception exception) { - DataConverterBedBlock.a.warn("Unable to datafix Bed blocks, level format may be missing tags."); - } - - return cmp; - } - } - - private static class DataConverterBedItem implements DataConverter { - - DataConverterBedItem() { - } - - public int getDataVersion() { - return 1125; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("minecraft:bed".equals(cmp.getString("id")) && cmp.getShort("Damage") == 0) { - cmp.putShort("Damage", (short) DyeColor.RED.getId()); - } - - return cmp; - } - } - - private static class DataConverterSignText implements DataConverter { - - public static final Gson a = new GsonBuilder().registerTypeAdapter(Component.class, new JsonDeserializer() { - MutableComponent a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { - if (jsonelement.isJsonPrimitive()) { - return new TextComponent(jsonelement.getAsString()); - } else if (jsonelement.isJsonArray()) { - JsonArray jsonarray = jsonelement.getAsJsonArray(); - MutableComponent ichatbasecomponent = null; - Iterator iterator = jsonarray.iterator(); - - while (iterator.hasNext()) { - JsonElement jsonelement1 = (JsonElement) iterator.next(); - MutableComponent ichatbasecomponent1 = this.a(jsonelement1, jsonelement1.getClass(), jsondeserializationcontext); - - if (ichatbasecomponent == null) { - ichatbasecomponent = ichatbasecomponent1; - } else { - ichatbasecomponent.append(ichatbasecomponent1); - } - } - - return ichatbasecomponent; - } else { - throw new JsonParseException("Don't know how to turn " + jsonelement + " into a Component"); - } - } - - public Object deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { - return this.a(jsonelement, type, jsondeserializationcontext); - } - }).create(); - - DataConverterSignText() { - } - - public int getDataVersion() { - return 101; - } - - public CompoundTag convert(CompoundTag cmp) { - if ("Sign".equals(cmp.getString("id"))) { - this.convert(cmp, "Text1"); - this.convert(cmp, "Text2"); - this.convert(cmp, "Text3"); - this.convert(cmp, "Text4"); - } - - return cmp; - } - - private void convert(CompoundTag nbttagcompound, String s) { - String s1 = nbttagcompound.getString(s); - Component object = null; - - if (!"null".equals(s1) && !StringUtil.isNullOrEmpty(s1)) { - if ((s1.charAt(0) != 34 || s1.charAt(s1.length() - 1) != 34) && (s1.charAt(0) != 123 || s1.charAt(s1.length() - 1) != 125)) { - object = new TextComponent(s1); - } else { - try { - object = GsonHelper.fromJson(DataConverterSignText.a, s1, Component.class, true); - if (object == null) { - object = new TextComponent(""); - } - } catch (JsonParseException jsonparseexception) { - ; - } - - if (object == null) { - try { - object = Component.Serializer.fromJson(s1); - } catch (JsonParseException jsonparseexception1) { - ; - } - } - - if (object == null) { - try { - object = Component.Serializer.fromJsonLenient(s1); - } catch (JsonParseException jsonparseexception2) { - ; - } - } - - if (object == null) { - object = new TextComponent(s1); - } - } - } else { - object = new TextComponent(""); - } - - nbttagcompound.putString(s, Component.Serializer.toJson(object)); - } - } - - private static class DataInspectorPlayerVehicle implements DataInspector { - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (cmp.contains("RootVehicle", 10)) { - CompoundTag nbttagcompound1 = cmp.getCompound("RootVehicle"); - - if (nbttagcompound1.contains("Entity", 10)) { - convertCompound(LegacyType.ENTITY, nbttagcompound1, "Entity", sourceVer, targetVer); - } - } - - return cmp; - } - } - - private static class DataInspectorLevelPlayer implements DataInspector { - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (cmp.contains("Player", 10)) { - convertCompound(LegacyType.PLAYER, cmp, "Player", sourceVer, targetVer); - } - - return cmp; - } - } - - private static class DataInspectorStructure implements DataInspector { - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - ListTag nbttaglist; - int j; - CompoundTag nbttagcompound1; - - if (cmp.contains("entities", 9)) { - nbttaglist = cmp.getList("entities", 10); - - for (j = 0; j < nbttaglist.size(); ++j) { - nbttagcompound1 = (CompoundTag) nbttaglist.get(j); - if (nbttagcompound1.contains("nbt", 10)) { - convertCompound(LegacyType.ENTITY, nbttagcompound1, "nbt", sourceVer, targetVer); - } - } - } - - if (cmp.contains("blocks", 9)) { - nbttaglist = cmp.getList("blocks", 10); - - for (j = 0; j < nbttaglist.size(); ++j) { - nbttagcompound1 = (CompoundTag) nbttaglist.get(j); - if (nbttagcompound1.contains("nbt", 10)) { - convertCompound(LegacyType.BLOCK_ENTITY, nbttagcompound1, "nbt", sourceVer, targetVer); - } - } - } - - return cmp; - } - } - - private static class DataInspectorChunks implements DataInspector { - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (cmp.contains("Level", 10)) { - CompoundTag nbttagcompound1 = cmp.getCompound("Level"); - ListTag nbttaglist; - int j; - - if (nbttagcompound1.contains("Entities", 9)) { - nbttaglist = nbttagcompound1.getList("Entities", 10); - - for (j = 0; j < nbttaglist.size(); ++j) { - nbttaglist.set(j, convert(LegacyType.ENTITY, (CompoundTag) nbttaglist.get(j), sourceVer, targetVer)); - } - } - - if (nbttagcompound1.contains("TileEntities", 9)) { - nbttaglist = nbttagcompound1.getList("TileEntities", 10); - - for (j = 0; j < nbttaglist.size(); ++j) { - nbttaglist.set(j, convert(LegacyType.BLOCK_ENTITY, (CompoundTag) nbttaglist.get(j), sourceVer, targetVer)); - } - } - } - - return cmp; - } - } - - private static class DataInspectorEntityPassengers implements DataInspector { - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (cmp.contains("Passengers", 9)) { - ListTag nbttaglist = cmp.getList("Passengers", 10); - - for (int j = 0; j < nbttaglist.size(); ++j) { - nbttaglist.set(j, convert(LegacyType.ENTITY, nbttaglist.getCompound(j), sourceVer, targetVer)); - } - } - - return cmp; - } - } - - private static class DataInspectorPlayer implements DataInspector { - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - convertItems(cmp, "Inventory", sourceVer, targetVer); - convertItems(cmp, "EnderItems", sourceVer, targetVer); - if (cmp.contains("ShoulderEntityLeft", 10)) { - convertCompound(LegacyType.ENTITY, cmp, "ShoulderEntityLeft", sourceVer, targetVer); - } - - if (cmp.contains("ShoulderEntityRight", 10)) { - convertCompound(LegacyType.ENTITY, cmp, "ShoulderEntityRight", sourceVer, targetVer); - } - - return cmp; - } - } - - private static class DataInspectorVillagers implements DataInspector { - ResourceLocation entityVillager = getKey("EntityVillager"); - - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (entityVillager.equals(new ResourceLocation(cmp.getString("id"))) && cmp.contains("Offers", 10)) { - CompoundTag nbttagcompound1 = cmp.getCompound("Offers"); - - if (nbttagcompound1.contains("Recipes", 9)) { - ListTag nbttaglist = nbttagcompound1.getList("Recipes", 10); - - for (int j = 0; j < nbttaglist.size(); ++j) { - CompoundTag nbttagcompound2 = nbttaglist.getCompound(j); - - convertItem(nbttagcompound2, "buy", sourceVer, targetVer); - convertItem(nbttagcompound2, "buyB", sourceVer, targetVer); - convertItem(nbttagcompound2, "sell", sourceVer, targetVer); - nbttaglist.set(j, nbttagcompound2); - } - } - } - - return cmp; - } - } - - private static class DataInspectorMobSpawnerMinecart implements DataInspector { - ResourceLocation entityMinecartMobSpawner = getKey("EntityMinecartMobSpawner"); - ResourceLocation tileEntityMobSpawner = getKey("TileEntityMobSpawner"); - - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - String s = cmp.getString("id"); - if (entityMinecartMobSpawner.equals(new ResourceLocation(s))) { - cmp.putString("id", tileEntityMobSpawner.toString()); - convert(LegacyType.BLOCK_ENTITY, cmp, sourceVer, targetVer); - cmp.putString("id", s); - } - - return cmp; - } - } - - private static class DataInspectorMobSpawnerMobs implements DataInspector { - ResourceLocation tileEntityMobSpawner = getKey("TileEntityMobSpawner"); - - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (tileEntityMobSpawner.equals(new ResourceLocation(cmp.getString("id")))) { - if (cmp.contains("SpawnPotentials", 9)) { - ListTag nbttaglist = cmp.getList("SpawnPotentials", 10); - - for (int j = 0; j < nbttaglist.size(); ++j) { - CompoundTag nbttagcompound1 = nbttaglist.getCompound(j); - - convertCompound(LegacyType.ENTITY, nbttagcompound1, "Entity", sourceVer, targetVer); - } - } - - convertCompound(LegacyType.ENTITY, cmp, "SpawnData", sourceVer, targetVer); - } - - return cmp; - } - } - - private static class DataInspectorCommandBlock implements DataInspector { - ResourceLocation tileEntityCommand = getKey("TileEntityCommand"); - - @Override - public CompoundTag inspect(CompoundTag cmp, int sourceVer, int targetVer) { - if (tileEntityCommand.equals(new ResourceLocation(cmp.getString("id")))) { - cmp.putString("id", "Control"); - convert(LegacyType.BLOCK_ENTITY, cmp, sourceVer, targetVer); - cmp.putString("id", "MinecartCommandBlock"); - } - - return cmp; - } - } -} diff --git a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightFakePlayer.java b/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightFakePlayer.java deleted file mode 100644 index f3097a98b..000000000 --- a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightFakePlayer.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.bukkit.adapter.impl.v1_18_R2; - -import com.mojang.authlib.GameProfile; -import net.minecraft.network.chat.ChatType; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ServerboundClientInformationPacket; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.stats.Stat; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.damagesource.DamageSource; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.level.block.entity.SignBlockEntity; -import net.minecraft.world.phys.Vec3; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - -import java.util.OptionalInt; -import java.util.UUID; - -class PaperweightFakePlayer extends ServerPlayer { - private static final GameProfile FAKE_WORLDEDIT_PROFILE = new GameProfile(UUID.nameUUIDFromBytes("worldedit".getBytes()), "[WorldEdit]"); - private static final Vec3 ORIGIN = new Vec3(0.0D, 0.0D, 0.0D); - - PaperweightFakePlayer(ServerLevel world) { - super(world.getServer(), world, FAKE_WORLDEDIT_PROFILE); - } - - @Override - public Vec3 position() { - return ORIGIN; - } - - @Override - public void tick() { - } - - @Override - public void die(DamageSource damagesource) { - } - - @Override - public Entity changeDimension(ServerLevel worldserver, TeleportCause cause) { - return this; - } - - @Override - public OptionalInt openMenu(MenuProvider factory) { - return OptionalInt.empty(); - } - - @Override - public void updateOptions(ServerboundClientInformationPacket packet) { - } - - @Override - public void displayClientMessage(Component message, boolean actionBar) { - } - - @Override - public void sendMessage(Component message, ChatType type, UUID sender) { - } - - @Override - public void awardStat(Stat stat, int amount) { - } - - @Override - public void awardStat(Stat stat) { - } - - @Override - public boolean isInvulnerableTo(DamageSource damageSource) { - return true; - } - - @Override - public void openTextEdit(SignBlockEntity sign) { - } -} diff --git a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightWorldNativeAccess.java b/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightWorldNativeAccess.java deleted file mode 100644 index 34775ae83..000000000 --- a/worldedit-bukkit/adapters/adapter-1.18.2/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/v1_18_R2/PaperweightWorldNativeAccess.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.bukkit.adapter.impl.v1_18_R2; - -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.internal.block.BlockStateIdAccess; -import com.sk89q.worldedit.internal.wna.WorldNativeAccess; -import com.sk89q.worldedit.util.SideEffect; -import com.sk89q.worldedit.util.SideEffectSet; -import com.sk89q.worldedit.world.block.BlockState; -import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; -import net.minecraft.server.level.ChunkHolder; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.chunk.LevelChunk; -import org.bukkit.craftbukkit.v1_18_R2.CraftWorld; -import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.enginehub.linbus.tree.LinCompoundTag; - -import java.lang.ref.WeakReference; -import java.util.Objects; -import javax.annotation.Nullable; - -public class PaperweightWorldNativeAccess implements WorldNativeAccess { - private static final int UPDATE = 1; - private static final int NOTIFY = 2; - - private final PaperweightAdapter adapter; - private final WeakReference world; - private SideEffectSet sideEffectSet; - - public PaperweightWorldNativeAccess(PaperweightAdapter adapter, WeakReference world) { - this.adapter = adapter; - this.world = world; - } - - private ServerLevel getWorld() { - return Objects.requireNonNull(world.get(), "The reference to the world was lost"); - } - - @Override - public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) { - this.sideEffectSet = sideEffectSet; - } - - @Override - public LevelChunk getChunk(int x, int z) { - return getWorld().getChunk(x, z); - } - - @Override - public net.minecraft.world.level.block.state.BlockState toNative(BlockState state) { - int stateId = BlockStateIdAccess.getBlockStateId(state); - return BlockStateIdAccess.isValidInternalId(stateId) - ? Block.stateById(stateId) - : ((CraftBlockData) BukkitAdapter.adapt(state)).getState(); - } - - @Override - public net.minecraft.world.level.block.state.BlockState getBlockState(LevelChunk chunk, BlockPos position) { - return chunk.getBlockState(position); - } - - @Nullable - @Override - public net.minecraft.world.level.block.state.BlockState setBlockState(LevelChunk chunk, BlockPos position, net.minecraft.world.level.block.state.BlockState state) { - return chunk.setBlockState(position, state, false, this.sideEffectSet.shouldApply(SideEffect.UPDATE)); - } - - @Override - public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(net.minecraft.world.level.block.state.BlockState block, BlockPos position) { - return Block.updateFromNeighbourShapes(block, getWorld(), position); - } - - @Override - public BlockPos getPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - @Override - public void updateLightingForBlock(BlockPos position) { - getWorld().getChunkSource().getLightEngine().checkBlock(position); - } - - @Override - public boolean updateTileEntity(BlockPos position, LinCompoundTag tag) { - // We will assume that the tile entity was created for us - BlockEntity tileEntity = getWorld().getBlockEntity(position); - if (tileEntity == null) { - return false; - } - Tag nativeTag = adapter.fromNative(tag); - PaperweightAdapter.readTagIntoTileEntity((CompoundTag) nativeTag, tileEntity); - return true; - } - - @Override - public void notifyBlockUpdate(LevelChunk chunk, BlockPos position, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { - if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) { - getWorld().sendBlockUpdated(position, oldState, newState, UPDATE | NOTIFY); - } - } - - @Override - public boolean isChunkTicking(LevelChunk chunk) { - return chunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING); - } - - @Override - public void markBlockChanged(LevelChunk chunk, BlockPos position) { - if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) { - getWorld().getChunkSource().blockChanged(position); - } - } - - @Override - public void notifyNeighbors(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { - ServerLevel world = getWorld(); - if (sideEffectSet.shouldApply(SideEffect.EVENTS)) { - world.updateNeighborsAt(pos, oldState.getBlock()); - } else { - // When we don't want events, manually run the physics without them. - Block block = oldState.getBlock(); - fireNeighborChanged(pos, world, block, pos.west()); - fireNeighborChanged(pos, world, block, pos.east()); - fireNeighborChanged(pos, world, block, pos.below()); - fireNeighborChanged(pos, world, block, pos.above()); - fireNeighborChanged(pos, world, block, pos.north()); - fireNeighborChanged(pos, world, block, pos.south()); - } - if (newState.hasAnalogOutputSignal()) { - world.updateNeighbourForOutputSignal(pos, newState.getBlock()); - } - } - - @Override - public void updateBlock(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { - ServerLevel world = getWorld(); - newState.onPlace(world, pos, oldState, false); - } - - private void fireNeighborChanged(BlockPos pos, ServerLevel world, Block block, BlockPos neighborPos) { - world.getBlockState(neighborPos).neighborChanged(world, neighborPos, block, pos, false); - } - - @Override - public void updateNeighbors(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState, int recursionLimit) { - ServerLevel world = getWorld(); - // a == updateNeighbors - // b == updateDiagonalNeighbors - oldState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit); - if (sideEffectSet.shouldApply(SideEffect.EVENTS)) { - CraftWorld craftWorld = world.getWorld(); - BlockPhysicsEvent event = new BlockPhysicsEvent(craftWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()), CraftBlockData.fromData(newState)); - world.getCraftServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - } - newState.updateNeighbourShapes(world, pos, NOTIFY, recursionLimit); - newState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit); - } - - @Override - public void onBlockStateChange(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { - getWorld().onBlockStateChange(pos, oldState, newState); - } -} diff --git a/worldedit-bukkit/adapters/adapter-1.19.4/build.gradle.kts b/worldedit-bukkit/adapters/adapter-1.19.4/build.gradle.kts index df1bae5c8..c52e5712d 100644 --- a/worldedit-bukkit/adapters/adapter-1.19.4/build.gradle.kts +++ b/worldedit-bukkit/adapters/adapter-1.19.4/build.gradle.kts @@ -1,6 +1,8 @@ import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension -applyPaperweightAdapterConfiguration() +plugins { + id("buildlogic.adapter") +} dependencies { // https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ diff --git a/worldedit-bukkit/adapters/adapter-1.20.2/build.gradle.kts b/worldedit-bukkit/adapters/adapter-1.20.2/build.gradle.kts index 968c53ee2..c2ce87151 100644 --- a/worldedit-bukkit/adapters/adapter-1.20.2/build.gradle.kts +++ b/worldedit-bukkit/adapters/adapter-1.20.2/build.gradle.kts @@ -1,6 +1,8 @@ import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension -applyPaperweightAdapterConfiguration() +plugins { + id("buildlogic.adapter") +} dependencies { // https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ diff --git a/worldedit-bukkit/adapters/adapter-1.20.4/build.gradle.kts b/worldedit-bukkit/adapters/adapter-1.20.4/build.gradle.kts index cdab328e7..8a6f722c9 100644 --- a/worldedit-bukkit/adapters/adapter-1.20.4/build.gradle.kts +++ b/worldedit-bukkit/adapters/adapter-1.20.4/build.gradle.kts @@ -1,6 +1,8 @@ import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension -applyPaperweightAdapterConfiguration() +plugins { + id("buildlogic.adapter") +} dependencies { // https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ diff --git a/worldedit-bukkit/adapters/adapter-1.20.5/build.gradle.kts b/worldedit-bukkit/adapters/adapter-1.20.5/build.gradle.kts index 4cf500733..130819e70 100644 --- a/worldedit-bukkit/adapters/adapter-1.20.5/build.gradle.kts +++ b/worldedit-bukkit/adapters/adapter-1.20.5/build.gradle.kts @@ -1,6 +1,8 @@ import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension -applyPaperweightAdapterConfiguration() +plugins { + id("buildlogic.adapter") +} dependencies { // https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ diff --git a/worldedit-bukkit/adapters/adapter-1.20/build.gradle.kts b/worldedit-bukkit/adapters/adapter-1.20/build.gradle.kts index 52ada7865..d1db9f9ac 100644 --- a/worldedit-bukkit/adapters/adapter-1.20/build.gradle.kts +++ b/worldedit-bukkit/adapters/adapter-1.20/build.gradle.kts @@ -1,6 +1,8 @@ import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension -applyPaperweightAdapterConfiguration() +plugins { + id("buildlogic.adapter") +} dependencies { // https://repo.papermc.io/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/ diff --git a/worldedit-bukkit/build.gradle.kts b/worldedit-bukkit/build.gradle.kts index b2ac1b362..e5b6e4108 100644 --- a/worldedit-bukkit/build.gradle.kts +++ b/worldedit-bukkit/build.gradle.kts @@ -3,14 +3,19 @@ plugins { `java-library` + id("buildlogic.platform") } -applyPlatformAndCoreConfiguration() -applyShadowConfiguration() +platform { + kind = buildlogic.WorldEditKind.Plugin + includeClasspath = true +} repositories { - maven { url = uri("https://hub.spigotmc.org/nexus/content/groups/public") } - maven { url = uri("https://repo.papermc.io/repository/maven-public/") } + maven { + name = "Spigot" + url = uri("https://hub.spigotmc.org/nexus/content/groups/public") + } } val localImplementation = configurations.create("localImplementation") { @@ -79,8 +84,6 @@ } } -addJarManifest(WorldEditKind.Plugin, includeClasspath = true) - tasks.named("shadowJar") { configurations.add(adapters) dependencies { diff --git a/worldedit-cli/build.gradle.kts b/worldedit-cli/build.gradle.kts index d830726ba..22f21f471 100644 --- a/worldedit-cli/build.gradle.kts +++ b/worldedit-cli/build.gradle.kts @@ -2,17 +2,16 @@ plugins { `java-library` + id("buildlogic.platform") } -applyPlatformAndCoreConfiguration() -applyShadowConfiguration() -addJarManifest( - WorldEditKind.Standalone("com.sk89q.worldedit.cli.CLIWorldEdit"), +platform { + kind = buildlogic.WorldEditKind.Standalone("com.sk89q.worldedit.cli.CLIWorldEdit") extraAttributes = mapOf( // We don't have any multi-release stuff, but Log4J does. "Multi-Release" to "true", - ), -) + ) +} dependencies { "compileOnly"(project(":worldedit-libs:core:ap")) diff --git a/worldedit-core/build.gradle.kts b/worldedit-core/build.gradle.kts index 4d0313867..6780e6871 100644 --- a/worldedit-core/build.gradle.kts +++ b/worldedit-core/build.gradle.kts @@ -4,10 +4,9 @@ plugins { `java-library` antlr + id("buildlogic.core-and-platform") } -applyPlatformAndCoreConfiguration() - repositories { ivy { url = uri("https://repo.enginehub.org/language-files/") diff --git a/worldedit-core/doctools/build.gradle.kts b/worldedit-core/doctools/build.gradle.kts index b921ebc72..d12701190 100644 --- a/worldedit-core/doctools/build.gradle.kts +++ b/worldedit-core/doctools/build.gradle.kts @@ -1,10 +1,9 @@ plugins { kotlin("jvm") version "1.9.23" application + id("buildlogic.common") } -applyCommonConfiguration() - application.mainClass.set("com.sk89q.worldedit.internal.util.DocumentationPrinter") tasks.named("run") { workingDir = rootProject.projectDir diff --git a/worldedit-fabric/build.gradle.kts b/worldedit-fabric/build.gradle.kts index 28c1dbc83..273b6d569 100644 --- a/worldedit-fabric/build.gradle.kts +++ b/worldedit-fabric/build.gradle.kts @@ -5,12 +5,20 @@ import net.fabricmc.loom.task.RunGameTask plugins { - id("fabric-loom") + alias(libs.plugins.fabric.loom) `java-library` + id("buildlogic.platform") } -applyPlatformAndCoreConfiguration() -applyShadowConfiguration() +commonJava { + // Not easy to do, because it's in a bunch of separate configurations + banSlf4j = false +} + +platform { + kind = buildlogic.WorldEditKind.Mod + includeClasspath = true +} val fabricApiConfiguration: Configuration = configurations.create("fabricApi") @@ -24,12 +32,12 @@ repositories { maven { - name = "Fabric" - url = uri("https://maven.fabricmc.net/") + name = "EngineHub" + url = uri("https://maven.enginehub.org/repo/") } getByName("Mojang") { content { - includeGroupByRegex("com\\.mojang\\..*") + includeGroupAndSubgroups("com.mojang") } } } @@ -60,11 +68,6 @@ // No need for this at runtime "modCompileOnly"(libs.fabric.permissions.api) - // Hook these up manually, because Fabric doesn't seem to quite do it properly. - "compileOnly"(libs.fabric.mixin) - "annotationProcessor"(libs.fabric.mixin) - "annotationProcessor"(libs.fabric.loom) - // Silence some warnings, since apparently this isn't on the compile classpath like it should be. "compileOnly"(libs.errorprone.annotations) } @@ -88,8 +91,6 @@ } } -addJarManifest(WorldEditKind.Mod, includeClasspath = true) - tasks.named("shadowJar") { archiveClassifier.set("dist-dev") dependencies { diff --git a/worldedit-libs/bukkit/build.gradle.kts b/worldedit-libs/bukkit/build.gradle.kts index d8fb8a56f..1efe39cef 100644 --- a/worldedit-libs/bukkit/build.gradle.kts +++ b/worldedit-libs/bukkit/build.gradle.kts @@ -1,11 +1,5 @@ -applyLibrariesConfiguration() -constrainDependenciesToLibsCore() - -repositories { - maven { - name = "SpigotMC" - url = uri("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") - } +plugins { + id("buildlogic.libs") } dependencies { diff --git a/worldedit-libs/cli/build.gradle.kts b/worldedit-libs/cli/build.gradle.kts index 388618cea..3f6c7e06c 100644 --- a/worldedit-libs/cli/build.gradle.kts +++ b/worldedit-libs/cli/build.gradle.kts @@ -1 +1,3 @@ -applyLibrariesConfiguration() +plugins { + id("buildlogic.libs") +} diff --git a/worldedit-libs/core/ap/build.gradle.kts b/worldedit-libs/core/ap/build.gradle.kts index f61061307..9d30deaea 100644 --- a/worldedit-libs/core/ap/build.gradle.kts +++ b/worldedit-libs/core/ap/build.gradle.kts @@ -1,4 +1,6 @@ -applyLibrariesConfiguration() +plugins { + id("buildlogic.libs") +} dependencies { // These are here because they use net.kyori:text-api -- so they need to be relocated too diff --git a/worldedit-libs/core/build.gradle.kts b/worldedit-libs/core/build.gradle.kts index abfd84c7b..f8e7a76e8 100644 --- a/worldedit-libs/core/build.gradle.kts +++ b/worldedit-libs/core/build.gradle.kts @@ -1,4 +1,6 @@ -applyLibrariesConfiguration() +plugins { + id("buildlogic.libs") +} dependencies { "shade"(libs.kyoriText.api) diff --git a/worldedit-libs/fabric/build.gradle.kts b/worldedit-libs/fabric/build.gradle.kts index 388618cea..3f6c7e06c 100644 --- a/worldedit-libs/fabric/build.gradle.kts +++ b/worldedit-libs/fabric/build.gradle.kts @@ -1 +1,3 @@ -applyLibrariesConfiguration() +plugins { + id("buildlogic.libs") +} diff --git a/worldedit-libs/neoforge/build.gradle.kts b/worldedit-libs/neoforge/build.gradle.kts index 388618cea..3f6c7e06c 100644 --- a/worldedit-libs/neoforge/build.gradle.kts +++ b/worldedit-libs/neoforge/build.gradle.kts @@ -1 +1,3 @@ -applyLibrariesConfiguration() +plugins { + id("buildlogic.libs") +} diff --git a/worldedit-libs/sponge/build.gradle.kts b/worldedit-libs/sponge/build.gradle.kts deleted file mode 100644 index 7f10cf012..000000000 --- a/worldedit-libs/sponge/build.gradle.kts +++ /dev/null @@ -1,11 +0,0 @@ -applyLibrariesConfiguration() -constrainDependenciesToLibsCore() - -repositories { - maven { - name = "Sponge" - url = uri("https://repo.spongepowered.org/maven") - } -} -dependencies { -} diff --git a/worldedit-mod/build.gradle.kts b/worldedit-mod/build.gradle.kts index fd3d91c1e..e1c39837f 100644 --- a/worldedit-mod/build.gradle.kts +++ b/worldedit-mod/build.gradle.kts @@ -4,10 +4,10 @@ plugins { base + id("buildlogic.common") + alias(libs.plugins.fabric.loom) apply false } -applyCommonConfiguration() - open class MergeManifests : DefaultTask() { @InputFiles val inputManifests: ConfigurableFileCollection = project.objects.fileCollection() diff --git a/worldedit-neoforge/build.gradle.kts b/worldedit-neoforge/build.gradle.kts index 61213ef54..3fc0bdbec 100644 --- a/worldedit-neoforge/build.gradle.kts +++ b/worldedit-neoforge/build.gradle.kts @@ -2,12 +2,19 @@ import net.neoforged.gradle.dsl.common.runs.run.Run plugins { - id("net.neoforged.gradle.userdev") + alias(libs.plugins.neogradle.userdev) `java-library` + id("buildlogic.platform") } -applyPlatformAndCoreConfiguration() -applyShadowConfiguration() +commonJava { + // Not easy to do, because it's in a bunch of separate configurations + banSlf4j = false +} + +platform { + kind = buildlogic.WorldEditKind.Mod +} val minecraftVersion = libs.versions.neoforge.minecraft.get() val nextMajorMinecraftVersion: String = minecraftVersion.split('.').let { (useless, major) -> @@ -20,20 +27,16 @@ } repositories { + val toRemove = mutableListOf() for (repo in project.repositories) { if (repo is MavenArtifactRepository && repo.url.toString() == "https://maven.neoforged.net/releases/") { - repo.mavenContent { - includeGroupAndSubgroups("net.neoforged") - } + toRemove.add(repo) } } - // For Fabric's mixin fork + toRemove.forEach { remove(it) } maven { - name = "Fabric" - url = uri("https://maven.fabricmc.net/") - mavenContent { - includeGroup("net.fabricmc") - } + name = "EngineHub" + url = uri("https://maven.enginehub.org/repo/") } } @@ -106,8 +109,6 @@ from(project(":worldedit-core").tasks.named("processResources")) } -addJarManifest(WorldEditKind.Mod, includeClasspath = false) - tasks.named("shadowJar") { dependencies { relocate("org.antlr.v4", "com.sk89q.worldedit.antlr4") diff --git a/worldedit-sponge/build.gradle.kts b/worldedit-sponge/build.gradle.kts deleted file mode 100644 index 9da479e09..000000000 --- a/worldedit-sponge/build.gradle.kts +++ /dev/null @@ -1,81 +0,0 @@ -import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar -import org.spongepowered.gradle.plugin.config.PluginLoaders -import org.spongepowered.plugin.metadata.model.PluginDependency - -plugins { - id("org.spongepowered.gradle.plugin") - id("org.spongepowered.gradle.vanilla") -} - -applyPlatformAndCoreConfiguration() -applyShadowConfiguration() - -repositories { - mavenCentral() -} - -minecraft { - version("1.20") -} - -val spongeApiVersion = "11.0.0-SNAPSHOT"; - -sponge { - apiVersion(spongeApiVersion) - license("GPL-3.0-or-later") - plugin("worldedit") { - loader { - name(PluginLoaders.JAVA_PLAIN) - version("1.0") - } - displayName("WorldEdit") - version(project.ext["internalVersion"].toString()) - entrypoint("com.sk89q.worldedit.sponge.SpongeWorldEdit") - description("WorldEdit is an easy-to-use in-game world editor for Minecraft, supporting both single- and multi-player.") - links { - homepage("https://enginehub.org/worldedit/") - source("https://github.com/EngineHub/WorldEdit") - issues("https://github.com/EngineHub/WorldEdit/issues") - } - contributor("EngineHub") { - description("Various members of the EngineHub team") - } - dependency("spongeapi") { - loadOrder(PluginDependency.LoadOrder.AFTER) - optional(false) - } - } -} - -dependencies { - api(project(":worldedit-core")) - api(project(":worldedit-libs:sponge")) - - api("org.apache.logging.log4j:log4j-api") - implementation("org.bstats:bstats-sponge:3.0.0") - implementation("it.unimi.dsi:fastutil") - - // Silence some warnings, since apparently this isn't on the compile classpath like it should be. - compileOnly("com.google.errorprone:error_prone_annotations:2.11.0") -} - -configure { - archivesName.set("${project.name}-api$spongeApiVersion") -} - -addJarManifest(WorldEditKind.Mod, includeClasspath = true) - -tasks.named("shadowJar") { - dependencies { - include(dependency("org.bstats:")) - include(dependency("org.antlr:antlr4-runtime")) - include(dependency("com.sk89q.lib:jlibnoise")) - - relocate("org.antlr.v4", "com.sk89q.worldedit.antlr4") - relocate("org.bstats", "com.sk89q.worldedit.sponge.bstats") - relocate("net.royawesome.jlibnoise", "com.sk89q.worldedit.jlibnoise") - } -} -tasks.named("assemble").configure { - dependsOn("shadowJar") -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/CUIChannelHandler.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/CUIChannelHandler.java deleted file mode 100644 index 79f23a134..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/CUIChannelHandler.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.util.lifecycle.SimpleLifecycled; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.lifecycle.RegisterChannelEvent; -import org.spongepowered.api.network.ServerPlayerConnection; -import org.spongepowered.api.network.channel.ChannelBuf; -import org.spongepowered.api.network.channel.raw.RawDataChannel; -import org.spongepowered.api.network.channel.raw.play.RawPlayDataHandler; - -import java.nio.charset.StandardCharsets; - -public class CUIChannelHandler implements RawPlayDataHandler { - public static final ResourceKey CUI_PLUGIN_CHANNEL = ResourceKey.of("worldedit", "cui"); - private static final SimpleLifecycled CHANNEL = SimpleLifecycled.invalid(); - - public static final class RegistrationHandler { - @Listener - public void onChannelRegistration(RegisterChannelEvent event) { - RawDataChannel channel = event.register(CUI_PLUGIN_CHANNEL, RawDataChannel.class); - channel.play().addHandler(ServerPlayerConnection.class, new CUIChannelHandler()); - CHANNEL.newValue(channel); - } - } - - public static RawDataChannel channel() { - return CHANNEL.valueOrThrow(); - } - - @Override - public void handlePayload(ChannelBuf data, ServerPlayerConnection connection) { - ServerPlayer player = connection.player(); - - SpongePlayer spongePlayer = SpongeAdapter.adapt(player); - LocalSession session = WorldEdit.getInstance().getSessionManager().get( - spongePlayer - ); - - session.handleCUIInitializationMessage( - new String(data.readBytes(data.available()), StandardCharsets.UTF_8), - spongePlayer - ); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/CommandAdapter.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/CommandAdapter.java deleted file mode 100644 index be08709a1..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/CommandAdapter.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.command.util.PermissionCondition; -import com.sk89q.worldedit.sponge.internal.LocaleResolver; -import net.kyori.adventure.text.Component; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.enginehub.piston.Command; -import org.spongepowered.api.command.CommandCause; - -import java.util.Collections; -import java.util.Optional; -import java.util.Set; - -public abstract class CommandAdapter implements org.spongepowered.api.command.Command.Raw { - private final Command command; - - protected CommandAdapter(Command command) { - this.command = command; - } - - @Override - public boolean canExecute(CommandCause cause) { - Set permissions = command.getCondition().as(PermissionCondition.class) - .map(PermissionCondition::getPermissions) - .orElseGet(Collections::emptySet); - - // Allow commands without permission nodes to always execute. - if (permissions.isEmpty()) { - return true; - } - - for (String perm : permissions) { - if (cause.hasPermission(perm)) { - return true; - } - } - return false; - } - - @Override - public Optional shortDescription(CommandCause cause) { - return Optional.of(command.getDescription()) - .map(desc -> SpongeTextAdapter.convert(desc, LocaleResolver.resolveLocale(cause.audience()))); - } - - @Override - public Optional extendedDescription(CommandCause cause) { - return command.getFooter() - .map(footer -> SpongeTextAdapter.convert(footer, LocaleResolver.resolveLocale(cause.audience()))); - } - - @Override - public Optional help(@NonNull CommandCause cause) { - return Optional.of(command.getFullHelp()) - .map(help -> SpongeTextAdapter.convert(help, LocaleResolver.resolveLocale(cause.audience()))); - } - - @Override - public Component usage(CommandCause cause) { - return SpongeTextAdapter.convert(command.getUsage(), LocaleResolver.resolveLocale(cause.audience())); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/Constants.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/Constants.java deleted file mode 100644 index 7edfd16c6..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/Constants.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import org.spongepowered.api.data.persistence.DataQuery; - -/** - * Kinda mirrors Sponge Common's Constants class. - * - *

Internal. Do not use.

- */ -public class Constants { - public static class Sponge { - public static final DataQuery UNSAFE_NBT = DataQuery.of("UnsafeData"); - - private Sponge() { - } - } - - private Constants() { - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeAdapter.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeAdapter.java deleted file mode 100644 index 401456b4a..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeAdapter.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.internal.block.BlockStateIdAccess; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.Vector3; -import com.sk89q.worldedit.sponge.internal.NbtAdapter; -import com.sk89q.worldedit.sponge.internal.SpongeTransmogrifier; -import com.sk89q.worldedit.util.Direction; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.concurrency.LazyReference; -import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.item.ItemTypes; -import net.minecraft.world.level.block.Block; -import org.enginehub.linbus.tree.LinCompoundTag; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.data.persistence.DataContainer; -import org.spongepowered.api.data.persistence.DataView; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.registry.RegistryKey; -import org.spongepowered.api.registry.RegistryReference; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.world.biome.Biome; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; -import org.spongepowered.math.vector.Vector3d; -import org.spongepowered.math.vector.Vector3i; - -import java.util.Objects; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Adapts between Sponge and WorldEdit equivalent objects. - */ -public class SpongeAdapter { - - public static org.spongepowered.api.block.BlockState adapt(BlockState blockState) { - int blockStateId = BlockStateIdAccess.getBlockStateId(blockState); - if (!BlockStateIdAccess.isValidInternalId(blockStateId)) { - return SpongeTransmogrifier.transmogToMinecraft(blockState); - } - return (org.spongepowered.api.block.BlockState) Block.stateById(blockStateId); - } - - public static BlockState adapt(org.spongepowered.api.block.BlockState blockState) { - int blockStateId = Block.getId((net.minecraft.world.level.block.state.BlockState) blockState); - BlockState worldEdit = BlockStateIdAccess.getBlockStateById(blockStateId); - if (worldEdit == null) { - return SpongeTransmogrifier.transmogToWorldEdit(blockState); - } - return worldEdit; - } - - /** - * Create a WorldEdit world from a Sponge world. - * - * @param world the Sponge world - * @return a WorldEdit world - */ - public static World adapt(ServerWorld world) { - checkNotNull(world); - return new SpongeWorld(world); - } - - /** - * Create a WorldEdit Player from a Sponge Player. - * - * @param player The Sponge player - * @return The WorldEdit player - */ - public static SpongePlayer adapt(ServerPlayer player) { - Objects.requireNonNull(player); - return new SpongePlayer(player); - } - - /** - * Create a Sponge Player from a WorldEdit Player. - * - * @param player The WorldEdit player - * @return The Bukkit player - */ - public static Player adapt(com.sk89q.worldedit.entity.Player player) { - return ((SpongePlayer) player).getPlayer(); - } - - /** - * Create a Sponge world from a WorldEdit world. - * - * @param world the WorldEdit world - * @return a Sponge world - */ - public static ServerWorld adapt(World world) { - checkNotNull(world); - if (world instanceof SpongeWorld) { - return ((SpongeWorld) world).getWorld(); - } else { - // Currently this is 99% certain to fail, we don't have consistent world name/id mapping - ServerWorld match = Sponge.server().worldManager().world( - ResourceKey.resolve(world.getName()) - ).orElse(null); - if (match != null) { - return match; - } else { - throw new IllegalArgumentException("Can't find a Sponge world for " + world); - } - } - } - - public static RegistryReference adapt(BiomeType biomeType) { - return RegistryKey.of(RegistryTypes.BIOME, ResourceKey.resolve(biomeType.id())) - .asReference(); - } - - public static BiomeType adapt(Biome biomeType) { - return BiomeType.REGISTRY.get(biomeType.toString()); - } - - /** - * Create a WorldEdit location from a Sponge location. - * - * @param location the Sponge location - * @return a WorldEdit location - */ - public static Location adapt(ServerLocation location, Vector3d rotation) { - checkNotNull(location); - Vector3 position = asVector(location); - return new Location( - adapt(location.world()), - position, - (float) rotation.y(), - (float) rotation.x() - ); - } - - /** - * Create a Sponge location from a WorldEdit location. - * - * @param location the WorldEdit location - * @return a Sponge location - */ - public static ServerLocation adapt(Location location) { - checkNotNull(location); - Vector3 position = location.toVector(); - return ServerLocation.of( - adapt((World) location.getExtent()), - position.x(), position.y(), position.z() - ); - } - - /** - * Create a Sponge rotation from a WorldEdit location. - * - * @param location the WorldEdit location - * @return a Sponge rotation - */ - public static Vector3d adaptRotation(Location location) { - checkNotNull(location); - return new Vector3d(location.getPitch(), location.getYaw(), 0); - } - - /** - * Create a WorldEdit Vector from a Sponge location. - * - * @param location The Sponge location - * @return a WorldEdit vector - */ - public static Vector3 asVector(ServerLocation location) { - checkNotNull(location); - return Vector3.at(location.x(), location.y(), location.z()); - } - - /** - * Create a WorldEdit BlockVector from a Sponge location. - * - * @param location The Sponge location - * @return a WorldEdit vector - */ - public static BlockVector3 asBlockVector(ServerLocation location) { - checkNotNull(location); - return BlockVector3.at(location.x(), location.y(), location.z()); - } - - public static BaseItemStack adapt(ItemStack itemStack) { - DataView tag = itemStack.toContainer().getView(Constants.Sponge.UNSAFE_NBT) - .orElse(null); - return new BaseItemStack( - ItemTypes.get(itemStack.type().key(RegistryTypes.ITEM_TYPE).asString()), - tag == null ? null : LazyReference.from(() -> NbtAdapter.adaptToWorldEdit(tag)), - itemStack.quantity() - ); - } - - public static ItemStack adapt(BaseItemStack itemStack) { - ItemStack stack = ItemStack.builder() - .itemType(() -> Sponge.game().registry(RegistryTypes.ITEM_TYPE) - .value(ResourceKey.resolve(itemStack.getType().id()))) - .quantity(itemStack.getAmount()) - .build(); - LinCompoundTag nbt = itemStack.getNbt(); - if (nbt != null) { - stack.setRawData( - DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED) - .set(Constants.Sponge.UNSAFE_NBT, NbtAdapter.adaptFromWorldEdit(nbt)) - ); - } - return stack; - } - - public static Direction adapt(org.spongepowered.api.util.Direction direction) { - return Direction.valueOf(direction.name()); - } - - public static Vector3i adaptVector3i(BlockVector3 bv3) { - return new Vector3i(bv3.x(), bv3.y(), bv3.z()); - } - - public static BlockVector3 adaptVector3i(Vector3i vec3i) { - return BlockVector3.at(vec3i.x(), vec3i.y(), vec3i.z()); - } - - private SpongeAdapter() { - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBiomeRegistry.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBiomeRegistry.java deleted file mode 100644 index 66e1b9c42..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBiomeRegistry.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; -import com.sk89q.worldedit.util.translation.TranslationManager; -import com.sk89q.worldedit.world.biome.BiomeData; -import com.sk89q.worldedit.world.registry.BiomeRegistry; -import org.spongepowered.api.registry.RegistryReference; -import org.spongepowered.api.world.biome.Biome; - -import javax.annotation.Nullable; - -/** - * Provides access to biome data in Sponge. - */ -class SpongeBiomeRegistry implements BiomeRegistry { - - @Override - public Component getRichName(com.sk89q.worldedit.world.biome.BiomeType biomeType) { - return TranslatableComponent.of( - TranslationManager.makeTranslationKey("biome", biomeType.id()) - ); - } - - @Deprecated - @Nullable - @Override - public BiomeData getData(com.sk89q.worldedit.world.biome.BiomeType biome) { - return new SpongeBiomeData(SpongeAdapter.adapt(biome)); - } - - @Deprecated - private static class SpongeBiomeData implements BiomeData { - private final RegistryReference biome; - - /** - * Create a new instance. - * - * @param biome the base biome - */ - private SpongeBiomeData(RegistryReference biome) { - this.biome = biome; - } - - @SuppressWarnings("deprecation") - @Override - public String getName() { - return biome.location().asString(); - } - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockCategoryRegistry.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockCategoryRegistry.java deleted file mode 100644 index 17b5236d8..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockCategoryRegistry.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.registry.BlockCategoryRegistry; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.registry.Registry; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.tag.Tag; - -import java.util.Set; -import java.util.stream.Collectors; - -public class SpongeBlockCategoryRegistry implements BlockCategoryRegistry { - @Override - public Set getCategorisedByName(String category) { - Registry blockTypeRegistry = - Sponge.game().registry(RegistryTypes.BLOCK_TYPE); - - return blockTypeRegistry.taggedValues(Tag.of(RegistryTypes.BLOCK_TYPE, ResourceKey.resolve(category))) - .stream() - .map(blockType -> BlockType.REGISTRY.get(blockTypeRegistry.valueKey(blockType).formatted())) - .collect(Collectors.toSet()); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockCommandSender.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockCommandSender.java deleted file mode 100644 index 45d00da69..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockCommandSender.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.platform.AbstractCommandBlockActor; -import com.sk89q.worldedit.session.SessionKey; -import com.sk89q.worldedit.util.auth.AuthorizationException; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.util.formatting.text.TextComponent; -import com.sk89q.worldedit.util.formatting.text.format.TextColor; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.block.BlockTypes; -import org.spongepowered.api.block.entity.CommandBlock; -import org.spongepowered.api.data.Keys; -import org.spongepowered.api.scheduler.Task; -import org.spongepowered.api.util.Ticks; -import org.spongepowered.math.vector.Vector3d; - -import java.nio.charset.StandardCharsets; -import java.util.Locale; -import java.util.UUID; - -import static com.google.common.base.Preconditions.checkNotNull; - -public class SpongeBlockCommandSender extends AbstractCommandBlockActor { - private final SpongeWorldEdit worldEdit; - private final CommandBlock sender; - private final UUID uuid; - - public SpongeBlockCommandSender(SpongeWorldEdit worldEdit, CommandBlock sender) { - super(SpongeAdapter.adapt(checkNotNull(sender).serverLocation(), Vector3d.ZERO)); - checkNotNull(worldEdit); - - this.worldEdit = worldEdit; - this.sender = sender; - this.uuid = UUID.nameUUIDFromBytes((UUID_PREFIX + sender.name()).getBytes(StandardCharsets.UTF_8)); - } - - @Override - public String getName() { - return sender.name(); - } - - @Override - @Deprecated - public void printRaw(String msg) { - for (String part : msg.split("\n")) { - sendMessage(net.kyori.adventure.text.Component.text(part)); - } - } - - @Override - @Deprecated - public void print(String msg) { - for (String part : msg.split("\n")) { - print(TextComponent.of(part, TextColor.LIGHT_PURPLE)); - } - } - - @Override - @Deprecated - public void printDebug(String msg) { - for (String part : msg.split("\n")) { - print(TextComponent.of(part, TextColor.GRAY)); - } - } - - @Override - @Deprecated - public void printError(String msg) { - for (String part : msg.split("\n")) { - print(TextComponent.of(part, TextColor.RED)); - } - } - - @Override - public void print(Component component) { - sendMessage(SpongeTextAdapter.convert(component, getLocale())); - } - - private void sendMessage(net.kyori.adventure.text.Component textComponent) { - this.sender.offer(Keys.LAST_COMMAND_OUTPUT, textComponent); - } - - @Override - public Locale getLocale() { - return WorldEdit.getInstance().getConfiguration().defaultLocale; - } - - @Override - public UUID getUniqueId() { - return uuid; - } - - @Override - public String[] getGroups() { - return new String[0]; - } - - @Override - public void checkPermission(String permission) throws AuthorizationException { - if (!hasPermission(permission)) { - throw new AuthorizationException(); - } - } - - @Override - public boolean hasPermission(String permission) { - return sender.hasPermission(permission); - } - - public CommandBlock getSender() { - return this.sender; - } - - @Override - public SessionKey getSessionKey() { - return new SessionKey() { - - private volatile boolean active = true; - - private void updateActive() { - BlockState block = sender.block(); - if (!sender.serverLocation().world().isChunkLoadedAtBlock(sender.blockPosition(), false)) { - active = false; - return; - } - BlockType type = block.type(); - active = type == BlockTypes.COMMAND_BLOCK.get() - || type == BlockTypes.CHAIN_COMMAND_BLOCK.get() - || type == BlockTypes.REPEATING_COMMAND_BLOCK.get(); - } - - @Override - public String getName() { - return sender.name(); - } - - @Override - public boolean isActive() { - if (Sponge.server().onMainThread()) { - // we can update eagerly - updateActive(); - } else { - // we should update it eventually - Task task = Task.builder().delay(Ticks.zero()).plugin(worldEdit.getPluginContainer()).execute(this::updateActive).build(); - Sponge.server().scheduler().submit(task); - } - return active; - } - - @Override - public boolean isPersistent() { - return true; - } - - @Override - public UUID getUniqueId() { - return uuid; - } - }; - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockMaterial.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockMaterial.java deleted file mode 100644 index 861b9d633..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockMaterial.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.world.registry.BlockMaterial; -import com.sk89q.worldedit.world.registry.PassthroughBlockMaterial; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.PushReaction; - -import javax.annotation.Nullable; - -/** - * Sponge block material that pulls as much info as possible from the Minecraft - * Material, and passes the rest to another implementation, typically the - * bundled block info. - */ -public class SpongeBlockMaterial extends PassthroughBlockMaterial { - - private final BlockState block; - - public SpongeBlockMaterial(BlockState block, @Nullable BlockMaterial secondary) { - super(secondary); - this.block = block; - } - - @Override - public boolean isAir() { - return block.isAir() || super.isAir(); - } - - @Override - public boolean isOpaque() { - return block.canOcclude(); - } - - @Override - @SuppressWarnings("deprecation") - public boolean isLiquid() { - return block.liquid(); - } - - @Override - @SuppressWarnings("deprecation") - public boolean isSolid() { - return block.isSolid(); - } - - @Override - public boolean isFragileWhenPushed() { - return block.getPistonPushReaction() == PushReaction.DESTROY; - } - - @Override - public boolean isUnpushable() { - return block.getPistonPushReaction() == PushReaction.BLOCK; - } - - @Override - @SuppressWarnings("deprecation") - public boolean isMovementBlocker() { - return block.blocksMotion(); - } - - @Override - public boolean isBurnable() { - return block.ignitedByLava(); - } - - @Override - public boolean isToolRequired() { - return block.requiresCorrectToolForDrops(); - } - - @Override - public boolean isReplacedDuringPlacement() { - return block.canBeReplaced(); - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockRegistry.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockRegistry.java deleted file mode 100644 index f692e9c27..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeBlockRegistry.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.registry.state.Property; -import com.sk89q.worldedit.sponge.internal.SpongeTransmogrifier; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.registry.BlockMaterial; -import com.sk89q.worldedit.world.registry.BundledBlockRegistry; -import net.minecraft.world.level.block.Block; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.state.StateProperty; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.OptionalInt; -import java.util.TreeMap; - -public class SpongeBlockRegistry extends BundledBlockRegistry { - - private final Map materialMap = - new HashMap<>(); - - @Override - public Component getRichName(BlockType blockType) { - return SpongeTextAdapter.convert(Sponge.game().registry(RegistryTypes.BLOCK_TYPE) - .value(ResourceKey.resolve(blockType.id())).asComponent()); - } - - @Override - public BlockMaterial getMaterial(BlockType blockType) { - org.spongepowered.api.block.BlockType spongeBlockType = - Sponge.game().registry(RegistryTypes.BLOCK_TYPE) - .value(ResourceKey.resolve(blockType.id())); - return materialMap.computeIfAbsent( - spongeBlockType.defaultState(), - m -> { - net.minecraft.world.level.block.state.BlockState blockState = - (net.minecraft.world.level.block.state.BlockState) m; - return new SpongeBlockMaterial( - blockState, - super.getMaterial(blockType) - ); - } - ); - } - - @Override - public Map> getProperties(BlockType blockType) { - org.spongepowered.api.block.BlockType spongeBlockType = - Sponge.game().registry(RegistryTypes.BLOCK_TYPE) - .value(ResourceKey.resolve(blockType.id())); - Map> map = new TreeMap<>(); - Collection> propertyKeys = spongeBlockType - .defaultState().stateProperties(); - for (StateProperty key : propertyKeys) { - map.put(key.name(), SpongeTransmogrifier.transmogToWorldEditProperty(key)); - } - return map; - } - - @Override - public OptionalInt getInternalBlockStateId(BlockState state) { - org.spongepowered.api.block.BlockState equivalent = SpongeAdapter.adapt(state); - return OptionalInt.of(Block.getId( - (net.minecraft.world.level.block.state.BlockState) equivalent - )); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeCommandSender.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeCommandSender.java deleted file mode 100644 index a75ee8fc6..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeCommandSender.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.internal.cui.CUIEvent; -import com.sk89q.worldedit.session.SessionKey; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.util.formatting.text.TextComponent; -import com.sk89q.worldedit.util.formatting.text.format.TextColor; -import net.kyori.adventure.audience.Audience; -import org.spongepowered.api.entity.living.player.Player; - -import java.io.File; -import java.util.Locale; -import java.util.UUID; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -public class SpongeCommandSender implements Actor { - - /** - * One time generated ID. - */ - private static final UUID DEFAULT_ID = UUID.fromString("a233eb4b-4cab-42cd-9fd9-7e7b9a3f74be"); - - private final Audience sender; - - public SpongeCommandSender(Audience sender) { - checkNotNull(sender); - checkArgument( - !(sender instanceof Player), - "Players should be wrapped using the specialized class" - ); - - this.sender = sender; - } - - @Override - public UUID getUniqueId() { - return DEFAULT_ID; - } - - @Override - public String getName() { - return "Console"; - } - - @Override - @Deprecated - public void printRaw(String msg) { - for (String part : msg.split("\n")) { - sender.sendMessage(net.kyori.adventure.text.Component.text(part)); - } - } - - @Override - @Deprecated - public void print(String msg) { - for (String part : msg.split("\n")) { - print(TextComponent.of(part, TextColor.LIGHT_PURPLE)); - } - } - - @Override - @Deprecated - public void printDebug(String msg) { - for (String part : msg.split("\n")) { - print(TextComponent.of(part, TextColor.GRAY)); - } - } - - @Override - @Deprecated - public void printError(String msg) { - for (String part : msg.split("\n")) { - print(TextComponent.of(part, TextColor.RED)); - } - } - - @Override - public void print(Component component) { - sender.sendMessage(SpongeTextAdapter.convert(component, getLocale())); - } - - @Override - public boolean canDestroyBedrock() { - return true; - } - - @Override - public String[] getGroups() { - return new String[0]; - } - - @Override - public boolean hasPermission(String perm) { - return true; - } - - @Override - public void checkPermission(String permission) { - } - - @Override - public boolean isPlayer() { - return false; - } - - @Override - public File openFileOpenDialog(String[] extensions) { - return null; - } - - @Override - public File openFileSaveDialog(String[] extensions) { - return null; - } - - @Override - public void dispatchCUIEvent(CUIEvent event) { - } - - @Override - public Locale getLocale() { - return WorldEdit.getInstance().getConfiguration().defaultLocale; - } - - @Override - public SessionKey getSessionKey() { - return new SessionKey() { - @Override - public String getName() { - return "Console"; - } - - @Override - public boolean isActive() { - return true; - } - - @Override - public boolean isPersistent() { - return true; - } - - @Override - public UUID getUniqueId() { - return DEFAULT_ID; - } - }; - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java deleted file mode 100644 index e8ad6b39d..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.entity.BaseEntity; -import com.sk89q.worldedit.entity.Entity; -import com.sk89q.worldedit.entity.metadata.EntityProperties; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.sponge.internal.NbtAdapter; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.concurrency.LazyReference; -import com.sk89q.worldedit.world.NullWorld; -import com.sk89q.worldedit.world.entity.EntityType; -import org.spongepowered.api.data.persistence.DataView; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.math.vector.Vector3d; - -import java.lang.ref.WeakReference; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkNotNull; - -class SpongeEntity implements Entity { - - private final WeakReference entityRef; - - SpongeEntity(org.spongepowered.api.entity.Entity entity) { - checkNotNull(entity); - this.entityRef = new WeakReference<>(entity); - } - - @Override - public BaseEntity getState() { - org.spongepowered.api.entity.Entity entity = entityRef.get(); - if (entity == null || entity.vehicle().isPresent()) { - return null; - } - EntityType entityType = EntityType.REGISTRY.get(entity.type().key(RegistryTypes.ENTITY_TYPE).asString()); - if (entityType == null) { - return null; - } - DataView dataView = entity.toContainer().getView(Constants.Sponge.UNSAFE_NBT) - .orElse(null); - return new BaseEntity( - entityType, - dataView == null ? null : LazyReference.from(() -> NbtAdapter.adaptToWorldEdit(dataView)) - ); - } - - @Override - public Location getLocation() { - org.spongepowered.api.entity.Entity entity = entityRef.get(); - if (entity != null) { - ServerLocation entityLoc = entity.serverLocation(); - Vector3d entityRot = entity.rotation(); - - return SpongeAdapter.adapt(entityLoc, entityRot); - } else { - return new Location(NullWorld.getInstance()); - } - } - - @Override - public boolean setLocation(Location location) { - org.spongepowered.api.entity.Entity entity = entityRef.get(); - if (entity != null) { - return entity.setLocation(SpongeAdapter.adapt(location)); - } else { - return false; - } - } - - @Override - public Extent getExtent() { - org.spongepowered.api.entity.Entity entity = entityRef.get(); - if (entity != null) { - return SpongeAdapter.adapt(entity.serverLocation().world()); - } else { - return NullWorld.getInstance(); - } - } - - @Override - public boolean remove() { - org.spongepowered.api.entity.Entity entity = entityRef.get(); - if (entity != null) { - entity.remove(); - } - return true; - } - - @SuppressWarnings("unchecked") - @Nullable - @Override - public T getFacet(Class cls) { - org.spongepowered.api.entity.Entity entity = entityRef.get(); - if (entity != null) { - if (EntityProperties.class.isAssignableFrom(cls)) { - return (T) new SpongeEntityProperties(entity); - } else { - return null; - } - } else { - return null; - } - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntityProperties.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntityProperties.java deleted file mode 100644 index f7b0269a7..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntityProperties.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.entity.metadata.EntityProperties; -import org.spongepowered.api.data.Keys; -import org.spongepowered.api.entity.Entity; -import org.spongepowered.api.entity.ExperienceOrb; -import org.spongepowered.api.entity.FallingBlock; -import org.spongepowered.api.entity.Item; -import org.spongepowered.api.entity.explosive.fused.PrimedTNT; -import org.spongepowered.api.entity.hanging.ItemFrame; -import org.spongepowered.api.entity.hanging.Painting; -import org.spongepowered.api.entity.living.Ambient; -import org.spongepowered.api.entity.living.ArmorStand; -import org.spongepowered.api.entity.living.ComplexLivingPart; -import org.spongepowered.api.entity.living.Humanoid; -import org.spongepowered.api.entity.living.Living; -import org.spongepowered.api.entity.living.animal.Animal; -import org.spongepowered.api.entity.living.aquatic.Aquatic; -import org.spongepowered.api.entity.living.golem.Golem; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.entity.living.trader.Trader; -import org.spongepowered.api.entity.projectile.Projectile; -import org.spongepowered.api.entity.vehicle.Boat; -import org.spongepowered.api.entity.vehicle.minecart.Minecart; - -import static com.google.common.base.Preconditions.checkNotNull; - -public class SpongeEntityProperties implements EntityProperties { - - private final Entity entity; - - public SpongeEntityProperties(Entity entity) { - checkNotNull(entity); - this.entity = entity; - } - - @Override - public boolean isPlayerDerived() { - return entity instanceof Humanoid; - } - - @Override - public boolean isProjectile() { - return entity instanceof Projectile; - } - - @Override - public boolean isItem() { - return entity instanceof Item; - } - - @Override - public boolean isFallingBlock() { - return entity instanceof FallingBlock; - } - - @Override - public boolean isPainting() { - return entity instanceof Painting; - } - - @Override - public boolean isItemFrame() { - return entity instanceof ItemFrame; - } - - @Override - public boolean isBoat() { - return entity instanceof Boat; - } - - @Override - public boolean isMinecart() { - return entity instanceof Minecart; - } - - @Override - public boolean isTNT() { - return entity instanceof PrimedTNT; - } - - @Override - public boolean isExperienceOrb() { - return entity instanceof ExperienceOrb; - } - - @Override - public boolean isLiving() { - return entity instanceof Living; - } - - @Override - public boolean isAnimal() { - return entity instanceof Animal; - } - - @Override - public boolean isAmbient() { - return entity instanceof Ambient; - } - - @Override - public boolean isNPC() { - return entity instanceof Trader; - } - - @Override - public boolean isGolem() { - return entity instanceof Golem; - } - - @Override - public boolean isTamed() { - return entity.get(Keys.IS_TAMED).orElse(false); - } - - @Override - public boolean isTagged() { - return entity.get(Keys.CUSTOM_NAME).isPresent(); - } - - @Override - public boolean isArmorStand() { - return entity instanceof ArmorStand; - } - - @Override - public boolean isPasteable() { - return !(entity instanceof Player || entity instanceof ComplexLivingPart); - } - - @Override - public boolean isWaterCreature() { - return entity instanceof Aquatic; - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeItemCategoryRegistry.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeItemCategoryRegistry.java deleted file mode 100644 index 39bc266ac..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeItemCategoryRegistry.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.world.item.ItemType; -import com.sk89q.worldedit.world.registry.ItemCategoryRegistry; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.registry.Registry; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.tag.Tag; - -import java.util.Collections; -import java.util.Set; -import java.util.stream.Collectors; - -public class SpongeItemCategoryRegistry implements ItemCategoryRegistry { - @Override - public Set getCategorisedByName(String category) { - Registry itemTypeRegistry = - Sponge.game().registry(RegistryTypes.ITEM_TYPE); - - return itemTypeRegistry.taggedValues(Tag.of(RegistryTypes.ITEM_TYPE, ResourceKey.resolve(category))) - .stream() - .map(itemType -> ItemType.REGISTRY.get(itemTypeRegistry.valueKey(itemType).formatted())) - .collect(Collectors.toSet()); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeItemRegistry.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeItemRegistry.java deleted file mode 100644 index 23936cbb2..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeItemRegistry.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; -import com.sk89q.worldedit.world.item.ItemType; -import com.sk89q.worldedit.world.registry.BundledItemRegistry; -import net.minecraft.world.item.ItemStack; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.registry.RegistryTypes; - -public class SpongeItemRegistry extends BundledItemRegistry { - - @Override - public Component getRichName(ItemType itemType) { - return SpongeTextAdapter.convert(Sponge.game().registry(RegistryTypes.ITEM_TYPE) - .value(ResourceKey.resolve(itemType.id())).asComponent()); - } - - @Override - public Component getRichName(BaseItemStack itemStack) { - return TranslatableComponent.of( - ((ItemStack) (Object) SpongeAdapter.adapt(itemStack)).getDescriptionId() - ); - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePermissionsProvider.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePermissionsProvider.java deleted file mode 100644 index da99c0eca..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePermissionsProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.service.permission.PermissionDescription; -import org.spongepowered.api.service.permission.PermissionService; -import org.spongepowered.api.service.permission.SubjectReference; - -public class SpongePermissionsProvider { - - public boolean hasPermission(ServerPlayer player, String permission) { - return player.hasPermission(permission); - } - - public void registerPermission(String permission) { - Sponge.game().serviceProvider().registration(PermissionService.class).ifPresent((permissionService -> { - PermissionDescription.Builder permissionBuilder = permissionService.service() - .newDescriptionBuilder(SpongeWorldEdit.inst().getPluginContainer()); - permissionBuilder.id(permission).register(); - })); - } - - public String[] getGroups(ServerPlayer player) { - return player.parents().stream() - .map(SubjectReference::subjectIdentifier) - .toArray(String[]::new); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlatform.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlatform.java deleted file mode 100644 index 011f932b1..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlatform.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.google.common.collect.ImmutableSet; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extension.platform.AbstractPlatform; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.extension.platform.MultiUserPlatform; -import com.sk89q.worldedit.extension.platform.Preference; -import com.sk89q.worldedit.sponge.config.SpongeConfiguration; -import com.sk89q.worldedit.util.SideEffect; -import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.registry.Registries; -import org.enginehub.piston.CommandManager; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.scheduler.Task; -import org.spongepowered.api.util.Ticks; -import org.spongepowered.api.world.server.ServerWorld; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nullable; - -import static java.util.stream.Collectors.toList; - -class SpongePlatform extends AbstractPlatform implements MultiUserPlatform { - - private final SpongeWorldEdit mod; - private boolean hookingEvents = false; - private int nextTaskId = 0; - - SpongePlatform(SpongeWorldEdit mod) { - this.mod = mod; - } - - boolean isHookingEvents() { - return hookingEvents; - } - - @Override - public Registries getRegistries() { - return SpongeRegistries.getInstance(); - } - - @Override - public int getDataVersion() { - return Sponge.platform().minecraftVersion().dataVersion().orElse(-1); - } - - @Override - public boolean isValidMobType(String type) { - return Sponge.game().registry(RegistryTypes.ENTITY_TYPE) - .findValue(ResourceKey.resolve(type)).isPresent(); - } - - @Override - public void reload() { - getConfiguration().load(); - super.reload(); - } - - @Override - public int schedule(long delay, long period, Runnable task) { - Sponge.server().scheduler().submit(Task.builder() - .delay(Ticks.of(delay)) - .interval(Ticks.of(period)) - .execute(task) - .plugin(SpongeWorldEdit.inst().getPluginContainer()) - .build()); - return nextTaskId++; - } - - @Override - public List getWorlds() { - Collection worlds = Sponge.server().worldManager().worlds(); - List ret = new ArrayList<>(worlds.size()); - for (ServerWorld world : worlds) { - ret.add(SpongeAdapter.adapt(world)); - } - return ret; - } - - @Nullable - @Override - public Player matchPlayer(Player player) { - if (player instanceof SpongePlayer) { - return player; - } else { - Optional optPlayer = Sponge.server().player(player.getUniqueId()); - return optPlayer.map(SpongePlayer::new).orElse(null); - } - } - - @Nullable - @Override - public World matchWorld(World world) { - if (world instanceof SpongeWorld) { - return world; - } else { - // TODO this needs fixing for world name shenanigans - for (ServerWorld spongeWorld : Sponge.server().worldManager().worlds()) { - if (spongeWorld.key().toString().equals(world.getName())) { - return SpongeAdapter.adapt(spongeWorld); - } - } - - return null; - } - } - - @Override - public void registerCommands(CommandManager manager) { - } - - @Override - public void setGameHooksEnabled(boolean enabled) { - this.hookingEvents = enabled; - } - - @Override - public SpongeConfiguration getConfiguration() { - return mod.getConfig(); - } - - @Override - public String getVersion() { - return mod.getInternalVersion(); - } - - @Override - public String getPlatformName() { - return "Sponge-Official"; - } - - @Override - public String getPlatformVersion() { - return mod.getInternalVersion(); - } - - @Override - public String id() { - return "enginehub:sponge"; - } - - @Override - public Map getCapabilities() { - Map capabilities = new EnumMap<>(Capability.class); - capabilities.put(Capability.CONFIGURATION, Preference.NORMAL); - capabilities.put(Capability.WORLDEDIT_CUI, Preference.NORMAL); - capabilities.put(Capability.GAME_HOOKS, Preference.NORMAL); - capabilities.put(Capability.PERMISSIONS, Preference.NORMAL); - capabilities.put(Capability.USER_COMMANDS, Preference.NORMAL); - capabilities.put(Capability.WORLD_EDITING, Preference.PREFERRED); - return capabilities; - } - - @Override - public Set getSupportedSideEffects() { - return ImmutableSet.of( - SideEffect.UPDATE, SideEffect.ENTITY_AI, SideEffect.LIGHTING, SideEffect.NEIGHBORS - ); - } - - @Override - public long getTickCount() { - return Sponge.server().runningTimeTicks().ticks(); - } - - @Override - public Collection getConnectedUsers() { - return Sponge.server().onlinePlayers().stream().map(SpongePlayer::new).collect(toList()); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java deleted file mode 100644 index a495924a5..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.util.StringUtil; -import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.entity.BaseEntity; -import com.sk89q.worldedit.extension.platform.AbstractPlayerActor; -import com.sk89q.worldedit.extent.inventory.BlockBag; -import com.sk89q.worldedit.internal.cui.CUIEvent; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.Vector3; -import com.sk89q.worldedit.session.SessionKey; -import com.sk89q.worldedit.sponge.internal.NbtAdapter; -import com.sk89q.worldedit.util.HandSide; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.gamemode.GameMode; -import com.sk89q.worldedit.world.gamemode.GameModes; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextColor; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.minecraft.core.BlockPos; -import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; -import net.minecraft.world.level.block.entity.StructureBlockEntity; -import org.enginehub.linbus.tree.LinCompoundTag; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.data.Keys; -import org.spongepowered.api.data.type.HandTypes; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.item.inventory.ItemStack; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.math.vector.Vector3d; - -import java.nio.charset.StandardCharsets; -import java.util.Locale; -import java.util.UUID; -import javax.annotation.Nullable; - -public class SpongePlayer extends AbstractPlayerActor { - private static final int STRUCTURE_BLOCK_PACKET_ID = 7; - - private final ServerPlayer player; - - protected SpongePlayer(ServerPlayer player) { - this.player = player; - ThreadSafeCache.getInstance().getOnlineIds().add(getUniqueId()); - } - - @Override - public UUID getUniqueId() { - return player.uniqueId(); - } - - @Override - public BaseItemStack getItemInHand(HandSide handSide) { - ItemStack is = this.player.itemInHand( - handSide == HandSide.MAIN_HAND ? HandTypes.MAIN_HAND : HandTypes.OFF_HAND - ); - return SpongeAdapter.adapt(is); - } - - @Override - public String getName() { - return this.player.name(); - } - - @Override - public String getDisplayName() { - return LegacyComponentSerializer.legacySection().serialize(player.displayName().get()); - } - - @Override - public BaseEntity getState() { - throw new UnsupportedOperationException("Cannot create a state from this object"); - } - - @Override - public Location getLocation() { - ServerLocation entityLoc = this.player.serverLocation(); - Vector3d entityRot = this.player.rotation(); - - return SpongeAdapter.adapt(entityLoc, entityRot); - } - - @Override - public boolean setLocation(Location location) { - return player.setLocation(SpongeAdapter.adapt(location)); - } - - @Override - public com.sk89q.worldedit.world.World getWorld() { - return SpongeAdapter.adapt(player.serverLocation().world()); - } - - @Override - public void giveItem(BaseItemStack itemStack) { - this.player.inventory().offer(SpongeAdapter.adapt(itemStack)); - } - - @Override - public void dispatchCUIEvent(CUIEvent event) { - String[] params = event.getParameters(); - String send = event.getTypeId(); - if (params.length > 0) { - send = send + "|" + StringUtil.joinString(params, "|"); - } - - String finalData = send; - CUIChannelHandler.channel().play().sendTo( - player, - buffer -> buffer.writeBytes(finalData.getBytes(StandardCharsets.UTF_8)) - ); - } - - @Override - @Deprecated - public void printRaw(String msg) { - for (String part : msg.split("\n")) { - this.player.sendMessage(LegacyComponentSerializer.legacySection().deserialize(part)); - } - } - - @Override - @Deprecated - public void printDebug(String msg) { - sendColorized(msg, NamedTextColor.GRAY); - } - - @Override - @Deprecated - public void print(String msg) { - sendColorized(msg, NamedTextColor.LIGHT_PURPLE); - } - - @Override - @Deprecated - public void printError(String msg) { - sendColorized(msg, NamedTextColor.RED); - } - - @Override - public void print(Component component) { - player.sendMessage(SpongeTextAdapter.convert(component, getLocale())); - } - - private void sendColorized(String msg, TextColor formatting) { - for (String part : msg.split("\n")) { - this.player.sendMessage( - LegacyComponentSerializer.legacySection().deserialize(part).color(formatting) - ); - } - } - - @Override - public boolean trySetPosition(Vector3 pos, float pitch, float yaw) { - ServerLocation loc = ServerLocation.of( - this.player.world(), pos.x(), pos.y(), pos.z() - ); - - return this.player.setLocationAndRotation(loc, new Vector3d(pitch, yaw, 0)); - } - - @Override - public String[] getGroups() { - return SpongeWorldEdit.inst().getPermissionsProvider().getGroups(this.player); - } - - @Override - public BlockBag getInventoryBlockBag() { - return null; - } - - @Override - public boolean hasPermission(String perm) { - return SpongeWorldEdit.inst().getPermissionsProvider().hasPermission(player, perm); - } - - @Nullable - @Override - public T getFacet(Class cls) { - return null; - } - - @Override - public GameMode getGameMode() { - return GameModes.get(player.gameMode().get().key(RegistryTypes.GAME_MODE).asString()); - } - - @Override - public void setGameMode(GameMode gameMode) { - player.gameMode().set( - Sponge.game().registry(RegistryTypes.GAME_MODE).value( - ResourceKey.resolve(gameMode.id()) - ) - ); - } - - @Override - public boolean isAllowedToFly() { - return player.get(Keys.CAN_FLY).orElse(super.isAllowedToFly()); - } - - @Override - public void setFlying(boolean flying) { - player.offer(Keys.IS_FLYING, flying); - } - - @Override - public > void sendFakeBlock(BlockVector3 pos, B block) { - if (block == null) { - player.resetBlockChange(pos.x(), pos.y(), pos.z()); - } else { - BlockState spongeBlock = SpongeAdapter.adapt(block.toImmutableState()); - player.sendBlockChange(pos.x(), pos.y(), pos.z(), spongeBlock); - if (block instanceof final BaseBlock baseBlock - && block.getBlockType().equals(com.sk89q.worldedit.world.block.BlockTypes.STRUCTURE_BLOCK)) { - final LinCompoundTag nbtData = baseBlock.getNbt(); - if (nbtData != null) { - net.minecraft.world.level.block.state.BlockState nativeBlock = - (net.minecraft.world.level.block.state.BlockState) spongeBlock; - net.minecraft.nbt.CompoundTag nativeNbtData = NbtAdapter.adaptNMSToWorldEdit(nbtData); - net.minecraft.server.level.ServerPlayer nativePlayer = - ((net.minecraft.server.level.ServerPlayer) player); - - StructureBlockEntity structureBlockEntity = - new StructureBlockEntity(new BlockPos(pos.x(), pos.y(), pos.z()), nativeBlock); - structureBlockEntity.load(nativeNbtData); - nativePlayer.connection.send( - ClientboundBlockEntityDataPacket.create(structureBlockEntity, it -> nativeNbtData)); - } - } - } - } - - @Override - public Locale getLocale() { - return player.locale(); - } - - @Override - public SessionKey getSessionKey() { - return new SessionKeyImpl(player); - } - - static class SessionKeyImpl implements SessionKey { - // If not static, this will leak a reference - - private final UUID uuid; - private final String name; - - SessionKeyImpl(Player player) { - this.uuid = player.uniqueId(); - this.name = player.name(); - } - - @Override - public UUID getUniqueId() { - return uuid; - } - - @Nullable - @Override - public String getName() { - return name; - } - - @Override - public boolean isActive() { - // We can't directly check if the player is online because - // the list of players is not thread safe - return ThreadSafeCache.getInstance().getOnlineIds().contains(uuid); - } - - @Override - public boolean isPersistent() { - return true; - } - - } - - public Player getPlayer() { - return player; - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeRegistries.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeRegistries.java deleted file mode 100644 index 04baa3936..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeRegistries.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.world.registry.BiomeRegistry; -import com.sk89q.worldedit.world.registry.BlockCategoryRegistry; -import com.sk89q.worldedit.world.registry.BlockRegistry; -import com.sk89q.worldedit.world.registry.BundledRegistries; -import com.sk89q.worldedit.world.registry.ItemCategoryRegistry; -import com.sk89q.worldedit.world.registry.ItemRegistry; - -/** - * World data for the Sponge platform. - */ -class SpongeRegistries extends BundledRegistries { - - private static final SpongeRegistries INSTANCE = new SpongeRegistries(); - - public static SpongeRegistries getInstance() { - return INSTANCE; - } - - private final BiomeRegistry biomeRegistry = new SpongeBiomeRegistry(); - private final BlockRegistry blockRegistry = new SpongeBlockRegistry(); - private final BlockCategoryRegistry blockCategoryRegistry = new SpongeBlockCategoryRegistry(); - private final ItemRegistry itemRegistry = new SpongeItemRegistry(); - private final ItemCategoryRegistry itemCategoryRegistry = new SpongeItemCategoryRegistry(); - - @Override - public BiomeRegistry getBiomeRegistry() { - return biomeRegistry; - } - - @Override - public BlockRegistry getBlockRegistry() { - return blockRegistry; - } - - @Override - public BlockCategoryRegistry getBlockCategoryRegistry() { - return blockCategoryRegistry; - } - - @Override - public ItemRegistry getItemRegistry() { - return itemRegistry; - } - - @Override - public ItemCategoryRegistry getItemCategoryRegistry() { - return itemCategoryRegistry; - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeTextAdapter.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeTextAdapter.java deleted file mode 100644 index 7709737e4..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeTextAdapter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.sk89q.worldedit.util.formatting.WorldEditText; -import com.sk89q.worldedit.util.formatting.text.Component; -import com.sk89q.worldedit.util.formatting.text.serializer.gson.GsonComponentSerializer; - -import java.util.Locale; - -public class SpongeTextAdapter { - - public static net.kyori.adventure.text.Component convert(Component component, Locale locale) { - component = WorldEditText.format(component, locale); - return net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson() - .deserialize(GsonComponentSerializer.INSTANCE.serialize(component)); - } - - public static Component convert(net.kyori.adventure.text.Component component) { - return GsonComponentSerializer.INSTANCE.deserialize( - net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson() - .serialize(component) - ); - } - - private SpongeTextAdapter() { - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java deleted file mode 100644 index 28258d5fa..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java +++ /dev/null @@ -1,507 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.google.common.collect.Sets; -import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.entity.BaseEntity; -import com.sk89q.worldedit.entity.Entity; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.internal.util.LogManagerCompat; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.Vector3; -import com.sk89q.worldedit.regions.CuboidRegion; -import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.sponge.internal.NbtAdapter; -import com.sk89q.worldedit.sponge.internal.SpongeWorldNativeAccess; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.SideEffect; -import com.sk89q.worldedit.util.SideEffectSet; -import com.sk89q.worldedit.util.TreeGenerator; -import com.sk89q.worldedit.world.AbstractWorld; -import com.sk89q.worldedit.world.RegenOptions; -import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.world.weather.WeatherType; -import com.sk89q.worldedit.world.weather.WeatherTypes; -import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.worldgen.features.EndFeatures; -import net.minecraft.data.worldgen.features.TreeFeatures; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import org.apache.logging.log4j.Logger; -import org.enginehub.linbus.tree.LinCompoundTag; -import org.enginehub.linbus.tree.LinIntTag; -import org.enginehub.linbus.tree.LinStringTag; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Server; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.block.entity.BlockEntity; -import org.spongepowered.api.block.entity.BlockEntityArchetype; -import org.spongepowered.api.block.entity.BlockEntityType; -import org.spongepowered.api.data.Keys; -import org.spongepowered.api.entity.EntityArchetype; -import org.spongepowered.api.entity.EntityType; -import org.spongepowered.api.entity.EntityTypes; -import org.spongepowered.api.entity.Item; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.util.Ticks; -import org.spongepowered.api.world.BlockChangeFlags; -import org.spongepowered.api.world.LightTypes; -import org.spongepowered.api.world.SerializationBehavior; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; -import org.spongepowered.api.world.server.WorldTemplate; -import org.spongepowered.api.world.volume.stream.StreamOptions; -import org.spongepowered.math.vector.Vector3d; -import org.spongepowered.math.vector.Vector3i; - -import java.lang.ref.WeakReference; -import java.nio.file.Path; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ThreadLocalRandom; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * An adapter to Minecraft worlds for WorldEdit. - */ -public final class SpongeWorld extends AbstractWorld { - - private static final RandomSource random = RandomSource.create(); - private static final Logger LOGGER = LogManagerCompat.getLogger(); - - private final WeakReference worldRef; - private final SpongeWorldNativeAccess worldNativeAccess; - - /** - * Construct a new world. - * - * @param world the world - */ - SpongeWorld(ServerWorld world) { - checkNotNull(world); - this.worldRef = new WeakReference<>(world); - this.worldNativeAccess = new SpongeWorldNativeAccess(new WeakReference<>((ServerLevel) world)); - } - - /** - * Get the underlying handle to the world. - * - * @return the world - * @throws RuntimeException thrown if a reference to the world was lost (i.e. world was - * unloaded) - */ - ServerWorld getWorld() { - ServerWorld world = worldRef.get(); - if (world != null) { - return world; - } else { - throw new RuntimeException("The reference to the world was lost (i.e. the world may have been unloaded)"); - } - } - - // This is sus but leaving it for later world name/id reworks - @Override - public String getName() { - return getWorld().key().asString(); - } - - @Override - public String id() { - return getWorld().key().asString(); - } - - @Override - public Path getStoragePath() { - return getWorld().directory(); - } - - @Override - public BlockState getBlock(BlockVector3 position) { - return SpongeAdapter.adapt(getWorld().block( - position.x(), position.y(), position.z() - )); - } - - @Override - public BaseBlock getFullBlock(BlockVector3 position) { - BlockEntity blockEntity = getWorld().blockEntity( - position.x(), position.y(), position.z() - ).orElse(null); - LinCompoundTag blockEntityData = null; - if (blockEntity != null) { - BlockEntityArchetype blockEntityArchetype = blockEntity.createArchetype(); - BlockEntityType blockEntityType = blockEntityArchetype.blockEntityType(); - ResourceKey blockEntityId = blockEntityType.key(RegistryTypes.BLOCK_ENTITY_TYPE); - blockEntityData = NbtAdapter.adaptToWorldEdit(blockEntityArchetype.blockEntityData()); - - // Add ID and position since Sponge's #blockEntityData does not save metadata - LinCompoundTag.Builder fullBlockEntityDataBuilder = blockEntityData.toBuilder(); - fullBlockEntityDataBuilder.put("id", LinStringTag.of(blockEntityId.formatted())); - fullBlockEntityDataBuilder.put("x", LinIntTag.of(position.x())); - fullBlockEntityDataBuilder.put("y", LinIntTag.of(position.y())); - fullBlockEntityDataBuilder.put("z", LinIntTag.of(position.z())); - blockEntityData = fullBlockEntityDataBuilder.build(); - } - return getBlock(position).toBaseBlock(blockEntityData); - } - - @Override - public > boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException { - checkNotNull(position); - checkNotNull(block); - - ServerWorld world = getWorld(); - - org.spongepowered.api.block.BlockState newState = SpongeAdapter.adapt(block.toImmutableState()); - - boolean didSet = world.setBlock( - position.x(), position.y(), position.z(), - newState, - BlockChangeFlags.NONE - .withUpdateNeighbors(sideEffects.shouldApply(SideEffect.NEIGHBORS)) - .withNotifyClients(true) - .withPhysics(sideEffects.shouldApply(SideEffect.UPDATE)) - .withNotifyObservers(sideEffects.shouldApply(SideEffect.UPDATE)) - .withLightingUpdates(sideEffects.shouldApply(SideEffect.LIGHTING)) - .withPathfindingUpdates(sideEffects.shouldApply(SideEffect.ENTITY_AI)) - .withNeighborDropsAllowed(false) - .withBlocksMoving(false) - .withForcedReRender(false) - .withIgnoreRender(false) - ); - if (!didSet) { - // still update NBT if the block is the same - if (world.block(position.x(), position.y(), position.z()) == newState) { - didSet = block.toBaseBlock().getNbt() != null; - } - } - - // Create the TileEntity - if (didSet && block instanceof BaseBlock baseBlock) { - LinCompoundTag nbt = baseBlock.getNbt(); - if (nbt != null) { - BlockEntityArchetype.builder() - .blockEntity( - Sponge.game().registry(RegistryTypes.BLOCK_ENTITY_TYPE) - .value(ResourceKey.resolve(baseBlock.getNbtId())) - ) - .blockEntityData(NbtAdapter.adaptFromWorldEdit(nbt)) - .state(newState) - .build() - .apply(ServerLocation.of(world, position.x(), position.y(), position.z())); - } - } - - return true; - } - - @Override - public Set applySideEffects(BlockVector3 position, com.sk89q.worldedit.world.block.BlockState previousType, SideEffectSet sideEffectSet) throws WorldEditException { - checkNotNull(position); - - worldNativeAccess.applySideEffects(position, previousType, sideEffectSet); - - return Sets.intersection( - SpongeWorldEdit.inst().getInternalPlatform().getSupportedSideEffects(), - sideEffectSet.getSideEffectsToApply() - ); - } - - @Override - public boolean clearContainerBlockContents(BlockVector3 position) { - getWorld().removeBlockEntity(position.x(), position.y(), position.z()); - return true; - } - - @Override - public boolean regenerate(Region region, Extent extent, RegenOptions options) { - Server server = Sponge.server(); - - final String id = "worldedittemp_" + getWorld().key().value(); - - WorldTemplate tempWorldProperties = WorldTemplate.builder().from(getWorld()) - .key(ResourceKey.of("worldedit", id)) - .add(Keys.IS_LOAD_ON_STARTUP, false) - .add(Keys.SERIALIZATION_BEHAVIOR, SerializationBehavior.NONE) - .add(Keys.SEED, options.getSeed().orElse(getWorld().properties().worldGenerationConfig().seed())) - .build(); - - ServerWorld tempWorld; - try { - tempWorld = server.worldManager().loadWorld(tempWorldProperties).get(); - } catch (InterruptedException | ExecutionException e) { - LOGGER.error("Failed to load temp world", e); - return false; - } - - try { - // Pre-gen all the chunks - // We need to also pull one more chunk in every direction - CuboidRegion expandedPreGen = new CuboidRegion(region.getMinimumPoint().subtract(16, 16, 16), region.getMaximumPoint().add(16, 16, 16)); - for (BlockVector3 chunk : expandedPreGen.getChunkCubes()) { - tempWorld.loadChunk(chunk.x(), chunk.y(), chunk.z(), true); - } - - World from = SpongeAdapter.adapt(tempWorld); - for (BlockVector3 vec : region) { - extent.setBlock(vec, from.getFullBlock(vec)); - if (options.shouldRegenBiomes()) { - extent.setBiome(vec, from.getBiome(vec)); - } - } - } catch (WorldEditException e) { - throw new RuntimeException(e); - } finally { - // Remove temp world - server.worldManager().unloadWorld(tempWorldProperties.key()).thenRun(() -> server.worldManager().deleteWorld(tempWorldProperties.key())); - } - - return true; - } - - - @Nullable - private static net.minecraft.resources.ResourceKey> createTreeFeatureGenerator(TreeGenerator.TreeType type) { - return switch (type) { - // Based off of the SaplingGenerator class, as well as uses of DefaultBiomeFeatures fields - case TREE -> TreeFeatures.OAK; - case BIG_TREE -> TreeFeatures.FANCY_OAK; - case REDWOOD -> TreeFeatures.SPRUCE; - case TALL_REDWOOD -> TreeFeatures.MEGA_SPRUCE; - case MEGA_REDWOOD -> TreeFeatures.MEGA_PINE; - case BIRCH -> TreeFeatures.BIRCH; - case JUNGLE -> TreeFeatures.MEGA_JUNGLE_TREE; - case SMALL_JUNGLE -> TreeFeatures.JUNGLE_TREE; - case SHORT_JUNGLE -> TreeFeatures.JUNGLE_TREE_NO_VINE; - case JUNGLE_BUSH -> TreeFeatures.JUNGLE_BUSH; - case SWAMP -> TreeFeatures.SWAMP_OAK; - case ACACIA -> TreeFeatures.ACACIA; - case DARK_OAK -> TreeFeatures.DARK_OAK; - case TALL_BIRCH -> TreeFeatures.SUPER_BIRCH_BEES_0002; - case RED_MUSHROOM -> TreeFeatures.HUGE_RED_MUSHROOM; - case BROWN_MUSHROOM -> TreeFeatures.HUGE_BROWN_MUSHROOM; - case WARPED_FUNGUS -> TreeFeatures.WARPED_FUNGUS; - case CRIMSON_FUNGUS -> TreeFeatures.CRIMSON_FUNGUS; - case CHORUS_PLANT -> EndFeatures.CHORUS_PLANT; - case MANGROVE -> TreeFeatures.MANGROVE; - case TALL_MANGROVE -> TreeFeatures.TALL_MANGROVE; - case CHERRY -> TreeFeatures.CHERRY; - case RANDOM -> - createTreeFeatureGenerator(TreeGenerator.TreeType.values()[ThreadLocalRandom.current().nextInt(TreeGenerator.TreeType.values().length)]); - default -> null; - }; - } - - @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) { - ServerLevel world = (ServerLevel) getWorld(); - ConfiguredFeature generator = Optional.ofNullable(createTreeFeatureGenerator(type)) - .map(k -> world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(k)) - .orElse(null); - return generator != null && generator.place( - world, world.getChunkSource().getGenerator(), random, - new BlockPos(position.x(), position.y(), position.z()) - ); - } - - @Override - public int getBlockLightLevel(BlockVector3 position) { - checkNotNull(position); - - int skyLight = getWorld().light(LightTypes.SKY, position.x(), position.y(), position.z()); - int groundLight = getWorld().light(LightTypes.BLOCK, position.x(), position.y(), position.z()); - - return Math.max(skyLight, groundLight); - - } - - @Override - public BiomeType getBiome(BlockVector3 position) { - checkNotNull(position); - return BiomeType.REGISTRY.get( - getWorld().registry(RegistryTypes.BIOME) - .valueKey(getWorld().biome(position.x(), position.y(), position.z())) - .asString() - ); - } - - @Override - public boolean setBiome(BlockVector3 position, BiomeType biome) { - checkNotNull(position); - checkNotNull(biome); - - getWorld().setBiome( - position.x(), position.y(), position.z(), - getWorld().registry(RegistryTypes.BIOME).value( - ResourceKey.resolve(biome.id()) - ) - ); - return true; - } - - @Override - public void dropItem(Vector3 position, BaseItemStack item) { - checkNotNull(position); - checkNotNull(item); - - if (item.getType() == ItemTypes.AIR) { - return; - } - - Item itemEntity = getWorld().createEntity( - EntityTypes.ITEM, - new Vector3d(position.x(), position.y(), position.z()) - ); - - itemEntity.item().set( - SpongeAdapter.adapt(item).createSnapshot() - ); - getWorld().spawnEntity(itemEntity); - } - - @Override - public void simulateBlockMine(BlockVector3 position) { - getWorld().destroyBlock( - new Vector3i(position.x(), position.y(), position.z()), - true - ); - } - - @Override - public boolean canPlaceAt(BlockVector3 position, com.sk89q.worldedit.world.block.BlockState blockState) { - return ((net.minecraft.world.level.block.state.BlockState) SpongeAdapter.adapt(blockState)) - .canSurvive( - ((LevelReader) getWorld()), - new BlockPos(position.x(), position.y(), position.z()) - ); - } - - @Override - public int hashCode() { - return getWorld().hashCode(); - } - - @Override - public boolean equals(Object o) { - if (o == null) { - return false; - } else if ((o instanceof SpongeWorld other)) { - ServerWorld otherWorld = other.worldRef.get(); - ServerWorld thisWorld = worldRef.get(); - return otherWorld != null && otherWorld.equals(thisWorld); - } else { - return o instanceof com.sk89q.worldedit.world.World - && ((com.sk89q.worldedit.world.World) o).getName().equals(getName()); - } - } - - @Override - public List getEntities(Region region) { - return getWorld() - .entityStream( - SpongeAdapter.adaptVector3i(region.getMinimumPoint()), - SpongeAdapter.adaptVector3i(region.getMaximumPoint()), - // We don't need to force load or clone to copy entities - StreamOptions.builder() - .setCarbonCopy(false) - .setLoadingStyle(StreamOptions.LoadingStyle.NONE) - .build() - ) - .toStream() - .map(ve -> new SpongeEntity(ve.type())) - .collect(Collectors.toList()); - } - - @Override - public List getEntities() { - return getWorld().entities().stream() - .map(SpongeEntity::new) - .collect(Collectors.toList()); - } - - @Nullable - @Override - public Entity createEntity(Location location, BaseEntity entity) { - Optional> entityType = Sponge.game().registry(RegistryTypes.ENTITY_TYPE) - .findValue(ResourceKey.resolve(entity.getType().id())); - if (entityType.isEmpty()) { - return null; - } - EntityArchetype.Builder builder = EntityArchetype.builder().type(entityType.get()); - var nativeTag = entity.getNbt(); - if (nativeTag != null) { - builder.entityData(NbtAdapter.adaptFromWorldEdit(nativeTag)); - } - return builder.build().apply(SpongeAdapter.adapt(location)).map(SpongeEntity::new).orElse(null); - } - - @Override - public WeatherType getWeather() { - return WeatherTypes.get( - getWorld().weather().type().key(RegistryTypes.WEATHER_TYPE).asString() - ); - } - - @Override - public long getRemainingWeatherDuration() { - return getWorld().weather().remainingDuration().ticks(); - } - - @Override - public void setWeather(WeatherType weatherType) { - getWorld().setWeather( - Sponge.game().registry(RegistryTypes.WEATHER_TYPE).value( - ResourceKey.resolve(weatherType.id()) - ) - ); - } - - @Override - public void setWeather(WeatherType weatherType, long duration) { - getWorld().setWeather( - Sponge.game().registry(RegistryTypes.WEATHER_TYPE).value( - ResourceKey.resolve(weatherType.id()) - ), - Ticks.of(duration) - ); - } - - @Override - public BlockVector3 getSpawnPosition() { - return SpongeAdapter.adaptVector3i(getWorld().properties().spawnPosition()); - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java deleted file mode 100644 index ed2e8b7a5..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import com.google.common.base.Joiner; -import com.google.inject.Inject; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.command.util.PermissionCondition; -import com.sk89q.worldedit.event.platform.CommandEvent; -import com.sk89q.worldedit.event.platform.CommandSuggestionEvent; -import com.sk89q.worldedit.event.platform.PlatformReadyEvent; -import com.sk89q.worldedit.event.platform.PlatformUnreadyEvent; -import com.sk89q.worldedit.event.platform.PlatformsRegisteredEvent; -import com.sk89q.worldedit.event.platform.SessionIdleEvent; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.extension.platform.Platform; -import com.sk89q.worldedit.extension.platform.PlatformManager; -import com.sk89q.worldedit.internal.anvil.ChunkDeleter; -import com.sk89q.worldedit.internal.command.CommandUtil; -import com.sk89q.worldedit.internal.event.InteractionDebouncer; -import com.sk89q.worldedit.sponge.config.SpongeConfiguration; -import com.sk89q.worldedit.world.biome.BiomeCategory; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BlockCategory; -import com.sk89q.worldedit.world.item.ItemCategory; -import net.kyori.adventure.audience.Audience; -import org.apache.logging.log4j.Logger; -import org.bstats.sponge.Metrics; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Server; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.block.BlockSnapshot; -import org.spongepowered.api.block.BlockType; -import org.spongepowered.api.block.entity.BlockEntity; -import org.spongepowered.api.block.entity.CommandBlock; -import org.spongepowered.api.command.Command; -import org.spongepowered.api.command.CommandCause; -import org.spongepowered.api.command.CommandCompletion; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.parameter.ArgumentReader; -import org.spongepowered.api.config.ConfigDir; -import org.spongepowered.api.data.type.HandTypes; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; -import org.spongepowered.api.event.EventContextKeys; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.action.InteractEvent; -import org.spongepowered.api.event.block.InteractBlockEvent; -import org.spongepowered.api.event.filter.cause.Root; -import org.spongepowered.api.event.item.inventory.InteractItemEvent; -import org.spongepowered.api.event.lifecycle.ConstructPluginEvent; -import org.spongepowered.api.event.lifecycle.RegisterCommandEvent; -import org.spongepowered.api.event.lifecycle.StartedEngineEvent; -import org.spongepowered.api.event.lifecycle.StartingEngineEvent; -import org.spongepowered.api.event.lifecycle.StoppingEngineEvent; -import org.spongepowered.api.event.network.ServerSideConnectionEvent; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.scheduler.Task; -import org.spongepowered.api.world.LocatableBlock; -import org.spongepowered.api.world.server.ServerLocation; -import org.spongepowered.api.world.server.ServerWorld; -import org.spongepowered.math.vector.Vector3d; -import org.spongepowered.plugin.PluginContainer; -import org.spongepowered.plugin.builtin.jvm.Plugin; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static com.sk89q.worldedit.internal.anvil.ChunkDeleter.DELCHUNKS_FILE_NAME; -import static java.util.stream.Collectors.toList; - -/** - * The Sponge implementation of WorldEdit. - */ -@Plugin(SpongeWorldEdit.MOD_ID) -public class SpongeWorldEdit { - - public static final String MOD_ID = "worldedit"; - private static final int BSTATS_PLUGIN_ID = 3329; - - private static SpongeWorldEdit inst; - - public static SpongeWorldEdit inst() { - return inst; - } - - private final Logger logger; - private final PluginContainer container; - private final SpongeConfiguration config; - private final Path workingDir; - - private InteractionDebouncer debouncer; - private SpongePermissionsProvider provider; - private SpongePlatform platform; - - @Inject - public SpongeWorldEdit(Logger logger, - PluginContainer container, - SpongeConfiguration config, - Metrics.Factory metricsFactory, - @ConfigDir(sharedRoot = false) - Path workingDir) { - this.logger = logger; - this.container = container; - this.config = config; - this.workingDir = workingDir; - metricsFactory.make(BSTATS_PLUGIN_ID); - inst = this; - } - - @Listener - public void onPluginConstruction(ConstructPluginEvent event) { - this.platform = new SpongePlatform(this); - debouncer = new InteractionDebouncer(platform); - - WorldEdit.getInstance().getPlatformManager().register(platform); - - this.provider = new SpongePermissionsProvider(); - - event.game().eventManager().registerListeners( - container, - new CUIChannelHandler.RegistrationHandler() - ); - logger.info("WorldEdit for Sponge (version " + getInternalVersion() + ") is loaded"); - } - - @Listener - public void serverStarting(StartingEngineEvent event) { - final Path delChunks = workingDir.resolve(DELCHUNKS_FILE_NAME); - if (Files.exists(delChunks)) { - ChunkDeleter.runFromFile(delChunks, true); - } - } - - @Listener - public void serverStarted(StartedEngineEvent event) { - event.engine().scheduler().submit(Task.builder() - .plugin(container) - .interval(30, TimeUnit.SECONDS) - .execute(ThreadSafeCache.getInstance()) - .build()); - - event.game().registry(RegistryTypes.BLOCK_TYPE).streamEntries().forEach(blockType -> { - String id = blockType.key().asString(); - if (!com.sk89q.worldedit.world.block.BlockType.REGISTRY.keySet().contains(id)) { - com.sk89q.worldedit.world.block.BlockType.REGISTRY.register(id, new com.sk89q.worldedit.world.block.BlockType( - id, - input -> { - BlockType spongeBlockType = Sponge.game().registry(RegistryTypes.BLOCK_TYPE).value( - ResourceKey.resolve(input.getBlockType().id()) - ); - return SpongeAdapter.adapt(spongeBlockType.defaultState()); - } - )); - } - }); - - event.game().registry(RegistryTypes.ITEM_TYPE).streamEntries().forEach(itemType -> { - String id = itemType.key().asString(); - if (!com.sk89q.worldedit.world.item.ItemType.REGISTRY.keySet().contains(id)) { - com.sk89q.worldedit.world.item.ItemType.REGISTRY.register(id, new com.sk89q.worldedit.world.item.ItemType(id)); - } - }); - - event.game().registry(RegistryTypes.ENTITY_TYPE).streamEntries().forEach(entityType -> { - String id = entityType.key().asString(); - if (!com.sk89q.worldedit.world.entity.EntityType.REGISTRY.keySet().contains(id)) { - com.sk89q.worldedit.world.entity.EntityType.REGISTRY.register(id, new com.sk89q.worldedit.world.entity.EntityType(id)); - } - }); - - for (ServerWorld world : event.engine().worldManager().worlds()) { - world.registry(RegistryTypes.BIOME).streamEntries().forEach(biomeType -> { - String id = biomeType.key().asString(); - if (!BiomeType.REGISTRY.keySet().contains(id)) { - BiomeType.REGISTRY.register(id, new BiomeType(id)); - } - }); - } - - event.game().registry(RegistryTypes.BLOCK_TYPE).tags().forEach(blockTypeTag -> { - String id = blockTypeTag.key().asString(); - if (!BlockCategory.REGISTRY.keySet().contains(id)) { - BlockCategory.REGISTRY.register(id, new BlockCategory(id)); - } - }); - event.game().registry(RegistryTypes.ITEM_TYPE).tags().forEach(itemTypeTag -> { - String id = itemTypeTag.key().asString(); - if (!ItemCategory.REGISTRY.keySet().contains(id)) { - ItemCategory.REGISTRY.register(id, new ItemCategory(id)); - } - }); - event.game().registry(RegistryTypes.BIOME).tags().forEach(biomeTag -> { - String id = biomeTag.key().asString(); - if (!BiomeCategory.REGISTRY.keySet().contains(id)) { - BiomeCategory.REGISTRY.register(id, new BiomeCategory(id, () -> event.game().registry(RegistryTypes.BIOME).taggedValues(biomeTag).stream().map(SpongeAdapter::adapt).collect(Collectors.toSet()))); - } - }); - - config.load(); - WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent(platform)); - } - - @Listener - public void serverStopping(StoppingEngineEvent event) { - WorldEdit worldEdit = WorldEdit.getInstance(); - worldEdit.getSessionManager().unload(); - WorldEdit.getInstance().getEventBus().post(new PlatformUnreadyEvent(platform)); - } - - @Listener - public void registerCommand(RegisterCommandEvent event) { - WorldEdit.getInstance().getEventBus().post(new PlatformsRegisteredEvent()); - PlatformManager manager = WorldEdit.getInstance().getPlatformManager(); - Platform commandsPlatform = manager.queryCapability(Capability.USER_COMMANDS); - if (commandsPlatform != platform || !platform.isHookingEvents()) { - // We're not in control of commands/events -- do not register. - return; - } - - List commands = manager.getPlatformCommandManager().getCommandManager() - .getAllCommands().toList(); - for (org.enginehub.piston.Command command : commands) { - registerAdaptedCommand(event, command); - - Set perms = command.getCondition().as(PermissionCondition.class) - .map(PermissionCondition::getPermissions) - .orElseGet(Collections::emptySet); - if (!perms.isEmpty()) { - perms.forEach(getPermissionsProvider()::registerPermission); - } - } - } - - private String rebuildArguments(String commandLabel, String args) { - int plSep = commandLabel.indexOf(':'); - if (plSep >= 0 && plSep < commandLabel.length() + 1) { - commandLabel = commandLabel.substring(plSep + 1); - } - - StringBuilder sb = new StringBuilder("/").append(commandLabel); - - String[] split = args.split(" ", -1); - if (split.length > 0) { - sb.append(" "); - } - return Joiner.on(" ").appendTo(sb, split).toString(); - } - - private void registerAdaptedCommand(RegisterCommandEvent event, org.enginehub.piston.Command command) { - CommandAdapter adapter = new CommandAdapter(command) { - @Override - public CommandResult process(CommandCause cause, ArgumentReader.Mutable arguments) { - CommandEvent weEvent = new CommandEvent(SpongeWorldEdit.inst().wrapCommandCause(cause), rebuildArguments(command.getName(), arguments.remaining()).trim()); - WorldEdit.getInstance().getEventBus().post(weEvent); - return weEvent.isCancelled() ? CommandResult.success() : CommandResult.builder().build(); - } - - @Override - public List complete(CommandCause cause, ArgumentReader.Mutable arguments) { - String args = rebuildArguments(command.getName(), arguments.remaining()); - CommandSuggestionEvent weEvent = new CommandSuggestionEvent(SpongeWorldEdit.inst().wrapCommandCause(cause), args); - WorldEdit.getInstance().getEventBus().post(weEvent); - return CommandUtil.fixSuggestions(args, weEvent.getSuggestions()) - .stream().map(CommandCompletion::of).collect(toList()); - } - }; - event.register( - container, adapter, command.getName(), command.getAliases().toArray(new String[0]) - ); - } - - private boolean skipEvents() { - return platform == null || !platform.isHookingEvents(); - } - - private boolean skipInteractionEvent(InteractEvent event) { - return skipEvents() || event.context().get(EventContextKeys.USED_HAND).orElse(null) != HandTypes.MAIN_HAND.get(); - } - - @Listener - public void onPlayerInteractItemPrimary(InteractItemEvent.Primary event, @Root ServerPlayer spongePlayer) { - if (skipInteractionEvent(event)) { - return; - } - - WorldEdit we = WorldEdit.getInstance(); - SpongePlayer player = SpongeAdapter.adapt(spongePlayer); - - Optional previousResult = debouncer.getDuplicateInteractionResult(player); - if (previousResult.isPresent()) { - return; - } - - boolean result = we.handleArmSwing(player); - debouncer.setLastInteraction(player, result); - } - - @Listener - public void onPlayerInteractItemSecondary(InteractItemEvent.Secondary event, @Root ServerPlayer spongePlayer) { - if (skipInteractionEvent(event)) { - return; - } - - WorldEdit we = WorldEdit.getInstance(); - SpongePlayer player = SpongeAdapter.adapt(spongePlayer); - - Optional previousResult = debouncer.getDuplicateInteractionResult(player); - if (previousResult.isPresent()) { - if (previousResult.get()) { - event.setCancelled(true); - } - return; - } - - boolean result = we.handleRightClick(player); - debouncer.setLastInteraction(player, result); - - if (result) { - event.setCancelled(true); - } - } - - @Listener - public void onPlayerInteractBlockPrimary(InteractBlockEvent.Primary.Start event, @Root ServerPlayer spongePlayer) { - if (skipInteractionEvent(event)) { - return; - } - - WorldEdit we = WorldEdit.getInstance(); - SpongePlayer player = SpongeAdapter.adapt(spongePlayer); - - BlockSnapshot targetBlock = event.block(); - Optional optLoc = targetBlock.location(); - - boolean result = false; - if (optLoc.isPresent()) { - ServerLocation loc = optLoc.get(); - com.sk89q.worldedit.util.Location pos = SpongeAdapter.adapt(loc, Vector3d.ZERO); - - result = we.handleBlockLeftClick(player, pos, SpongeAdapter.adapt(event.targetSide())); - } - - result = we.handleArmSwing(player) || result; - debouncer.setLastInteraction(player, result); - - if (result) { - event.setCancelled(true); - } - } - - @Listener - public void onPlayerInteractBlockSecondary(InteractBlockEvent.Secondary event, @Root ServerPlayer spongePlayer) { - if (skipInteractionEvent(event)) { - return; - } - - WorldEdit we = WorldEdit.getInstance(); - SpongePlayer player = SpongeAdapter.adapt(spongePlayer); - - BlockSnapshot targetBlock = event.block(); - Optional optLoc = targetBlock.location(); - - boolean result = false; - if (optLoc.isPresent()) { - ServerLocation loc = optLoc.get(); - com.sk89q.worldedit.util.Location pos = SpongeAdapter.adapt(loc, Vector3d.ZERO); - - result = we.handleBlockRightClick(player, pos, SpongeAdapter.adapt(event.targetSide())); - } - - result = we.handleRightClick(player) || result; - debouncer.setLastInteraction(player, result); - - if (result) { - event.setCancelled(true); - } - } - - @Listener - public void onPlayerQuit(ServerSideConnectionEvent.Disconnect event) { - debouncer.clearInteraction(SpongeAdapter.adapt(event.player())); - - WorldEdit.getInstance().getEventBus() - .post(new SessionIdleEvent(new SpongePlayer.SessionKeyImpl(event.player()))); - } - - public PluginContainer getPluginContainer() { - return container; - } - - /** - * Get the configuration. - * - * @return the Sponge configuration - */ - SpongeConfiguration getConfig() { - return this.config; - } - - public Actor wrapCommandCause(CommandCause cause) { - Object rootCause = cause.root(); - if (rootCause instanceof ServerPlayer) { - return SpongeAdapter.adapt((ServerPlayer) rootCause); - } - if (rootCause instanceof LocatableBlock locatableBlock) { - Optional optionalBlockEntity = locatableBlock.world().blockEntity(locatableBlock.blockPosition()); - if (optionalBlockEntity.isPresent()) { - BlockEntity blockEntity = optionalBlockEntity.get(); - if (blockEntity instanceof CommandBlock commandBlock) { - return new SpongeBlockCommandSender(this, commandBlock); - } - } - } - if (rootCause instanceof Audience) { - return new SpongeCommandSender((Audience) rootCause); - } - - throw new UnsupportedOperationException("Cannot wrap " + rootCause.getClass()); - } - - - /** - * Get the WorldEdit proxy for the platform. - * - * @return the WorldEdit platform - */ - public Platform getPlatform() { - return this.platform; - } - - SpongePlatform getInternalPlatform() { - return this.platform; - } - - /** - * Get the working directory where WorldEdit's files are stored. - * - * @return the working directory - */ - public Path getWorkingDir() { - return this.workingDir; - } - - /** - * Get the version of the WorldEdit Sponge implementation. - * - * @return a version string - */ - String getInternalVersion() { - return container.metadata().version().toString(); - } - - public void setPermissionsProvider(SpongePermissionsProvider provider) { - this.provider = provider; - } - - public SpongePermissionsProvider getPermissionsProvider() { - return provider; - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/ThreadSafeCache.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/ThreadSafeCache.java deleted file mode 100644 index b6f131444..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/ThreadSafeCache.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge; - -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArraySet; - -/** - * Caches data that cannot be accessed from another thread safely. - */ -public class ThreadSafeCache implements Runnable { - - private static final ThreadSafeCache INSTANCE = new ThreadSafeCache(); - private Set onlineIds = new CopyOnWriteArraySet<>(); - - /** - * Get an concurrent-safe set of UUIDs of online players. - * - * @return a set of UUIDs - */ - public Set getOnlineIds() { - return onlineIds; - } - - @Override - public void run() { - List onlineIds = new ArrayList<>(); - - for (ServerPlayer player : Sponge.server().onlinePlayers()) { - onlineIds.add(player.uniqueId()); - } - - this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); - } - - public static ThreadSafeCache getInstance() { - return INSTANCE; - } - -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java deleted file mode 100644 index b9f043752..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.config; - -import com.google.common.collect.ImmutableList; -import com.sk89q.worldedit.LocalConfiguration; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.session.SessionManager; -import com.sk89q.worldedit.util.report.Unreported; -import com.sk89q.worldedit.world.registry.LegacyMapper; -import org.apache.logging.log4j.Logger; -import org.spongepowered.configurate.CommentedConfigurationNode; -import org.spongepowered.configurate.ConfigurationOptions; -import org.spongepowered.configurate.loader.ConfigurationLoader; -import org.spongepowered.configurate.serialize.SerializationException; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Locale; - -public class ConfigurateConfiguration extends LocalConfiguration { - - @Unreported - protected final ConfigurationLoader config; - @Unreported - protected final Logger logger; - - @Unreported - protected CommentedConfigurationNode node; - - public ConfigurateConfiguration(ConfigurationLoader config, Logger logger) { - this.config = config; - this.logger = logger; - } - - @Override - public void load() { - try { - ConfigurationOptions options = ConfigurationOptions.defaults(); - options = options.shouldCopyDefaults(true); - - node = config.load(options); - } catch (IOException e) { - logger.warn("Error loading WorldEdit configuration", e); - } - - profile = node.node("debug").getBoolean(profile); - traceUnflushedSessions = node.node("debugging", "trace-unflushed-sessions").getBoolean(traceUnflushedSessions); - wandItem = node.node("wand-item").getString(wandItem).toLowerCase(Locale.ROOT); - try { - wandItem = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(wandItem)).id(); - } catch (Throwable ignored) { - } - - defaultChangeLimit = Math.max(-1, node.node("limits", "max-blocks-changed", "default").getInt(defaultChangeLimit)); - maxChangeLimit = Math.max(-1, node.node("limits", "max-blocks-changed", "maximum").getInt(maxChangeLimit)); - - defaultVerticalHeight = Math.max(1, node.node("limits", "vertical-height", "default").getInt(defaultVerticalHeight)); - - defaultMaxPolygonalPoints = Math.max(-1, node.node("limits", "max-polygonal-points", "default").getInt(defaultMaxPolygonalPoints)); - maxPolygonalPoints = Math.max(-1, node.node("limits", "max-polygonal-points", "maximum").getInt(maxPolygonalPoints)); - - maxRadius = Math.max(-1, node.node("limits", "max-radius").getInt(maxRadius)); - maxBrushRadius = node.node("limits", "max-brush-radius").getInt(maxBrushRadius); - maxSuperPickaxeSize = Math.max(1, node.node("limits", "max-super-pickaxe-size").getInt(maxSuperPickaxeSize)); - - butcherDefaultRadius = Math.max(-1, node.node("limits", "butcher-radius", "default").getInt(butcherDefaultRadius)); - butcherMaxRadius = Math.max(-1, node.node("limits", "butcher-radius", "maximum").getInt(butcherMaxRadius)); - - try { - disallowedBlocks = new HashSet<>( - node.node("limits", "disallowed-blocks").getList( - String.class, - ImmutableList.copyOf(getDefaultDisallowedBlocks()) - ) - ); - } catch (SerializationException e) { - logger.warn("Error loading WorldEdit configuration", e); - } - try { - allowedDataCycleBlocks = new HashSet<>( - node.node("limits", "allowed-data-cycle-blocks").getList(String.class, ImmutableList.of()) - ); - } catch (SerializationException e) { - logger.warn("Error loading WorldEdit configuration", e); - } - - registerHelp = node.node("register-help").getBoolean(true); - logCommands = node.node("logging", "log-commands").getBoolean(logCommands); - logFile = node.node("logging", "file").getString(logFile); - logFormat = node.node("logging", "format").getString(logFormat); - - superPickaxeDrop = node.node("super-pickaxe", "drop-items").getBoolean(superPickaxeDrop); - superPickaxeManyDrop = node.node("super-pickaxe", "many-drop-items").getBoolean(superPickaxeManyDrop); - - useInventory = node.node("use-inventory", "enable").getBoolean(useInventory); - useInventoryOverride = node.node("use-inventory", "allow-override").getBoolean(useInventoryOverride); - useInventoryCreativeOverride = node.node("use-inventory", "creative-mode-overrides").getBoolean(useInventoryCreativeOverride); - - navigationWand = node.node("navigation-wand", "item").getString(navigationWand).toLowerCase(Locale.ROOT); - try { - navigationWand = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(navigationWand)).id(); - } catch (Throwable ignored) { - } - navigationWandMaxDistance = node.node("navigation-wand", "max-distance").getInt(navigationWandMaxDistance); - navigationUseGlass = node.node("navigation", "use-glass").getBoolean(navigationUseGlass); - - scriptTimeout = node.node("scripting", "timeout").getInt(scriptTimeout); - scriptsDir = node.node("scripting", "dir").getString(scriptsDir); - - saveDir = node.node("saving", "dir").getString(saveDir); - - allowSymlinks = node.node("files", "allow-symbolic-links").getBoolean(false); - LocalSession.MAX_HISTORY_SIZE = Math.max(0, node.node("history", "size").getInt(15)); - SessionManager.EXPIRATION_GRACE = node.node("history", "expiration").getInt(10) * 60 * 1000; - - showHelpInfo = node.node("show-help-on-first-use").getBoolean(true); - serverSideCUI = node.node("server-side-cui").getBoolean(true); - - String snapshotsDir = node.node("snapshots", "directory").getString(""); - boolean experimentalSnapshots = node.node("snapshots", "experimental").getBoolean(false); - initializeSnapshotConfiguration(snapshotsDir, experimentalSnapshots); - - String type = node.node("shell-save-type").getString("").trim(); - shellSaveType = type.isEmpty() ? null : type; - - extendedYLimit = node.node("compat", "extended-y-limit").getBoolean(false); - setDefaultLocaleName(node.node("default-locale").getString(defaultLocaleName)); - - commandBlockSupport = node.node("command-block-support").getBoolean(false); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/SpongeConfiguration.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/SpongeConfiguration.java deleted file mode 100644 index bb58a5d8c..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/SpongeConfiguration.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.config; - -import com.google.inject.Inject; -import com.sk89q.worldedit.sponge.SpongeWorldEdit; -import org.apache.logging.log4j.Logger; -import org.spongepowered.api.config.DefaultConfig; -import org.spongepowered.configurate.CommentedConfigurationNode; -import org.spongepowered.configurate.loader.ConfigurationLoader; - -import java.io.IOException; -import java.nio.file.Path; - -public class SpongeConfiguration extends ConfigurateConfiguration { - - public boolean creativeEnable = false; - public boolean cheatMode = false; - - @Inject - public SpongeConfiguration(@DefaultConfig(sharedRoot = false) - ConfigurationLoader config, - Logger logger) { - super(config, logger); - } - - @Override - public void load() { - super.load(); - - creativeEnable = node.node("use-in-creative").getBoolean(false); - cheatMode = node.node("cheat-mode").getBoolean(false); - - try { - config.save(node); - } catch (IOException e) { - logger.warn("Error loading WorldEdit configuration", e); - } - } - - @Override - public Path getWorkingDirectoryPath() { - return SpongeWorldEdit.inst().getWorkingDir(); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/ExtendedChunk.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/ExtendedChunk.java deleted file mode 100644 index 47e0451e2..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/ExtendedChunk.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.internal; - -import com.sk89q.worldedit.util.SideEffect; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.LevelChunk; - -import javax.annotation.Nullable; - -public interface ExtendedChunk { - /** - * {@link LevelChunk#setBlockState(BlockPos, BlockState, boolean)} with the extra - * {@link SideEffect#UPDATE} flag. - * - * @param pos the position to set - * @param state the state to set - * @param moved I honestly have no idea and can't be bothered to investigate, we pass {@code - * false} - * @param update the update flag, see side-effect for details - * @return the old block state, or {@code null} if unchanged - */ - @Nullable - BlockState setBlockState(BlockPos pos, BlockState state, boolean moved, boolean update); -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/LocaleResolver.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/LocaleResolver.java deleted file mode 100644 index 4f7f4c8a5..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/LocaleResolver.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.internal; - -import com.sk89q.worldedit.WorldEdit; -import net.kyori.adventure.audience.Audience; -import org.spongepowered.api.util.locale.LocaleSource; - -import java.util.Locale; - -public class LocaleResolver { - public static Locale resolveLocale(Audience audience) { - if (audience instanceof LocaleSource) { - return ((LocaleSource) audience).locale(); - } - return WorldEdit.getInstance().getConfiguration().defaultLocale; - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/NbtAdapter.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/NbtAdapter.java deleted file mode 100644 index 2b7fe5f77..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/NbtAdapter.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.internal; - -import net.minecraft.nbt.ByteArrayTag; -import net.minecraft.nbt.ByteTag; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.DoubleTag; -import net.minecraft.nbt.FloatTag; -import net.minecraft.nbt.IntArrayTag; -import net.minecraft.nbt.IntTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.LongArrayTag; -import net.minecraft.nbt.LongTag; -import net.minecraft.nbt.ShortTag; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; -import org.enginehub.linbus.tree.LinByteArrayTag; -import org.enginehub.linbus.tree.LinByteTag; -import org.enginehub.linbus.tree.LinCompoundTag; -import org.enginehub.linbus.tree.LinDoubleTag; -import org.enginehub.linbus.tree.LinFloatTag; -import org.enginehub.linbus.tree.LinIntArrayTag; -import org.enginehub.linbus.tree.LinIntTag; -import org.enginehub.linbus.tree.LinListTag; -import org.enginehub.linbus.tree.LinLongArrayTag; -import org.enginehub.linbus.tree.LinLongTag; -import org.enginehub.linbus.tree.LinShortTag; -import org.enginehub.linbus.tree.LinStringTag; -import org.enginehub.linbus.tree.LinTag; -import org.enginehub.linbus.tree.LinTagType; -import org.spongepowered.api.data.persistence.DataContainer; -import org.spongepowered.api.data.persistence.DataQuery; -import org.spongepowered.api.data.persistence.DataSerializable; -import org.spongepowered.api.data.persistence.DataView; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class NbtAdapter { - /** - * A separator to introduce errors if there is something to be separated. We should only see - * single-part keys. - */ - private static final String BREAKING_SEPARATOR = "if you see this, something is wrong"; - - public static LinCompoundTag adaptToWorldEdit(DataView view) { - LinCompoundTag.Builder builder = LinCompoundTag.builder(); - for (Map.Entry entry : view.values(false).entrySet()) { - builder.put( - entry.getKey().asString(BREAKING_SEPARATOR), - adaptUnknownToWorldEdit(entry.getValue()) - ); - } - return builder.build(); - } - - private static LinTag adaptUnknownToWorldEdit(Object object) { - if (object instanceof DataView) { - return adaptToWorldEdit((DataView) object); - } - if (object instanceof Boolean) { - return LinByteTag.of((byte) ((Boolean) object ? 1 : 0)); - } - if (object instanceof Byte) { - return LinByteTag.of((Byte) object); - } - if (object instanceof Short) { - return LinShortTag.of(((Short) object)); - } - if (object instanceof Integer) { - return LinIntTag.of(((Integer) object)); - } - if (object instanceof Long) { - return LinLongTag.of(((Long) object)); - } - if (object instanceof Float) { - return LinFloatTag.of(((Float) object)); - } - if (object instanceof Double) { - return LinDoubleTag.of(((Double) object)); - } - if (object instanceof String) { - return LinStringTag.of((String) object); - } - if (object instanceof byte[]) { - return LinByteArrayTag.of(((byte[]) object)); - } - if (object instanceof Byte[] array) { - byte[] copy = new byte[array.length]; - for (int i = 0; i < copy.length; i++) { - copy[i] = array[i]; - } - return LinByteArrayTag.of(copy); - } - if (object instanceof int[]) { - return LinIntArrayTag.of(((int[]) object)); - } - if (object instanceof Integer[] array) { - int[] copy = new int[array.length]; - for (int i = 0; i < copy.length; i++) { - copy[i] = array[i]; - } - return LinIntArrayTag.of(copy); - } - if (object instanceof long[]) { - return LinLongArrayTag.of(((long[]) object)); - } - if (object instanceof Long[] array) { - long[] copy = new long[array.length]; - for (int i = 0; i < copy.length; i++) { - copy[i] = array[i]; - } - return LinLongArrayTag.of(copy); - } - if (object instanceof List objects) { - if (objects.isEmpty()) { - return LinListTag.empty(LinTagType.endTag()); - } - LinTag first = adaptUnknownToWorldEdit(objects.get(0)); - @SuppressWarnings("unchecked") - LinListTag.Builder> builder = LinListTag.builder((LinTagType>) first.type()); - builder.add(first); - for (int i = 1; i < objects.size(); i++) { - Object value = objects.get(i); - builder.add(adaptUnknownToWorldEdit(value)); - } - return builder.build(); - } - if (object instanceof Map) { - LinCompoundTag.Builder builder = LinCompoundTag.builder(); - for (Map.Entry entry : ((Map) object).entrySet()) { - String key = entry.getKey() instanceof DataQuery - ? ((DataQuery) entry.getKey()).asString(BREAKING_SEPARATOR) - : entry.getKey().toString(); - builder.put(key, adaptUnknownToWorldEdit(entry.getValue())); - } - return builder.build(); - } - if (object instanceof DataSerializable) { - return adaptToWorldEdit(((DataSerializable) object).toContainer()); - } - throw new UnsupportedOperationException("Unable to translate into NBT: " + object.getClass()); - } - - public static DataContainer adaptFromWorldEdit(LinCompoundTag tag) { - // copy to container, no cloning used because it's unlikely to leak - // and it's cheaper this way - DataContainer container = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED); - for (var entry : tag.value().entrySet()) { - container.set(DataQuery.of(entry.getKey()), adaptTagFromWorldEdit(entry.getValue())); - } - return container; - } - - private static Object adaptTagFromWorldEdit(LinTag value) { - if (value instanceof LinListTag listTag) { - return listTag.value().stream() - .map(NbtAdapter::adaptTagFromWorldEdit) - .collect(Collectors.toList()); - } - if (value instanceof LinCompoundTag compoundTag) { - return adaptFromWorldEdit(compoundTag); - } - // everything else is raw JDK types, so we can use it directly - return value.value(); - } - - public static Tag adaptNMSToWorldEdit(LinTag tag) { - if (tag instanceof LinIntArrayTag intArrayTag) { - return adaptNMSToWorldEdit(intArrayTag); - } else if (tag instanceof LinListTag listTag) { - return adaptNMSToWorldEdit(listTag); - } else if (tag instanceof LinLongTag longTag) { - return adaptNMSToWorldEdit(longTag); - } else if (tag instanceof LinLongArrayTag longArrayTag) { - return adaptNMSToWorldEdit(longArrayTag); - } else if (tag instanceof LinStringTag stringTag) { - return adaptNMSToWorldEdit(stringTag); - } else if (tag instanceof LinIntTag intTag) { - return adaptNMSToWorldEdit(intTag); - } else if (tag instanceof LinByteTag byteTag) { - return adaptNMSToWorldEdit(byteTag); - } else if (tag instanceof LinByteArrayTag byteArrayTag) { - return adaptNMSToWorldEdit(byteArrayTag); - } else if (tag instanceof LinCompoundTag compoundTag) { - return adaptNMSToWorldEdit(compoundTag); - } else if (tag instanceof LinFloatTag floatTag) { - return adaptNMSToWorldEdit(floatTag); - } else if (tag instanceof LinShortTag shortTag) { - return adaptNMSToWorldEdit(shortTag); - } else if (tag instanceof LinDoubleTag doubleTag) { - return adaptNMSToWorldEdit(doubleTag); - } else { - throw new IllegalArgumentException("Can't convert tag of type " + tag.getClass().getCanonicalName()); - } - } - - public static IntArrayTag adaptNMSToWorldEdit(LinIntArrayTag tag) { - return new IntArrayTag(tag.value()); - } - - public static ListTag adaptNMSToWorldEdit(LinListTag tag) { - ListTag list = new ListTag(); - for (LinTag child : tag.value()) { - list.add(adaptNMSToWorldEdit(child)); - } - return list; - } - - public static LongTag adaptNMSToWorldEdit(LinLongTag tag) { - return LongTag.valueOf(tag.valueAsLong()); - } - - public static LongArrayTag adaptNMSToWorldEdit(LinLongArrayTag tag) { - return new LongArrayTag(tag.value()); - } - - public static StringTag adaptNMSToWorldEdit(LinStringTag tag) { - return StringTag.valueOf(tag.value()); - } - - public static IntTag adaptNMSToWorldEdit(LinIntTag tag) { - return IntTag.valueOf(tag.valueAsInt()); - } - - public static ByteTag adaptNMSToWorldEdit(LinByteTag tag) { - return ByteTag.valueOf(tag.valueAsByte()); - } - - public static ByteArrayTag adaptNMSToWorldEdit(LinByteArrayTag tag) { - return new ByteArrayTag(tag.value()); - } - - public static CompoundTag adaptNMSToWorldEdit(LinCompoundTag tag) { - CompoundTag compound = new CompoundTag(); - for (var child : tag.value().entrySet()) { - compound.put(child.getKey(), adaptNMSToWorldEdit(child.getValue())); - } - return compound; - } - - public static FloatTag adaptNMSToWorldEdit(LinFloatTag tag) { - return FloatTag.valueOf(tag.valueAsFloat()); - } - - public static ShortTag adaptNMSToWorldEdit(LinShortTag tag) { - return ShortTag.valueOf(tag.valueAsShort()); - } - - public static DoubleTag adaptNMSToWorldEdit(LinDoubleTag tag) { - return DoubleTag.valueOf(tag.valueAsDouble()); - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/SpongeTransmogrifier.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/SpongeTransmogrifier.java deleted file mode 100644 index 0bedfe64a..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/SpongeTransmogrifier.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.internal; - -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableList; -import com.sk89q.worldedit.registry.state.BooleanProperty; -import com.sk89q.worldedit.registry.state.DirectionalProperty; -import com.sk89q.worldedit.registry.state.EnumProperty; -import com.sk89q.worldedit.registry.state.IntegerProperty; -import com.sk89q.worldedit.registry.state.Property; -import com.sk89q.worldedit.util.Direction; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockType; -import net.minecraft.util.StringRepresentable; -import org.spongepowered.api.ResourceKey; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.registry.RegistryTypes; -import org.spongepowered.api.state.StateProperty; - -import java.util.Comparator; -import java.util.Map; -import java.util.Optional; -import java.util.TreeMap; - -/** - * Raw, un-cached transformations. - */ -public class SpongeTransmogrifier { - - private static final LoadingCache, Property> PROPERTY_CACHE = CacheBuilder.newBuilder().build(new CacheLoader<>() { - @Override - public Property load(StateProperty property) { - net.minecraft.world.level.block.state.properties.Property nativeProperty = - (net.minecraft.world.level.block.state.properties.Property) property; - String propertyName = nativeProperty.getName(); - if (nativeProperty instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) { - return new BooleanProperty(propertyName, - ImmutableList.copyOf(((net.minecraft.world.level.block.state.properties.BooleanProperty) nativeProperty).getPossibleValues())); - } - if (nativeProperty instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) { - return new IntegerProperty(propertyName, - ImmutableList.copyOf(((net.minecraft.world.level.block.state.properties.IntegerProperty) nativeProperty).getPossibleValues())); - } - if (isDirectionProperty(nativeProperty)) { - return new DirectionalProperty(propertyName, - ((net.minecraft.world.level.block.state.properties.EnumProperty) nativeProperty).getPossibleValues().stream() - .map(x -> adaptDirection((net.minecraft.core.Direction) x)) - .toList() - ); - } - if (nativeProperty instanceof net.minecraft.world.level.block.state.properties.EnumProperty) { - return new EnumProperty(propertyName, - ((net.minecraft.world.level.block.state.properties.EnumProperty) nativeProperty).getPossibleValues().stream() - .map(StringRepresentable::getSerializedName) - .toList()); - } - throw new IllegalStateException("Unknown property type"); - } - }); - - public static Property transmogToWorldEditProperty(StateProperty property) { - return PROPERTY_CACHE.getUnchecked(property); - } - - private static Map, Object> transmogToWorldEditProperties( - BlockType block, - net.minecraft.world.level.block.state.BlockState blockState - ) { - Map, Object> properties = new TreeMap<>(Comparator.comparing(Property::getName)); - for (net.minecraft.world.level.block.state.properties.Property nativeProperty: blockState.getProperties()) { - Object value = blockState.getValue(nativeProperty); - if (isDirectionProperty(nativeProperty)) { - net.minecraft.core.Direction nativeDirectionValue = (net.minecraft.core.Direction) value; - value = adaptDirection(nativeDirectionValue); - } else if (nativeProperty instanceof net.minecraft.world.level.block.state.properties.EnumProperty) { - value = ((StringRepresentable) value).getSerializedName(); - } - properties.put(block.getProperty(nativeProperty.getName()), value); - } - return properties; - } - - private static boolean isDirectionProperty(net.minecraft.world.level.block.state.properties.Property property) { - return property instanceof net.minecraft.world.level.block.state.properties.EnumProperty - && property.getValueClass().isAssignableFrom(net.minecraft.core.Direction.class); - } - - private static Direction adaptDirection(net.minecraft.core.Direction direction) { - switch (direction) { - case UP: - return Direction.UP; - case DOWN: - return Direction.DOWN; - case EAST: - return Direction.EAST; - case WEST: - return Direction.WEST; - case NORTH: - return Direction.NORTH; - case SOUTH: - return Direction.SOUTH; - default: - throw new AssertionError("New direction added: " + direction); - } - } - - private static net.minecraft.core.Direction adaptDirection(Direction direction) { - switch (direction) { - case UP: - return net.minecraft.core.Direction.UP; - case DOWN: - return net.minecraft.core.Direction.DOWN; - case EAST: - return net.minecraft.core.Direction.EAST; - case WEST: - return net.minecraft.core.Direction.WEST; - case NORTH: - return net.minecraft.core.Direction.NORTH; - case SOUTH: - return net.minecraft.core.Direction.SOUTH; - default: - throw new AssertionError("New direction added: " + direction); - } - } - - private static net.minecraft.world.level.block.state.properties.Property findPropertyByName( - net.minecraft.world.level.block.state.BlockState blockState, - String propertyName - ) { - for (net.minecraft.world.level.block.state.properties.Property property: blockState.getProperties()) { - if (property.getName().equals(propertyName)) { - return property; - } - } - - throw new IllegalStateException("Missing property in " + blockState.getBlock() + ": " + propertyName); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static org.spongepowered.api.block.BlockState transmogToMinecraftProperties( - org.spongepowered.api.block.BlockState blockState, - Map, Object> states - ) { - net.minecraft.world.level.block.state.BlockState nativeBlockState = - (net.minecraft.world.level.block.state.BlockState) blockState; - for (Map.Entry, Object> stateEntry: states.entrySet()) { - Property property = stateEntry.getKey(); - Object value = stateEntry.getValue(); - net.minecraft.world.level.block.state.properties.Property nativeProperty = - findPropertyByName(nativeBlockState, property.getName()); - Comparable nativeValue; - if (property instanceof DirectionalProperty) { - Direction directionValue = (Direction) value; - nativeValue = adaptDirection(directionValue); - } else if (property instanceof EnumProperty) { - String valueName = (String) value; - Optional> nativeValueOpt = nativeProperty.getValue(valueName); - if (nativeValueOpt.isEmpty()) { - throw new IllegalStateException("Failed to parse " + valueName + " into " + property.getName()); - } - nativeValue = nativeValueOpt.get(); - } else { - nativeValue = (Comparable) value; - } - nativeBlockState = nativeBlockState.setValue( - (net.minecraft.world.level.block.state.properties.Property) nativeProperty, (Comparable) nativeValue); - } - - return (org.spongepowered.api.block.BlockState) nativeBlockState; - } - - public static org.spongepowered.api.block.BlockState transmogToMinecraft(BlockState blockState) { - org.spongepowered.api.block.BlockType mcBlock = Sponge.game().registry(RegistryTypes.BLOCK_TYPE) - .value(ResourceKey.resolve(blockState.getBlockType().id())); - org.spongepowered.api.block.BlockState newState = mcBlock.defaultState(); - Map, Object> states = blockState.getStates(); - return transmogToMinecraftProperties(newState, states); - } - - public static BlockState transmogToWorldEdit(org.spongepowered.api.block.BlockState blockState) { - BlockType blockType = BlockType.REGISTRY.get( - blockState.type().key(RegistryTypes.BLOCK_TYPE).asString() - ); - return blockType.getState(transmogToWorldEditProperties(blockType, - (net.minecraft.world.level.block.state.BlockState) blockState)); - } - - private SpongeTransmogrifier() { - } -} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/SpongeWorldNativeAccess.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/SpongeWorldNativeAccess.java deleted file mode 100644 index 9d382c263..000000000 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/internal/SpongeWorldNativeAccess.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.sponge.internal; - -import com.sk89q.worldedit.internal.wna.WorldNativeAccess; -import com.sk89q.worldedit.sponge.SpongeAdapter; -import com.sk89q.worldedit.util.SideEffect; -import com.sk89q.worldedit.util.SideEffectSet; -import com.sk89q.worldedit.world.storage.ChunkStore; -import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.FullChunkStatus; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.LevelChunk; -import org.enginehub.linbus.tree.LinCompoundTag; - -import java.lang.ref.WeakReference; -import java.util.Objects; -import javax.annotation.Nullable; - -public class SpongeWorldNativeAccess implements WorldNativeAccess { - private static final int UPDATE = 1; - private static final int NOTIFY = 2; - - private final WeakReference world; - private SideEffectSet sideEffectSet; - - public SpongeWorldNativeAccess(WeakReference world) { - this.world = world; - } - - private ServerLevel getWorld() { - return Objects.requireNonNull(world.get(), "The reference to the world was lost"); - } - - @Override - public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) { - this.sideEffectSet = sideEffectSet; - } - - @Override - public LevelChunk getChunk(int x, int z) { - return getWorld().getChunk(x, z); - } - - @Override - public BlockState toNative(com.sk89q.worldedit.world.block.BlockState state) { - return (BlockState) SpongeAdapter.adapt(state); - } - - @Override - public BlockState getBlockState(LevelChunk chunk, BlockPos position) { - return chunk.getBlockState(position); - } - - @Nullable - @Override - public BlockState setBlockState(LevelChunk chunk, BlockPos position, BlockState state) { - if (chunk instanceof ExtendedChunk) { - return ((ExtendedChunk) chunk).setBlockState( - position, state, false, sideEffectSet.shouldApply(SideEffect.UPDATE) - ); - } - return chunk.setBlockState(position, state, false); - } - - @Override - public BlockState getValidBlockForPosition(BlockState block, BlockPos position) { - return Block.updateFromNeighbourShapes(block, getWorld(), position); - } - - @Override - public BlockPos getPosition(int x, int y, int z) { - return new BlockPos(x, y, z); - } - - @Override - public void updateLightingForBlock(BlockPos position) { - getWorld().getChunkSource().getLightEngine().checkBlock(position); - } - - @Override - public boolean updateTileEntity(BlockPos position, LinCompoundTag tag) { - CompoundTag nativeTag = NbtAdapter.adaptNMSToWorldEdit(tag); - BlockEntity tileEntity = getWorld().getChunk(position).getBlockEntity(position); - if (tileEntity == null) { - return false; - } - tileEntity.setLevel(getWorld()); - tileEntity.load(nativeTag); - return true; - } - - @Override - public void notifyBlockUpdate(LevelChunk chunk, BlockPos position, BlockState oldState, BlockState newState) { - if (chunk.getSections()[position.getY() >> ChunkStore.CHUNK_SHIFTS] != null) { // TODO 1.17 - world.get().getSectionIndex(position.getY()) - getWorld().sendBlockUpdated(position, oldState, newState, UPDATE | NOTIFY); - } - } - - @Override - public boolean isChunkTicking(LevelChunk chunk) { - return chunk.getFullStatus().isOrAfter(FullChunkStatus.BLOCK_TICKING); - } - - @Override - public void markBlockChanged(LevelChunk chunk, BlockPos position) { - if (chunk.getSections()[position.getY() >> ChunkStore.CHUNK_SHIFTS] != null) { // TODO 1.17 - world.getSectionIndex(position.getY()) - getWorld().getChunkSource().blockChanged(position); - } - } - - @Override - public void notifyNeighbors(BlockPos pos, BlockState oldState, BlockState newState) { - getWorld().updateNeighborsAt(pos, oldState.getBlock()); - if (newState.hasAnalogOutputSignal()) { - getWorld().updateNeighbourForOutputSignal(pos, newState.getBlock()); - } - } - - @Override - public void updateBlock(BlockPos pos, BlockState oldState, BlockState newState) { - ServerLevel world = getWorld(); - newState.onPlace(world, pos, oldState, false); - } - - @Override - public void updateNeighbors(BlockPos pos, BlockState oldState, BlockState newState, int recursionLimit) { - ServerLevel world = getWorld(); - oldState.updateNeighbourShapes(world, pos, NOTIFY, recursionLimit); - newState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit); - newState.updateNeighbourShapes(world, pos, NOTIFY, recursionLimit); - } - - @Override - public void onBlockStateChange(BlockPos pos, BlockState oldState, BlockState newState) { - getWorld().onBlockStateChange(pos, oldState, newState); - } -}