diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index ace4c3574..d94091eb9 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -8,16 +8,16 @@ jobs: runs-on: ubuntu-latest steps: - - name: Clone repository + - name: ๐Ÿ“ฅ Clone repository uses: actions/checkout@v3 - - name: Set up Java + - name: ๐Ÿ“ฅ Set up Java uses: actions/setup-java@v3 with: java-version: 17 distribution: 'temurin' - - name: Setup Gradle + - name: ๐Ÿ“ฅ Setup Gradle uses: gradle/gradle-build-action@v2 with: cache-read-only: ${{ !startsWith(github.ref, 'refs/heads/mc-') }} @@ -27,39 +27,45 @@ jobs: mkdir -p ~/.gradle echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties - - name: Build with Gradle - run: | - ./gradlew assemble || ./gradlew assemble - ./gradlew downloadAssets || ./gradlew downloadAssets - ./gradlew build + - name: โš’๏ธ Build + run: ./gradlew assemble || ./gradlew assemble - - name: Run client tests + - name: ๐Ÿ’ก Lint + uses: pre-commit/action@v3.0.0 + + - name: ๐Ÿงช Run tests + run: ./gradlew test validateMixinNames checkChangelog + + - name: ๐Ÿ“ฅ Download assets for game tests + run: ./gradlew downloadAssets || ./gradlew downloadAssets + + - name: ๐Ÿงช Run integration tests + run: ./gradlew runGametest + + - name: ๐Ÿงช Run client tests run: ./gradlew runGametestClient # Not checkClient, as no point running rendering tests. # These are a little flaky on GH actions: its useful to run them, but don't break the build. continue-on-error: true - - name: Prepare Jars + - name: ๐Ÿงช Parse test reports + run: ./tools/parse-reports.py + if: ${{ failure() }} + + - name: ๐Ÿ“ฆ Prepare Jars run: | # Find the main jar and append the git hash onto it. mkdir -p jars find projects/forge/build/libs projects/fabric/build/libs -type f -regex '.*[0-9.]+\(-SNAPSHOT\)?\.jar$' -exec bash -c 'cp {} "jars/$(basename {} .jar)-$(git rev-parse HEAD).jar"' \; - - name: Upload Jar + - name: ๐Ÿ“ค Upload Jar uses: actions/upload-artifact@v3 with: name: CC-Tweaked path: ./jars - - name: Upload coverage + - name: ๐Ÿ“ค Upload coverage uses: codecov/codecov-action@v3 - - name: Parse test reports - run: ./tools/parse-reports.py - if: ${{ failure() }} - - - name: Run linters - uses: pre-commit/action@v3.0.0 - build-core: strategy: fail-fast: false diff --git a/.github/workflows/make-doc.yml b/.github/workflows/make-doc.yml index 08ca1df77..5b22ee6f2 100644 --- a/.github/workflows/make-doc.yml +++ b/.github/workflows/make-doc.yml @@ -4,6 +4,7 @@ on: push: branches: - mc-1.19.x + - mc-1.20.x jobs: make_doc: diff --git a/.reuse/dep5 b/.reuse/dep5 index de4dbc14b..11297f06f 100644 --- a/.reuse/dep5 +++ b/.reuse/dep5 @@ -6,6 +6,7 @@ Upstream-Contact: Jonathan Coates Files: projects/common/src/main/resources/assets/computercraft/sounds.json projects/common/src/main/resources/assets/computercraft/sounds/empty.ogg + projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/* projects/common/src/testMod/resources/data/cctest/structures/* projects/fabric/src/generated/* projects/forge/src/generated/* diff --git a/buildSrc/src/main/kotlin/cc-tweaked.forge.gradle.kts b/buildSrc/src/main/kotlin/cc-tweaked.forge.gradle.kts index 9ffe48f81..ece233e6f 100644 --- a/buildSrc/src/main/kotlin/cc-tweaked.forge.gradle.kts +++ b/buildSrc/src/main/kotlin/cc-tweaked.forge.gradle.kts @@ -10,8 +10,9 @@ import cc.tweaked.gradle.IdeaRunConfigurations import cc.tweaked.gradle.MinecraftConfigurations plugins { - id("cc-tweaked.java-convention") id("net.minecraftforge.gradle") + // We must apply java-convention after Forge, as we need the fg extension to be present. + id("cc-tweaked.java-convention") id("org.parchmentmc.librarian.forgegradle") } diff --git a/buildSrc/src/main/kotlin/cc-tweaked.java-convention.gradle.kts b/buildSrc/src/main/kotlin/cc-tweaked.java-convention.gradle.kts index d8dfb6b4e..75c739613 100644 --- a/buildSrc/src/main/kotlin/cc-tweaked.java-convention.gradle.kts +++ b/buildSrc/src/main/kotlin/cc-tweaked.java-convention.gradle.kts @@ -37,9 +37,25 @@ java { repositories { mavenCentral() - maven("https://squiddev.cc/maven") { + + val mainMaven = maven("https://squiddev.cc/maven") { name = "SquidDev" content { + // Until https://github.com/SpongePowered/Mixin/pull/593 is merged + includeModule("org.spongepowered", "mixin") + } + } + + exclusiveContent { + forRepositories(mainMaven) + + // Include the ForgeGradle repository if present. This requires that ForgeGradle is already present, which we + // enforce in our Forge overlay. + val fg = + project.extensions.findByType(net.minecraftforge.gradle.userdev.DependencyManagementExtension::class.java) + if (fg != null) forRepositories(fg.repository) + + filter { includeGroup("org.squiddev") includeGroup("cc.tweaked") // Things we mirror @@ -49,8 +65,6 @@ repositories { includeGroup("me.shedaniel.cloth") includeGroup("mezz.jei") includeModule("com.terraformersmc", "modmenu") - // Until https://github.com/SpongePowered/Mixin/pull/593 is merged - includeModule("org.spongepowered", "mixin") } } } diff --git a/buildSrc/src/main/kotlin/cc/tweaked/gradle/ForgeExtensions.kt b/buildSrc/src/main/kotlin/cc/tweaked/gradle/ForgeExtensions.kt new file mode 100644 index 000000000..bbf6e86c5 --- /dev/null +++ b/buildSrc/src/main/kotlin/cc/tweaked/gradle/ForgeExtensions.kt @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package cc.tweaked.gradle + +import net.minecraftforge.gradle.common.util.RunConfig +import net.minecraftforge.gradle.common.util.runs.setRunConfigInternal +import org.gradle.api.plugins.JavaPluginExtension +import org.gradle.api.tasks.JavaExec +import org.gradle.jvm.toolchain.JavaToolchainService +import java.nio.file.Files + +/** + * Set [JavaExec] task to run a given [RunConfig]. + */ +fun JavaExec.setRunConfig(config: RunConfig) { + dependsOn("prepareRuns") + setRunConfigInternal(project, this, config) + doFirst("Create working directory") { Files.createDirectories(workingDir.toPath()) } + + javaLauncher.set( + project.extensions.getByType(JavaToolchainService::class.java) + .launcherFor(project.extensions.getByType(JavaPluginExtension::class.java).toolchain), + ) +} diff --git a/buildSrc/src/main/kotlin/cc/tweaked/gradle/Illuaminate.kt b/buildSrc/src/main/kotlin/cc/tweaked/gradle/Illuaminate.kt index d44596fb1..0035ab118 100644 --- a/buildSrc/src/main/kotlin/cc/tweaked/gradle/Illuaminate.kt +++ b/buildSrc/src/main/kotlin/cc/tweaked/gradle/Illuaminate.kt @@ -60,7 +60,7 @@ class IlluaminatePlugin : Plugin { /** Define a dependency for illuaminate from a version number and the current operating system. */ private fun illuaminateArtifact(project: Project, version: String): Dependency { - val osName = System.getProperty("os.name").toLowerCase() + val osName = System.getProperty("os.name").lowercase() val (os, suffix) = when { osName.contains("windows") -> Pair("windows", ".exe") osName.contains("mac os") || osName.contains("darwin") -> Pair("macos", "") @@ -68,7 +68,7 @@ class IlluaminatePlugin : Plugin { else -> error("Unsupported OS $osName for illuaminate") } - val osArch = System.getProperty("os.arch").toLowerCase() + val osArch = System.getProperty("os.arch").lowercase() val arch = when { // On macOS the x86_64 binary will work for both ARM and Intel Macs through Rosetta. os == "macos" -> "x86_64" diff --git a/buildSrc/src/main/kotlin/cc/tweaked/gradle/MinecraftExec.kt b/buildSrc/src/main/kotlin/cc/tweaked/gradle/MinecraftExec.kt index 75cb7b51a..7bc6af2cf 100644 --- a/buildSrc/src/main/kotlin/cc/tweaked/gradle/MinecraftExec.kt +++ b/buildSrc/src/main/kotlin/cc/tweaked/gradle/MinecraftExec.kt @@ -32,11 +32,14 @@ abstract class ClientJavaExec : JavaExec() { usesService(clientRunner) } + @get:Input + val renderdoc get() = project.hasProperty("renderdoc") + /** * When [false], tests will not be run automatically, allowing the user to debug rendering. */ @get:Input - val clientDebug get() = project.hasProperty("clientDebug") + val clientDebug get() = renderdoc || project.hasProperty("clientDebug") /** * When [false], tests will not run under a framebuffer. @@ -63,6 +66,7 @@ abstract class ClientJavaExec : JavaExec() { task.copyToFull(this) if (!clientDebug) systemProperty("cctest.client", "") + if (renderdoc) environment("LD_PRELOAD", "/usr/lib/librenderdoc.so") systemProperty("cctest.gametest-report", testResults.get().asFile.absoluteFile) workingDir(project.buildDir.resolve("gametest").resolve(name)) } diff --git a/buildSrc/src/main/kotlin/net/minecraftforge/gradle/common/util/runs/RunConfigSetup.kt b/buildSrc/src/main/kotlin/net/minecraftforge/gradle/common/util/runs/RunConfigSetup.kt new file mode 100644 index 000000000..a74d0008d --- /dev/null +++ b/buildSrc/src/main/kotlin/net/minecraftforge/gradle/common/util/runs/RunConfigSetup.kt @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package net.minecraftforge.gradle.common.util.runs + +import net.minecraftforge.gradle.common.util.RunConfig +import org.gradle.api.Project +import org.gradle.process.CommandLineArgumentProvider +import org.gradle.process.JavaExecSpec +import java.io.File +import java.util.function.Supplier +import java.util.stream.Collectors +import java.util.stream.Stream + +/** + * Set up a [JavaExecSpec] to execute a [RunConfig]. + * + * [MinecraftRunTask] sets up all its properties when the task is executed, rather than when configured. As such, it's + * not possible to use [cc.tweaked.gradle.copyToFull] like we do for Fabric. Instead, we set up the task manually. + * + * Unfortunately most of the functionality we need is package-private, and so we have to put our code into the package. + */ +internal fun setRunConfigInternal(project: Project, spec: JavaExecSpec, config: RunConfig) { + spec.workingDir = File(config.workingDirectory) + + spec.mainClass.set(config.main) + for (source in config.allSources) spec.classpath(source.runtimeClasspath) + + val originalTask = project.tasks.named(config.taskName, MinecraftRunTask::class.java) + + // Add argument and JVM argument via providers, to be as lazy as possible with fetching artifacts. + val lazyTokens = RunConfigGenerator.configureTokensLazy( + project, config, RunConfigGenerator.mapModClassesToGradle(project, config), + originalTask.get().minecraftArtifacts, + originalTask.get().runtimeClasspathArtifacts, + ) + spec.argumentProviders.add( + CommandLineArgumentProvider { + RunConfigGenerator.getArgsStream(config, lazyTokens, false).toList() + }, + ) + spec.jvmArgumentProviders.add( + CommandLineArgumentProvider { + (if (config.isClient) config.jvmArgs + originalTask.get().additionalClientArgs.get() else config.jvmArgs).map { config.replace(lazyTokens, it) } + + config.properties.map { (k, v) -> "-D${k}=${config.replace(lazyTokens, v)}" } + }, + ) + + for ((key, value) in config.environment) spec.environment(key, config.replace(lazyTokens, value)) +} diff --git a/doc/events/websocket_closed.md b/doc/events/websocket_closed.md index 06a991fa8..c6870258b 100644 --- a/doc/events/websocket_closed.md +++ b/doc/events/websocket_closed.md @@ -13,6 +13,15 @@ The @{websocket_closed} event is fired when an open WebSocket connection is clos ## Return Values 1. @{string}: The event name. 2. @{string}: The URL of the WebSocket that was closed. +3. @{string}|@{nil}: The [server-provided reason][close_reason] + the websocket was closed. This will be @{nil} if the connection was closed + abnormally. +4. @{number}|@{nil}: The [connection close code][close_code], + indicating why the socket was closed. This will be @{nil} if the connection + was closed abnormally. + +[close_reason]: https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6 "The WebSocket Connection Close Reason, RFC 6455" +[close_code]: https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5 "The WebSocket Connection Close Code, RFC 6455" ## Example Prints a message when a WebSocket is closed (this may take a minute): diff --git a/gradle.properties b/gradle.properties index 8e6994dab..62d1c6ea0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,7 +10,7 @@ kotlin.jvm.target.validation.mode=error # Mod properties isUnstable=false -modVersion=1.105.0 +modVersion=1.106.0 # Minecraft properties: We want to configure this here so we can read it in settings.gradle mcVersion=1.20.1 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 38c8357ca..f65c3cf62 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -53,8 +53,8 @@ checkstyle = "10.3.4" curseForgeGradle = "1.0.14" errorProne-core = "2.18.0" errorProne-plugin = "3.0.1" -fabric-loom = "1.1.10" -forgeGradle = "5.1.+" +fabric-loom = "1.3.7" +forgeGradle = "6.0.8" githubRelease = "2.2.12" ideaExt = "1.1.6" illuaminate = "0.1.0-28-ga7efd71" diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 249e5832f..c1962a79e 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 070cb702f..37aef8d3f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index a69d9cb6c..aeb74cbb4 100755 --- a/gradlew +++ b/gradlew @@ -55,7 +55,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +80,10 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -143,12 +140,16 @@ fi if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -193,6 +194,10 @@ if "$cygwin" || "$msys" ; then done fi + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + # Collect all arguments for the java command; # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in diff --git a/gradlew.bat b/gradlew.bat index f127cfd49..93e3f59f1 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% diff --git a/projects/common-api/src/client/java/dan200/computercraft/api/client/turtle/TurtleUpgradeModeller.java b/projects/common-api/src/client/java/dan200/computercraft/api/client/turtle/TurtleUpgradeModeller.java index b1a1e72c6..76a57ecf3 100644 --- a/projects/common-api/src/client/java/dan200/computercraft/api/client/turtle/TurtleUpgradeModeller.java +++ b/projects/common-api/src/client/java/dan200/computercraft/api/client/turtle/TurtleUpgradeModeller.java @@ -11,6 +11,7 @@ import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleUpgradeSerialiser; import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import javax.annotation.Nullable; @@ -28,12 +29,27 @@ public interface TurtleUpgradeModeller { * When the current turtle is {@literal null}, this function should be constant for a given upgrade and side. * * @param upgrade The upgrade that you're getting the model for. - * @param turtle Access to the turtle that the upgrade resides on. This will be null when getting item models! + * @param turtle Access to the turtle that the upgrade resides on. This will be null when getting item models, unless + * {@link #getModel(ITurtleUpgrade, CompoundTag, TurtleSide)} is overriden. * @param side Which side of the turtle (left or right) the upgrade resides on. * @return The model that you wish to be used to render your upgrade. */ TransformedModel getModel(T upgrade, @Nullable ITurtleAccess turtle, TurtleSide side); + /** + * Obtain the model to be used when rendering a turtle peripheral. + *

+ * This is used when rendering the turtle's item model, and so no {@link ITurtleAccess} is available. + * + * @param upgrade The upgrade that you're getting the model for. + * @param data Upgrade data instance for current turtle side. + * @param side Which side of the turtle (left or right) the upgrade resides on. + * @return The model that you wish to be used to render your upgrade. + */ + default TransformedModel getModel(T upgrade, CompoundTag data, TurtleSide side) { + return getModel(upgrade, (ITurtleAccess) null, side); + } + /** * A basic {@link TurtleUpgradeModeller} which renders using the upgrade's {@linkplain ITurtleUpgrade#getCraftingItem() * crafting item}. diff --git a/projects/common-api/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java b/projects/common-api/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java index 7cadb1b8b..99ac916b9 100644 --- a/projects/common-api/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java +++ b/projects/common-api/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java @@ -5,9 +5,11 @@ package dan200.computercraft.api.pocket; import dan200.computercraft.api.peripheral.IPeripheral; +import dan200.computercraft.api.upgrades.UpgradeBase; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; import java.util.Map; @@ -69,6 +71,8 @@ public interface IPocketAccess { * * @return The upgrade's NBT. * @see #updateUpgradeNBTData() + * @see UpgradeBase#getUpgradeItem(CompoundTag) + * @see UpgradeBase#getUpgradeData(ItemStack) */ CompoundTag getUpgradeNBTData(); @@ -80,7 +84,10 @@ public interface IPocketAccess { void updateUpgradeNBTData(); /** - * Remove the current peripheral and create a new one. You may wish to do this if the methods available change. + * Remove the current peripheral and create a new one. + *

+ * You may wish to do this if the methods available change, for instance when the {@linkplain #getEntity() owning + * entity} changes. */ void invalidatePeripheral(); @@ -88,6 +95,8 @@ public interface IPocketAccess { * Get a list of all upgrades for the pocket computer. * * @return A collection of all upgrade names. + * @deprecated This is a relic of a previous API, which no longer makes sense with newer versions of ComputerCraft. */ + @Deprecated(forRemoval = true) Map getUpgrades(); } diff --git a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java index bc3aa0477..9565a6e2d 100644 --- a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java +++ b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java @@ -8,10 +8,13 @@ import com.mojang.authlib.GameProfile; import dan200.computercraft.api.lua.ILuaCallback; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.peripheral.IPeripheral; +import dan200.computercraft.api.upgrades.UpgradeBase; +import dan200.computercraft.api.upgrades.UpgradeData; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.Container; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import org.jetbrains.annotations.ApiStatus; @@ -221,23 +224,51 @@ public interface ITurtleAccess { void playAnimation(TurtleAnimation animation); /** - * Returns the turtle on the specified side of the turtle, if there is one. + * Returns the upgrade on the specified side of the turtle, if there is one. * * @param side The side to get the upgrade from. * @return The upgrade on the specified side of the turtle, if there is one. - * @see #setUpgrade(TurtleSide, ITurtleUpgrade) + * @see #getUpgradeWithData(TurtleSide) + * @see #setUpgradeWithData(TurtleSide, UpgradeData) */ @Nullable ITurtleUpgrade getUpgrade(TurtleSide side); + /** + * Returns the upgrade on the specified side of the turtle, along with its {@linkplain #getUpgradeNBTData(TurtleSide) + * update data}. + * + * @param side The side to get the upgrade from. + * @return The upgrade on the specified side of the turtle, along with its upgrade data, if there is one. + * @see #getUpgradeWithData(TurtleSide) + * @see #setUpgradeWithData(TurtleSide, UpgradeData) + */ + default @Nullable UpgradeData getUpgradeWithData(TurtleSide side) { + var upgrade = getUpgrade(side); + return upgrade == null ? null : UpgradeData.of(upgrade, getUpgradeNBTData(side)); + } + /** * Set the upgrade for a given side, resetting peripherals and clearing upgrade specific data. * * @param side The side to set the upgrade on. * @param upgrade The upgrade to set, may be {@code null} to clear. * @see #getUpgrade(TurtleSide) + * @deprecated Use {@link #setUpgradeWithData(TurtleSide, UpgradeData)} */ - void setUpgrade(TurtleSide side, @Nullable ITurtleUpgrade upgrade); + @Deprecated + default void setUpgrade(TurtleSide side, @Nullable ITurtleUpgrade upgrade) { + setUpgradeWithData(side, upgrade == null ? null : UpgradeData.ofDefault(upgrade)); + } + + /** + * Set the upgrade for a given side and its upgrade data. + * + * @param side The side to set the upgrade on. + * @param upgrade The upgrade to set, may be {@code null} to clear. + * @see #getUpgradeWithData(TurtleSide) + */ + void setUpgradeWithData(TurtleSide side, @Nullable UpgradeData upgrade); /** * Returns the peripheral created by the upgrade on the specified side of the turtle, if there is one. @@ -257,6 +288,8 @@ public interface ITurtleAccess { * @param side The side to get the upgrade data for. * @return The upgrade-specific data. * @see #updateUpgradeNBTData(TurtleSide) + * @see UpgradeBase#getUpgradeItem(CompoundTag) + * @see UpgradeBase#getUpgradeData(ItemStack) */ CompoundTag getUpgradeNBTData(TurtleSide side); diff --git a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java index b39d8429c..2e4d7616b 100644 --- a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java +++ b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java @@ -7,6 +7,7 @@ package dan200.computercraft.api.turtle; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.upgrades.UpgradeBase; import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; import javax.annotation.Nullable; @@ -79,4 +80,17 @@ public interface ITurtleUpgrade extends UpgradeBase { */ default void update(ITurtleAccess turtle, TurtleSide side) { } + + /** + * Get upgrade data that should be persisted when the turtle was broken. + *

+ * This method should be overridden when you don't need to store all upgrade data by default. For instance, if you + * store peripheral state in the upgrade data, which should be lost when the turtle is broken. + * + * @param upgradeData Data that currently stored for this upgrade + * @return Filtered version of this data. + */ + default CompoundTag getPersistedData(CompoundTag upgradeData) { + return upgradeData; + } } diff --git a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleToolDurability.java b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleToolDurability.java new file mode 100644 index 000000000..5487dbdea --- /dev/null +++ b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleToolDurability.java @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.api.turtle; + +import net.minecraft.util.StringRepresentable; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.item.ItemStack; + +/** + * Indicates if an equipped turtle item will consume durability. + * + * @see TurtleUpgradeDataProvider.ToolBuilder#consumeDurability(TurtleToolDurability) + */ +public enum TurtleToolDurability implements StringRepresentable { + /** + * The equipped tool always consumes durability when using. + */ + ALWAYS("always"), + + /** + * The equipped tool consumes durability if it is {@linkplain ItemStack#isEnchanted() enchanted} or has + * {@linkplain ItemStack#getAttributeModifiers(EquipmentSlot) custom attribute modifiers}. + */ + WHEN_ENCHANTED("when_enchanted"), + + /** + * The equipped tool never consumes durability. Tools which have been damaged cannot be used as upgrades. + */ + NEVER("never"); + + private final String serialisedName; + + /** + * The codec which may be used for serialising/deserialising {@link TurtleToolDurability}s. + */ + public static final StringRepresentable.EnumCodec CODEC = StringRepresentable.fromEnum(TurtleToolDurability::values); + + TurtleToolDurability(String serialisedName) { + this.serialisedName = serialisedName; + } + + @Override + public String getSerializedName() { + return serialisedName; + } +} diff --git a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeDataProvider.java b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeDataProvider.java index 7aef277d6..1a8118544 100644 --- a/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeDataProvider.java +++ b/projects/common-api/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeDataProvider.java @@ -13,8 +13,10 @@ import net.minecraft.data.DataGenerator; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import javax.annotation.Nullable; @@ -61,6 +63,8 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider breakable; + private boolean allowEnchantments = false; + private TurtleToolDurability consumeDurability = TurtleToolDurability.NEVER; ToolBuilder(ResourceLocation id, TurtleUpgradeSerialiser serialiser, Item toolItem) { this.id = id; @@ -104,6 +108,28 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider + * While upgrades can store upgrade data ({@link ITurtleAccess#getUpgradeNBTData(TurtleSide)} and + * {@link IPocketAccess#getUpgradeNBTData()}}, by default this data is discarded when an upgrade is unequipped, + * and the original item stack is returned. + *

+ * By overriding this method, you can create a new {@link ItemStack} which contains enough data to + * {@linkplain #getUpgradeData(ItemStack) re-create the upgrade data} if the item is re-equipped. + *

+ * When overriding this, you should override {@link #getUpgradeData(ItemStack)} and {@link #isItemSuitable(ItemStack)} + * at the same time, + * + * @param upgradeData The current upgrade data. This should NOT be mutated. + * @return The item stack returned when unequipping. + */ + default ItemStack getUpgradeItem(CompoundTag upgradeData) { + return getCraftingItem(); + } + + /** + * Extract upgrade data from an {@link ItemStack}. + *

+ * This upgrade data will be available with {@link ITurtleAccess#getUpgradeNBTData(TurtleSide)} or + * {@link IPocketAccess#getUpgradeNBTData()}. + *

+ * This should be an inverse to {@link #getUpgradeItem(CompoundTag)}. + * + * @param stack The stack that was equipped by the turtle or pocket computer. This will have the same item as + * {@link #getCraftingItem()}. + * @return The upgrade data that should be set on the turtle or pocket computer. + */ + default CompoundTag getUpgradeData(ItemStack stack) { + return new CompoundTag(); + } + /** * Determine if an item is suitable for being used for this upgrade. *

diff --git a/projects/common-api/src/main/java/dan200/computercraft/api/upgrades/UpgradeData.java b/projects/common-api/src/main/java/dan200/computercraft/api/upgrades/UpgradeData.java new file mode 100644 index 000000000..27dd914f2 --- /dev/null +++ b/projects/common-api/src/main/java/dan200/computercraft/api/upgrades/UpgradeData.java @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.api.upgrades; + +import dan200.computercraft.api.pocket.IPocketUpgrade; +import dan200.computercraft.api.turtle.ITurtleUpgrade; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Contract; + +import javax.annotation.Nullable; + +/** + * An upgrade (i.e. a {@link ITurtleUpgrade}) and its current upgrade data. + *

+ * IMPORTANT: The {@link #data()} in an upgrade data is often a reference to the original upgrade data. + * Be careful to take a {@linkplain #copy() defensive copy} if you plan to use the data in this upgrade. + * + * @param upgrade The current upgrade. + * @param data The upgrade's data. + * @param The type of upgrade, either {@link ITurtleUpgrade} or {@link IPocketUpgrade}. + */ +public record UpgradeData(T upgrade, CompoundTag data) { + /** + * A utility method to construct a new {@link UpgradeData} instance. + * + * @param upgrade An upgrade. + * @param data The upgrade's data. + * @param The type of upgrade. + * @return The new {@link UpgradeData} instance. + */ + public static UpgradeData of(T upgrade, CompoundTag data) { + return new UpgradeData<>(upgrade, data); + } + + /** + * Create an {@link UpgradeData} containing the default {@linkplain #data() data} for an upgrade. + * + * @param upgrade The upgrade instance. + * @param The type of upgrade. + * @return The default upgrade data. + */ + public static UpgradeData ofDefault(T upgrade) { + return of(upgrade, upgrade.getUpgradeData(upgrade.getCraftingItem())); + } + + /** + * Take a copy of a (possibly {@code null}) {@link UpgradeData} instance. + * + * @param upgrade The copied upgrade data. + * @param The type of upgrade. + * @return The newly created upgrade data. + */ + @Contract("!null -> !null; null -> null") + public static @Nullable UpgradeData copyOf(@Nullable UpgradeData upgrade) { + return upgrade == null ? null : upgrade.copy(); + } + + /** + * Get the {@linkplain UpgradeBase#getUpgradeItem(CompoundTag) upgrade item} for this upgrade. + *

+ * This returns a defensive copy of the item, to prevent accidental mutation of the upgrade data or original + * {@linkplain UpgradeBase#getCraftingItem() upgrade stack}. + * + * @return This upgrade's item. + */ + public ItemStack getUpgradeItem() { + return upgrade.getUpgradeItem(data).copy(); + } + + /** + * Take a copy of this {@link UpgradeData}. This returns a new instance with the same upgrade and a fresh copy of + * the upgrade data. + * + * @return A copy of the current instance. + */ + public UpgradeData copy() { + return new UpgradeData<>(upgrade(), data().copy()); + } +} diff --git a/projects/common/build.gradle.kts b/projects/common/build.gradle.kts index e42b0fcb1..c4f40639e 100644 --- a/projects/common/build.gradle.kts +++ b/projects/common/build.gradle.kts @@ -7,6 +7,7 @@ import cc.tweaked.gradle.clientClasses import cc.tweaked.gradle.commonClasses plugins { + id("cc-tweaked.publishing") id("cc-tweaked.vanilla") id("cc-tweaked.gametest") } diff --git a/projects/common/src/client/java/dan200/computercraft/client/model/turtle/TurtleModelParts.java b/projects/common/src/client/java/dan200/computercraft/client/model/turtle/TurtleModelParts.java index e5a2b7365..fec6d4d7d 100644 --- a/projects/common/src/client/java/dan200/computercraft/client/model/turtle/TurtleModelParts.java +++ b/projects/common/src/client/java/dan200/computercraft/client/model/turtle/TurtleModelParts.java @@ -4,11 +4,13 @@ package dan200.computercraft.client.model.turtle; +import com.google.common.cache.CacheBuilder; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Transformation; import dan200.computercraft.api.client.TransformedModel; import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.TurtleSide; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.client.platform.ClientPlatformHelper; import dan200.computercraft.client.render.TurtleBlockEntityRenderer; import dan200.computercraft.client.turtle.TurtleUpgradeModellers; @@ -21,15 +23,17 @@ import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; import java.util.function.Function; /** * Combines several individual models together to form a turtle. + * + * @param The type of the resulting "baked model". */ -public final class TurtleModelParts { +public final class TurtleModelParts { private static final Transformation identity, flip; static { @@ -42,33 +46,67 @@ public final class TurtleModelParts { flip = new Transformation(stack.last().pose()); } - public record Combination( + private record Combination( boolean colour, - @Nullable ITurtleUpgrade leftUpgrade, - @Nullable ITurtleUpgrade rightUpgrade, + @Nullable UpgradeData leftUpgrade, + @Nullable UpgradeData rightUpgrade, @Nullable ResourceLocation overlay, boolean christmas, boolean flip ) { + Combination copy() { + if (leftUpgrade == null && rightUpgrade == null) return this; + return new Combination( + colour, UpgradeData.copyOf(leftUpgrade), UpgradeData.copyOf(rightUpgrade), + overlay, christmas, flip + ); + } } private final BakedModel familyModel; private final BakedModel colourModel; private final Function transformer; + private final Function buildModel; /** * A cache of {@link TransformedModel} to the transformed {@link BakedModel}. This helps us pool the transformed * instances, reducing memory usage and hopefully ensuring their caches are hit more often! */ - private final Map transformCache = new HashMap<>(); + private final Map transformCache = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .expireAfterAccess(30, TimeUnit.SECONDS) + .build() + .asMap(); - public TurtleModelParts(BakedModel familyModel, BakedModel colourModel, ModelTransformer transformer) { + /** + * A cache of {@link Combination}s to the combined model. + */ + private final Map modelCache = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .expireAfterAccess(30, TimeUnit.SECONDS) + .build() + .asMap(); + + public TurtleModelParts(BakedModel familyModel, BakedModel colourModel, ModelTransformer transformer, Function, T> combineModel) { this.familyModel = familyModel; this.colourModel = colourModel; this.transformer = x -> transformer.transform(x.getModel(), x.getMatrix()); + buildModel = x -> combineModel.apply(buildModel(x)); } - public Combination getCombination(ItemStack stack) { + public T getModel(ItemStack stack) { + var combination = getCombination(stack); + var existing = modelCache.get(combination); + if (existing != null) return existing; + + // Take a defensive copy of the upgrade data, and add it to the cache. + var newCombination = combination.copy(); + var newModel = buildModel.apply(newCombination); + modelCache.put(newCombination, newModel); + return newModel; + } + + private Combination getCombination(ItemStack stack) { var christmas = Holiday.getCurrent() == Holiday.CHRISTMAS; if (!(stack.getItem() instanceof TurtleItem turtle)) { @@ -76,8 +114,8 @@ public final class TurtleModelParts { } var colour = turtle.getColour(stack); - var leftUpgrade = turtle.getUpgrade(stack, TurtleSide.LEFT); - var rightUpgrade = turtle.getUpgrade(stack, TurtleSide.RIGHT); + var leftUpgrade = turtle.getUpgradeWithData(stack, TurtleSide.LEFT); + var rightUpgrade = turtle.getUpgradeWithData(stack, TurtleSide.RIGHT); var overlay = turtle.getOverlay(stack); var label = turtle.getLabel(stack); var flip = label != null && (label.equals("Dinnerbone") || label.equals("Grumm")); @@ -85,7 +123,7 @@ public final class TurtleModelParts { return new Combination(colour != -1, leftUpgrade, rightUpgrade, overlay, christmas, flip); } - public List buildModel(Combination combo) { + private List buildModel(Combination combo) { var mc = Minecraft.getInstance(); var modelManager = mc.getItemRenderer().getItemModelShaper().getModelManager(); @@ -97,19 +135,20 @@ public final class TurtleModelParts { if (overlayModelLocation != null) { parts.add(transform(ClientPlatformHelper.get().getModel(modelManager, overlayModelLocation), transformation)); } - if (combo.leftUpgrade() != null) { - var model = TurtleUpgradeModellers.getModel(combo.leftUpgrade(), null, TurtleSide.LEFT); - parts.add(transform(model.getModel(), transformation.compose(model.getMatrix()))); - } - if (combo.rightUpgrade() != null) { - var model = TurtleUpgradeModellers.getModel(combo.rightUpgrade(), null, TurtleSide.RIGHT); - parts.add(transform(model.getModel(), transformation.compose(model.getMatrix()))); - } + + addUpgrade(parts, transformation, TurtleSide.LEFT, combo.leftUpgrade()); + addUpgrade(parts, transformation, TurtleSide.RIGHT, combo.rightUpgrade()); return parts; } - public BakedModel transform(BakedModel model, Transformation transformation) { + private void addUpgrade(List parts, Transformation transformation, TurtleSide side, @Nullable UpgradeData upgrade) { + if (upgrade == null) return; + var model = TurtleUpgradeModellers.getModel(upgrade.upgrade(), upgrade.data(), side); + parts.add(transform(model.getModel(), transformation.compose(model.getMatrix()))); + } + + private BakedModel transform(BakedModel model, Transformation transformation) { if (transformation.equals(Transformation.identity())) return model; return transformCache.computeIfAbsent(new TransformedModel(model, transformation), transformer); } diff --git a/projects/common/src/client/java/dan200/computercraft/client/turtle/TurtleUpgradeModellers.java b/projects/common/src/client/java/dan200/computercraft/client/turtle/TurtleUpgradeModellers.java index 9037748f9..49b08801c 100644 --- a/projects/common/src/client/java/dan200/computercraft/client/turtle/TurtleUpgradeModellers.java +++ b/projects/common/src/client/java/dan200/computercraft/client/turtle/TurtleUpgradeModellers.java @@ -14,8 +14,8 @@ import dan200.computercraft.api.turtle.TurtleUpgradeSerialiser; import dan200.computercraft.impl.TurtleUpgrades; import dan200.computercraft.impl.UpgradeManager; import net.minecraft.client.Minecraft; +import net.minecraft.nbt.CompoundTag; -import javax.annotation.Nullable; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; @@ -52,12 +52,18 @@ public final class TurtleUpgradeModellers { } } - public static TransformedModel getModel(ITurtleUpgrade upgrade, @Nullable ITurtleAccess access, TurtleSide side) { + public static TransformedModel getModel(ITurtleUpgrade upgrade, ITurtleAccess access, TurtleSide side) { @SuppressWarnings("unchecked") var modeller = (TurtleUpgradeModeller) modelCache.computeIfAbsent(upgrade, TurtleUpgradeModellers::getModeller); return modeller.getModel(upgrade, access, side); } + public static TransformedModel getModel(ITurtleUpgrade upgrade, CompoundTag data, TurtleSide side) { + @SuppressWarnings("unchecked") + var modeller = (TurtleUpgradeModeller) modelCache.computeIfAbsent(upgrade, TurtleUpgradeModellers::getModeller); + return modeller.getModel(upgrade, data, side); + } + private static TurtleUpgradeModeller getModeller(ITurtleUpgrade upgradeA) { var wrapper = TurtleUpgrades.instance().getWrapper(upgradeA); if (wrapper == null) return NULL_TURTLE_MODELLER; diff --git a/projects/common/src/main/java/dan200/computercraft/data/RecipeProvider.java b/projects/common/src/main/java/dan200/computercraft/data/RecipeProvider.java index 46854e04d..f23d6711c 100644 --- a/projects/common/src/main/java/dan200/computercraft/data/RecipeProvider.java +++ b/projects/common/src/main/java/dan200/computercraft/data/RecipeProvider.java @@ -8,6 +8,7 @@ import com.google.gson.JsonObject; import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.pocket.PocketUpgradeDataProvider; import dan200.computercraft.api.turtle.TurtleUpgradeDataProvider; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.core.util.Colour; import dan200.computercraft.shared.ModRegistry; import dan200.computercraft.shared.common.IColouredItem; @@ -110,7 +111,7 @@ class RecipeProvider extends net.minecraft.data.recipes.RecipeProvider { var nameId = turtleItem.getFamily().name().toLowerCase(Locale.ROOT); for (var upgrade : turtleUpgrades.getGeneratedUpgrades()) { - var result = turtleItem.create(-1, null, -1, null, upgrade, -1, null); + var result = turtleItem.create(-1, null, -1, null, UpgradeData.ofDefault(upgrade), -1, null); ShapedRecipeBuilder .shaped(RecipeCategory.REDSTONE, result.getItem()) .group(String.format("%s:turtle_%s", ComputerCraftAPI.MOD_ID, nameId)) @@ -146,7 +147,7 @@ class RecipeProvider extends net.minecraft.data.recipes.RecipeProvider { var nameId = pocket.getFamily().name().toLowerCase(Locale.ROOT); for (var upgrade : pocketUpgrades.getGeneratedUpgrades()) { - var result = pocket.create(-1, null, -1, upgrade); + var result = pocket.create(-1, null, -1, UpgradeData.ofDefault(upgrade)); ShapedRecipeBuilder .shaped(RecipeCategory.REDSTONE, result.getItem()) .group(String.format("%s:pocket_%s", ComputerCraftAPI.MOD_ID, nameId)) diff --git a/projects/common/src/main/java/dan200/computercraft/impl/AbstractComputerCraftAPI.java b/projects/common/src/main/java/dan200/computercraft/impl/AbstractComputerCraftAPI.java index 45e4ed707..dc4ca4f7a 100644 --- a/projects/common/src/main/java/dan200/computercraft/impl/AbstractComputerCraftAPI.java +++ b/projects/common/src/main/java/dan200/computercraft/impl/AbstractComputerCraftAPI.java @@ -19,8 +19,6 @@ import dan200.computercraft.api.pocket.PocketUpgradeSerialiser; import dan200.computercraft.api.redstone.BundledRedstoneProvider; import dan200.computercraft.api.turtle.TurtleRefuelHandler; import dan200.computercraft.api.turtle.TurtleUpgradeSerialiser; -import dan200.computercraft.core.apis.ApiFactories; -import dan200.computercraft.core.asm.GenericMethod; import dan200.computercraft.core.filesystem.WritableFileMount; import dan200.computercraft.impl.detail.DetailRegistryImpl; import dan200.computercraft.impl.network.wired.WiredNodeImpl; @@ -79,7 +77,7 @@ public abstract class AbstractComputerCraftAPI implements ComputerCraftAPIServic @Override public final void registerGenericSource(GenericSource source) { - GenericMethod.register(source); + GenericSources.register(source); } @Override diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/ApiFactories.java b/projects/common/src/main/java/dan200/computercraft/impl/ApiFactories.java similarity index 54% rename from projects/core/src/main/java/dan200/computercraft/core/apis/ApiFactories.java rename to projects/common/src/main/java/dan200/computercraft/impl/ApiFactories.java index 232419aa1..388854fce 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/ApiFactories.java +++ b/projects/common/src/main/java/dan200/computercraft/impl/ApiFactories.java @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: MPL-2.0 -package dan200.computercraft.core.apis; +package dan200.computercraft.impl; import dan200.computercraft.api.lua.ILuaAPIFactory; @@ -11,19 +11,24 @@ import java.util.Collections; import java.util.LinkedHashSet; import java.util.Objects; +/** + * The global factory for {@link ILuaAPIFactory}s. + * + * @see dan200.computercraft.core.ComputerContext.Builder#apiFactories(Collection) + * @see dan200.computercraft.api.ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) + */ public final class ApiFactories { private ApiFactories() { } private static final Collection factories = new LinkedHashSet<>(); - private static final Collection factoriesView = Collections.unmodifiableCollection(factories); - public static synchronized void register(ILuaAPIFactory factory) { + static synchronized void register(ILuaAPIFactory factory) { Objects.requireNonNull(factory, "provider cannot be null"); factories.add(factory); } - public static Iterable getAll() { - return factoriesView; + public static Collection getAll() { + return Collections.unmodifiableCollection(factories); } } diff --git a/projects/common/src/main/java/dan200/computercraft/impl/GenericSources.java b/projects/common/src/main/java/dan200/computercraft/impl/GenericSources.java new file mode 100644 index 000000000..0ba250c9c --- /dev/null +++ b/projects/common/src/main/java/dan200/computercraft/impl/GenericSources.java @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.impl; + +import dan200.computercraft.api.lua.GenericSource; +import dan200.computercraft.core.asm.GenericMethod; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.Objects; + +/** + * The global registry for {@link GenericSource}s. + * + * @see dan200.computercraft.core.ComputerContext.Builder#genericMethods(Collection) + * @see dan200.computercraft.api.ComputerCraftAPI#registerGenericSource(GenericSource) + */ +public final class GenericSources { + private GenericSources() { + } + + private static final Collection sources = new LinkedHashSet<>(); + + static synchronized void register(GenericSource source) { + Objects.requireNonNull(source, "provider cannot be null"); + sources.add(source); + } + + public static Collection getAllMethods() { + return sources.stream().flatMap(GenericMethod::getMethods).toList(); + } +} diff --git a/projects/common/src/main/java/dan200/computercraft/impl/UpgradeManager.java b/projects/common/src/main/java/dan200/computercraft/impl/UpgradeManager.java index 440d4bd2b..a3e25eae5 100644 --- a/projects/common/src/main/java/dan200/computercraft/impl/UpgradeManager.java +++ b/projects/common/src/main/java/dan200/computercraft/impl/UpgradeManager.java @@ -7,6 +7,7 @@ package dan200.computercraft.impl; import com.google.gson.*; import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.upgrades.UpgradeBase; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.api.upgrades.UpgradeSerialiser; import dan200.computercraft.shared.platform.PlatformHelper; import net.minecraft.core.Registry; @@ -74,13 +75,13 @@ public class UpgradeManager, T extends } @Nullable - public T get(ItemStack stack) { + public UpgradeData get(ItemStack stack) { if (stack.isEmpty()) return null; for (var wrapper : current.values()) { var craftingStack = wrapper.upgrade().getCraftingItem(); if (!craftingStack.isEmpty() && craftingStack.getItem() == stack.getItem() && wrapper.upgrade().isItemSuitable(stack)) { - return wrapper.upgrade(); + return UpgradeData.of(wrapper.upgrade, wrapper.upgrade.getUpgradeData(stack)); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/ModRegistry.java b/projects/common/src/main/java/dan200/computercraft/shared/ModRegistry.java index f174d6240..b0de287c8 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/ModRegistry.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/ModRegistry.java @@ -11,6 +11,7 @@ import dan200.computercraft.api.detail.VanillaDetailRegistries; import dan200.computercraft.api.media.IMedia; import dan200.computercraft.api.pocket.PocketUpgradeSerialiser; import dan200.computercraft.api.turtle.TurtleUpgradeSerialiser; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.core.util.Colour; import dan200.computercraft.impl.PocketUpgrades; import dan200.computercraft.impl.TurtleUpgrades; @@ -445,12 +446,12 @@ public final class ModRegistry { private static void addTurtle(CreativeModeTab.Output out, TurtleItem turtle) { out.accept(turtle.create(-1, null, -1, null, null, 0, null)); TurtleUpgrades.getVanillaUpgrades() - .map(x -> turtle.create(-1, null, -1, null, x, 0, null)) + .map(x -> turtle.create(-1, null, -1, null, UpgradeData.ofDefault(x), 0, null)) .forEach(out::accept); } private static void addPocket(CreativeModeTab.Output out, PocketComputerItem pocket) { out.accept(pocket.create(-1, null, -1, null)); - PocketUpgrades.getVanillaUpgrades().map(x -> pocket.create(-1, null, -1, x)).forEach(out::accept); + PocketUpgrades.getVanillaUpgrades().map(x -> pocket.create(-1, null, -1, UpgradeData.ofDefault(x))).forEach(out::accept); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java b/projects/common/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java index 4f148eab8..f6798f77d 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java @@ -6,9 +6,12 @@ package dan200.computercraft.shared.command; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; import dan200.computercraft.core.computer.ComputerSide; import dan200.computercraft.core.metrics.Metrics; +import dan200.computercraft.shared.command.arguments.ComputersArgumentType; import dan200.computercraft.shared.command.text.TableBuilder; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ServerComputer; @@ -173,7 +176,10 @@ public final class CommandComputerCraft { .then(command("queue") .requires(UserLevel.ANYONE) - .arg("computer", manyComputers()) + .arg( + RequiredArgumentBuilder.argument("computer", manyComputers()) + .suggests((context, builder) -> Suggestions.empty()) + ) .argManyValue("args", StringArgumentType.string(), Collections.emptyList()) .executes((ctx, args) -> { var computers = getComputersArgument(ctx, "computer"); diff --git a/projects/common/src/main/java/dan200/computercraft/shared/command/UserLevel.java b/projects/common/src/main/java/dan200/computercraft/shared/command/UserLevel.java index 2d9438121..c8bdbb0f2 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/command/UserLevel.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/command/UserLevel.java @@ -49,6 +49,29 @@ public enum UserLevel implements Predicate { return source.hasPermission(toLevel()); } + /** + * Take the union of two {@link UserLevel}s. + *

+ * This satisfies the property that for all sources {@code s}, {@code a.test(s) || b.test(s) == (a โˆช b).test(s)}. + * + * @param left The first user level to take the union of. + * @param right The second user level to take the union of. + * @return The union of two levels. + */ + public static UserLevel union(UserLevel left, UserLevel right) { + if (left == right) return left; + + // x โˆช ANYONE = ANYONE + if (left == ANYONE || right == ANYONE) return ANYONE; + + // x โˆช OWNER = OWNER + if (left == OWNER) return right; + if (right == OWNER) return left; + + // At this point, we have x != y and x, y โˆˆ { OP, OWNER_OP }. + return OWNER_OP; + } + private static boolean isOwner(CommandSourceStack source) { var server = source.getServer(); var sender = source.getEntity(); diff --git a/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java b/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java index f67200b9c..d263cb5ca 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/ComputersArgumentType.java @@ -18,7 +18,6 @@ import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.synchronization.ArgumentTypeInfo; import net.minecraft.network.FriendlyByteBuf; -import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.CompletableFuture; @@ -159,14 +158,14 @@ public final class ComputersArgumentType implements ArgumentType { @Override - public ComputersArgumentType instantiate(@NotNull CommandBuildContext context) { + public ComputersArgumentType instantiate(CommandBuildContext context) { return requireSome ? SOME : MANY; } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java b/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java index bc35280b2..51ff6c5fc 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java @@ -17,7 +17,6 @@ import net.minecraft.commands.synchronization.ArgumentTypeInfo; import net.minecraft.commands.synchronization.ArgumentTypeInfos; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; -import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; @@ -144,7 +143,7 @@ public final class RepeatArgumentType implements ArgumentType> { ) implements ArgumentTypeInfo.Template> { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) - public RepeatArgumentType instantiate(@NotNull CommandBuildContext commandBuildContext) { + public RepeatArgumentType instantiate(CommandBuildContext commandBuildContext) { var child = child().instantiate(commandBuildContext); return flatten ? RepeatArgumentType.someFlat((ArgumentType) child, some()) : RepeatArgumentType.some(child, some()); } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java b/projects/common/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java index 3fe77ff48..2a395ff7b 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java @@ -48,11 +48,15 @@ public class CommandBuilder implements CommandNodeBuilder> { return this; } - public CommandBuilder arg(String name, ArgumentType type) { - args.add(RequiredArgumentBuilder.argument(name, type)); + public CommandBuilder arg(ArgumentBuilder arg) { + args.add(arg); return this; } + public CommandBuilder arg(String name, ArgumentType type) { + return arg(RequiredArgumentBuilder.argument(name, type)); + } + public CommandNodeBuilder>> argManyValue(String name, ArgumentType type, List empty) { return argMany(name, type, () -> empty); } @@ -74,7 +78,7 @@ public class CommandBuilder implements CommandNodeBuilder> { return command -> { // The node for no arguments - var tail = tail(ctx -> command.run(ctx, empty.get())); + var tail = setupTail(ctx -> command.run(ctx, empty.get())); // The node for one or more arguments ArgumentBuilder moreArg = RequiredArgumentBuilder @@ -83,7 +87,7 @@ public class CommandBuilder implements CommandNodeBuilder> { // Chain all of them together! tail.then(moreArg); - return link(tail); + return buildTail(tail); }; } @@ -94,20 +98,16 @@ public class CommandBuilder implements CommandNodeBuilder> { @Override public CommandNode executes(Command command) { - if (args.isEmpty()) throw new IllegalStateException("Cannot have empty arg chain builder"); - - return link(tail(command)); + return buildTail(setupTail(command)); } - private ArgumentBuilder tail(Command command) { - var defaultTail = args.get(args.size() - 1); - defaultTail.executes(command); - if (requires != null) defaultTail.requires(requires); - return defaultTail; + private ArgumentBuilder setupTail(Command command) { + return args.get(args.size() - 1).executes(command); } - private CommandNode link(ArgumentBuilder tail) { + private CommandNode buildTail(ArgumentBuilder tail) { for (var i = args.size() - 2; i >= 0; i--) tail = args.get(i).then(tail); + if (requires != null) tail.requires(requires); return tail.build(); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java b/projects/common/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java index 56c50c218..16c7811d2 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java @@ -10,6 +10,7 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.tree.CommandNode; import com.mojang.brigadier.tree.LiteralCommandNode; +import dan200.computercraft.shared.command.UserLevel; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.ClickEvent; @@ -18,6 +19,8 @@ import net.minecraft.network.chat.Component; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Stream; import static dan200.computercraft.core.util.Nullability.assertNonNull; import static dan200.computercraft.shared.command.text.ChatHelpers.coloured; @@ -37,6 +40,29 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder requires(Predicate requirement) { + throw new IllegalStateException("Cannot use requires on a HelpingArgumentBuilder"); + } + + @Override + public Predicate getRequirement() { + // The requirement of this node is the union of all child's requirements. + var requirements = Stream.concat( + children.stream().map(ArgumentBuilder::getRequirement), + getArguments().stream().map(CommandNode::getRequirement) + ).toList(); + + // If all requirements are a UserLevel, take the union of those instead. + var userLevel = UserLevel.OWNER; + for (var requirement : requirements) { + if (!(requirement instanceof UserLevel level)) return x -> requirements.stream().anyMatch(y -> y.test(x)); + userLevel = UserLevel.union(userLevel, level); + } + + return userLevel; + } + @Override public LiteralArgumentBuilder executes(final Command command) { throw new IllegalStateException("Cannot use executes on a HelpingArgumentBuilder"); @@ -80,9 +106,7 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilderliteral("help") - .requires(x -> getArguments().stream().anyMatch(y -> y.getRequirement().test(x))) - .executes(helpCommand); + var helpNode = LiteralArgumentBuilder.literal("help").executes(helpCommand); // Add all normal command children to this and the help node for (var child : getArguments()) { diff --git a/projects/common/src/main/java/dan200/computercraft/shared/computer/core/ServerContext.java b/projects/common/src/main/java/dan200/computercraft/shared/computer/core/ServerContext.java index b2d266133..64480353b 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/computer/core/ServerContext.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/computer/core/ServerContext.java @@ -9,13 +9,16 @@ import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.filesystem.Mount; import dan200.computercraft.api.network.PacketNetwork; import dan200.computercraft.core.ComputerContext; -import dan200.computercraft.core.computer.ComputerThread; import dan200.computercraft.core.computer.GlobalEnvironment; import dan200.computercraft.core.computer.mainthread.MainThread; import dan200.computercraft.core.computer.mainthread.MainThreadConfig; import dan200.computercraft.core.lua.CobaltLuaMachine; import dan200.computercraft.core.lua.ILuaMachine; +import dan200.computercraft.core.methods.MethodSupplier; +import dan200.computercraft.core.methods.PeripheralMethod; import dan200.computercraft.impl.AbstractComputerCraftAPI; +import dan200.computercraft.impl.ApiFactories; +import dan200.computercraft.impl.GenericSources; import dan200.computercraft.shared.CommonHooks; import dan200.computercraft.shared.computer.metrics.GlobalMetrics; import dan200.computercraft.shared.config.ConfigSpec; @@ -67,11 +70,13 @@ public final class ServerContext { this.server = server; storageDir = server.getWorldPath(FOLDER); mainThread = new MainThread(mainThreadConfig); - context = new ComputerContext( - new Environment(server), - new ComputerThread(ConfigSpec.computerThreads.get()), - mainThread, luaMachine - ); + context = ComputerContext.builder(new Environment(server)) + .computerThreads(ConfigSpec.computerThreads.get()) + .mainThreadScheduler(mainThread) + .luaFactory(luaMachine) + .apiFactories(ApiFactories.getAll()) + .genericMethods(GenericSources.getAllMethods()) + .build(); idAssigner = new IDAssigner(storageDir.resolve("ids.json")); } @@ -133,6 +138,16 @@ public final class ServerContext { return context; } + /** + * Get the {@link MethodSupplier} used to find methods on peripherals. + * + * @return The {@link PeripheralMethod} method supplier. + * @see ComputerContext#peripheralMethods() + */ + public MethodSupplier peripheralMethods() { + return context.peripheralMethods(); + } + /** * Tick all components of this server context. This should NOT be called outside of {@link CommonHooks}. */ diff --git a/projects/common/src/main/java/dan200/computercraft/shared/computer/upload/TransferredFile.java b/projects/common/src/main/java/dan200/computercraft/shared/computer/upload/TransferredFile.java index 687ea6989..c059496f2 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/computer/upload/TransferredFile.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/computer/upload/TransferredFile.java @@ -7,7 +7,7 @@ package dan200.computercraft.shared.computer.upload; import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.core.apis.handles.BinaryReadableHandle; import dan200.computercraft.core.apis.handles.ByteBufferChannel; -import dan200.computercraft.core.asm.ObjectSource; +import dan200.computercraft.core.methods.ObjectSource; import java.nio.ByteBuffer; import java.util.Collections; diff --git a/projects/common/src/main/java/dan200/computercraft/shared/config/AddressRuleConfig.java b/projects/common/src/main/java/dan200/computercraft/shared/config/AddressRuleConfig.java index 8974c9185..c063569a7 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/config/AddressRuleConfig.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/config/AddressRuleConfig.java @@ -4,21 +4,19 @@ package dan200.computercraft.shared.config; +import com.electronwill.nightconfig.core.CommentedConfig; import com.electronwill.nightconfig.core.Config; import com.electronwill.nightconfig.core.InMemoryCommentedFormat; import com.electronwill.nightconfig.core.UnmodifiableConfig; import dan200.computercraft.core.apis.http.options.Action; import dan200.computercraft.core.apis.http.options.AddressRule; +import dan200.computercraft.core.apis.http.options.InvalidRuleException; import dan200.computercraft.core.apis.http.options.PartialOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; -import java.util.Locale; -import java.util.Optional; -import java.util.OptionalInt; -import java.util.OptionalLong; -import java.util.concurrent.ConcurrentHashMap; +import java.util.*; +import java.util.function.Consumer; /** * Parses, checks and generates {@link Config}s for {@link AddressRule}. @@ -26,49 +24,65 @@ import java.util.concurrent.ConcurrentHashMap; class AddressRuleConfig { private static final Logger LOG = LoggerFactory.getLogger(AddressRuleConfig.class); - public static UnmodifiableConfig makeRule(String host, Action action) { - var config = InMemoryCommentedFormat.defaultInstance().createConfig(ConcurrentHashMap::new); - config.add("host", host); - config.add("action", action.name().toLowerCase(Locale.ROOT)); + private static final AddressRule REJECT_ALL = AddressRule.parse("*", OptionalInt.empty(), Action.DENY.toPartial()); - if (host.equals("*") && action == Action.ALLOW) { - config.setComment("max_download", """ - The maximum size (in bytes) that a computer can download in a single request. - Note that responses may receive more data than allowed, but this data will not - be returned to the client."""); - config.set("max_download", AddressRule.MAX_DOWNLOAD); + public static List defaultRules() { + return List.of( + makeRule(config -> { + config.setComment("host", """ + The magic "$private" host matches all private address ranges, such as localhost and 192.168.0.0/16. + This rule prevents computers accessing internal services, and is strongly recommended."""); + config.add("host", "$private"); - config.setComment("max_upload", """ - The maximum size (in bytes) that a computer can upload in a single request. This - includes headers and POST text."""); - config.set("max_upload", AddressRule.MAX_UPLOAD); + config.setComment("action", "Deny all requests to private IP addresses."); + config.add("action", Action.DENY.name().toLowerCase(Locale.ROOT)); + }), + makeRule(config -> { + config.setComment("host", """ + The wildcard "*" rule matches all remaining hosts."""); + config.add("host", "*"); - config.setComment("max_websocket_message", "The maximum size (in bytes) that a computer can send or receive in one websocket packet."); - config.set("max_websocket_message", AddressRule.WEBSOCKET_MESSAGE); + config.setComment("action", "Allow all non-denied hosts."); + config.add("action", Action.ALLOW.name().toLowerCase(Locale.ROOT)); - config.setComment("use_proxy", "Enable use of the HTTP/SOCKS proxy if it is configured."); - config.set("use_proxy", false); - } + config.setComment("max_download", """ + The maximum size (in bytes) that a computer can download in a single request. + Note that responses may receive more data than allowed, but this data will not + be returned to the client."""); + config.set("max_download", AddressRule.MAX_DOWNLOAD); + config.setComment("max_upload", """ + The maximum size (in bytes) that a computer can upload in a single request. This + includes headers and POST text."""); + config.set("max_upload", AddressRule.MAX_UPLOAD); + + config.setComment("max_websocket_message", "The maximum size (in bytes) that a computer can send or receive in one websocket packet."); + config.set("max_websocket_message", AddressRule.WEBSOCKET_MESSAGE); + + config.setComment("use_proxy", "Enable use of the HTTP/SOCKS proxy if it is configured."); + config.set("use_proxy", false); + }) + ); + } + + private static UnmodifiableConfig makeRule(Consumer setup) { + var config = InMemoryCommentedFormat.defaultInstance().createConfig(LinkedHashMap::new); + setup.accept(config); return config; } - public static boolean checkRule(UnmodifiableConfig builder) { - var hostObj = get(builder, "host", String.class).orElse(null); - var port = unboxOptInt(get(builder, "port", Number.class)); - return hostObj != null && checkEnum(builder, "action", Action.class) - && check(builder, "port", Number.class) - && check(builder, "max_upload", Number.class) - && check(builder, "max_download", Number.class) - && check(builder, "websocket_message", Number.class) - && check(builder, "use_proxy", Boolean.class) - && AddressRule.parse(hostObj, port, PartialOptions.DEFAULT) != null; + public static AddressRule parseRule(UnmodifiableConfig builder) { + try { + return doParseRule(builder); + } catch (InvalidRuleException e) { + LOG.error("Malformed HTTP rule: {} HTTP will NOT work until this is fixed.", e.getMessage()); + return REJECT_ALL; + } } - @Nullable - public static AddressRule parseRule(UnmodifiableConfig builder) { + public static AddressRule doParseRule(UnmodifiableConfig builder) { var hostObj = get(builder, "host", String.class).orElse(null); - if (hostObj == null) return null; + if (hostObj == null) throw new InvalidRuleException("No 'host' specified"); var action = getEnum(builder, "action", Action.class).orElse(null); var port = unboxOptInt(get(builder, "port", Number.class)); @@ -88,38 +102,19 @@ class AddressRuleConfig { return AddressRule.parse(hostObj, port, options); } - private static boolean check(UnmodifiableConfig config, String field, Class klass) { - var value = config.get(field); - if (value == null || klass.isInstance(value)) return true; - - LOG.warn("HTTP rule's {} is not a {}.", field, klass.getSimpleName()); - return false; - } - - private static > boolean checkEnum(UnmodifiableConfig config, String field, Class klass) { - var value = config.get(field); - if (value == null) return true; - - if (!(value instanceof String)) { - LOG.warn("HTTP rule's {} is not a string", field); - return false; - } - - if (parseEnum(klass, (String) value) == null) { - LOG.warn("HTTP rule's {} is not a known option", field); - return false; - } - - return true; - } - private static Optional get(UnmodifiableConfig config, String field, Class klass) { var value = config.get(field); - return klass.isInstance(value) ? Optional.of(klass.cast(value)) : Optional.empty(); + if (value == null) return Optional.empty(); + if (klass.isInstance(value)) return Optional.of(klass.cast(value)); + + throw new InvalidRuleException(String.format( + "Field '%s' should be a '%s' but is a %s.", + field, klass.getSimpleName(), value.getClass().getSimpleName() + )); } private static > Optional getEnum(UnmodifiableConfig config, String field, Class klass) { - return get(config, field, String.class).map(x -> parseEnum(klass, x)); + return get(config, field, String.class).map(x -> parseEnum(field, klass, x)); } private static OptionalLong unboxOptLong(Optional value) { @@ -130,11 +125,14 @@ class AddressRuleConfig { return value.map(Number::intValue).map(OptionalInt::of).orElse(OptionalInt.empty()); } - @Nullable - private static > T parseEnum(Class klass, String x) { + private static > T parseEnum(String field, Class klass, String x) { for (var value : klass.getEnumConstants()) { if (value.name().equalsIgnoreCase(x)) return value; } - return null; + + throw new InvalidRuleException(String.format( + "Field '%s' should be one of %s, but is '%s'.", + field, Arrays.stream(klass.getEnumConstants()).map(Enum::name).toList(), x + )); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/config/ConfigSpec.java b/projects/common/src/main/java/dan200/computercraft/shared/config/ConfigSpec.java index fdd603ade..347f7fff0 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/config/ConfigSpec.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/config/ConfigSpec.java @@ -9,7 +9,6 @@ import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.core.CoreConfig; import dan200.computercraft.core.Logging; import dan200.computercraft.core.apis.http.NetworkUtils; -import dan200.computercraft.core.apis.http.options.Action; import dan200.computercraft.core.apis.http.options.ProxyType; import dan200.computercraft.core.computer.mainthread.MainThreadConfig; import dan200.computercraft.shared.peripheral.monitor.MonitorRenderer; @@ -20,9 +19,7 @@ import org.apache.logging.log4j.core.filter.MarkerFilter; import javax.annotation.Nullable; import java.nio.file.Path; -import java.util.Arrays; import java.util.List; -import java.util.Objects; import java.util.concurrent.TimeUnit; public final class ConfigSpec { @@ -182,9 +179,9 @@ public final class ConfigSpec { httpEnabled = builder .comment(""" - Enable the "http" API on Computers. This also disables the "pastebin" and "wget" - programs, that many users rely on. It's recommended to leave this on and use the - "rules" config option to impose more fine-grained control.""") + Enable the "http" API on Computers. Disabling this also disables the "pastebin" and + "wget" programs, that many users rely on. It's recommended to leave this on and use + the "rules" config option to impose more fine-grained control.""") .define("enabled", CoreConfig.httpEnabled); httpWebsocketEnabled = builder @@ -194,16 +191,23 @@ public final class ConfigSpec { httpRules = builder .comment(""" A list of rules which control behaviour of the "http" API for specific domains or - IPs. Each rule is an item with a 'host' to match against, and a series of - properties. Rules are evaluated in order, meaning earlier rules override later - ones. - The host may be a domain name ("pastebin.com"), wildcard ("*.pastebin.com") or - CIDR notation ("127.0.0.0/8"). - If no rules, the domain is blocked.""") - .defineList("rules", Arrays.asList( - AddressRuleConfig.makeRule("$private", Action.DENY), - AddressRuleConfig.makeRule("*", Action.ALLOW) - ), x -> x instanceof UnmodifiableConfig && AddressRuleConfig.checkRule((UnmodifiableConfig) x)); + IPs. Each rule matches against a hostname and an optional port, and then sets several + properties for the request. Rules are evaluated in order, meaning earlier rules override + later ones. + + Valid properties: + - "host" (required): The domain or IP address this rule matches. This may be a domain name + ("pastebin.com"), wildcard ("*.pastebin.com") or CIDR notation ("127.0.0.0/8"). + - "port" (optional): Only match requests for a specific port, such as 80 or 443. + + - "action" (optional): Whether to allow or deny this request. + - "max_download" (optional): The maximum size (in bytes) that a computer can download in this + request. + - "max_upload" (optional): The maximum size (in bytes) that a computer can upload in a this request. + - "max_websocket_message" (optional): The maximum size (in bytes) that a computer can send or + receive in one websocket packet. + - "use_proxy" (optional): Enable use of the HTTP/SOCKS proxy if it is configured.""") + .defineList("rules", AddressRuleConfig.defaultRules(), x -> x instanceof UnmodifiableConfig); httpMaxRequests = builder .comment(""" @@ -395,8 +399,8 @@ public final class ConfigSpec { // HTTP CoreConfig.httpEnabled = httpEnabled.get(); CoreConfig.httpWebsocketEnabled = httpWebsocketEnabled.get(); - CoreConfig.httpRules = httpRules.get().stream() - .map(AddressRuleConfig::parseRule).filter(Objects::nonNull).toList(); + + CoreConfig.httpRules = httpRules.get().stream().map(AddressRuleConfig::parseRule).toList(); CoreConfig.httpMaxRequests = httpMaxRequests.get(); CoreConfig.httpMaxWebsockets = httpMaxWebsockets.get(); diff --git a/projects/common/src/main/java/dan200/computercraft/shared/integration/RecipeModHelpers.java b/projects/common/src/main/java/dan200/computercraft/shared/integration/RecipeModHelpers.java index 1e93c30a9..e848accef 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/integration/RecipeModHelpers.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/integration/RecipeModHelpers.java @@ -5,6 +5,7 @@ package dan200.computercraft.shared.integration; import dan200.computercraft.api.ComputerCraftAPI; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.impl.PocketUpgrades; import dan200.computercraft.impl.TurtleUpgrades; import dan200.computercraft.shared.ModRegistry; @@ -56,14 +57,14 @@ public final class RecipeModHelpers { for (var turtleSupplier : TURTLES) { var turtle = turtleSupplier.get(); for (var upgrade : TurtleUpgrades.instance().getUpgrades()) { - upgradeItems.add(turtle.create(-1, null, -1, null, upgrade, 0, null)); + upgradeItems.add(turtle.create(-1, null, -1, null, UpgradeData.ofDefault(upgrade), 0, null)); } } for (var pocketSupplier : POCKET_COMPUTERS) { var pocket = pocketSupplier.get(); for (var upgrade : PocketUpgrades.instance().getUpgrades()) { - upgradeItems.add(pocket.create(-1, null, -1, upgrade)); + upgradeItems.add(pocket.create(-1, null, -1, UpgradeData.ofDefault(upgrade))); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java b/projects/common/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java index 0dbe35b5d..253f76a28 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/integration/UpgradeRecipeGenerator.java @@ -9,6 +9,7 @@ import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.upgrades.UpgradeBase; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.impl.PocketUpgrades; import dan200.computercraft.impl.TurtleUpgrades; import dan200.computercraft.shared.pocket.items.PocketComputerItem; @@ -111,20 +112,22 @@ public class UpgradeRecipeGenerator { if (stack.getItem() instanceof TurtleItem item) { // Suggest possible upgrades which can be applied to this turtle - var left = item.getUpgrade(stack, TurtleSide.LEFT); - var right = item.getUpgrade(stack, TurtleSide.RIGHT); + var left = item.getUpgradeWithData(stack, TurtleSide.LEFT); + var right = item.getUpgradeWithData(stack, TurtleSide.RIGHT); if (left != null && right != null) return Collections.emptyList(); List recipes = new ArrayList<>(); var ingredient = Ingredient.of(stack); for (var upgrade : turtleUpgrades) { + if (upgrade.turtle == null) throw new NullPointerException(); + // The turtle is facing towards us, so upgrades on the left are actually crafted on the right. if (left == null) { - recipes.add(turtle(ingredient, upgrade.ingredient, turtleWith(stack, upgrade.turtle, right))); + recipes.add(turtle(ingredient, upgrade.ingredient, turtleWith(stack, UpgradeData.ofDefault(upgrade.turtle), right))); } if (right == null) { - recipes.add(turtle(upgrade.ingredient, ingredient, turtleWith(stack, left, upgrade.turtle))); + recipes.add(turtle(upgrade.ingredient, ingredient, turtleWith(stack, left, UpgradeData.ofDefault(upgrade.turtle)))); } } @@ -137,7 +140,8 @@ public class UpgradeRecipeGenerator { List recipes = new ArrayList<>(); var ingredient = Ingredient.of(stack); for (var upgrade : pocketUpgrades) { - recipes.add(pocket(upgrade.ingredient, ingredient, pocketWith(stack, upgrade.pocket))); + if (upgrade.pocket == null) throw new NullPointerException(); + recipes.add(pocket(upgrade.ingredient, ingredient, pocketWith(stack, UpgradeData.ofDefault(upgrade.pocket)))); } return Collections.unmodifiableList(recipes); @@ -180,21 +184,21 @@ public class UpgradeRecipeGenerator { if (stack.getItem() instanceof TurtleItem item) { List recipes = new ArrayList<>(0); - var left = item.getUpgrade(stack, TurtleSide.LEFT); - var right = item.getUpgrade(stack, TurtleSide.RIGHT); + var left = item.getUpgradeWithData(stack, TurtleSide.LEFT); + var right = item.getUpgradeWithData(stack, TurtleSide.RIGHT); // The turtle is facing towards us, so upgrades on the left are actually crafted on the right. if (left != null) { recipes.add(turtle( Ingredient.of(turtleWith(stack, null, right)), - Ingredient.of(left.getCraftingItem()), + Ingredient.of(left.getUpgradeItem()), stack )); } if (right != null) { recipes.add(turtle( - Ingredient.of(right.getCraftingItem()), + Ingredient.of(right.getUpgradeItem()), Ingredient.of(turtleWith(stack, left, null)), stack )); @@ -204,9 +208,9 @@ public class UpgradeRecipeGenerator { } else if (stack.getItem() instanceof PocketComputerItem) { List recipes = new ArrayList<>(0); - var back = PocketComputerItem.getUpgrade(stack); + var back = PocketComputerItem.getUpgradeWithData(stack); if (back != null) { - recipes.add(pocket(Ingredient.of(back.getCraftingItem()), Ingredient.of(pocketWith(stack, null)), stack)); + recipes.add(pocket(Ingredient.of(back.getUpgradeItem()), Ingredient.of(pocketWith(stack, null)), stack)); } return Collections.unmodifiableList(recipes); @@ -215,7 +219,7 @@ public class UpgradeRecipeGenerator { } } - private static ItemStack turtleWith(ItemStack stack, @Nullable ITurtleUpgrade left, @Nullable ITurtleUpgrade right) { + private static ItemStack turtleWith(ItemStack stack, @Nullable UpgradeData left, @Nullable UpgradeData right) { var item = (TurtleItem) stack.getItem(); return item.create( item.getComputerID(stack), item.getLabel(stack), item.getColour(stack), @@ -223,7 +227,7 @@ public class UpgradeRecipeGenerator { ); } - private static ItemStack pocketWith(ItemStack stack, @Nullable IPocketUpgrade back) { + private static ItemStack pocketWith(ItemStack stack, @Nullable UpgradeData back) { var item = (PocketComputerItem) stack.getItem(); return item.create( item.getComputerID(stack), item.getLabel(stack), item.getColour(stack), back @@ -272,7 +276,7 @@ public class UpgradeRecipeGenerator { recipes.add(turtle( ingredient, // Right upgrade, recipe on left Ingredient.of(turtleItem.create(-1, null, -1, null, null, 0, null)), - turtleItem.create(-1, null, -1, null, turtle, 0, null) + turtleItem.create(-1, null, -1, null, UpgradeData.ofDefault(turtle), 0, null) )); } } @@ -283,7 +287,7 @@ public class UpgradeRecipeGenerator { recipes.add(pocket( ingredient, Ingredient.of(pocketItem.create(-1, null, -1, null)), - pocketItem.create(-1, null, -1, pocket) + pocketItem.create(-1, null, -1, UpgradeData.ofDefault(pocket)) )); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java index f181ae7c4..8874a12b9 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java @@ -12,19 +12,23 @@ import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IDynamicPeripheral; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.platform.RegistryWrappers; +import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.BlockEntity; import javax.annotation.Nullable; import java.util.List; import java.util.Set; -class GenericPeripheral implements IDynamicPeripheral { +public final class GenericPeripheral implements IDynamicPeripheral { + private final BlockEntity tile; + private final Direction side; + private final String type; private final Set additionalTypes; - private final BlockEntity tile; private final List methods; - GenericPeripheral(BlockEntity tile, @Nullable String name, Set additionalTypes, List methods) { + GenericPeripheral(BlockEntity tile, Direction side, @Nullable String name, Set additionalTypes, List methods) { + this.side = side; var type = RegistryWrappers.BLOCK_ENTITY_TYPES.getKey(tile.getType()); this.tile = tile; this.type = name != null ? name : type.toString(); @@ -32,6 +36,10 @@ class GenericPeripheral implements IDynamicPeripheral { this.methods = methods; } + public Direction side() { + return side; + } + @Override public String[] getMethodNames() { var names = new String[methods.size()]; @@ -54,7 +62,6 @@ class GenericPeripheral implements IDynamicPeripheral { return additionalTypes; } - @Nullable @Override public Object getTarget() { return tile; diff --git a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralBuilder.java b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralBuilder.java new file mode 100644 index 000000000..e6b69f0cb --- /dev/null +++ b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralBuilder.java @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.shared.peripheral.generic; + +import dan200.computercraft.api.peripheral.IPeripheral; +import dan200.computercraft.api.peripheral.PeripheralType; +import dan200.computercraft.core.methods.MethodSupplier; +import dan200.computercraft.core.methods.NamedMethod; +import dan200.computercraft.core.methods.PeripheralMethod; +import dan200.computercraft.shared.computer.core.ServerContext; +import net.minecraft.core.Direction; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.level.block.entity.BlockEntity; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +/** + * A builder for a {@link GenericPeripheral}. + *

+ * This handles building a list of {@linkplain SaturatedMethod methods} and computing the appropriate + * {@link PeripheralType} from the {@linkplain NamedMethod#genericType() methods' peripheral types}. + *

+ * See the platform-specific peripheral providers for the usage of this. + */ +final class GenericPeripheralBuilder { + private final MethodSupplier peripheralMethods; + + private @Nullable String name; + private final Set additionalTypes = new HashSet<>(0); + private final ArrayList methods = new ArrayList<>(); + + GenericPeripheralBuilder(MinecraftServer server) { + peripheralMethods = ServerContext.get(server).peripheralMethods(); + } + + @Nullable + IPeripheral toPeripheral(BlockEntity blockEntity, Direction side) { + if (methods.isEmpty()) return null; + + methods.trimToSize(); + return new GenericPeripheral(blockEntity, side, name, additionalTypes, methods); + } + + boolean addMethods(Object target) { + return peripheralMethods.forEachSelfMethod(target, (name, method, info) -> { + methods.add(new SaturatedMethod(target, name, method)); + + // If we have a peripheral type, use it. Always pick the smallest one, so it's consistent (assuming mods + // don't change). + var type = info == null ? null : info.genericType(); + if (type != null && type.getPrimaryType() != null) { + var primaryType = type.getPrimaryType(); + if (this.name == null || this.name.compareTo(primaryType) > 0) this.name = primaryType; + } + if (type != null) additionalTypes.addAll(type.getAdditionalTypes()); + }); + } +} diff --git a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java index 78049da8c..ce978718c 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java @@ -9,18 +9,20 @@ import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.core.asm.NamedMethod; -import dan200.computercraft.core.asm.PeripheralMethod; +import dan200.computercraft.core.methods.PeripheralMethod; +/** + * A {@link PeripheralMethod} along with the method's target. + */ final class SaturatedMethod { private final Object target; private final String name; private final PeripheralMethod method; - SaturatedMethod(Object target, NamedMethod method) { + SaturatedMethod(Object target, String name, PeripheralMethod method) { this.target = target; - name = method.getName(); - this.method = method.getMethod(); + this.name = name; + this.method = method; } MethodResult apply(ILuaContext context, IComputerAccess computer, IArguments args) throws LuaException { diff --git a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java index 49eccfea8..a4956ac69 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java @@ -16,10 +16,12 @@ import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.NotAttachedException; import dan200.computercraft.api.peripheral.WorkMonitor; import dan200.computercraft.core.apis.PeripheralAPI; -import dan200.computercraft.core.asm.PeripheralMethod; +import dan200.computercraft.core.methods.PeripheralMethod; import dan200.computercraft.core.util.LuaUtil; +import dan200.computercraft.shared.computer.core.ServerContext; import dan200.computercraft.shared.peripheral.modem.ModemPeripheral; import dan200.computercraft.shared.peripheral.modem.ModemState; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -284,7 +286,8 @@ public abstract class WiredModemPeripheral extends ModemPeripheral implements Wi private void attachPeripheralImpl(IComputerAccess computer, ConcurrentMap peripherals, String periphName, IPeripheral peripheral) { if (!peripherals.containsKey(periphName) && !periphName.equals(getLocalPeripheral().getConnectedName())) { - var wrapper = new RemotePeripheralWrapper(modem, peripheral, computer, periphName); + var methods = ServerContext.get(((ServerLevel) getLevel()).getServer()).peripheralMethods().getSelfMethods(peripheral); + var wrapper = new RemotePeripheralWrapper(modem, peripheral, computer, periphName, methods); peripherals.put(periphName, wrapper); wrapper.attach(); } @@ -314,7 +317,7 @@ public abstract class WiredModemPeripheral extends ModemPeripheral implements Wi private volatile boolean attached; private final Set mounts = new HashSet<>(); - RemotePeripheralWrapper(WiredModemElement element, IPeripheral peripheral, IComputerAccess computer, String name) { + RemotePeripheralWrapper(WiredModemElement element, IPeripheral peripheral, IComputerAccess computer, String name, Map methods) { this.element = element; this.peripheral = peripheral; this.computer = computer; @@ -322,7 +325,7 @@ public abstract class WiredModemPeripheral extends ModemPeripheral implements Wi type = Objects.requireNonNull(peripheral.getType(), "Peripheral type cannot be null"); additionalTypes = peripheral.getAdditionalTypes(); - methodMap = PeripheralAPI.getMethods(peripheral); + methodMap = methods; } public void attach() { diff --git a/projects/common/src/main/java/dan200/computercraft/shared/platform/FakePlayerConstants.java b/projects/common/src/main/java/dan200/computercraft/shared/platform/FakePlayerConstants.java new file mode 100644 index 000000000..a50c8be85 --- /dev/null +++ b/projects/common/src/main/java/dan200/computercraft/shared/platform/FakePlayerConstants.java @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.shared.platform; + +import com.mojang.authlib.GameProfile; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; + +/** + * Shared constants for {@linkplain PlatformHelper#createFakePlayer(ServerLevel, GameProfile) fake player} + * implementations. + * + * @see net.minecraft.server.level.ServerPlayer + * @see net.minecraft.world.entity.player.Player + */ +final class FakePlayerConstants { + private FakePlayerConstants() { + } + + /** + * The maximum distance this player can reach. + *

+ * This is used in the override of {@link net.minecraft.world.entity.player.Player#mayUseItemAt(BlockPos, Direction, ItemStack)}, + * to prevent the fake player reaching more than 2 blocks away. + */ + static final double MAX_REACH = 2; +} diff --git a/projects/common/src/main/java/dan200/computercraft/shared/platform/PlatformHelper.java b/projects/common/src/main/java/dan200/computercraft/shared/platform/PlatformHelper.java index 3b90d1e26..7df773f10 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/platform/PlatformHelper.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/platform/PlatformHelper.java @@ -69,6 +69,13 @@ public interface PlatformHelper extends dan200.computercraft.impl.PlatformHelper return (PlatformHelper) dan200.computercraft.impl.PlatformHelper.get(); } + /** + * Check if we're running in a development environment. + * + * @return If we're running in a development environment. + */ + boolean isDevelopmentEnvironment(); + /** * Create a new config builder. * diff --git a/projects/common/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java b/projects/common/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java index e1b1cb0ad..a0749450d 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java @@ -7,6 +7,7 @@ package dan200.computercraft.shared.pocket.apis; import dan200.computercraft.api.lua.ILuaAPI; import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.pocket.IPocketUpgrade; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.impl.PocketUpgrades; import dan200.computercraft.shared.pocket.core.PocketServerComputer; import net.minecraft.core.NonNullList; @@ -14,6 +15,7 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; +import java.util.Objects; /** * Control the current pocket computer, adding or removing upgrades. @@ -68,7 +70,7 @@ public class PocketAPI implements ILuaAPI { if (newUpgrade == null) return new Object[]{ false, "Cannot find a valid upgrade" }; // Remove the current upgrade - if (previousUpgrade != null) storeItem(player, previousUpgrade.getCraftingItem().copy()); + if (previousUpgrade != null) storeItem(player, previousUpgrade.getUpgradeItem()); // Set the new upgrade computer.setUpgrade(newUpgrade); @@ -93,7 +95,7 @@ public class PocketAPI implements ILuaAPI { computer.setUpgrade(null); - storeItem(player, previousUpgrade.getCraftingItem().copy()); + storeItem(player, previousUpgrade.getUpgradeItem()); return new Object[]{ true }; } @@ -105,13 +107,13 @@ public class PocketAPI implements ILuaAPI { } } - private static @Nullable IPocketUpgrade findUpgrade(NonNullList inv, int start, @Nullable IPocketUpgrade previous) { + private static @Nullable UpgradeData findUpgrade(NonNullList inv, int start, @Nullable UpgradeData previous) { for (var i = 0; i < inv.size(); i++) { var invStack = inv.get((i + start) % inv.size()); if (!invStack.isEmpty()) { var newUpgrade = PocketUpgrades.instance().get(invStack); - if (newUpgrade != null && newUpgrade != previous) { + if (newUpgrade != null && !Objects.equals(newUpgrade, previous)) { // Consume an item from this stack and exit the loop invStack = invStack.copy(); invStack.shrink(1); diff --git a/projects/common/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java b/projects/common/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java index eec54879b..a6662c93d 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java @@ -7,6 +7,7 @@ package dan200.computercraft.shared.pocket.core; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.pocket.IPocketAccess; import dan200.computercraft.api.pocket.IPocketUpgrade; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.core.computer.ComputerSide; import dan200.computercraft.shared.common.IColouredItem; import dan200.computercraft.shared.computer.core.ComputerFamily; @@ -104,12 +105,13 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces } @Override + @Deprecated(forRemoval = true) public Map getUpgrades() { return upgrade == null ? Collections.emptyMap() : Collections.singletonMap(upgrade.getUpgradeID(), getPeripheral(ComputerSide.BACK)); } - public @Nullable IPocketUpgrade getUpgrade() { - return upgrade; + public @Nullable UpgradeData getUpgrade() { + return upgrade == null ? null : UpgradeData.of(upgrade, getUpgradeNBTData()); } /** @@ -119,13 +121,11 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces * * @param upgrade The new upgrade to set it to, may be {@code null}. */ - public void setUpgrade(@Nullable IPocketUpgrade upgrade) { - if (this.upgrade == upgrade) return; - + public void setUpgrade(@Nullable UpgradeData upgrade) { synchronized (this) { PocketComputerItem.setUpgrade(stack, upgrade); updateUpgradeNBTData(); - this.upgrade = upgrade; + this.upgrade = upgrade == null ? null : upgrade.upgrade(); invalidatePeripheral(); } } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItem.java b/projects/common/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItem.java index 03c3d7274..25a976e81 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItem.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItem.java @@ -10,6 +10,7 @@ import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.filesystem.Mount; import dan200.computercraft.api.media.IMedia; import dan200.computercraft.api.pocket.IPocketUpgrade; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.core.computer.ComputerSide; import dan200.computercraft.impl.PocketUpgrades; import dan200.computercraft.shared.ModRegistry; @@ -23,6 +24,7 @@ import dan200.computercraft.shared.pocket.apis.PocketAPI; import dan200.computercraft.shared.pocket.core.PocketServerComputer; import dan200.computercraft.shared.pocket.inventory.PocketComputerMenuProvider; import dan200.computercraft.shared.util.IDAssigner; +import dan200.computercraft.shared.util.NBTUtil; import net.minecraft.ChatFormatting; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; @@ -58,7 +60,7 @@ public class PocketComputerItem extends Item implements IComputerItem, IMedia, I this.family = family; } - public static ItemStack create(int id, @Nullable String label, int colour, ComputerFamily family, @Nullable IPocketUpgrade upgrade) { + public static ItemStack create(int id, @Nullable String label, int colour, ComputerFamily family, @Nullable UpgradeData upgrade) { return switch (family) { case NORMAL -> ModRegistry.Items.POCKET_COMPUTER_NORMAL.get().create(id, label, colour, upgrade); case ADVANCED -> ModRegistry.Items.POCKET_COMPUTER_ADVANCED.get().create(id, label, colour, upgrade); @@ -66,11 +68,14 @@ public class PocketComputerItem extends Item implements IComputerItem, IMedia, I }; } - public ItemStack create(int id, @Nullable String label, int colour, @Nullable IPocketUpgrade upgrade) { + public ItemStack create(int id, @Nullable String label, int colour, @Nullable UpgradeData upgrade) { var result = new ItemStack(this); if (id >= 0) result.getOrCreateTag().putInt(NBT_ID, id); if (label != null) result.setHoverName(Component.literal(label)); - if (upgrade != null) result.getOrCreateTag().putString(NBT_UPGRADE, upgrade.getUpgradeID().toString()); + if (upgrade != null) { + result.getOrCreateTag().putString(NBT_UPGRADE, upgrade.upgrade().getUpgradeID().toString()); + if (!upgrade.data().isEmpty()) result.getOrCreateTag().put(NBT_UPGRADE_INFO, upgrade.data().copy()); + } if (colour != -1) result.getOrCreateTag().putInt(NBT_COLOUR, colour); return result; } @@ -208,7 +213,9 @@ public class PocketComputerItem extends Item implements IComputerItem, IMedia, I setInstanceID(stack, computer.register()); setSessionID(stack, registry.getSessionID()); - computer.updateValues(entity, stack, getUpgrade(stack)); + var upgrade = getUpgrade(stack); + + computer.updateValues(entity, stack, upgrade); computer.addAPI(new PocketAPI(computer)); // Only turn on when initially creating the computer, rather than each tick. @@ -245,7 +252,7 @@ public class PocketComputerItem extends Item implements IComputerItem, IMedia, I public ItemStack withFamily(ItemStack stack, ComputerFamily family) { return create( getComputerID(stack), getLabel(stack), getColour(stack), - family, getUpgrade(stack) + family, getUpgradeWithData(stack) ); } @@ -295,20 +302,27 @@ public class PocketComputerItem extends Item implements IComputerItem, IMedia, I public static @Nullable IPocketUpgrade getUpgrade(ItemStack stack) { var compound = stack.getTag(); - return compound != null && compound.contains(NBT_UPGRADE) - ? PocketUpgrades.instance().get(compound.getString(NBT_UPGRADE)) : null; + if (compound == null || !compound.contains(NBT_UPGRADE)) return null; + return PocketUpgrades.instance().get(compound.getString(NBT_UPGRADE)); } - public static void setUpgrade(ItemStack stack, @Nullable IPocketUpgrade upgrade) { + public static @Nullable UpgradeData getUpgradeWithData(ItemStack stack) { + var compound = stack.getTag(); + if (compound == null || !compound.contains(NBT_UPGRADE)) return null; + var upgrade = PocketUpgrades.instance().get(compound.getString(NBT_UPGRADE)); + return upgrade == null ? null : UpgradeData.of(upgrade, NBTUtil.getCompoundOrEmpty(compound, NBT_UPGRADE_INFO)); + } + + public static void setUpgrade(ItemStack stack, @Nullable UpgradeData upgrade) { var compound = stack.getOrCreateTag(); if (upgrade == null) { compound.remove(NBT_UPGRADE); + compound.remove(NBT_UPGRADE_INFO); } else { - compound.putString(NBT_UPGRADE, upgrade.getUpgradeID().toString()); + compound.putString(NBT_UPGRADE, upgrade.upgrade().getUpgradeID().toString()); + compound.put(NBT_UPGRADE_INFO, upgrade.data().copy()); } - - compound.remove(NBT_UPGRADE_INFO); } public static CompoundTag getUpgradeInfo(ItemStack stack) { diff --git a/projects/common/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java b/projects/common/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java index 6c74ea7b6..b0b25bd87 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java @@ -5,6 +5,7 @@ package dan200.computercraft.shared.pocket.recipes; import dan200.computercraft.api.pocket.IPocketUpgrade; +import dan200.computercraft.api.upgrades.UpgradeData; import dan200.computercraft.impl.PocketUpgrades; import dan200.computercraft.shared.ModRegistry; import dan200.computercraft.shared.pocket.items.PocketComputerItem; @@ -62,7 +63,7 @@ public final class PocketComputerUpgradeRecipe extends CustomRecipe { if (PocketComputerItem.getUpgrade(computer) != null) return ItemStack.EMPTY; // Check for upgrades around the item - IPocketUpgrade upgrade = null; + UpgradeData upgrade = null; for (var y = 0; y < inventory.getHeight(); y++) { for (var x = 0; x < inventory.getWidth(); x++) { var item = inventory.getItem(x + y * inventory.getWidth()); diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java index ece4f31d0..12af726ca 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java @@ -555,7 +555,7 @@ public class TurtleAPI implements ILuaAPI { * @cc.usage Refuel a turtle from the currently selected slot. *

{@code
      * local level = turtle.getFuelLevel()
-     * if new_level == "unlimited" then error("Turtle does not need fuel", 0) end
+     * if level == "unlimited" then error("Turtle does not need fuel", 0) end
      *
      * local ok, err = turtle.refuel()
      * if ok then
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/blocks/TurtleBlock.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/blocks/TurtleBlock.java
index 7e058698e..157bb876b 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/blocks/TurtleBlock.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/blocks/TurtleBlock.java
@@ -5,7 +5,9 @@
 package dan200.computercraft.shared.turtle.blocks;
 
 import dan200.computercraft.annotations.ForgeOverride;
+import dan200.computercraft.api.turtle.ITurtleUpgrade;
 import dan200.computercraft.api.turtle.TurtleSide;
+import dan200.computercraft.api.upgrades.UpgradeData;
 import dan200.computercraft.shared.computer.blocks.AbstractComputerBlock;
 import dan200.computercraft.shared.computer.blocks.AbstractComputerBlockEntity;
 import dan200.computercraft.shared.computer.core.ComputerFamily;
@@ -128,7 +130,7 @@ public class TurtleBlock extends AbstractComputerBlock implem
             if (stack.getItem() instanceof TurtleItem item) {
                 // Set Upgrades
                 for (var side : TurtleSide.values()) {
-                    turtle.getAccess().setUpgrade(side, item.getUpgrade(stack, side));
+                    turtle.getAccess().setUpgradeWithData(side, item.getUpgradeWithData(stack, side));
                 }
 
                 turtle.getAccess().setFuelLevel(item.getFuelLevel(stack));
@@ -161,11 +163,16 @@ public class TurtleBlock extends AbstractComputerBlock implem
         var access = turtle.getAccess();
         return TurtleItem.create(
             turtle.getComputerID(), turtle.getLabel(), access.getColour(), turtle.getFamily(),
-            access.getUpgrade(TurtleSide.LEFT), access.getUpgrade(TurtleSide.RIGHT),
+            withPersistedData(access.getUpgradeWithData(TurtleSide.LEFT)),
+            withPersistedData(access.getUpgradeWithData(TurtleSide.RIGHT)),
             access.getFuelLevel(), turtle.getOverlay()
         );
     }
 
+    private static @Nullable UpgradeData withPersistedData(@Nullable UpgradeData upgrade) {
+        return upgrade == null ? null : UpgradeData.of(upgrade.upgrade(), upgrade.upgrade().getPersistedData(upgrade.data()));
+    }
+
     @Override
     @Nullable
     public  BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) {
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java
index f2efe7b67..23e5cc977 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java
@@ -13,8 +13,8 @@ import dan200.computercraft.api.turtle.ITurtleUpgrade;
 import dan200.computercraft.api.turtle.TurtleAnimation;
 import dan200.computercraft.api.turtle.TurtleCommand;
 import dan200.computercraft.api.turtle.TurtleSide;
+import dan200.computercraft.api.upgrades.UpgradeData;
 import dan200.computercraft.core.computer.ComputerSide;
-import dan200.computercraft.core.util.Colour;
 import dan200.computercraft.impl.TurtleUpgrades;
 import dan200.computercraft.shared.computer.core.ComputerFamily;
 import dan200.computercraft.shared.computer.core.ServerComputer;
@@ -34,7 +34,6 @@ import net.minecraft.tags.FluidTags;
 import net.minecraft.world.Container;
 import net.minecraft.world.entity.Entity;
 import net.minecraft.world.entity.MoverType;
-import net.minecraft.world.item.DyeColor;
 import net.minecraft.world.item.ItemStack;
 import net.minecraft.world.level.Level;
 import net.minecraft.world.level.material.PushReaction;
@@ -141,17 +140,16 @@ public class TurtleBrain implements TurtleAccessInternal {
         overlay = nbt.contains(NBT_OVERLAY) ? new ResourceLocation(nbt.getString(NBT_OVERLAY)) : null;
 
         // Read upgrades
-        setUpgradeDirect(TurtleSide.LEFT, nbt.contains(NBT_LEFT_UPGRADE) ? TurtleUpgrades.instance().get(nbt.getString(NBT_LEFT_UPGRADE)) : null);
-        setUpgradeDirect(TurtleSide.RIGHT, nbt.contains(NBT_RIGHT_UPGRADE) ? TurtleUpgrades.instance().get(nbt.getString(NBT_RIGHT_UPGRADE)) : null);
+        setUpgradeDirect(TurtleSide.LEFT, readUpgrade(nbt, NBT_LEFT_UPGRADE, NBT_LEFT_UPGRADE_DATA));
+        setUpgradeDirect(TurtleSide.RIGHT, readUpgrade(nbt, NBT_RIGHT_UPGRADE, NBT_RIGHT_UPGRADE_DATA));
+    }
 
-        // NBT
-        upgradeNBTData.clear();
-        if (nbt.contains(NBT_LEFT_UPGRADE_DATA)) {
-            upgradeNBTData.put(TurtleSide.LEFT, nbt.getCompound(NBT_LEFT_UPGRADE_DATA).copy());
-        }
-        if (nbt.contains(NBT_RIGHT_UPGRADE_DATA)) {
-            upgradeNBTData.put(TurtleSide.RIGHT, nbt.getCompound(NBT_RIGHT_UPGRADE_DATA).copy());
-        }
+    private @Nullable UpgradeData readUpgrade(CompoundTag tag, String upgradeKey, String dataKey) {
+        if (!tag.contains(upgradeKey)) return null;
+        var upgrade = TurtleUpgrades.instance().get(tag.getString(upgradeKey));
+        if (upgrade == null) return null;
+
+        return UpgradeData.of(upgrade, tag.getCompound(dataKey));
     }
 
     private void writeCommon(CompoundTag nbt) {
@@ -463,23 +461,6 @@ public class TurtleBrain implements TurtleAccessInternal {
         }
     }
 
-    public @Nullable DyeColor getDyeColour() {
-        if (colourHex == -1) return null;
-        var colour = Colour.fromHex(colourHex);
-        return colour == null ? null : DyeColor.byId(15 - colour.ordinal());
-    }
-
-    public void setDyeColour(@Nullable DyeColor dyeColour) {
-        var newColour = -1;
-        if (dyeColour != null) {
-            newColour = Colour.values()[15 - dyeColour.getId()].getHex();
-        }
-        if (colourHex != newColour) {
-            colourHex = newColour;
-            BlockEntityHelpers.updateBlock(owner);
-        }
-    }
-
     @Override
     public void setColour(int colour) {
         if (colour >= 0 && colour <= 0xFFFFFF) {
@@ -514,7 +495,7 @@ public class TurtleBrain implements TurtleAccessInternal {
     }
 
     @Override
-    public void setUpgrade(TurtleSide side, @Nullable ITurtleUpgrade upgrade) {
+    public void setUpgradeWithData(TurtleSide side, @Nullable UpgradeData upgrade) {
         if (!setUpgradeDirect(side, upgrade) || owner.getLevel() == null) return;
 
         // This is a separate function to avoid updating the block when reading the NBT. We don't need to do this as
@@ -527,19 +508,18 @@ public class TurtleBrain implements TurtleAccessInternal {
         owner.updateInputsImmediately();
     }
 
-    private boolean setUpgradeDirect(TurtleSide side, @Nullable ITurtleUpgrade upgrade) {
+    private boolean setUpgradeDirect(TurtleSide side, @Nullable UpgradeData upgrade) {
         // Remove old upgrade
-        if (upgrades.containsKey(side)) {
-            if (upgrades.get(side) == upgrade) return false;
-            upgrades.remove(side);
-        } else {
-            if (upgrade == null) return false;
-        }
-
-        upgradeNBTData.remove(side);
+        var oldUpgrade = upgrades.remove(side);
+        if (oldUpgrade == null && upgrade == null) return false;
 
         // Set new upgrade
-        if (upgrade != null) upgrades.put(side, upgrade);
+        if (upgrade == null) {
+            upgradeNBTData.remove(side);
+        } else {
+            upgrades.put(side, upgrade.upgrade());
+            upgradeNBTData.put(side, upgrade.data().copy());
+        }
 
         // Notify clients and create peripherals
         if (owner.getLevel() != null && !owner.getLevel().isClientSide) {
@@ -593,7 +573,7 @@ public class TurtleBrain implements TurtleAccessInternal {
 
     public float getToolRenderAngle(TurtleSide side, float f) {
         return (side == TurtleSide.LEFT && animation == TurtleAnimation.SWING_LEFT_TOOL) ||
-            (side == TurtleSide.RIGHT && animation == TurtleAnimation.SWING_RIGHT_TOOL)
+               (side == TurtleSide.RIGHT && animation == TurtleAnimation.SWING_RIGHT_TOOL)
             ? 45.0f * (float) Math.sin(getAnimationFraction(f) * Math.PI)
             : 0.0f;
     }
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java
index 1a15bb840..ae373f697 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java
@@ -5,6 +5,7 @@
 package dan200.computercraft.shared.turtle.core;
 
 import dan200.computercraft.api.turtle.*;
+import dan200.computercraft.api.upgrades.UpgradeData;
 import dan200.computercraft.impl.TurtleUpgrades;
 import dan200.computercraft.shared.turtle.TurtleUtil;
 
@@ -18,10 +19,10 @@ public class TurtleEquipCommand implements TurtleCommand {
     @Override
     public TurtleCommandResult execute(ITurtleAccess turtle) {
         // Determine the upgrade to replace
-        var oldUpgrade = turtle.getUpgrade(side);
+        var oldUpgrade = turtle.getUpgradeWithData(side);
 
         // Determine the upgrade to equipLeft
-        ITurtleUpgrade newUpgrade;
+        UpgradeData newUpgrade;
         var selectedStack = turtle.getInventory().getItem(turtle.getSelectedSlot());
         if (!selectedStack.isEmpty()) {
             newUpgrade = TurtleUpgrades.instance().get(selectedStack);
@@ -32,8 +33,8 @@ public class TurtleEquipCommand implements TurtleCommand {
 
         // Do the swapping:
         if (newUpgrade != null) turtle.getInventory().removeItem(turtle.getSelectedSlot(), 1);
-        if (oldUpgrade != null) TurtleUtil.storeItemOrDrop(turtle, oldUpgrade.getCraftingItem().copy());
-        turtle.setUpgrade(side, newUpgrade);
+        if (oldUpgrade != null) TurtleUtil.storeItemOrDrop(turtle, oldUpgrade.getUpgradeItem());
+        turtle.setUpgradeWithData(side, newUpgrade);
 
         // Animate
         if (newUpgrade != null || oldUpgrade != null) {
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java
index 82b58c4ce..75dc94b8a 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java
@@ -75,19 +75,7 @@ public class TurtlePlaceCommand implements TurtleCommand {
         }
     }
 
-    public static boolean deployCopiedItem(
-        ItemStack stack, ITurtleAccess turtle, Direction direction, @Nullable Object[] extraArguments, @Nullable ErrorMessage outErrorMessage
-    ) {
-        // Create a fake player, and orient it appropriately
-        var playerPosition = turtle.getPosition().relative(direction);
-        var turtlePlayer = TurtlePlayer.getWithPosition(turtle, playerPosition, direction);
-        turtlePlayer.loadInventory(stack);
-        var result = deploy(stack, turtle, turtlePlayer, direction, extraArguments, outErrorMessage);
-        turtlePlayer.player().getInventory().clearContent();
-        return result;
-    }
-
-    private static boolean deploy(
+    public static boolean deploy(
         ItemStack stack, ITurtleAccess turtle, TurtlePlayer turtlePlayer, Direction direction,
         @Nullable Object[] extraArguments, @Nullable ErrorMessage outErrorMessage
     ) {
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/inventory/UpgradeContainer.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/inventory/UpgradeContainer.java
index 22d918626..9fff2789a 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/inventory/UpgradeContainer.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/inventory/UpgradeContainer.java
@@ -7,12 +7,14 @@ package dan200.computercraft.shared.turtle.inventory;
 import dan200.computercraft.api.turtle.ITurtleAccess;
 import dan200.computercraft.api.turtle.ITurtleUpgrade;
 import dan200.computercraft.api.turtle.TurtleSide;
+import dan200.computercraft.api.upgrades.UpgradeData;
 import dan200.computercraft.impl.TurtleUpgrades;
 import net.minecraft.core.NonNullList;
 import net.minecraft.world.Container;
 import net.minecraft.world.entity.player.Player;
 import net.minecraft.world.item.ItemStack;
 
+import javax.annotation.Nullable;
 import java.util.Arrays;
 import java.util.List;
 
@@ -27,7 +29,7 @@ class UpgradeContainer implements Container {
 
     private final ITurtleAccess turtle;
 
-    private final List lastUpgrade = Arrays.asList(null, null);
+    private final List> lastUpgrade = Arrays.asList(null, null);
     private final NonNullList lastStack = NonNullList.withSize(2, ItemStack.EMPTY);
 
     UpgradeContainer(ITurtleAccess turtle) {
@@ -44,22 +46,29 @@ class UpgradeContainer implements Container {
 
     @Override
     public ItemStack getItem(int slot) {
-        var upgrade = turtle.getUpgrade(getSide(slot));
+        var side = getSide(slot);
+        var upgrade = turtle.getUpgradeWithData(side);
+        if (upgrade == null) return ItemStack.EMPTY;
 
-        // We don't want to return getCraftingItem directly here, as consumers may mutate the stack (they shouldn't!,
-        // but if they do it's a pain to track down). To avoid recreating the stack each tick, we maintain a simple
-        // cache.
-        if (upgrade == lastUpgrade.get(slot)) return lastStack.get(slot);
+        // We don't want to return getUpgradeItem directly here, as we'd end up recreating the stack each tick. To
+        // avoid that, we maintain a simple cache.
+        if (upgrade.equals(lastUpgrade.get(slot))) return lastStack.get(slot);
 
-        var stack = upgrade == null ? ItemStack.EMPTY : upgrade.getCraftingItem().copy();
-        lastUpgrade.set(slot, upgrade);
+        return setUpgradeStack(slot, upgrade);
+    }
+
+    private ItemStack setUpgradeStack(int slot, @Nullable UpgradeData upgrade) {
+        var stack = upgrade == null ? ItemStack.EMPTY : upgrade.getUpgradeItem();
+        lastUpgrade.set(slot, UpgradeData.copyOf(upgrade));
         lastStack.set(slot, stack);
         return stack;
     }
 
     @Override
     public void setItem(int slot, ItemStack itemStack) {
-        turtle.setUpgrade(getSide(slot), TurtleUpgrades.instance().get(itemStack));
+        var upgrade = TurtleUpgrades.instance().get(itemStack);
+        turtle.setUpgradeWithData(getSide(slot), upgrade);
+        setUpgradeStack(slot, upgrade);
     }
 
     @Override
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItem.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItem.java
index 91bc45717..640872b23 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItem.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItem.java
@@ -8,12 +8,14 @@ import dan200.computercraft.annotations.ForgeOverride;
 import dan200.computercraft.api.ComputerCraftAPI;
 import dan200.computercraft.api.turtle.ITurtleUpgrade;
 import dan200.computercraft.api.turtle.TurtleSide;
+import dan200.computercraft.api.upgrades.UpgradeData;
 import dan200.computercraft.impl.TurtleUpgrades;
 import dan200.computercraft.shared.ModRegistry;
 import dan200.computercraft.shared.common.IColouredItem;
 import dan200.computercraft.shared.computer.core.ComputerFamily;
 import dan200.computercraft.shared.computer.items.AbstractComputerItem;
 import dan200.computercraft.shared.turtle.blocks.TurtleBlock;
+import dan200.computercraft.shared.util.NBTUtil;
 import net.minecraft.core.cauldron.CauldronInteraction;
 import net.minecraft.network.chat.Component;
 import net.minecraft.resources.ResourceLocation;
@@ -32,7 +34,7 @@ public class TurtleItem extends AbstractComputerItem implements IColouredItem {
 
     public static ItemStack create(
         int id, @Nullable String label, int colour, ComputerFamily family,
-        @Nullable ITurtleUpgrade leftUpgrade, @Nullable ITurtleUpgrade rightUpgrade,
+        @Nullable UpgradeData leftUpgrade, @Nullable UpgradeData rightUpgrade,
         int fuelLevel, @Nullable ResourceLocation overlay
     ) {
         return switch (family) {
@@ -46,7 +48,7 @@ public class TurtleItem extends AbstractComputerItem implements IColouredItem {
 
     public ItemStack create(
         int id, @Nullable String label, int colour,
-        @Nullable ITurtleUpgrade leftUpgrade, @Nullable ITurtleUpgrade rightUpgrade,
+        @Nullable UpgradeData leftUpgrade, @Nullable UpgradeData rightUpgrade,
         int fuelLevel, @Nullable ResourceLocation overlay
     ) {
         // Build the stack
@@ -58,11 +60,15 @@ public class TurtleItem extends AbstractComputerItem implements IColouredItem {
         if (overlay != null) stack.getOrCreateTag().putString(NBT_OVERLAY, overlay.toString());
 
         if (leftUpgrade != null) {
-            stack.getOrCreateTag().putString(NBT_LEFT_UPGRADE, leftUpgrade.getUpgradeID().toString());
+            var tag = stack.getOrCreateTag();
+            tag.putString(NBT_LEFT_UPGRADE, leftUpgrade.upgrade().getUpgradeID().toString());
+            if (!leftUpgrade.data().isEmpty()) tag.put(NBT_LEFT_UPGRADE_DATA, leftUpgrade.data().copy());
         }
 
         if (rightUpgrade != null) {
-            stack.getOrCreateTag().putString(NBT_RIGHT_UPGRADE, rightUpgrade.getUpgradeID().toString());
+            var tag = stack.getOrCreateTag();
+            tag.putString(NBT_RIGHT_UPGRADE, rightUpgrade.upgrade().getUpgradeID().toString());
+            if (!rightUpgrade.data().isEmpty()) tag.put(NBT_RIGHT_UPGRADE_DATA, rightUpgrade.data().copy());
         }
 
         return stack;
@@ -117,7 +123,7 @@ public class TurtleItem extends AbstractComputerItem implements IColouredItem {
         return create(
             getComputerID(stack), getLabel(stack),
             getColour(stack), family,
-            getUpgrade(stack, TurtleSide.LEFT), getUpgrade(stack, TurtleSide.RIGHT),
+            getUpgradeWithData(stack, TurtleSide.LEFT), getUpgradeWithData(stack, TurtleSide.RIGHT),
             getFuelLevel(stack), getOverlay(stack)
         );
     }
@@ -127,7 +133,20 @@ public class TurtleItem extends AbstractComputerItem implements IColouredItem {
         if (tag == null) return null;
 
         var key = side == TurtleSide.LEFT ? NBT_LEFT_UPGRADE : NBT_RIGHT_UPGRADE;
-        return tag.contains(key) ? TurtleUpgrades.instance().get(tag.getString(key)) : null;
+        if (!tag.contains(key)) return null;
+        return TurtleUpgrades.instance().get(tag.getString(key));
+    }
+
+    public @Nullable UpgradeData getUpgradeWithData(ItemStack stack, TurtleSide side) {
+        var tag = stack.getTag();
+        if (tag == null) return null;
+
+        var key = side == TurtleSide.LEFT ? NBT_LEFT_UPGRADE : NBT_RIGHT_UPGRADE;
+        if (!tag.contains(key)) return null;
+        var upgrade = TurtleUpgrades.instance().get(tag.getString(key));
+        if (upgrade == null) return null;
+        var dataKey = side == TurtleSide.LEFT ? NBT_LEFT_UPGRADE_DATA : NBT_RIGHT_UPGRADE_DATA;
+        return UpgradeData.of(upgrade, NBTUtil.getCompoundOrEmpty(tag, dataKey));
     }
 
     public @Nullable ResourceLocation getOverlay(ItemStack stack) {
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleOverlayRecipe.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleOverlayRecipe.java
index 4076a3662..7f31bca95 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleOverlayRecipe.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleOverlayRecipe.java
@@ -38,8 +38,8 @@ public class TurtleOverlayRecipe extends ShapelessRecipe {
             turtle.getComputerID(stack),
             turtle.getLabel(stack),
             turtle.getColour(stack),
-            turtle.getUpgrade(stack, TurtleSide.LEFT),
-            turtle.getUpgrade(stack, TurtleSide.RIGHT),
+            turtle.getUpgradeWithData(stack, TurtleSide.LEFT),
+            turtle.getUpgradeWithData(stack, TurtleSide.RIGHT),
             turtle.getFuelLevel(stack),
             overlay
         );
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java
index 4dcd9e5a2..3ad657e47 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java
@@ -6,6 +6,7 @@ package dan200.computercraft.shared.turtle.recipes;
 
 import dan200.computercraft.api.turtle.ITurtleUpgrade;
 import dan200.computercraft.api.turtle.TurtleSide;
+import dan200.computercraft.api.upgrades.UpgradeData;
 import dan200.computercraft.impl.TurtleUpgrades;
 import dan200.computercraft.shared.ModRegistry;
 import dan200.computercraft.shared.turtle.items.TurtleItem;
@@ -104,9 +105,10 @@ public final class TurtleUpgradeRecipe extends CustomRecipe {
         // At this point we have a turtle + 1 or 2 items
         // Get the turtle we already have
         var itemTurtle = (TurtleItem) turtle.getItem();
-        var upgrades = new ITurtleUpgrade[]{
-            itemTurtle.getUpgrade(turtle, TurtleSide.LEFT),
-            itemTurtle.getUpgrade(turtle, TurtleSide.RIGHT),
+        @SuppressWarnings({ "unchecked", "rawtypes" })
+        UpgradeData[] upgrades = new UpgradeData[]{
+            itemTurtle.getUpgradeWithData(turtle, TurtleSide.LEFT),
+            itemTurtle.getUpgradeWithData(turtle, TurtleSide.RIGHT),
         };
 
         // Get the upgrades for the new items
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java
index 4c514de2d..7235d4431 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java
@@ -9,6 +9,7 @@ import dan200.computercraft.api.turtle.*;
 import dan200.computercraft.shared.peripheral.modem.ModemState;
 import dan200.computercraft.shared.peripheral.modem.wireless.WirelessModemPeripheral;
 import net.minecraft.core.Direction;
+import net.minecraft.nbt.CompoundTag;
 import net.minecraft.resources.ResourceLocation;
 import net.minecraft.world.item.ItemStack;
 import net.minecraft.world.level.Level;
@@ -77,4 +78,9 @@ public class TurtleModem extends AbstractTurtleUpgrade {
             }
         }
     }
+
+    @Override
+    public CompoundTag getPersistedData(CompoundTag upgradeData) {
+        return new CompoundTag();
+    }
 }
diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java
index 9f8b80150..ad24abff9 100644
--- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java
+++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java
@@ -14,16 +14,22 @@ import dan200.computercraft.shared.util.DropConsumer;
 import dan200.computercraft.shared.util.WorldUtil;
 import net.minecraft.core.BlockPos;
 import net.minecraft.core.Direction;
+import net.minecraft.nbt.CompoundTag;
 import net.minecraft.resources.ResourceLocation;
 import net.minecraft.server.level.ServerLevel;
+import net.minecraft.server.level.ServerPlayer;
 import net.minecraft.tags.TagKey;
+import net.minecraft.world.InteractionHand;
 import net.minecraft.world.InteractionResult;
 import net.minecraft.world.entity.Entity;
+import net.minecraft.world.entity.LivingEntity;
+import net.minecraft.world.entity.MobType;
 import net.minecraft.world.entity.ai.attributes.Attributes;
 import net.minecraft.world.entity.decoration.ArmorStand;
 import net.minecraft.world.entity.player.Player;
 import net.minecraft.world.item.Item;
 import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.enchantment.EnchantmentHelper;
 import net.minecraft.world.level.BlockGetter;
 import net.minecraft.world.level.Level;
 import net.minecraft.world.level.block.Block;
@@ -32,46 +38,127 @@ import net.minecraft.world.level.block.state.BlockState;
 import net.minecraft.world.phys.EntityHitResult;
 
 import javax.annotation.Nullable;
+import java.util.Objects;
+import java.util.function.Function;
 
 import static net.minecraft.nbt.Tag.TAG_COMPOUND;
 import static net.minecraft.nbt.Tag.TAG_LIST;
 
 public class TurtleTool extends AbstractTurtleUpgrade {
-    protected static final TurtleCommandResult UNBREAKABLE = TurtleCommandResult.failure("Cannot break unbreakable block");
-    protected static final TurtleCommandResult INEFFECTIVE = TurtleCommandResult.failure("Cannot break block with this tool");
+    private static final TurtleCommandResult UNBREAKABLE = TurtleCommandResult.failure("Cannot break unbreakable block");
+    private static final TurtleCommandResult INEFFECTIVE = TurtleCommandResult.failure("Cannot break block with this tool");
+
+    private static final String TAG_ITEM_TAG = "Tag";
 
     final ItemStack item;
     final float damageMulitiplier;
-    @Nullable
-    final TagKey breakable;
+    final boolean allowEnchantments;
+    final TurtleToolDurability consumeDurability;
+    final @Nullable TagKey breakable;
 
-    public TurtleTool(ResourceLocation id, String adjective, Item craftItem, ItemStack toolItem, float damageMulitiplier, @Nullable TagKey breakable) {
+    public TurtleTool(
+        ResourceLocation id, String adjective, Item craftItem, ItemStack toolItem, float damageMulitiplier,
+        boolean allowEnchantments, TurtleToolDurability consumeDurability, @Nullable TagKey breakable
+    ) {
         super(id, TurtleUpgradeType.TOOL, adjective, new ItemStack(craftItem));
         item = toolItem;
         this.damageMulitiplier = damageMulitiplier;
+        this.allowEnchantments = allowEnchantments;
+        this.consumeDurability = consumeDurability;
         this.breakable = breakable;
     }
 
     @Override
     public boolean isItemSuitable(ItemStack stack) {
-        var tag = stack.getTag();
-        if (tag == null || tag.isEmpty()) return true;
+        if (consumeDurability == TurtleToolDurability.NEVER && stack.isDamaged()) return false;
+        if (!allowEnchantments && isEnchanted(stack)) return false;
+        return true;
+    }
 
-        // Check we've not got anything vaguely interesting on the item. We allow other mods to add their
-        // own NBT, with the understanding such details will be lost to the mist of time.
-        if (stack.isDamaged() || stack.isEnchanted() || stack.hasCustomHoverName()) return false;
-        if (tag.contains("AttributeModifiers", TAG_LIST) && !tag.getList("AttributeModifiers", TAG_COMPOUND).isEmpty()) {
-            return false;
+    private static boolean isEnchanted(ItemStack stack) {
+        return !stack.isEmpty() && isEnchanted(stack.getTag());
+    }
+
+    private static boolean isEnchanted(@Nullable CompoundTag tag) {
+        if (tag == null || tag.isEmpty()) return false;
+        return (tag.contains(ItemStack.TAG_ENCH, TAG_LIST) && !tag.getList(ItemStack.TAG_ENCH, TAG_COMPOUND).isEmpty())
+               || (tag.contains("AttributeModifiers", TAG_LIST) && !tag.getList("AttributeModifiers", TAG_COMPOUND).isEmpty());
+    }
+
+    @Override
+    public CompoundTag getUpgradeData(ItemStack stack) {
+        var upgradeData = super.getUpgradeData(stack);
+
+        // Store the item's current tag.
+        var itemTag = stack.getTag();
+        if (itemTag != null) upgradeData.put(TAG_ITEM_TAG, itemTag);
+
+        return upgradeData;
+    }
+
+    @Override
+    public ItemStack getUpgradeItem(CompoundTag upgradeData) {
+        // Copy upgrade data back to the item.
+        var item = super.getUpgradeItem(upgradeData).copy();
+        item.setTag(upgradeData.contains(TAG_ITEM_TAG, TAG_COMPOUND) ? upgradeData.getCompound(TAG_ITEM_TAG).copy() : null);
+        return item;
+    }
+
+    private ItemStack getToolStack(ITurtleAccess turtle, TurtleSide side) {
+        return getUpgradeItem(turtle.getUpgradeNBTData(side));
+    }
+
+    private void setToolStack(ITurtleAccess turtle, TurtleSide side, ItemStack stack) {
+        var upgradeData = turtle.getUpgradeNBTData(side);
+
+        var useDurability = switch (consumeDurability) {
+            case NEVER -> false;
+            case WHEN_ENCHANTED ->
+                upgradeData.contains(TAG_ITEM_TAG, TAG_COMPOUND) && isEnchanted(upgradeData.getCompound(TAG_ITEM_TAG));
+            case ALWAYS -> true;
+        };
+        if (!useDurability) return;
+
+        // If the tool has broken, remove the upgrade!
+        if (stack.isEmpty()) {
+            turtle.setUpgradeWithData(side, null);
+            return;
         }
 
-        return true;
+        // If the tool has changed, no clue what's going on.
+        if (stack.getItem() != item.getItem()) return;
+
+        var itemTag = stack.getTag();
+
+        // Early return if the item hasn't changed to avoid redundant syncs with the client.
+        if (Objects.equals(itemTag, upgradeData.get(TAG_ITEM_TAG))) return;
+
+        if (itemTag == null) {
+            upgradeData.remove(TAG_ITEM_TAG);
+        } else {
+            upgradeData.put(TAG_ITEM_TAG, itemTag);
+        }
+
+        turtle.updateUpgradeNBTData(side);
+    }
+
+    private  T withEquippedItem(ITurtleAccess turtle, TurtleSide side, Direction direction, Function action) {
+        var turtlePlayer = TurtlePlayer.getWithPosition(turtle, turtle.getPosition(), direction);
+        turtlePlayer.loadInventory(getToolStack(turtle, side));
+
+        var result = action.apply(turtlePlayer);
+
+        setToolStack(turtle, side, turtlePlayer.player().getItemInHand(InteractionHand.MAIN_HAND));
+        turtlePlayer.player().getInventory().clearContent();
+
+        return result;
     }
 
     @Override
     public TurtleCommandResult useTool(ITurtleAccess turtle, TurtleSide side, TurtleVerb verb, Direction direction) {
         return switch (verb) {
-            case ATTACK -> attack(turtle, direction);
-            case DIG -> dig(turtle, direction);
+            case ATTACK -> attack(turtle, side, direction);
+            case DIG -> dig(turtle, side, direction);
         };
     }
 
@@ -86,16 +173,14 @@ public class TurtleTool extends AbstractTurtleUpgrade {
     }
 
     /**
-     * Attack an entity. This is a very cut down version of {@link Player#attack(Entity)}, which doesn't handle
-     * enchantments, knockback, etc... Unfortunately we can't call attack directly as damage calculations are rather
-     * different (and we don't want to play sounds/particles).
+     * Attack an entity.
      *
      * @param turtle    The current turtle.
+     * @param side      The side the tool is on.
      * @param direction The direction we're attacking in.
      * @return Whether an attack occurred.
-     * @see Player#attack(Entity)
      */
-    private TurtleCommandResult attack(ITurtleAccess turtle, Direction direction) {
+    private TurtleCommandResult attack(ITurtleAccess turtle, TurtleSide side, Direction direction) {
         // Create a fake player, and orient it appropriately
         var world = turtle.getLevel();
         var position = turtle.getPosition();
@@ -107,10 +192,11 @@ public class TurtleTool extends AbstractTurtleUpgrade {
         var turtlePos = player.position();
         var rayDir = player.getViewVector(1.0f);
         var hit = WorldUtil.clip(world, turtlePos, rayDir, 1.5, null);
+        var attacked = false;
         if (hit instanceof EntityHitResult entityHit) {
             // Load up the turtle's inventory
-            var stackCopy = item.copy();
-            turtlePlayer.loadInventory(stackCopy);
+            var stack = getToolStack(turtle, side);
+            turtlePlayer.loadInventory(stack);
 
             var hitEntity = entityHit.getEntity();
 
@@ -118,66 +204,125 @@ public class TurtleTool extends AbstractTurtleUpgrade {
             DropConsumer.set(hitEntity, TurtleUtil.dropConsumer(turtle));
 
             // Attack the entity
-            var attacked = false;
             var result = PlatformHelper.get().canAttackEntity(player, hitEntity);
             if (result.consumesAction()) {
                 attacked = true;
             } else if (result == InteractionResult.PASS && hitEntity.isAttackable() && !hitEntity.skipAttackInteraction(player)) {
-                var damage = (float) player.getAttributeValue(Attributes.ATTACK_DAMAGE) * damageMulitiplier;
-                if (damage > 0.0f) {
-                    var source = player.damageSources().playerAttack(player);
-                    if (hitEntity instanceof ArmorStand) {
-                        // Special case for armor stands: attack twice to guarantee destroy
-                        hitEntity.hurt(source, damage);
-                        if (hitEntity.isAlive()) hitEntity.hurt(source, damage);
-                        attacked = true;
-                    } else {
-                        if (hitEntity.hurt(source, damage)) attacked = true;
-                    }
-                }
+                attacked = attack(player, direction, hitEntity);
             }
 
             // Stop claiming drops
             TurtleUtil.stopConsuming(turtle);
 
-            // Put everything we collected into the turtles inventory, then return
+            // Put everything we collected into the turtles inventory.
+            setToolStack(turtle, side, player.getItemInHand(InteractionHand.MAIN_HAND));
             player.getInventory().clearContent();
-            if (attacked) return TurtleCommandResult.success();
         }
 
-        return TurtleCommandResult.failure("Nothing to attack here");
+        return attacked ? TurtleCommandResult.success() : TurtleCommandResult.failure("Nothing to attack here");
     }
 
-    private TurtleCommandResult dig(ITurtleAccess turtle, Direction direction) {
-        if (PlatformHelper.get().hasToolUsage(item) && TurtlePlaceCommand.deployCopiedItem(item.copy(), turtle, direction, null, null)) {
-            return TurtleCommandResult.success();
+    /**
+     * Attack an entity. This is a copy of {@link Player#attack(Entity)}, with some unwanted features removed (sweeping
+     * edge). This is a little limited.
+     * 

+ * Ideally we'd use attack directly (if other mods mixin to that method, we won't support their features). + * Unfortunately,that doesn't give us any feedback to whether the attack occurred or not (and we don't want to play + * sounds/particles). + * + * @param player The fake player doing the attacking. + * @param direction The direction the turtle is attacking. + * @param entity The entity to attack. + * @return Whether we attacked or not. + * @see Player#attack(Entity) + */ + private boolean attack(ServerPlayer player, Direction direction, Entity entity) { + var baseDamage = (float) player.getAttributeValue(Attributes.ATTACK_DAMAGE) * damageMulitiplier; + var bonusDamage = EnchantmentHelper.getDamageBonus( + player.getItemInHand(InteractionHand.MAIN_HAND), entity instanceof LivingEntity target ? target.getMobType() : MobType.UNDEFINED + ); + var damage = baseDamage + bonusDamage; + if (damage <= 0) return false; + + var knockBack = EnchantmentHelper.getKnockbackBonus(player); + + // We follow the logic in Player.attack of setting the entity on fire before attacking, so it's burning when it + // (possibly) dies. + var fireAspect = EnchantmentHelper.getFireAspect(player); + var onFire = false; + if (entity instanceof LivingEntity target && fireAspect > 0 && !target.isOnFire()) { + onFire = true; + target.setSecondsOnFire(1); } - var level = (ServerLevel) turtle.getLevel(); - var turtlePosition = turtle.getPosition(); + var source = player.damageSources().playerAttack(player); + if (!entity.hurt(source, damage)) { + // If we failed to damage the entity, undo us setting the entity on fire. + if (onFire) entity.clearFire(); + return false; + } - var blockPosition = turtlePosition.relative(direction); + // Special case for armor stands: attack twice to guarantee destroy + if (entity.isAlive() && entity instanceof ArmorStand) entity.hurt(source, damage); + + // Apply knockback + if (knockBack > 0) { + if (entity instanceof LivingEntity target) { + target.knockback(knockBack * 0.5, -direction.getStepX(), -direction.getStepZ()); + } else { + entity.push(direction.getStepX() * knockBack * 0.5, 0.1, direction.getStepZ() * knockBack * 0.5); + } + } + + // Apply remaining enchantments + if (entity instanceof LivingEntity target) EnchantmentHelper.doPostHurtEffects(target, player); + EnchantmentHelper.doPostDamageEffects(player, entity); + + // Damage the original item stack. + if (entity instanceof LivingEntity target) { + player.getItemInHand(InteractionHand.MAIN_HAND).hurtEnemy(target, player); + } + + // Apply fire aspect + if (entity instanceof LivingEntity target && fireAspect > 0 && !target.isOnFire()) { + target.setSecondsOnFire(4 * fireAspect); + } + + return true; + } + + private TurtleCommandResult dig(ITurtleAccess turtle, TurtleSide side, Direction direction) { + var level = (ServerLevel) turtle.getLevel(); + + var blockPosition = turtle.getPosition().relative(direction); if (level.isEmptyBlock(blockPosition) || WorldUtil.isLiquidBlock(level, blockPosition)) { return TurtleCommandResult.failure("Nothing to dig here"); } - var turtlePlayer = TurtlePlayer.getWithPosition(turtle, turtlePosition, direction); - turtlePlayer.loadInventory(item.copy()); + return withEquippedItem(turtle, side, direction, turtlePlayer -> { + var stack = turtlePlayer.player().getItemInHand(InteractionHand.MAIN_HAND); - // Check if we can break the block - var breakable = checkBlockBreakable(level, blockPosition, turtlePlayer); - if (!breakable.isSuccess()) return breakable; + // Right-click the block when using a shovel/hoe. + if (PlatformHelper.get().hasToolUsage(item) && TurtlePlaceCommand.deploy(stack, turtle, turtlePlayer, direction, null, null)) { + return TurtleCommandResult.success(); + } - DropConsumer.set(level, blockPosition, TurtleUtil.dropConsumer(turtle)); - var broken = !turtlePlayer.isBlockProtected(level, blockPosition) && turtlePlayer.player().gameMode.destroyBlock(blockPosition); - TurtleUtil.stopConsuming(turtle); + // Check if we can break the block + var breakable = checkBlockBreakable(level, blockPosition, turtlePlayer); + if (!breakable.isSuccess()) return breakable; - // Check spawn protection - return broken ? TurtleCommandResult.success() : TurtleCommandResult.failure("Cannot break protected block"); + // And break it! + DropConsumer.set(level, blockPosition, TurtleUtil.dropConsumer(turtle)); + var broken = !turtlePlayer.isBlockProtected(level, blockPosition) && turtlePlayer.player().gameMode.destroyBlock(blockPosition); + TurtleUtil.stopConsuming(turtle); + + return broken ? TurtleCommandResult.success() : TurtleCommandResult.failure("Cannot break protected block"); + }); } private static boolean isTriviallyBreakable(BlockGetter reader, BlockPos pos, BlockState state) { - return state.is(ComputerCraftTags.Blocks.TURTLE_ALWAYS_BREAKABLE) + return + state.is(ComputerCraftTags.Blocks.TURTLE_ALWAYS_BREAKABLE) // Allow breaking any "instabreak" block. || state.getDestroySpeed(reader, pos) == 0; } diff --git a/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleToolSerialiser.java b/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleToolSerialiser.java index 7a635c214..dc3443879 100644 --- a/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleToolSerialiser.java +++ b/projects/common/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleToolSerialiser.java @@ -5,6 +5,7 @@ package dan200.computercraft.shared.turtle.upgrades; import com.google.gson.JsonObject; +import dan200.computercraft.api.turtle.TurtleToolDurability; import dan200.computercraft.api.turtle.TurtleUpgradeSerialiser; import dan200.computercraft.api.upgrades.UpgradeBase; import dan200.computercraft.shared.platform.RegistryWrappers; @@ -28,6 +29,8 @@ public final class TurtleToolSerialiser implements TurtleUpgradeSerialiser breakable = null; if (object.has("breakable")) { @@ -35,7 +38,7 @@ public final class TurtleToolSerialiser implements TurtleUpgradeSerialiser 0", - "gui.computercraft.config.http.rules.tooltip": "Une liste de rรจgles qui contrรดlent le comportement de l'API \"http\" pour des domaines\nou des IP spรฉcifiques. Chaque rรจgle est un รฉlรฉment avec un 'hรดte' ร  comparer et une sรฉrie\nde propriรฉtรฉs. Les rรจgles sont รฉvaluรฉes dans l'ordre, ce qui signifie que les rรจgles antรฉrieures\nremplacent les suivantes.\nL'hรดte peut รชtre un nom de domaine (\"pastebin.com\"), un astรฉrisque (\"*.pastebin.com\") ou\nune notation CIDR (\"127.0.0.0/8\").\nS'il n'y a pas de rรจgles, le domaine est bloquรฉ." + "gui.computercraft.config.http.rules.tooltip": "Une liste de rรจgles qui contrรดlent le comportement de l'API \"http\" pour des domaines\nou des IP spรฉcifiques. Chaque rรจgle est un รฉlรฉment avec un 'hรดte' ร  comparer et une sรฉrie\nde propriรฉtรฉs. Les rรจgles sont รฉvaluรฉes dans l'ordre, ce qui signifie que les rรจgles antรฉrieures\nremplacent les suivantes.\nL'hรดte peut รชtre un nom de domaine (\"pastebin.com\"), un astรฉrisque (\"*.pastebin.com\") ou\nune notation CIDR (\"127.0.0.0/8\").\nS'il n'y a pas de rรจgles, le domaine est bloquรฉ.", + "gui.computercraft.config.http.proxy.host.tooltip": "Le nom d'hรดte ou l'adresse IP du serveur proxy.", + "gui.computercraft.config.http.proxy.tooltip": "Tunnelise les requรชtes HTTP et websocket via un serveur proxy. Affecte uniquement\nles rรจgles HTTP avec \"use_proxy\" dรฉfini sur true (dรฉsactivรฉ par dรฉfaut).\nSi l'authentification est requise pour le proxy, crรฉez un fichier \"computercraft-proxy.pw\"\ndans le mรชme dossier que \"computercraft-server.toml\", contenant le\nnom d'utilisateur et mot de passe sรฉparรฉs par deux-points, par ex. \"monutilisateur:monmotdepasse\". Pour\nProxy SOCKS4, seul le nom d'utilisateur est requis.", + "gui.computercraft.config.upload_max_size.tooltip": "La taille limite de tรฉlรฉversement de fichier, en octets. Doit รชtre compris entre 1ย Kio et 16ย Mio.\nGardez ร  l'esprit que les tรฉlรฉversements sont traitรฉs en un seul clic - les fichiers volumineux ou\nde mauvaises performances rรฉseau peuvent bloquer le thread du rรฉseau. Et attention ร  l'espace disque !\nPlage : 1024 ~ 16777216", + "gui.computercraft.config.http.proxy": "Proxy", + "gui.computercraft.config.http.proxy.host": "Nom d'hรดte", + "gui.computercraft.config.http.proxy.port": "Port", + "gui.computercraft.config.http.proxy.port.tooltip": "Le port du serveur proxy.\nPlage : 1 ~ 65536", + "gui.computercraft.config.http.proxy.type": "Type de proxy", + "gui.computercraft.config.http.proxy.type.tooltip": "Le type de proxy ร  utiliser.\nValeurs autorisรฉesย : HTTP, HTTPS, SOCKS4, SOCKS5", + "gui.computercraft.config.upload_max_size": "Taille limite de tรฉlรฉversement de fichiers (octets)" } diff --git a/projects/common/src/main/resources/assets/computercraft/lang/ru_ru.json b/projects/common/src/main/resources/assets/computercraft/lang/ru_ru.json index 8495d2376..66a7390ca 100644 --- a/projects/common/src/main/resources/assets/computercraft/lang/ru_ru.json +++ b/projects/common/src/main/resources/assets/computercraft/lang/ru_ru.json @@ -177,5 +177,23 @@ "gui.computercraft.config.turtle.need_fuel": "ะ’ะบะปัŽั‡ะธั‚ัŒ ะผะตั…ะฐะฝะธะบัƒ ั‚ะพะฟะปะธะฒะฐ", "gui.computercraft.config.turtle.normal_fuel_limit": "ะ›ะธะผะธั‚ ั‚ะพะฟะปะธะฒะฐ ะงะตั€ะตะฟะฐัˆะตะบ", "gui.computercraft.config.turtle.normal_fuel_limit.tooltip": "ะ›ะธะผะธั‚ ั‚ะพะฟะปะธะฒะฐ ะดะปั ะงะตั€ะตะฟะฐัˆะตะบ.\nะžะณั€ะฐะฝะธั‡ะตะฝะธะต: > 0", - "gui.computercraft.config.turtle.tooltip": "ะ ะฐะทะฝั‹ะต ะฝะฐัั‚ั€ะพะนะบะธ, ัะฒัะทะฐะฝะฝั‹ะต ั ั‡ะตั€ะตะฟะฐัˆะบะฐะผะธ." + "gui.computercraft.config.turtle.tooltip": "ะ ะฐะทะฝั‹ะต ะฝะฐัั‚ั€ะพะนะบะธ, ัะฒัะทะฐะฝะฝั‹ะต ั ั‡ะตั€ะตะฟะฐัˆะบะฐะผะธ.", + "gui.computercraft.config.http.proxy.port": "ะŸะพั€ั‚", + "gui.computercraft.config.http.proxy.port.tooltip": "ะŸะพั€ั‚ ะฟั€ะพะบัะธ-ัะตั€ะฒะตั€ะฐ.\nะ”ะธะฐะฟะฐะทะพะฝ: 1 ~ 65536", + "gui.computercraft.config.http.proxy.host": "ะ˜ะผั ั…ะพัั‚ะฐ", + "gui.computercraft.config.http.proxy": "Proxy", + "gui.computercraft.config.http.proxy.host.tooltip": "ะ˜ะผั ั…ะพัั‚ะฐ ะธะปะธ IP-ะฐะดั€ะตั ะฟั€ะพะบัะธ-ัะตั€ะฒะตั€ะฐ.", + "gui.computercraft.config.http.proxy.tooltip": "ะขัƒะฝะฝะตะปะธั€ัƒะตั‚ HTTP-ะทะฐะฟั€ะพัั‹ ะธ ะทะฐะฟั€ะพัั‹ websocket ั‡ะตั€ะตะท ะฟั€ะพะบัะธ-ัะตั€ะฒะตั€. ะ’ะปะธัะตั‚ ั‚ะพะปัŒะบะพ ะฝะฐ HTTP\nะฟั€ะฐะฒะธะปะฐ ั ะฟะฐั€ะฐะผะตั‚ั€ะพะผ \"use_proxy\" ะฒ ะทะฝะฐั‡ะตะฝะธะธ true (ะพั‚ะบะปัŽั‡ะตะฝะพ ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ).\nะ•ัะปะธ ะดะปั ะฟั€ะพะบัะธ-ัะตั€ะฒะตั€ะฐ ั‚ั€ะตะฑัƒะตั‚ัั ะฐัƒั‚ะตะฝั‚ะธั„ะธะบะฐั†ะธั, ัะพะทะดะฐะนั‚ะต \"computercraft-proxy.pw\"\nั„ะฐะนะป ะฒ ั‚ะพะผ ะถะต ะบะฐั‚ะฐะปะพะณะต, ั‡ั‚ะพ ะธ \"computercraft-server.toml\", ัะพะดะตั€ะถะฐั‰ะธะน ะธะผั\nะฟะพะปัŒะทะพะฒะฐั‚ะตะปั ะธ ะฟะฐั€ะพะปัŒ, ั€ะฐะทะดะตะปะตะฝะฝั‹ะต ะดะฒะพะตั‚ะพั‡ะธะตะผ, ะฝะฐะฟั€ะธะผะตั€ \"myuser:mypassword\". ะ”ะปั\nะฟั€ะพะบัะธ-ัะตั€ะฒะตั€ะพะฒ SOCKS4 ั‚ั€ะตะฑัƒะตั‚ัั ั‚ะพะปัŒะบะพ ะธะผั ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั.", + "gui.computercraft.config.http.proxy.type": "ะขะธะฟ ะฟั€ะพะบัะธ-ัะตั€ะฒะตั€ะฐ", + "gui.computercraft.config.http.proxy.type.tooltip": "ะขะธะฟ ะธัะฟะพะปัŒะทัƒะตะผะพะณะพ ะฟั€ะพะบัะธ-ัะตั€ะฒะตั€ะฐ.\nะ”ะพะฟัƒัั‚ะธะผั‹ะต ะทะฝะฐั‡ะตะฝะธั: HTTP, HTTPS, SOCKS4, SOCKS5", + "gui.computercraft.upload.no_response.msg": "ะ’ะฐัˆ ะบะพะผะฟัŒัŽั‚ะตั€ ะฝะต ะธัะฟะพะปัŒะทะพะฒะฐะป ะฟะตั€ะตะดะฐะฝะฝั‹ะต ะฒะฐะผะธ ั„ะฐะนะปั‹. ะ’ะพะทะผะพะถะฝะพ, ะฒะฐะผ ะฟะพั‚ั€ะตะฑัƒะตั‚ัั ะทะฐะฟัƒัั‚ะธั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ %s ะธ ะฟะพะฒั‚ะพั€ะธั‚ัŒ ะฟะพะฟั‹ั‚ะบัƒ.", + "tracking_field.computercraft.max": "%s (ะผะฐะบัะธะผะฐะปัŒะฝะพะต)", + "tracking_field.computercraft.count": "%s (ะบะพะปะธั‡ะตัั‚ะฒะพ)", + "gui.computercraft.config.http.rules": "ะ ะฐะทั€ะตัˆะฐัŽั‰ะธะต/ะทะฐะฟั€ะตั‰ะฐัŽั‰ะธะต ะฟั€ะฐะฒะธะปะฐ", + "gui.computercraft.config.http.websocket_enabled": "ะ’ะบะปัŽั‡ะธั‚ัŒ ะฒะตะฑ-ัะพะบะตั‚ั‹", + "gui.computercraft.config.http.websocket_enabled.tooltip": "ะ’ะบะปัŽั‡ะธั‚ัŒ ะธัะฟะพะปัŒะทะพะฒะฐะฝะธะต http ะฒะตะฑ-ัะพะบะตั‚ะพะฒ. ะ”ะปั ัั‚ะพะณะพ ะฝะตะพะฑั…ะพะดะธะผะพ, ั‡ั‚ะพะฑั‹ ะฟะฐั€ะฐะผะตั‚ั€ ยซhttp_enableยป ะฑั‹ะป true.", + "gui.computercraft.config.log_computer_errors": "ะ ะตะณะธัั‚ั€ะธั€ะพะฒะฐั‚ัŒ ะพัˆะธะฑะบะธ ะบะพะผะฟัŒัŽั‚ะตั€ะฐ", + "gui.computercraft.config.log_computer_errors.tooltip": "ะ ะตะณะธัั‚ั€ะธั€ะพะฒะฐั‚ัŒ ะธัะบะปัŽั‡ะตะฝะธั, ะฒั‹ะทะฒะฐะฝะฝั‹ะต ะฟะตั€ะธั„ะตั€ะธะนะฝั‹ะผะธ ัƒัั‚ั€ะพะนัั‚ะฒะฐะผะธ ะธ ะดั€ัƒะณะธะผะธ ะพะฑัŠะตะบั‚ะฐะผะธ Lua. ะญั‚ะพ ะพะฑะปะตะณั‡ะฐะตั‚\nะดะปั ะฐะฒั‚ะพั€ะฐะผ ะผะพะดะพะฒ ัƒัั‚ั€ะฐะฝะตะฝะธะต ะฟั€ะพะฑะปะตะผ, ะฝะพ ะผะพะถะตั‚ ะฟั€ะธะฒะตัั‚ะธ ะบ ัะฟะฐะผัƒ ะฒ ะปะพะณะฐั…, ะตัะปะธ ะปัŽะดะธ ะฑัƒะดัƒั‚ ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ\nะณะปัŽั‡ะฝั‹ะต ะผะตั‚ะพะดั‹.", + "gui.computercraft.config.maximum_open_files": "ะœะฐะบัะธะผะฐะปัŒะฝะพะต ะบะพะปะธั‡ะตัั‚ะฒะพ ั„ะฐะนะปะพะฒ, ะพั‚ะบั€ั‹ั‚ั‹ั… ะฝะฐ ะพะดะฝะพะผ ะบะพะผะฟัŒัŽั‚ะตั€ะต", + "gui.computercraft.config.http.rules.tooltip": "ะกะฟะธัะพะบ ะฟั€ะฐะฒะธะป, ะบะพั‚ะพั€ั‹ะต ะบะพะฝั‚ั€ะพะปะธั€ัƒัŽั‚ ะฟะพะฒะตะดะตะฝะธะต ยซhttpยป API ะดะปั ะพะฟั€ะตะดะตะปะตะฝะฝั‹ั… ะดะพะผะตะฝะพะฒ ะธะปะธ\nIP-ะฐะดั€ะตัะพะฒ. ะšะฐะถะดะพะต ะฟั€ะฐะฒะธะปะพ ะฟั€ะตะดัั‚ะฐะฒะปัะตั‚ ัะพะฑะพะน ัะปะตะผะตะฝั‚ ั ยซัƒะทะปะพะผยป ะดะปั ัะพะฟะพัั‚ะฐะฒะปะตะฝะธั ะธ ะฝะฐะฑะพั€ะพะผ\nัะฒะพะนัั‚ะฒ. ะŸั€ะฐะฒะธะปะฐ ะพั†ะตะฝะธะฒะฐัŽั‚ัั ะฟะพ ะฟะพั€ัะดะบัƒ, ั‚ะพ ะตัั‚ัŒ ะฑะพะปะตะต ั€ะฐะฝะฝะธะต ะฟั€ะฐะฒะธะปะฐ ะฟะตั€ะตะฒะตัˆะธะฒะฐัŽั‚\nะฑะพะปะตะต ะฟะพะทะดะฝะธะต.\nะฅะพัั‚ ะผะพะถะตั‚ ะฑั‹ั‚ัŒ ะดะพะผะตะฝะฝั‹ะผ ะธะผะตะฝะตะผ (\"pastebin.com\"), wildcard-ัะตั€ั‚ะธั„ะธะบะฐั‚ะพะผ (\"*.pastebin.com\") ะธะปะธ\nะฝะพั‚ะฐั†ะธะตะน CIDR (\"127.0.0.0/8\").\nะ•ัะปะธ ะฟั€ะฐะฒะธะป ะฝะตั‚, ะดะพะผะตะฝ ะฑะปะพะบะธั€ัƒะตั‚ัั." } diff --git a/projects/common/src/test/java/dan200/computercraft/TestPlatformHelper.java b/projects/common/src/test/java/dan200/computercraft/TestPlatformHelper.java index 0d998af47..b2919effc 100644 --- a/projects/common/src/test/java/dan200/computercraft/TestPlatformHelper.java +++ b/projects/common/src/test/java/dan200/computercraft/TestPlatformHelper.java @@ -59,6 +59,11 @@ import java.util.function.Predicate; @AutoService({ PlatformHelper.class, dan200.computercraft.impl.PlatformHelper.class, ComputerCraftAPIService.class }) public class TestPlatformHelper extends AbstractComputerCraftAPI implements PlatformHelper { + @Override + public boolean isDevelopmentEnvironment() { + return true; + } + @Override public ConfigFile.Builder createConfigBuilder() { throw new UnsupportedOperationException("Cannot create config file inside tests"); diff --git a/projects/common/src/testMod/kotlin/dan200/computercraft/gametest/Turtle_Test.kt b/projects/common/src/testMod/kotlin/dan200/computercraft/gametest/Turtle_Test.kt index 259ff9b8d..94f226dc3 100644 --- a/projects/common/src/testMod/kotlin/dan200/computercraft/gametest/Turtle_Test.kt +++ b/projects/common/src/testMod/kotlin/dan200/computercraft/gametest/Turtle_Test.kt @@ -7,9 +7,13 @@ package dan200.computercraft.gametest import dan200.computercraft.api.detail.BasicItemDetailProvider import dan200.computercraft.api.detail.VanillaDetailRegistries import dan200.computercraft.api.lua.ObjectArguments +import dan200.computercraft.api.turtle.ITurtleUpgrade +import dan200.computercraft.api.turtle.TurtleSide +import dan200.computercraft.api.upgrades.UpgradeData import dan200.computercraft.core.apis.PeripheralAPI import dan200.computercraft.gametest.api.* import dan200.computercraft.gametest.core.TestHooks +import dan200.computercraft.impl.TurtleUpgrades import dan200.computercraft.mixin.gametest.GameTestHelperAccessor import dan200.computercraft.mixin.gametest.GameTestInfoAccessor import dan200.computercraft.shared.ModRegistry @@ -30,13 +34,17 @@ import net.minecraft.world.entity.EntityType import net.minecraft.world.entity.item.PrimedTnt import net.minecraft.world.item.ItemStack import net.minecraft.world.item.Items +import net.minecraft.world.item.enchantment.Enchantments import net.minecraft.world.level.block.Blocks import net.minecraft.world.level.block.FenceBlock +import net.minecraft.world.level.block.state.properties.BlockStateProperties import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.Matchers.* +import org.hamcrest.Matchers.array +import org.hamcrest.Matchers.instanceOf import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals import java.util.* +import java.util.concurrent.CopyOnWriteArrayList import kotlin.time.Duration.Companion.milliseconds class Turtle_Test { @@ -78,6 +86,26 @@ class Turtle_Test { thenExecute { helper.assertBlockPresent(Blocks.LAVA, BlockPos(2, 2, 2)) } } + /** + * Checks that calling [net.minecraft.world.item.Item.use] will not place blocks too far away. + * + * This is caused by items using [net.minecraft.world.item.Item.getPlayerPOVHitResult] to perform a ray trace, which + * ignores turtle's reduced reach distance. + * + * @see [#1497](https://github.com/cc-tweaked/CC-Tweaked/issues/1497) + */ + @GameTest + fun Place_use_reach_limit(helper: GameTestHelper) = helper.sequence { + thenOnComputer { + turtle.placeDown(ObjectArguments()).await() + .assertArrayEquals(true, message = "Placed water") + } + thenExecute { + helper.assertBlockPresent(Blocks.AIR, BlockPos(2, 2, 2)) + helper.assertBlockHas(BlockPos(2, 5, 2), BlockStateProperties.WATERLOGGED, true) + } + } + /** * Checks turtles can place when waterlogged. * @@ -151,6 +179,85 @@ class Turtle_Test { } } + /** + * Digging using a pickaxe with `{"consumesDurability": "always"}`, consumes durability. + */ + @GameTest + fun Dig_consume_durability(helper: GameTestHelper) = helper.sequence { + thenOnComputer { turtle.dig(Optional.empty()).await() } + thenExecute { + helper.assertBlockPresent(Blocks.AIR, BlockPos(2, 2, 3)) + helper.assertContainerExactly(BlockPos(2, 2, 2), listOf(ItemStack(Items.COBBLESTONE))) + + val turtle = helper.getBlockEntity(BlockPos(2, 2, 2), ModRegistry.BlockEntities.TURTLE_NORMAL.get()).access + val upgrade = turtle.getUpgrade(TurtleSide.LEFT) + assertEquals(TurtleUpgrades.instance().get("cctest:wooden_pickaxe"), upgrade, "Upgrade is a wooden pickaxe") + + val item = ItemStack(Items.WOODEN_PICKAXE) + item.damageValue = 1 + helper.assertUpgradeItem(item, turtle.getUpgradeWithData(TurtleSide.LEFT)!!) + } + } + + /** + * Digging using a pickaxe with `{"consumesDurability": "always"}` and no durability removes the tool. + */ + @GameTest + fun Dig_breaks_tool(helper: GameTestHelper) = helper.sequence { + thenOnComputer { turtle.dig(Optional.empty()).await() } + thenExecute { + helper.assertBlockPresent(Blocks.AIR, BlockPos(2, 2, 3)) + helper.assertContainerExactly(BlockPos(2, 2, 2), listOf(ItemStack(Items.COBBLESTONE))) + + val turtle = helper.getBlockEntity(BlockPos(2, 2, 2), ModRegistry.BlockEntities.TURTLE_NORMAL.get()).access + val upgrade = turtle.getUpgrade(TurtleSide.LEFT) + assertEquals(null, upgrade, "Upgrade broke") + + helper.assertUpgradeItem( + ItemStack(Items.WOODEN_PICKAXE), + UpgradeData.ofDefault(TurtleUpgrades.instance().get("cctest:wooden_pickaxe")), + ) + } + } + + /** + * Digging using a silk-touch enchanted pickaxe with `{"consumesDurability": "when_enchanted"}`, consumes durability + * uses silk touch. + */ + @GameTest + fun Dig_enchanted_consume_durability(helper: GameTestHelper) = helper.sequence { + thenOnComputer { turtle.dig(Optional.empty()).await() } + thenExecute { + helper.assertBlockPresent(Blocks.AIR, BlockPos(2, 2, 3)) + helper.assertContainerExactly(BlockPos(2, 2, 2), listOf(ItemStack(Items.STONE))) + + val turtle = helper.getBlockEntity(BlockPos(2, 2, 2), ModRegistry.BlockEntities.TURTLE_NORMAL.get()).access + val upgrade = turtle.getUpgrade(TurtleSide.LEFT) + assertEquals( + TurtleUpgrades.instance().get("cctest:netherite_pickaxe"), + upgrade, + "Upgrade is a netherite pickaxe", + ) + + val item = ItemStack(Items.NETHERITE_PICKAXE) + item.damageValue = 1 + item.enchant(Enchantments.SILK_TOUCH, 1) + item.setRepairCost(1) + + helper.assertUpgradeItem(item, turtle.getUpgradeWithData(TurtleSide.LEFT)!!) + } + } + + private fun GameTestHelper.assertUpgradeItem(expected: ItemStack, upgrade: UpgradeData) { + if (!ItemStack.matches(expected, upgrade.upgradeItem)) { + fail("Invalid upgrade item\n Expected => ${expected.tag}\n Actual => ${upgrade.upgradeItem.tag}") + } + + if (!ItemStack.matches(ItemStack(expected.item), upgrade.upgrade.craftingItem)) { + fail("Original upgrade item has changed (is now ${upgrade.upgrade.craftingItem})") + } + } + /** * Checks turtles can place monitors * @@ -466,7 +573,7 @@ class Turtle_Test { fun Peripheral_change(helper: GameTestHelper) = helper.sequence { val testInfo = (helper as GameTestHelperAccessor).testInfo as GameTestInfoAccessor - val events = mutableListOf>() + val events = CopyOnWriteArrayList>() var running = false thenStartComputer("listen") { running = true @@ -485,15 +592,13 @@ class Turtle_Test { turtle.back().await().assertArrayEquals(true, message = "Moved turtle forward") TestHooks.LOG.info("[{}] Finished turtle at {}", testInfo, testInfo.`computercraft$getTick`()) } - thenIdle(4) // Should happen immediately, but computers might be slow. - thenExecute { - assertEquals( - listOf( - "peripheral_detach" to "right", - "peripheral" to "right", - ), - events, + thenWaitUntil { + val expected = listOf( + "peripheral_detach" to "right", + "peripheral" to "right", ) + + if (events != expected) helper.fail("Expected $expected, but received $events") } } diff --git a/projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/netherite_pickaxe.json b/projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/netherite_pickaxe.json new file mode 100644 index 000000000..42aa7fa85 --- /dev/null +++ b/projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/netherite_pickaxe.json @@ -0,0 +1,6 @@ +{ + "type": "computercraft:tool", + "item": "minecraft:netherite_pickaxe", + "allowEnchantments": true, + "consumeDurability": "when_enchanted" +} diff --git a/projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/wooden_pickaxe.json b/projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/wooden_pickaxe.json new file mode 100644 index 000000000..0516dd1bb --- /dev/null +++ b/projects/common/src/testMod/resources/data/cctest/computercraft/turtle_upgrades/wooden_pickaxe.json @@ -0,0 +1,5 @@ +{ + "type": "computercraft:tool", + "item": "minecraft:wooden_pickaxe", + "consumeDurability": "always" +} diff --git a/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_breaks_tool.snbt b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_breaks_tool.snbt new file mode 100644 index 000000000..7a1f5a7a8 --- /dev/null +++ b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_breaks_tool.snbt @@ -0,0 +1,138 @@ +{ + DataVersion: 3218, + size: [5, 5, 5], + data: [ + {pos: [0, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [0, 1, 0], state: "minecraft:air"}, + {pos: [0, 1, 1], state: "minecraft:air"}, + {pos: [0, 1, 2], state: "minecraft:air"}, + {pos: [0, 1, 3], state: "minecraft:air"}, + {pos: [0, 1, 4], state: "minecraft:air"}, + {pos: [1, 1, 0], state: "minecraft:air"}, + {pos: [1, 1, 1], state: "minecraft:air"}, + {pos: [1, 1, 2], state: "minecraft:air"}, + {pos: [1, 1, 3], state: "minecraft:air"}, + {pos: [1, 1, 4], state: "minecraft:air"}, + {pos: [2, 1, 0], state: "minecraft:air"}, + {pos: [2, 1, 1], state: "minecraft:air"}, + {pos: [2, 1, 2], state: "computercraft:turtle_normal{facing:south,waterlogged:false}", nbt: {ComputerId: 1, Fuel: 80, Items: [], Label: "turtle_test.dig_breaks_tool", LeftUpgrade: "cctest:wooden_pickaxe", LeftUpgradeNbt: {Tag: {Damage: 58}}, On: 1b, Owner: {LowerId: -6876936588741668278L, Name: "Dev", UpperId: 4039158846114182220L}, Slot: 0, id: "computercraft:turtle_normal"}}, + {pos: [2, 1, 3], state: "minecraft:stone"}, + {pos: [2, 1, 4], state: "minecraft:air"}, + {pos: [3, 1, 0], state: "minecraft:air"}, + {pos: [3, 1, 1], state: "minecraft:air"}, + {pos: [3, 1, 2], state: "minecraft:air"}, + {pos: [3, 1, 3], state: "minecraft:air"}, + {pos: [3, 1, 4], state: "minecraft:air"}, + {pos: [4, 1, 0], state: "minecraft:air"}, + {pos: [4, 1, 1], state: "minecraft:air"}, + {pos: [4, 1, 2], state: "minecraft:air"}, + {pos: [4, 1, 3], state: "minecraft:air"}, + {pos: [4, 1, 4], state: "minecraft:air"}, + {pos: [0, 2, 0], state: "minecraft:air"}, + {pos: [0, 2, 1], state: "minecraft:air"}, + {pos: [0, 2, 2], state: "minecraft:air"}, + {pos: [0, 2, 3], state: "minecraft:air"}, + {pos: [0, 2, 4], state: "minecraft:air"}, + {pos: [1, 2, 0], state: "minecraft:air"}, + {pos: [1, 2, 1], state: "minecraft:air"}, + {pos: [1, 2, 2], state: "minecraft:air"}, + {pos: [1, 2, 3], state: "minecraft:air"}, + {pos: [1, 2, 4], state: "minecraft:air"}, + {pos: [2, 2, 0], state: "minecraft:air"}, + {pos: [2, 2, 1], state: "minecraft:air"}, + {pos: [2, 2, 2], state: "minecraft:air"}, + {pos: [2, 2, 3], state: "minecraft:air"}, + {pos: [2, 2, 4], state: "minecraft:air"}, + {pos: [3, 2, 0], state: "minecraft:air"}, + {pos: [3, 2, 1], state: "minecraft:air"}, + {pos: [3, 2, 2], state: "minecraft:air"}, + {pos: [3, 2, 3], state: "minecraft:air"}, + {pos: [3, 2, 4], state: "minecraft:air"}, + {pos: [4, 2, 0], state: "minecraft:air"}, + {pos: [4, 2, 1], state: "minecraft:air"}, + {pos: [4, 2, 2], state: "minecraft:air"}, + {pos: [4, 2, 3], state: "minecraft:air"}, + {pos: [4, 2, 4], state: "minecraft:air"}, + {pos: [0, 3, 0], state: "minecraft:air"}, + {pos: [0, 3, 1], state: "minecraft:air"}, + {pos: [0, 3, 2], state: "minecraft:air"}, + {pos: [0, 3, 3], state: "minecraft:air"}, + {pos: [0, 3, 4], state: "minecraft:air"}, + {pos: [1, 3, 0], state: "minecraft:air"}, + {pos: [1, 3, 1], state: "minecraft:air"}, + {pos: [1, 3, 2], state: "minecraft:air"}, + {pos: [1, 3, 3], state: "minecraft:air"}, + {pos: [1, 3, 4], state: "minecraft:air"}, + {pos: [2, 3, 0], state: "minecraft:air"}, + {pos: [2, 3, 1], state: "minecraft:air"}, + {pos: [2, 3, 2], state: "minecraft:air"}, + {pos: [2, 3, 3], state: "minecraft:air"}, + {pos: [2, 3, 4], state: "minecraft:air"}, + {pos: [3, 3, 0], state: "minecraft:air"}, + {pos: [3, 3, 1], state: "minecraft:air"}, + {pos: [3, 3, 2], state: "minecraft:air"}, + {pos: [3, 3, 3], state: "minecraft:air"}, + {pos: [3, 3, 4], state: "minecraft:air"}, + {pos: [4, 3, 0], state: "minecraft:air"}, + {pos: [4, 3, 1], state: "minecraft:air"}, + {pos: [4, 3, 2], state: "minecraft:air"}, + {pos: [4, 3, 3], state: "minecraft:air"}, + {pos: [4, 3, 4], state: "minecraft:air"}, + {pos: [0, 4, 0], state: "minecraft:air"}, + {pos: [0, 4, 1], state: "minecraft:air"}, + {pos: [0, 4, 2], state: "minecraft:air"}, + {pos: [0, 4, 3], state: "minecraft:air"}, + {pos: [0, 4, 4], state: "minecraft:air"}, + {pos: [1, 4, 0], state: "minecraft:air"}, + {pos: [1, 4, 1], state: "minecraft:air"}, + {pos: [1, 4, 2], state: "minecraft:air"}, + {pos: [1, 4, 3], state: "minecraft:air"}, + {pos: [1, 4, 4], state: "minecraft:air"}, + {pos: [2, 4, 0], state: "minecraft:air"}, + {pos: [2, 4, 1], state: "minecraft:air"}, + {pos: [2, 4, 2], state: "minecraft:air"}, + {pos: [2, 4, 3], state: "minecraft:air"}, + {pos: [2, 4, 4], state: "minecraft:air"}, + {pos: [3, 4, 0], state: "minecraft:air"}, + {pos: [3, 4, 1], state: "minecraft:air"}, + {pos: [3, 4, 2], state: "minecraft:air"}, + {pos: [3, 4, 3], state: "minecraft:air"}, + {pos: [3, 4, 4], state: "minecraft:air"}, + {pos: [4, 4, 0], state: "minecraft:air"}, + {pos: [4, 4, 1], state: "minecraft:air"}, + {pos: [4, 4, 2], state: "minecraft:air"}, + {pos: [4, 4, 3], state: "minecraft:air"}, + {pos: [4, 4, 4], state: "minecraft:air"} + ], + entities: [], + palette: [ + "minecraft:polished_andesite", + "minecraft:stone", + "minecraft:air", + "computercraft:turtle_normal{facing:south,waterlogged:false}" + ] +} diff --git a/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_consume_durability.snbt b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_consume_durability.snbt new file mode 100644 index 000000000..a75b00e45 --- /dev/null +++ b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_consume_durability.snbt @@ -0,0 +1,138 @@ +{ + DataVersion: 3218, + size: [5, 5, 5], + data: [ + {pos: [0, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [0, 1, 0], state: "minecraft:air"}, + {pos: [0, 1, 1], state: "minecraft:air"}, + {pos: [0, 1, 2], state: "minecraft:air"}, + {pos: [0, 1, 3], state: "minecraft:air"}, + {pos: [0, 1, 4], state: "minecraft:air"}, + {pos: [1, 1, 0], state: "minecraft:air"}, + {pos: [1, 1, 1], state: "minecraft:air"}, + {pos: [1, 1, 2], state: "minecraft:air"}, + {pos: [1, 1, 3], state: "minecraft:air"}, + {pos: [1, 1, 4], state: "minecraft:air"}, + {pos: [2, 1, 0], state: "minecraft:air"}, + {pos: [2, 1, 1], state: "minecraft:air"}, + {pos: [2, 1, 2], state: "computercraft:turtle_normal{facing:south,waterlogged:false}", nbt: {ComputerId: 1, Fuel: 80, Items: [], Label: "turtle_test.dig_consume_durability", LeftUpgrade: "cctest:wooden_pickaxe", On: 1b, Owner: {LowerId: -6876936588741668278L, Name: "Dev", UpperId: 4039158846114182220L}, Slot: 0, id: "computercraft:turtle_normal"}}, + {pos: [2, 1, 3], state: "minecraft:stone"}, + {pos: [2, 1, 4], state: "minecraft:air"}, + {pos: [3, 1, 0], state: "minecraft:air"}, + {pos: [3, 1, 1], state: "minecraft:air"}, + {pos: [3, 1, 2], state: "minecraft:air"}, + {pos: [3, 1, 3], state: "minecraft:air"}, + {pos: [3, 1, 4], state: "minecraft:air"}, + {pos: [4, 1, 0], state: "minecraft:air"}, + {pos: [4, 1, 1], state: "minecraft:air"}, + {pos: [4, 1, 2], state: "minecraft:air"}, + {pos: [4, 1, 3], state: "minecraft:air"}, + {pos: [4, 1, 4], state: "minecraft:air"}, + {pos: [0, 2, 0], state: "minecraft:air"}, + {pos: [0, 2, 1], state: "minecraft:air"}, + {pos: [0, 2, 2], state: "minecraft:air"}, + {pos: [0, 2, 3], state: "minecraft:air"}, + {pos: [0, 2, 4], state: "minecraft:air"}, + {pos: [1, 2, 0], state: "minecraft:air"}, + {pos: [1, 2, 1], state: "minecraft:air"}, + {pos: [1, 2, 2], state: "minecraft:air"}, + {pos: [1, 2, 3], state: "minecraft:air"}, + {pos: [1, 2, 4], state: "minecraft:air"}, + {pos: [2, 2, 0], state: "minecraft:air"}, + {pos: [2, 2, 1], state: "minecraft:air"}, + {pos: [2, 2, 2], state: "minecraft:air"}, + {pos: [2, 2, 3], state: "minecraft:air"}, + {pos: [2, 2, 4], state: "minecraft:air"}, + {pos: [3, 2, 0], state: "minecraft:air"}, + {pos: [3, 2, 1], state: "minecraft:air"}, + {pos: [3, 2, 2], state: "minecraft:air"}, + {pos: [3, 2, 3], state: "minecraft:air"}, + {pos: [3, 2, 4], state: "minecraft:air"}, + {pos: [4, 2, 0], state: "minecraft:air"}, + {pos: [4, 2, 1], state: "minecraft:air"}, + {pos: [4, 2, 2], state: "minecraft:air"}, + {pos: [4, 2, 3], state: "minecraft:air"}, + {pos: [4, 2, 4], state: "minecraft:air"}, + {pos: [0, 3, 0], state: "minecraft:air"}, + {pos: [0, 3, 1], state: "minecraft:air"}, + {pos: [0, 3, 2], state: "minecraft:air"}, + {pos: [0, 3, 3], state: "minecraft:air"}, + {pos: [0, 3, 4], state: "minecraft:air"}, + {pos: [1, 3, 0], state: "minecraft:air"}, + {pos: [1, 3, 1], state: "minecraft:air"}, + {pos: [1, 3, 2], state: "minecraft:air"}, + {pos: [1, 3, 3], state: "minecraft:air"}, + {pos: [1, 3, 4], state: "minecraft:air"}, + {pos: [2, 3, 0], state: "minecraft:air"}, + {pos: [2, 3, 1], state: "minecraft:air"}, + {pos: [2, 3, 2], state: "minecraft:air"}, + {pos: [2, 3, 3], state: "minecraft:air"}, + {pos: [2, 3, 4], state: "minecraft:air"}, + {pos: [3, 3, 0], state: "minecraft:air"}, + {pos: [3, 3, 1], state: "minecraft:air"}, + {pos: [3, 3, 2], state: "minecraft:air"}, + {pos: [3, 3, 3], state: "minecraft:air"}, + {pos: [3, 3, 4], state: "minecraft:air"}, + {pos: [4, 3, 0], state: "minecraft:air"}, + {pos: [4, 3, 1], state: "minecraft:air"}, + {pos: [4, 3, 2], state: "minecraft:air"}, + {pos: [4, 3, 3], state: "minecraft:air"}, + {pos: [4, 3, 4], state: "minecraft:air"}, + {pos: [0, 4, 0], state: "minecraft:air"}, + {pos: [0, 4, 1], state: "minecraft:air"}, + {pos: [0, 4, 2], state: "minecraft:air"}, + {pos: [0, 4, 3], state: "minecraft:air"}, + {pos: [0, 4, 4], state: "minecraft:air"}, + {pos: [1, 4, 0], state: "minecraft:air"}, + {pos: [1, 4, 1], state: "minecraft:air"}, + {pos: [1, 4, 2], state: "minecraft:air"}, + {pos: [1, 4, 3], state: "minecraft:air"}, + {pos: [1, 4, 4], state: "minecraft:air"}, + {pos: [2, 4, 0], state: "minecraft:air"}, + {pos: [2, 4, 1], state: "minecraft:air"}, + {pos: [2, 4, 2], state: "minecraft:air"}, + {pos: [2, 4, 3], state: "minecraft:air"}, + {pos: [2, 4, 4], state: "minecraft:air"}, + {pos: [3, 4, 0], state: "minecraft:air"}, + {pos: [3, 4, 1], state: "minecraft:air"}, + {pos: [3, 4, 2], state: "minecraft:air"}, + {pos: [3, 4, 3], state: "minecraft:air"}, + {pos: [3, 4, 4], state: "minecraft:air"}, + {pos: [4, 4, 0], state: "minecraft:air"}, + {pos: [4, 4, 1], state: "minecraft:air"}, + {pos: [4, 4, 2], state: "minecraft:air"}, + {pos: [4, 4, 3], state: "minecraft:air"}, + {pos: [4, 4, 4], state: "minecraft:air"} + ], + entities: [], + palette: [ + "minecraft:polished_andesite", + "minecraft:stone", + "minecraft:air", + "computercraft:turtle_normal{facing:south,waterlogged:false}" + ] +} diff --git a/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_enchanted_consume_durability.snbt b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_enchanted_consume_durability.snbt new file mode 100644 index 000000000..e461da3ea --- /dev/null +++ b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.dig_enchanted_consume_durability.snbt @@ -0,0 +1,138 @@ +{ + DataVersion: 3337, + size: [5, 5, 5], + data: [ + {pos: [0, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [0, 1, 0], state: "minecraft:air"}, + {pos: [0, 1, 1], state: "minecraft:air"}, + {pos: [0, 1, 2], state: "minecraft:air"}, + {pos: [0, 1, 3], state: "minecraft:air"}, + {pos: [0, 1, 4], state: "minecraft:air"}, + {pos: [1, 1, 0], state: "minecraft:air"}, + {pos: [1, 1, 1], state: "minecraft:air"}, + {pos: [1, 1, 2], state: "minecraft:air"}, + {pos: [1, 1, 3], state: "minecraft:air"}, + {pos: [1, 1, 4], state: "minecraft:air"}, + {pos: [2, 1, 0], state: "minecraft:air"}, + {pos: [2, 1, 1], state: "minecraft:air"}, + {pos: [2, 1, 2], state: "computercraft:turtle_normal{facing:south,waterlogged:false}", nbt: {ComputerId: 1, Fuel: 80, Items: [], Label: "turtle_test.dig_enchanted_consume_durability", LeftUpgrade: "cctest:netherite_pickaxe", LeftUpgradeNbt: {Tag: {Damage: 0, Enchantments: [{id: "minecraft:silk_touch", lvl: 1s}], RepairCost: 1}}, On: 1b, Owner: {LowerId: -6876936588741668278L, Name: "Dev", UpperId: 4039158846114182220L}, Slot: 0, id: "computercraft:turtle_normal"}}, + {pos: [2, 1, 3], state: "minecraft:stone"}, + {pos: [2, 1, 4], state: "minecraft:air"}, + {pos: [3, 1, 0], state: "minecraft:air"}, + {pos: [3, 1, 1], state: "minecraft:air"}, + {pos: [3, 1, 2], state: "minecraft:air"}, + {pos: [3, 1, 3], state: "minecraft:air"}, + {pos: [3, 1, 4], state: "minecraft:air"}, + {pos: [4, 1, 0], state: "minecraft:air"}, + {pos: [4, 1, 1], state: "minecraft:air"}, + {pos: [4, 1, 2], state: "minecraft:air"}, + {pos: [4, 1, 3], state: "minecraft:air"}, + {pos: [4, 1, 4], state: "minecraft:air"}, + {pos: [0, 2, 0], state: "minecraft:air"}, + {pos: [0, 2, 1], state: "minecraft:air"}, + {pos: [0, 2, 2], state: "minecraft:air"}, + {pos: [0, 2, 3], state: "minecraft:air"}, + {pos: [0, 2, 4], state: "minecraft:air"}, + {pos: [1, 2, 0], state: "minecraft:air"}, + {pos: [1, 2, 1], state: "minecraft:air"}, + {pos: [1, 2, 2], state: "minecraft:air"}, + {pos: [1, 2, 3], state: "minecraft:air"}, + {pos: [1, 2, 4], state: "minecraft:air"}, + {pos: [2, 2, 0], state: "minecraft:air"}, + {pos: [2, 2, 1], state: "minecraft:air"}, + {pos: [2, 2, 2], state: "minecraft:air"}, + {pos: [2, 2, 3], state: "minecraft:air"}, + {pos: [2, 2, 4], state: "minecraft:air"}, + {pos: [3, 2, 0], state: "minecraft:air"}, + {pos: [3, 2, 1], state: "minecraft:air"}, + {pos: [3, 2, 2], state: "minecraft:air"}, + {pos: [3, 2, 3], state: "minecraft:air"}, + {pos: [3, 2, 4], state: "minecraft:air"}, + {pos: [4, 2, 0], state: "minecraft:air"}, + {pos: [4, 2, 1], state: "minecraft:air"}, + {pos: [4, 2, 2], state: "minecraft:air"}, + {pos: [4, 2, 3], state: "minecraft:air"}, + {pos: [4, 2, 4], state: "minecraft:air"}, + {pos: [0, 3, 0], state: "minecraft:air"}, + {pos: [0, 3, 1], state: "minecraft:air"}, + {pos: [0, 3, 2], state: "minecraft:air"}, + {pos: [0, 3, 3], state: "minecraft:air"}, + {pos: [0, 3, 4], state: "minecraft:air"}, + {pos: [1, 3, 0], state: "minecraft:air"}, + {pos: [1, 3, 1], state: "minecraft:air"}, + {pos: [1, 3, 2], state: "minecraft:air"}, + {pos: [1, 3, 3], state: "minecraft:air"}, + {pos: [1, 3, 4], state: "minecraft:air"}, + {pos: [2, 3, 0], state: "minecraft:air"}, + {pos: [2, 3, 1], state: "minecraft:air"}, + {pos: [2, 3, 2], state: "minecraft:air"}, + {pos: [2, 3, 3], state: "minecraft:air"}, + {pos: [2, 3, 4], state: "minecraft:air"}, + {pos: [3, 3, 0], state: "minecraft:air"}, + {pos: [3, 3, 1], state: "minecraft:air"}, + {pos: [3, 3, 2], state: "minecraft:air"}, + {pos: [3, 3, 3], state: "minecraft:air"}, + {pos: [3, 3, 4], state: "minecraft:air"}, + {pos: [4, 3, 0], state: "minecraft:air"}, + {pos: [4, 3, 1], state: "minecraft:air"}, + {pos: [4, 3, 2], state: "minecraft:air"}, + {pos: [4, 3, 3], state: "minecraft:air"}, + {pos: [4, 3, 4], state: "minecraft:air"}, + {pos: [0, 4, 0], state: "minecraft:air"}, + {pos: [0, 4, 1], state: "minecraft:air"}, + {pos: [0, 4, 2], state: "minecraft:air"}, + {pos: [0, 4, 3], state: "minecraft:air"}, + {pos: [0, 4, 4], state: "minecraft:air"}, + {pos: [1, 4, 0], state: "minecraft:air"}, + {pos: [1, 4, 1], state: "minecraft:air"}, + {pos: [1, 4, 2], state: "minecraft:air"}, + {pos: [1, 4, 3], state: "minecraft:air"}, + {pos: [1, 4, 4], state: "minecraft:air"}, + {pos: [2, 4, 0], state: "minecraft:air"}, + {pos: [2, 4, 1], state: "minecraft:air"}, + {pos: [2, 4, 2], state: "minecraft:air"}, + {pos: [2, 4, 3], state: "minecraft:air"}, + {pos: [2, 4, 4], state: "minecraft:air"}, + {pos: [3, 4, 0], state: "minecraft:air"}, + {pos: [3, 4, 1], state: "minecraft:air"}, + {pos: [3, 4, 2], state: "minecraft:air"}, + {pos: [3, 4, 3], state: "minecraft:air"}, + {pos: [3, 4, 4], state: "minecraft:air"}, + {pos: [4, 4, 0], state: "minecraft:air"}, + {pos: [4, 4, 1], state: "minecraft:air"}, + {pos: [4, 4, 2], state: "minecraft:air"}, + {pos: [4, 4, 3], state: "minecraft:air"}, + {pos: [4, 4, 4], state: "minecraft:air"} + ], + entities: [], + palette: [ + "minecraft:polished_andesite", + "minecraft:stone", + "minecraft:air", + "computercraft:turtle_normal{facing:south,waterlogged:false}" + ] +} diff --git a/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.place_use_reach_limit.snbt b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.place_use_reach_limit.snbt new file mode 100644 index 000000000..aaf9f9181 --- /dev/null +++ b/projects/common/src/testMod/resources/data/cctest/structures/turtle_test.place_use_reach_limit.snbt @@ -0,0 +1,139 @@ +{ + DataVersion: 3337, + size: [5, 5, 5], + data: [ + {pos: [0, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [0, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [1, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [2, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [3, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 0], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 1], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 2], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 3], state: "minecraft:polished_andesite"}, + {pos: [4, 0, 4], state: "minecraft:polished_andesite"}, + {pos: [0, 1, 0], state: "minecraft:air"}, + {pos: [0, 1, 1], state: "minecraft:air"}, + {pos: [0, 1, 2], state: "minecraft:air"}, + {pos: [0, 1, 3], state: "minecraft:air"}, + {pos: [0, 1, 4], state: "minecraft:air"}, + {pos: [1, 1, 0], state: "minecraft:air"}, + {pos: [1, 1, 1], state: "minecraft:air"}, + {pos: [1, 1, 2], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 1, 3], state: "minecraft:air"}, + {pos: [1, 1, 4], state: "minecraft:air"}, + {pos: [2, 1, 0], state: "minecraft:air"}, + {pos: [2, 1, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 1, 2], state: "minecraft:air"}, + {pos: [2, 1, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 1, 4], state: "minecraft:air"}, + {pos: [3, 1, 0], state: "minecraft:air"}, + {pos: [3, 1, 1], state: "minecraft:air"}, + {pos: [3, 1, 2], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 1, 3], state: "minecraft:air"}, + {pos: [3, 1, 4], state: "minecraft:air"}, + {pos: [4, 1, 0], state: "minecraft:air"}, + {pos: [4, 1, 1], state: "minecraft:air"}, + {pos: [4, 1, 2], state: "minecraft:air"}, + {pos: [4, 1, 3], state: "minecraft:air"}, + {pos: [4, 1, 4], state: "minecraft:air"}, + {pos: [0, 2, 0], state: "minecraft:air"}, + {pos: [0, 2, 1], state: "minecraft:air"}, + {pos: [0, 2, 2], state: "minecraft:air"}, + {pos: [0, 2, 3], state: "minecraft:air"}, + {pos: [0, 2, 4], state: "minecraft:air"}, + {pos: [1, 2, 0], state: "minecraft:air"}, + {pos: [1, 2, 1], state: "minecraft:air"}, + {pos: [1, 2, 2], state: "minecraft:air"}, + {pos: [1, 2, 3], state: "minecraft:air"}, + {pos: [1, 2, 4], state: "minecraft:air"}, + {pos: [2, 2, 0], state: "minecraft:air"}, + {pos: [2, 2, 1], state: "minecraft:air"}, + {pos: [2, 2, 2], state: "minecraft:ladder{facing:north,waterlogged:false}"}, + {pos: [2, 2, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 2, 4], state: "minecraft:air"}, + {pos: [3, 2, 0], state: "minecraft:air"}, + {pos: [3, 2, 1], state: "minecraft:air"}, + {pos: [3, 2, 2], state: "minecraft:air"}, + {pos: [3, 2, 3], state: "minecraft:air"}, + {pos: [3, 2, 4], state: "minecraft:air"}, + {pos: [4, 2, 0], state: "minecraft:air"}, + {pos: [4, 2, 1], state: "minecraft:air"}, + {pos: [4, 2, 2], state: "minecraft:air"}, + {pos: [4, 2, 3], state: "minecraft:air"}, + {pos: [4, 2, 4], state: "minecraft:air"}, + {pos: [0, 3, 0], state: "minecraft:air"}, + {pos: [0, 3, 1], state: "minecraft:air"}, + {pos: [0, 3, 2], state: "minecraft:air"}, + {pos: [0, 3, 3], state: "minecraft:air"}, + {pos: [0, 3, 4], state: "minecraft:air"}, + {pos: [1, 3, 0], state: "minecraft:air"}, + {pos: [1, 3, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 3, 2], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 3, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 3, 4], state: "minecraft:air"}, + {pos: [2, 3, 0], state: "minecraft:air"}, + {pos: [2, 3, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 3, 2], state: "minecraft:air"}, + {pos: [2, 3, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 3, 4], state: "minecraft:air"}, + {pos: [3, 3, 0], state: "minecraft:air"}, + {pos: [3, 3, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 3, 2], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 3, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 3, 4], state: "minecraft:air"}, + {pos: [4, 3, 0], state: "minecraft:air"}, + {pos: [4, 3, 1], state: "minecraft:air"}, + {pos: [4, 3, 2], state: "minecraft:air"}, + {pos: [4, 3, 3], state: "minecraft:air"}, + {pos: [4, 3, 4], state: "minecraft:air"}, + {pos: [0, 4, 0], state: "minecraft:air"}, + {pos: [0, 4, 1], state: "minecraft:air"}, + {pos: [0, 4, 2], state: "minecraft:air"}, + {pos: [0, 4, 3], state: "minecraft:air"}, + {pos: [0, 4, 4], state: "minecraft:air"}, + {pos: [1, 4, 0], state: "minecraft:air"}, + {pos: [1, 4, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 4, 2], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 4, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [1, 4, 4], state: "minecraft:air"}, + {pos: [2, 4, 0], state: "minecraft:air"}, + {pos: [2, 4, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 4, 2], state: "computercraft:turtle_normal{facing:north,waterlogged:false}", nbt: {ComputerId: 1, Fuel: 0, Items: [{Count: 1b, Slot: 0b, id: "minecraft:water_bucket"}], Label: "turtle_test.place_use_reach_limit", On: 1b, Slot: 0, id: "computercraft:turtle_normal"}}, + {pos: [2, 4, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [2, 4, 4], state: "minecraft:air"}, + {pos: [3, 4, 0], state: "minecraft:air"}, + {pos: [3, 4, 1], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 4, 2], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 4, 3], state: "minecraft:light_gray_stained_glass"}, + {pos: [3, 4, 4], state: "minecraft:air"}, + {pos: [4, 4, 0], state: "minecraft:air"}, + {pos: [4, 4, 1], state: "minecraft:air"}, + {pos: [4, 4, 2], state: "minecraft:air"}, + {pos: [4, 4, 3], state: "minecraft:air"}, + {pos: [4, 4, 4], state: "minecraft:air"} + ], + entities: [], + palette: [ + "minecraft:polished_andesite", + "minecraft:light_gray_stained_glass", + "minecraft:air", + "minecraft:ladder{facing:north,waterlogged:false}", + "computercraft:turtle_normal{facing:north,waterlogged:false}" + ] +} diff --git a/projects/core-api/src/main/java/dan200/computercraft/api/lua/IArguments.java b/projects/core-api/src/main/java/dan200/computercraft/api/lua/IArguments.java index 3f3e0f894..336f0b926 100644 --- a/projects/core-api/src/main/java/dan200/computercraft/api/lua/IArguments.java +++ b/projects/core-api/src/main/java/dan200/computercraft/api/lua/IArguments.java @@ -479,9 +479,11 @@ public interface IArguments { * yourself. * * @return An {@link IArguments} instance which can escape the current scope. May be {@code this}. - * @throws LuaException For the same reasons as {@link #get(int)}. + * @throws LuaException For the same reasons as {@link #get(int)}. + * @throws IllegalStateException If marking these arguments as escaping outside the scope of the original function. */ default IArguments escapes() throws LuaException { + // TODO(1.21.0): Make this return void, require that it mutates this. return this; } } diff --git a/projects/core/src/main/java/dan200/computercraft/core/ComputerContext.java b/projects/core/src/main/java/dan200/computercraft/core/ComputerContext.java index 305b598a9..b7fefae86 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/ComputerContext.java +++ b/projects/core/src/main/java/dan200/computercraft/core/ComputerContext.java @@ -4,13 +4,26 @@ package dan200.computercraft.core; +import dan200.computercraft.api.lua.ILuaAPIFactory; +import dan200.computercraft.core.asm.GenericMethod; +import dan200.computercraft.core.asm.LuaMethodSupplier; +import dan200.computercraft.core.asm.PeripheralMethodSupplier; import dan200.computercraft.core.computer.ComputerThread; import dan200.computercraft.core.computer.GlobalEnvironment; import dan200.computercraft.core.computer.mainthread.MainThreadScheduler; +import dan200.computercraft.core.computer.mainthread.NoWorkMainThreadScheduler; import dan200.computercraft.core.lua.CobaltLuaMachine; import dan200.computercraft.core.lua.ILuaMachine; +import dan200.computercraft.core.lua.MachineEnvironment; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.MethodSupplier; +import dan200.computercraft.core.methods.PeripheralMethod; import javax.annotation.CheckReturnValue; +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeUnit; /** @@ -20,27 +33,24 @@ public final class ComputerContext { private final GlobalEnvironment globalEnvironment; private final ComputerThread computerScheduler; private final MainThreadScheduler mainThreadScheduler; - private final ILuaMachine.Factory factory; + private final ILuaMachine.Factory luaFactory; + private final List apiFactories; + private final MethodSupplier luaMethods; + private final MethodSupplier peripheralMethods; - public ComputerContext( + ComputerContext( GlobalEnvironment globalEnvironment, ComputerThread computerScheduler, - MainThreadScheduler mainThreadScheduler, ILuaMachine.Factory factory + MainThreadScheduler mainThreadScheduler, ILuaMachine.Factory luaFactory, + List apiFactories, MethodSupplier luaMethods, + MethodSupplier peripheralMethods ) { this.globalEnvironment = globalEnvironment; this.computerScheduler = computerScheduler; this.mainThreadScheduler = mainThreadScheduler; - this.factory = factory; - } - - /** - * Create a default {@link ComputerContext} with the given global environment. - * - * @param environment The current global environment. - * @param threads The number of threads to use for the {@link #computerScheduler()} - * @param mainThreadScheduler The main thread scheduler to use. - */ - public ComputerContext(GlobalEnvironment environment, int threads, MainThreadScheduler mainThreadScheduler) { - this(environment, new ComputerThread(threads), mainThreadScheduler, CobaltLuaMachine::new); + this.luaFactory = luaFactory; + this.apiFactories = apiFactories; + this.luaMethods = luaMethods; + this.peripheralMethods = peripheralMethods; } /** @@ -77,7 +87,35 @@ public final class ComputerContext { * @return The current Lua machine factory. */ public ILuaMachine.Factory luaFactory() { - return factory; + return luaFactory; + } + + /** + * Additional APIs to inject into each computer. + * + * @return All available API factories. + */ + public List apiFactories() { + return apiFactories; + } + + /** + * Get the {@link MethodSupplier} used to find methods on Lua values. + * + * @return The {@link LuaMethod} method supplier. + * @see MachineEnvironment#luaMethods() + */ + public MethodSupplier luaMethods() { + return luaMethods; + } + + /** + * Get the {@link MethodSupplier} used to find methods on peripherals. + * + * @return The {@link PeripheralMethod} method supplier. + */ + public MethodSupplier peripheralMethods() { + return peripheralMethods; } /** @@ -106,4 +144,119 @@ public final class ComputerContext { throw new IllegalStateException("Failed to shutdown ComputerContext in time."); } } + + /** + * Create a new {@linkplain Builder builder} for a computer context. + * + * @param environment The {@linkplain ComputerContext#globalEnvironment() global environment} for this context. + * @return The builder for a new context. + */ + public static Builder builder(GlobalEnvironment environment) { + return new Builder(environment); + } + + /** + * A builder for a {@link ComputerContext}. + * + * @see ComputerContext#builder(GlobalEnvironment) + */ + public static class Builder { + private final GlobalEnvironment environment; + private int threads = 1; + private @Nullable MainThreadScheduler mainThreadScheduler; + private @Nullable ILuaMachine.Factory luaFactory; + private @Nullable List apiFactories; + private @Nullable List genericMethods; + + Builder(GlobalEnvironment environment) { + this.environment = environment; + } + + /** + * Set the number of threads the {@link ComputerThread} will use. + * + * @param threads The number of threads to use. + * @return {@code this}, for chaining + * @see ComputerContext#computerScheduler() + */ + public Builder computerThreads(int threads) { + if (threads < 1) throw new IllegalArgumentException("Threads must be >= 1"); + this.threads = threads; + return this; + } + + /** + * Set the {@link MainThreadScheduler} for this context. + * + * @param scheduler The main thread scheduler. + * @return {@code this}, for chaining + * @see ComputerContext#mainThreadScheduler() + */ + public Builder mainThreadScheduler(MainThreadScheduler scheduler) { + Objects.requireNonNull(scheduler); + if (mainThreadScheduler != null) throw new IllegalStateException("Main-thread scheduler already specified"); + mainThreadScheduler = scheduler; + return this; + } + + /** + * Set the {@link ILuaMachine.Factory} for this context. + * + * @param factory The Lua machine factory. + * @return {@code this}, for chaining + * @see ComputerContext#luaFactory() + */ + public Builder luaFactory(ILuaMachine.Factory factory) { + Objects.requireNonNull(factory); + if (luaFactory != null) throw new IllegalStateException("Main-thread scheduler already specified"); + luaFactory = factory; + return this; + } + + /** + * Set the additional {@linkplain ILuaAPIFactory APIs} to add to each computer. + * + * @param apis A list of API factories. + * @return {@code this}, for chaining + * @see ComputerContext#apiFactories() + */ + public Builder apiFactories(Collection apis) { + Objects.requireNonNull(apis); + if (apiFactories != null) throw new IllegalStateException("Main-thread scheduler already specified"); + apiFactories = List.copyOf(apis); + return this; + } + + /** + * Set the set of {@link GenericMethod}s used by the {@linkplain MethodSupplier method suppliers}. + * + * @param genericMethods A list of API factories. + * @return {@code this}, for chaining + * @see ComputerContext#luaMethods() + * @see ComputerContext#peripheralMethods() + */ + public Builder genericMethods(Collection genericMethods) { + Objects.requireNonNull(genericMethods); + if (this.genericMethods != null) throw new IllegalStateException("Main-thread scheduler already specified"); + this.genericMethods = List.copyOf(genericMethods); + return this; + } + + /** + * Create a new {@link ComputerContext}. + * + * @return The newly created context. + */ + public ComputerContext build() { + return new ComputerContext( + environment, + new ComputerThread(threads), + mainThreadScheduler == null ? new NoWorkMainThreadScheduler() : mainThreadScheduler, + luaFactory == null ? CobaltLuaMachine::new : luaFactory, + apiFactories == null ? List.of() : apiFactories, + LuaMethodSupplier.create(genericMethods == null ? List.of() : genericMethods), + PeripheralMethodSupplier.create(genericMethods == null ? List.of() : genericMethods) + ); + } + } } diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java b/projects/core/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java index 9f19cf95f..a8b3e9112 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/IAPIEnvironment.java @@ -10,9 +10,9 @@ import dan200.computercraft.core.computer.ComputerEnvironment; import dan200.computercraft.core.computer.ComputerSide; import dan200.computercraft.core.computer.GlobalEnvironment; import dan200.computercraft.core.filesystem.FileSystem; -import dan200.computercraft.core.metrics.OperationTimer; import dan200.computercraft.core.metrics.Metric; import dan200.computercraft.core.metrics.MetricsObserver; +import dan200.computercraft.core.metrics.OperationTimer; import dan200.computercraft.core.terminal.Terminal; import javax.annotation.Nullable; diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/OSAPI.java b/projects/core/src/main/java/dan200/computercraft/core/apis/OSAPI.java index 0d2e2347f..86b395e9b 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/OSAPI.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/OSAPI.java @@ -132,7 +132,8 @@ public class OSAPI implements ILuaAPI { * @param name The name of the event to queue. * @param args The parameters of the event. * @cc.tparam string name The name of the event to queue. - * @cc.param ... The parameters of the event. + * @cc.param ... The parameters of the event. These can be any primitive type (boolean, number, string) as well as + * tables. Other types (like functions), as well as metatables, will not be preserved. * @cc.see os.pullEvent To pull the event queued */ @LuaFunction diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java b/projects/core/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java index 5c8ab85d4..70fdb0b1c 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/PeripheralAPI.java @@ -7,13 +7,12 @@ package dan200.computercraft.core.apis; import dan200.computercraft.api.filesystem.Mount; import dan200.computercraft.api.filesystem.WritableMount; import dan200.computercraft.api.lua.*; -import dan200.computercraft.api.peripheral.IDynamicPeripheral; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.NotAttachedException; import dan200.computercraft.api.peripheral.WorkMonitor; -import dan200.computercraft.core.asm.LuaMethod; -import dan200.computercraft.core.asm.PeripheralMethod; import dan200.computercraft.core.computer.ComputerSide; +import dan200.computercraft.core.methods.MethodSupplier; +import dan200.computercraft.core.methods.PeripheralMethod; import dan200.computercraft.core.metrics.Metrics; import dan200.computercraft.core.util.LuaUtil; @@ -44,7 +43,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange type = Objects.requireNonNull(peripheral.getType(), "Peripheral type cannot be null"); additionalTypes = peripheral.getAdditionalTypes(); - methodMap = PeripheralAPI.getMethods(peripheral); + methodMap = peripheralMethods.getSelfMethods(peripheral); } public IPeripheral getPeripheral() { @@ -172,11 +171,13 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange } private final IAPIEnvironment environment; + private final MethodSupplier peripheralMethods; private final PeripheralWrapper[] peripherals = new PeripheralWrapper[6]; private boolean running; - public PeripheralAPI(IAPIEnvironment environment) { + public PeripheralAPI(IAPIEnvironment environment, MethodSupplier peripheralMethods) { this.environment = environment; + this.peripheralMethods = peripheralMethods; this.environment.setPeripheralChangeListener(this); running = false; } @@ -315,21 +316,4 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange throw e; } } - - public static Map getMethods(IPeripheral peripheral) { - var dynamicMethods = peripheral instanceof IDynamicPeripheral - ? Objects.requireNonNull(((IDynamicPeripheral) peripheral).getMethodNames(), "Peripheral methods cannot be null") - : LuaMethod.EMPTY_METHODS; - - var methods = PeripheralMethod.GENERATOR.getMethods(peripheral.getClass()); - - Map methodMap = new HashMap<>(methods.size() + dynamicMethods.length); - for (var i = 0; i < dynamicMethods.length; i++) { - methodMap.put(dynamicMethods[i], PeripheralMethod.DYNAMIC.get(i)); - } - for (var method : methods) { - methodMap.put(method.getName(), method.getMethod()); - } - return methodMap; - } } diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/TableHelper.java b/projects/core/src/main/java/dan200/computercraft/core/apis/TableHelper.java index 9f3f505f0..d4ed5dc9f 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/TableHelper.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/TableHelper.java @@ -103,7 +103,7 @@ public final class TableHelper { public static Optional optRealField(Map table, String key) throws LuaException { var value = table.get(key); - if(value == null) { + if (value == null) { return Optional.empty(); } else { return Optional.of(getRealField(table, key)); diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java b/projects/core/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java index 517e67790..9a18f4b3d 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java @@ -27,7 +27,6 @@ import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.ReadTimeoutException; import io.netty.handler.traffic.AbstractTrafficShapingHandler; import io.netty.handler.traffic.GlobalTrafficShapingHandler; -import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -193,7 +192,7 @@ public final class NetworkUtils { * @return The SSL handler. * @see io.netty.handler.ssl.SslHandler */ - private static SslHandler makeSslHandler(SocketChannel ch, @NotNull SslContext sslContext, int timeout, String peerHost, int peerPort) { + private static SslHandler makeSslHandler(SocketChannel ch, SslContext sslContext, int timeout, String peerHost, int peerPort) { var handler = sslContext.newHandler(ch.alloc(), peerHost, peerPort); if (timeout > 0) handler.setHandshakeTimeoutMillis(timeout); return handler; diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressPredicate.java b/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressPredicate.java index ce4760452..1dfd09819 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressPredicate.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressPredicate.java @@ -5,13 +5,14 @@ package dan200.computercraft.core.apis.http.options; import com.google.common.net.InetAddresses; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; +import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.Set; import java.util.regex.Pattern; +import java.util.stream.Collectors; /** * A predicate on an address. Matches against a domain and an ip address. @@ -19,8 +20,6 @@ import java.util.regex.Pattern; * @see AddressRule#apply(Iterable, String, InetSocketAddress) for the actual handling of this rule. */ interface AddressPredicate { - Logger LOG = LoggerFactory.getLogger(AddressPredicate.class); - default boolean matches(String domain) { return false; } @@ -51,28 +50,25 @@ interface AddressPredicate { return true; } - @Nullable public static HostRange parse(String addressStr, String prefixSizeStr) { int prefixSize; try { prefixSize = Integer.parseInt(prefixSizeStr); } catch (NumberFormatException e) { - LOG.error( - "Malformed http whitelist/blacklist entry '{}': Cannot extract size of CIDR mask from '{}'.", + throw new InvalidRuleException(String.format( + "Invalid host host '%s': Cannot extract size of CIDR mask from '%s'.", addressStr + '/' + prefixSizeStr, prefixSizeStr - ); - return null; + )); } InetAddress address; try { address = InetAddresses.forString(addressStr); } catch (IllegalArgumentException e) { - LOG.error( - "Malformed http whitelist/blacklist entry '{}': Cannot extract IP address from '{}'.", - addressStr + '/' + prefixSizeStr, prefixSizeStr - ); - return null; + throw new InvalidRuleException(String.format( + "Invalid host '%s': Cannot extract IP address from '%s'.", + addressStr + '/' + prefixSizeStr, addressStr + )); } // Mask the bytes of the IP address. @@ -112,16 +108,38 @@ interface AddressPredicate { } } - final class PrivatePattern implements AddressPredicate { static final PrivatePattern INSTANCE = new PrivatePattern(); + private static final Set additionalAddresses = Arrays.stream(new String[]{ + // Block various cloud providers internal IPs. + "100.100.100.200", // Alibaba + "192.0.0.192", // Oracle + }).map(InetAddresses::forString).collect(Collectors.toUnmodifiableSet()); + @Override public boolean matches(InetAddress socketAddress) { - return socketAddress.isAnyLocalAddress() - || socketAddress.isLoopbackAddress() - || socketAddress.isLinkLocalAddress() - || socketAddress.isSiteLocalAddress(); + return + socketAddress.isAnyLocalAddress() // 0.0.0.0, ::0 + || socketAddress.isLoopbackAddress() // 127.0.0.0/8, ::1 + || socketAddress.isLinkLocalAddress() // 169.254.0.0/16, fe80::/10 + || socketAddress.isSiteLocalAddress() // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fec0::/10 + || socketAddress.isMulticastAddress() // 224.0.0.0/4, ff00::/8 + || isUniqueLocalAddress(socketAddress) // fd00::/8 + || additionalAddresses.contains(socketAddress); + } + + /** + * Determine if an IP address lives inside the ULA address range. + * + * @param address The IP address to test. + * @return Whether this address sits in the ULA address range. + * @see Unique local address on Wikipedia + */ + private boolean isUniqueLocalAddress(InetAddress address) { + // ULA is actually defined as fc00::/7 (so both fc00::/8 and fd00::/8). However, only the latter is actually + // defined right now, so let's be conservative. + return address instanceof Inet6Address && (address.getAddress()[0] & 0xff) == 0xfd; } } diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java b/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java index 96857b967..3673e8da0 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java @@ -35,14 +35,13 @@ public final class AddressRule { this.port = port; } - @Nullable public static AddressRule parse(String filter, OptionalInt port, PartialOptions partial) { var cidr = filter.indexOf('/'); if (cidr >= 0) { var addressStr = filter.substring(0, cidr); var prefixSizeStr = filter.substring(cidr + 1); var range = HostRange.parse(addressStr, prefixSizeStr); - return range == null ? null : new AddressRule(range, port, partial); + return new AddressRule(range, port, partial); } else if (filter.equalsIgnoreCase("$private")) { return new AddressRule(PrivatePattern.INSTANCE, port, partial); } else { diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/InvalidRuleException.java b/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/InvalidRuleException.java new file mode 100644 index 000000000..ce9f55c10 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/http/options/InvalidRuleException.java @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.apis.http.options; + +import java.io.Serial; +import java.util.OptionalInt; + +/** + * Throw when a {@link AddressRule} cannot be parsed. + * + * @see AddressRule#parse(String, OptionalInt, PartialOptions) + * @see AddressPredicate.HostRange#parse(String, String) + */ +public class InvalidRuleException extends RuntimeException { + @Serial + private static final long serialVersionUID = 1303376302865132758L; + + public InvalidRuleException(String message) { + super(message); + } +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java b/projects/core/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java index dba9683a6..e82e5c3ad 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java +++ b/projects/core/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java @@ -10,7 +10,7 @@ import dan200.computercraft.core.apis.HTTPAPI; import dan200.computercraft.core.apis.handles.BinaryReadableHandle; import dan200.computercraft.core.apis.handles.EncodedReadableHandle; import dan200.computercraft.core.apis.handles.HandleGeneric; -import dan200.computercraft.core.asm.ObjectSource; +import dan200.computercraft.core.methods.ObjectSource; import java.util.Collections; import java.util.Map; diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/Generator.java b/projects/core/src/main/java/dan200/computercraft/core/asm/Generator.java index ea2870384..7a973f5b3 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/Generator.java +++ b/projects/core/src/main/java/dan200/computercraft/core/asm/Generator.java @@ -10,7 +10,6 @@ import com.google.common.cache.LoadingCache; import com.google.common.primitives.Primitives; import com.google.common.reflect.TypeToken; import dan200.computercraft.api.lua.*; -import dan200.computercraft.api.peripheral.PeripheralType; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; @@ -20,17 +19,14 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import static org.objectweb.asm.Opcodes.*; -public final class Generator { +final class Generator { private static final Logger LOG = LoggerFactory.getLogger(Generator.class); private static final AtomicInteger METHOD_ID = new AtomicInteger(); @@ -54,10 +50,6 @@ public final class Generator { private final Function wrap; - private final LoadingCache, List>> classCache = CacheBuilder - .newBuilder() - .build(CacheLoader.from(catching(this::build, Collections.emptyList()))); - private final LoadingCache> methodCache = CacheBuilder .newBuilder() .build(CacheLoader.from(catching(this::build, Optional.empty()))); @@ -74,58 +66,8 @@ public final class Generator { this.methodDesc = methodDesc.toString(); } - public List> getMethods(Class klass) { - try { - return classCache.get(klass); - } catch (ExecutionException e) { - LOG.error("Error getting methods for {}.", klass.getName(), e.getCause()); - return Collections.emptyList(); - } - } - - private List> build(Class klass) { - ArrayList> methods = null; - for (var method : klass.getMethods()) { - var annotation = method.getAnnotation(LuaFunction.class); - if (annotation == null) continue; - - if (Modifier.isStatic(method.getModifiers())) { - LOG.warn("LuaFunction method {}.{} should be an instance method.", method.getDeclaringClass(), method.getName()); - continue; - } - - var instance = methodCache.getUnchecked(method).orElse(null); - if (instance == null) continue; - - if (methods == null) methods = new ArrayList<>(); - addMethod(methods, method, annotation, null, instance); - } - - for (var method : GenericMethod.all()) { - if (!method.target.isAssignableFrom(klass)) continue; - - var instance = methodCache.getUnchecked(method.method).orElse(null); - if (instance == null) continue; - - if (methods == null) methods = new ArrayList<>(); - addMethod(methods, method.method, method.annotation, method.peripheralType, instance); - } - - if (methods == null) return Collections.emptyList(); - methods.trimToSize(); - return Collections.unmodifiableList(methods); - } - - private void addMethod(List> methods, Method method, LuaFunction annotation, @Nullable PeripheralType genericType, T instance) { - var names = annotation.value(); - var isSimple = method.getReturnType() != MethodResult.class && !annotation.mainThread(); - if (names.length == 0) { - methods.add(new NamedMethod<>(method.getName(), instance, isSimple, genericType)); - } else { - for (var name : names) { - methods.add(new NamedMethod<>(name, instance, isSimple, genericType)); - } - } + Optional getMethod(Method method) { + return methodCache.getUnchecked(method); } private Optional build(Method method) { @@ -336,7 +278,7 @@ public final class Generator { } @SuppressWarnings("Guava") - private static com.google.common.base.Function catching(Function function, U def) { + static com.google.common.base.Function catching(Function function, U def) { return x -> { try { return function.apply(x); diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/GenericMethod.java b/projects/core/src/main/java/dan200/computercraft/core/asm/GenericMethod.java index d7a8468bf..1e18b0a0b 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/GenericMethod.java +++ b/projects/core/src/main/java/dan200/computercraft/core/asm/GenericMethod.java @@ -14,16 +14,14 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import java.util.Objects; import java.util.stream.Stream; /** * A generic method is a method belonging to a {@link GenericSource} with a known target. */ -public class GenericMethod { +public final class GenericMethod { private static final Logger LOG = LoggerFactory.getLogger(GenericMethod.class); final Method method; @@ -31,37 +29,24 @@ public class GenericMethod { final Class target; final @Nullable PeripheralType peripheralType; - private static final List sources = new ArrayList<>(); - private static @Nullable List cache; - - GenericMethod(Method method, LuaFunction annotation, Class target, @Nullable PeripheralType peripheralType) { + private GenericMethod(Method method, LuaFunction annotation, Class target, @Nullable PeripheralType peripheralType) { this.method = method; this.annotation = annotation; this.target = target; this.peripheralType = peripheralType; } + public String name() { + return method.getName(); + } + /** * Find all public static methods annotated with {@link LuaFunction} which belong to a {@link GenericSource}. * + * @param source The given generic source. * @return All available generic methods. */ - static List all() { - if (cache != null) return cache; - return cache = sources.stream().flatMap(GenericMethod::getMethods).toList(); - } - - public static synchronized void register(GenericSource source) { - Objects.requireNonNull(source, "Source cannot be null"); - - if (cache != null) { - LOG.warn("Registering a generic source {} after cache has been built. This source will be ignored.", cache); - } - - sources.add(source); - } - - private static Stream getMethods(GenericSource source) { + public static Stream getMethods(GenericSource source) { Class klass = source.getClass(); var type = source instanceof GenericPeripheral generic ? generic.getType() : null; diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/IntCache.java b/projects/core/src/main/java/dan200/computercraft/core/asm/IntCache.java index 850c6303a..3509dfc4a 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/IntCache.java +++ b/projects/core/src/main/java/dan200/computercraft/core/asm/IntCache.java @@ -7,7 +7,7 @@ package dan200.computercraft.core.asm; import java.util.Arrays; import java.util.function.IntFunction; -public final class IntCache { +final class IntCache { private final IntFunction factory; private volatile Object[] cache = new Object[16]; diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/LuaMethod.java b/projects/core/src/main/java/dan200/computercraft/core/asm/LuaMethod.java deleted file mode 100644 index 7de22ff1b..000000000 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/LuaMethod.java +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers -// -// SPDX-License-Identifier: MPL-2.0 - -package dan200.computercraft.core.asm; - -import dan200.computercraft.api.lua.*; - -import java.util.Collections; - -public interface LuaMethod { - Generator GENERATOR = new Generator<>(LuaMethod.class, Collections.singletonList(ILuaContext.class), - m -> (target, context, args) -> context.executeMainThreadTask(() -> ResultHelpers.checkNormalResult(m.apply(target, context, args.escapes()))) - ); - - IntCache DYNAMIC = new IntCache<>( - method -> (instance, context, args) -> ((IDynamicLuaObject) instance).callMethod(context, method, args) - ); - - String[] EMPTY_METHODS = new String[0]; - - MethodResult apply(Object target, ILuaContext context, IArguments args) throws LuaException; -} diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/LuaMethodSupplier.java b/projects/core/src/main/java/dan200/computercraft/core/asm/LuaMethodSupplier.java new file mode 100644 index 000000000..7058ed5b5 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/asm/LuaMethodSupplier.java @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.asm; + +import dan200.computercraft.api.lua.IDynamicLuaObject; +import dan200.computercraft.api.lua.ILuaContext; +import dan200.computercraft.core.ComputerContext; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.MethodSupplier; + +import java.util.List; +import java.util.Objects; + +/** + * Provides a {@link MethodSupplier} for {@link LuaMethod}s. + *

+ * This is used by {@link ComputerContext} to construct {@linkplain ComputerContext#peripheralMethods() the context-wide + * method supplier}. It should not be used directly. + */ +public final class LuaMethodSupplier { + private static final Generator GENERATOR = new Generator<>(LuaMethod.class, List.of(ILuaContext.class), + m -> (target, context, args) -> { + var escArgs = args.escapes(); + return context.executeMainThreadTask(() -> ResultHelpers.checkNormalResult(m.apply(target, context, escArgs))); + } + ); + private static final IntCache DYNAMIC = new IntCache<>( + method -> (instance, context, args) -> ((IDynamicLuaObject) instance).callMethod(context, method, args) + ); + + private LuaMethodSupplier() { + } + + public static MethodSupplier create(List genericMethods) { + return new MethodSupplierImpl<>(genericMethods, GENERATOR, DYNAMIC, x -> x instanceof IDynamicLuaObject dynamic + ? Objects.requireNonNull(dynamic.getMethodNames(), "Dynamic methods cannot be null") + : null + ); + } +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/MethodSupplierImpl.java b/projects/core/src/main/java/dan200/computercraft/core/asm/MethodSupplierImpl.java new file mode 100644 index 000000000..44e5775e4 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/asm/MethodSupplierImpl.java @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.asm; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import dan200.computercraft.api.lua.LuaFunction; +import dan200.computercraft.api.lua.MethodResult; +import dan200.computercraft.api.peripheral.PeripheralType; +import dan200.computercraft.core.methods.MethodSupplier; +import dan200.computercraft.core.methods.NamedMethod; +import dan200.computercraft.core.methods.ObjectSource; +import org.jetbrains.annotations.VisibleForTesting; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.function.Function; + +import static dan200.computercraft.core.asm.Generator.catching; + +final class MethodSupplierImpl implements MethodSupplier { + private static final Logger LOG = LoggerFactory.getLogger(MethodSupplierImpl.class); + + private final List genericMethods; + private final Generator generator; + private final IntCache dynamic; + private final Function dynamicMethods; + + private final LoadingCache, List>> classCache = CacheBuilder + .newBuilder() + .build(CacheLoader.from(catching(this::getMethodsImpl, List.of()))); + + MethodSupplierImpl( + List genericMethods, + Generator generator, + IntCache dynamic, + Function dynamicMethods + ) { + this.genericMethods = genericMethods; + this.generator = generator; + this.dynamic = dynamic; + this.dynamicMethods = dynamicMethods; + } + + @Override + public boolean forEachSelfMethod(Object object, UntargetedConsumer consumer) { + var methods = getMethods(object.getClass()); + for (var method : methods) consumer.accept(method.name(), method.method(), method); + + var dynamicMethods = this.dynamicMethods.apply(object); + if (dynamicMethods != null) { + for (var i = 0; i < dynamicMethods.length; i++) consumer.accept(dynamicMethods[i], dynamic.get(i), null); + } + + return !methods.isEmpty() || dynamicMethods != null; + } + + @Override + public boolean forEachMethod(Object object, TargetedConsumer consumer) { + var methods = getMethods(object.getClass()); + for (var method : methods) consumer.accept(object, method.name(), method.method(), method); + + var hasMethods = !methods.isEmpty(); + + if (object instanceof ObjectSource source) { + for (var extra : source.getExtra()) { + var extraMethods = getMethods(extra.getClass()); + if (!extraMethods.isEmpty()) hasMethods = true; + for (var method : extraMethods) consumer.accept(object, method.name(), method.method(), method); + } + } + + var dynamicMethods = this.dynamicMethods.apply(object); + if (dynamicMethods != null) { + hasMethods = true; + for (var i = 0; i < dynamicMethods.length; i++) { + consumer.accept(object, dynamicMethods[i], dynamic.get(i), null); + } + } + + return hasMethods; + } + + @VisibleForTesting + List> getMethods(Class klass) { + try { + return classCache.get(klass); + } catch (ExecutionException e) { + LOG.error("Error getting methods for {}.", klass.getName(), e.getCause()); + return List.of(); + } + } + + private List> getMethodsImpl(Class klass) { + ArrayList> methods = null; + + // Find all methods on the current class + for (var method : klass.getMethods()) { + var annotation = method.getAnnotation(LuaFunction.class); + if (annotation == null) continue; + + if (Modifier.isStatic(method.getModifiers())) { + LOG.warn("LuaFunction method {}.{} should be an instance method.", method.getDeclaringClass(), method.getName()); + continue; + } + + var instance = generator.getMethod(method).orElse(null); + if (instance == null) continue; + + if (methods == null) methods = new ArrayList<>(); + addMethod(methods, method, annotation, null, instance); + } + + // Inject generic methods + for (var method : genericMethods) { + if (!method.target.isAssignableFrom(klass)) continue; + + var instance = generator.getMethod(method.method).orElse(null); + if (instance == null) continue; + + if (methods == null) methods = new ArrayList<>(); + addMethod(methods, method.method, method.annotation, method.peripheralType, instance); + } + + if (methods == null) return List.of(); + methods.trimToSize(); + return Collections.unmodifiableList(methods); + } + + private void addMethod(List> methods, Method method, LuaFunction annotation, @Nullable PeripheralType genericType, T instance) { + var names = annotation.value(); + var isSimple = method.getReturnType() != MethodResult.class && !annotation.mainThread(); + if (names.length == 0) { + methods.add(new NamedMethod<>(method.getName(), instance, isSimple, genericType)); + } else { + for (var name : names) { + methods.add(new NamedMethod<>(name, instance, isSimple, genericType)); + } + } + } + +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/NamedMethod.java b/projects/core/src/main/java/dan200/computercraft/core/asm/NamedMethod.java deleted file mode 100644 index 35f5c51c7..000000000 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/NamedMethod.java +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers -// -// SPDX-License-Identifier: MPL-2.0 - -package dan200.computercraft.core.asm; - -import dan200.computercraft.api.peripheral.PeripheralType; - -import javax.annotation.Nullable; - -public final class NamedMethod { - private final String name; - private final T method; - private final boolean nonYielding; - - private final @Nullable PeripheralType genericType; - - NamedMethod(String name, T method, boolean nonYielding, @Nullable PeripheralType genericType) { - this.name = name; - this.method = method; - this.nonYielding = nonYielding; - this.genericType = genericType; - } - - public String getName() { - return name; - } - - public T getMethod() { - return method; - } - - public boolean nonYielding() { - return nonYielding; - } - - @Nullable - public PeripheralType getGenericType() { - return genericType; - } -} diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/ObjectSource.java b/projects/core/src/main/java/dan200/computercraft/core/asm/ObjectSource.java deleted file mode 100644 index 3328c9b89..000000000 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/ObjectSource.java +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers -// -// SPDX-License-Identifier: MPL-2.0 - -package dan200.computercraft.core.asm; - -import java.util.function.BiConsumer; - -/** - * A Lua object which exposes additional methods. - *

- * This can be used to merge multiple objects together into one. Ideally this'd be part of the API, but I'm not entirely - * happy with the interface - something I'd like to think about first. - */ -public interface ObjectSource { - Iterable getExtra(); - - static void allMethods(Generator generator, Object object, BiConsumer> accept) { - for (var method : generator.getMethods(object.getClass())) accept.accept(object, method); - - if (object instanceof ObjectSource source) { - for (var extra : source.getExtra()) { - for (var method : generator.getMethods(extra.getClass())) accept.accept(extra, method); - } - } - } -} diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java b/projects/core/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java deleted file mode 100644 index f20b85998..000000000 --- a/projects/core/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers -// -// SPDX-License-Identifier: MPL-2.0 - -package dan200.computercraft.core.asm; - -import dan200.computercraft.api.lua.IArguments; -import dan200.computercraft.api.lua.ILuaContext; -import dan200.computercraft.api.lua.LuaException; -import dan200.computercraft.api.lua.MethodResult; -import dan200.computercraft.api.peripheral.IComputerAccess; -import dan200.computercraft.api.peripheral.IDynamicPeripheral; - -import java.util.Arrays; - -public interface PeripheralMethod { - Generator GENERATOR = new Generator<>(PeripheralMethod.class, Arrays.asList(ILuaContext.class, IComputerAccess.class), - m -> (target, context, computer, args) -> context.executeMainThreadTask(() -> ResultHelpers.checkNormalResult(m.apply(target, context, computer, args.escapes()))) - ); - - IntCache DYNAMIC = new IntCache<>( - method -> (instance, context, computer, args) -> ((IDynamicPeripheral) instance).callMethod(computer, context, method, args) - ); - - MethodResult apply(Object target, ILuaContext context, IComputerAccess computer, IArguments args) throws LuaException; -} diff --git a/projects/core/src/main/java/dan200/computercraft/core/asm/PeripheralMethodSupplier.java b/projects/core/src/main/java/dan200/computercraft/core/asm/PeripheralMethodSupplier.java new file mode 100644 index 000000000..ca7fa8ff3 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/asm/PeripheralMethodSupplier.java @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.asm; + +import dan200.computercraft.api.lua.ILuaContext; +import dan200.computercraft.api.peripheral.IComputerAccess; +import dan200.computercraft.api.peripheral.IDynamicPeripheral; +import dan200.computercraft.core.ComputerContext; +import dan200.computercraft.core.methods.MethodSupplier; +import dan200.computercraft.core.methods.PeripheralMethod; + +import java.util.List; +import java.util.Objects; + +/** + * Provides a {@link MethodSupplier} for {@link PeripheralMethod}s. + *

+ * This is used by {@link ComputerContext} to construct {@linkplain ComputerContext#peripheralMethods() the context-wide + * method supplier}. It should not be used directly. + */ +public class PeripheralMethodSupplier { + private static final Generator GENERATOR = new Generator<>(PeripheralMethod.class, List.of(ILuaContext.class, IComputerAccess.class), + m -> (target, context, computer, args) -> { + var escArgs = args.escapes(); + return context.executeMainThreadTask(() -> ResultHelpers.checkNormalResult(m.apply(target, context, computer, escArgs))); + } + ); + private static final IntCache DYNAMIC = new IntCache<>( + method -> (instance, context, computer, args) -> ((IDynamicPeripheral) instance).callMethod(computer, context, method, args) + ); + + public static MethodSupplier create(List genericMethods) { + return new MethodSupplierImpl<>(genericMethods, GENERATOR, DYNAMIC, x -> x instanceof IDynamicPeripheral dynamic + ? Objects.requireNonNull(dynamic.getMethodNames(), "Dynamic methods cannot be null") + : null + ); + } +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java b/projects/core/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java index 36220801e..3680ccba1 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java +++ b/projects/core/src/main/java/dan200/computercraft/core/computer/ComputerExecutor.java @@ -15,6 +15,8 @@ import dan200.computercraft.core.filesystem.FileSystemException; import dan200.computercraft.core.lua.ILuaMachine; import dan200.computercraft.core.lua.MachineEnvironment; import dan200.computercraft.core.lua.MachineException; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.MethodSupplier; import dan200.computercraft.core.metrics.Metrics; import dan200.computercraft.core.metrics.MetricsObserver; import dan200.computercraft.core.util.Colour; @@ -61,6 +63,7 @@ final class ComputerExecutor { private final MetricsObserver metrics; private final List apis = new ArrayList<>(); private final ComputerThread scheduler; + private final MethodSupplier luaMethods; final TimeoutState timeout; private @Nullable FileSystem fileSystem; @@ -168,6 +171,7 @@ final class ComputerExecutor { metrics = computerEnvironment.getMetrics(); luaFactory = context.luaFactory(); scheduler = context.computerScheduler(); + luaMethods = context.luaMethods(); timeout = new TimeoutState(scheduler); var environment = computer.getEnvironment(); @@ -176,12 +180,12 @@ final class ComputerExecutor { apis.add(new TermAPI(environment)); apis.add(new RedstoneAPI(environment)); apis.add(new FSAPI(environment)); - apis.add(new PeripheralAPI(environment)); + apis.add(new PeripheralAPI(environment, context.peripheralMethods())); apis.add(new OSAPI(environment)); if (CoreConfig.httpEnabled) apis.add(new HTTPAPI(environment)); // Load in the externally registered APIs. - for (var factory : ApiFactories.getAll()) { + for (var factory : context.apiFactories()) { var system = new ComputerSystem(environment); var api = factory.create(system); if (api != null) apis.add(new ApiWrapper(api, system)); @@ -382,6 +386,7 @@ final class ComputerExecutor { return luaFactory.create(new MachineEnvironment( new LuaContext(computer), metrics, timeout, () -> apis.stream().map(api -> api instanceof ApiWrapper wrapper ? wrapper.getDelegate() : api).iterator(), + luaMethods, computer.getGlobalEnvironment().getHostString() ), bios); } catch (IOException e) { diff --git a/projects/core/src/main/java/dan200/computercraft/core/lua/BasicFunction.java b/projects/core/src/main/java/dan200/computercraft/core/lua/BasicFunction.java index dc9593fb7..44924be57 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/lua/BasicFunction.java +++ b/projects/core/src/main/java/dan200/computercraft/core/lua/BasicFunction.java @@ -8,7 +8,7 @@ import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.core.Logging; -import dan200.computercraft.core.asm.LuaMethod; +import dan200.computercraft.core.methods.LuaMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.squiddev.cobalt.LuaError; diff --git a/projects/core/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java b/projects/core/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java index 40174a438..7d181d5fb 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java +++ b/projects/core/src/main/java/dan200/computercraft/core/lua/CobaltLuaMachine.java @@ -10,9 +10,9 @@ import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaFunction; import dan200.computercraft.core.CoreConfig; import dan200.computercraft.core.Logging; -import dan200.computercraft.core.asm.LuaMethod; -import dan200.computercraft.core.asm.ObjectSource; import dan200.computercraft.core.computer.TimeoutState; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.MethodSupplier; import dan200.computercraft.core.util.Nullability; import dan200.computercraft.core.util.SanitisedError; import org.slf4j.Logger; @@ -39,6 +39,7 @@ public class CobaltLuaMachine implements ILuaMachine { private final TimeoutState timeout; private final Runnable timeoutListener = this::updateTimeout; private final ILuaContext context; + private final MethodSupplier luaMethods; private final LuaState state; private final LuaThread mainRoutine; @@ -51,6 +52,7 @@ public class CobaltLuaMachine implements ILuaMachine { public CobaltLuaMachine(MachineEnvironment environment, InputStream bios) throws MachineException, IOException { timeout = environment.timeout(); context = environment.context(); + luaMethods = environment.luaMethods(); // Create an environment to run in var state = this.state = LuaState.builder() @@ -161,28 +163,13 @@ public class CobaltLuaMachine implements ILuaMachine { @Nullable private LuaTable wrapLuaObject(Object object) { - var dynamicMethods = object instanceof IDynamicLuaObject dynamic - ? Objects.requireNonNull(dynamic.getMethodNames(), "Methods cannot be null") - : LuaMethod.EMPTY_METHODS; - var table = new LuaTable(); - for (var i = 0; i < dynamicMethods.length; i++) { - var method = dynamicMethods[i]; - table.rawset(method, new ResultInterpreterFunction(this, LuaMethod.DYNAMIC.get(i), object, context, method)); - } + var found = luaMethods.forEachMethod(object, (target, name, method, info) -> + table.rawset(name, info != null && info.nonYielding() + ? new BasicFunction(this, method, target, context, name) + : new ResultInterpreterFunction(this, method, target, context, name))); - ObjectSource.allMethods(LuaMethod.GENERATOR, object, (instance, method) -> - table.rawset(method.getName(), method.nonYielding() - ? new BasicFunction(this, method.getMethod(), instance, context, method.getName()) - : new ResultInterpreterFunction(this, method.getMethod(), instance, context, method.getName()))); - - try { - if (table.next(Constants.NIL).first().isNil()) return null; - } catch (LuaError ignored) { - // next should never throw on nil. - } - - return table; + return found ? table : null; } private LuaValue toValue(@Nullable Object object, @Nullable IdentityHashMap values) { diff --git a/projects/core/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java b/projects/core/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java index f3b7f51d5..2e9d5529c 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java +++ b/projects/core/src/main/java/dan200/computercraft/core/lua/MachineEnvironment.java @@ -8,6 +8,8 @@ import dan200.computercraft.api.lua.ILuaAPI; import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.core.computer.GlobalEnvironment; import dan200.computercraft.core.computer.TimeoutState; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.MethodSupplier; import dan200.computercraft.core.metrics.MetricsObserver; /** @@ -18,6 +20,7 @@ import dan200.computercraft.core.metrics.MetricsObserver; * @param timeout The current timeout state. This should be used by the machine to interrupt its execution. * @param apis APIs to inject into the global environment. Each API should be converted into a Lua object * (following the same rules as any other value), and then set to all names in {@link ILuaAPI#getNames()}. + * @param luaMethods A {@link MethodSupplier} to find methods on returned values. * @param hostString A {@linkplain GlobalEnvironment#getHostString() host string} to identify the current environment. * @see ILuaMachine.Factory */ @@ -26,6 +29,7 @@ public record MachineEnvironment( MetricsObserver metrics, TimeoutState timeout, Iterable apis, + MethodSupplier luaMethods, String hostString ) { } diff --git a/projects/core/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java b/projects/core/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java index 04ed846f0..57e09f561 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java +++ b/projects/core/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java @@ -9,7 +9,7 @@ import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.core.Logging; -import dan200.computercraft.core.asm.LuaMethod; +import dan200.computercraft.core.methods.LuaMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.squiddev.cobalt.*; diff --git a/projects/core/src/main/java/dan200/computercraft/core/lua/VarargArguments.java b/projects/core/src/main/java/dan200/computercraft/core/lua/VarargArguments.java index 4289d2919..51b71de8c 100644 --- a/projects/core/src/main/java/dan200/computercraft/core/lua/VarargArguments.java +++ b/projects/core/src/main/java/dan200/computercraft/core/lua/VarargArguments.java @@ -191,6 +191,7 @@ final class VarargArguments implements IArguments { @Override public IArguments escapes() { if (escapes) return this; + if (isClosed()) throw new IllegalStateException("Cannot call escapes after IArguments has been closed."); var cache = this.cache; var typeNames = this.typeNames; diff --git a/projects/core/src/main/java/dan200/computercraft/core/methods/LuaMethod.java b/projects/core/src/main/java/dan200/computercraft/core/methods/LuaMethod.java new file mode 100644 index 000000000..58052f23a --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/methods/LuaMethod.java @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.methods; + +import dan200.computercraft.api.lua.*; + +/** + * A basic Lua function (i.e. one not associated with a peripheral) on some object (such as a {@link IDynamicLuaObject} + * or {@link ILuaAPI}. + *

+ * This interface is not typically implemented yourself, but instead generated from a {@link LuaFunction}-annotated + * method. + * + * @see NamedMethod + */ +@FunctionalInterface +public interface LuaMethod { + /** + * Apply this method. + * + * @param target The object instance that this method targets. + * @param context The Lua context for this function call. + * @param args Arguments to this function. + * @return The return call of this function. + * @throws LuaException Thrown by the underlying method call. + * @see IDynamicLuaObject#callMethod(ILuaContext, int, IArguments) + */ + MethodResult apply(Object target, ILuaContext context, IArguments args) throws LuaException; +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/methods/MethodSupplier.java b/projects/core/src/main/java/dan200/computercraft/core/methods/MethodSupplier.java new file mode 100644 index 000000000..13f45b915 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/methods/MethodSupplier.java @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.methods; + +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; + +/** + * Finds methods available on an object and yields them. + * + * @param The type of method, such as {@link LuaMethod} or {@link PeripheralMethod}. + */ +public interface MethodSupplier { + /** + * Iterate over methods available on an object, ignoring {@link ObjectSource}s. + * + * @param object The object to find methods for. + * @param consumer The consumer to call for each method. + * @return Whether any methods were found. + */ + boolean forEachSelfMethod(Object object, UntargetedConsumer consumer); + + /** + * Generate a map of all methods targeting the current object, ignoring {@link ObjectSource}s. + * + * @param object The object to find methods for. + * @return A map of all methods on the object. + */ + default Map getSelfMethods(Object object) { + var map = new HashMap(); + forEachSelfMethod(object, (n, m, i) -> map.put(n, m)); + return map; + } + + /** + * Iterate over all methods on an object, including {@link ObjectSource}s. + * + * @param object The object to find methods for. + * @param consumer The consumer to call for each method. + * @return Whether any methods were found. + */ + boolean forEachMethod(Object object, TargetedConsumer consumer); + + /** + * A function which is called for each method on an object. + * + * @param The type of method, such as {@link LuaMethod} or {@link PeripheralMethod}. + * @see #forEachSelfMethod(Object, UntargetedConsumer) + */ + @FunctionalInterface + interface UntargetedConsumer { + /** + * Consume a method on an object. + * + * @param name The name of this method. + * @param method The actual method definition. + * @param info Additional information about the method, such as whether it will yield. May be {@code null}. + */ + void accept(String name, T method, @Nullable NamedMethod info); + } + + /** + * A function which is called for each method on an object and possibly nested objects. + * + * @param The type of method, such as {@link LuaMethod} or {@link PeripheralMethod}. + * @see #forEachMethod(Object, TargetedConsumer) + */ + @FunctionalInterface + interface TargetedConsumer { + /** + * Consume a method on an object. + * + * @param object The object this method targets, should be passed to the method's {@code apply(...)} function. + * @param name The name of this method. + * @param method The actual method definition. + * @param info Additional information about the method, such as whether it will yield. May be {@code null}. + */ + void accept(Object object, String name, T method, @Nullable NamedMethod info); + } +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/methods/NamedMethod.java b/projects/core/src/main/java/dan200/computercraft/core/methods/NamedMethod.java new file mode 100644 index 000000000..f4f5de441 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/methods/NamedMethod.java @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.methods; + +import dan200.computercraft.api.lua.LuaFunction; +import dan200.computercraft.api.lua.MethodResult; +import dan200.computercraft.api.peripheral.GenericPeripheral; +import dan200.computercraft.api.peripheral.PeripheralType; + +import javax.annotation.Nullable; + +/** + * A method generated from a {@link LuaFunction}. + * + * @param name The name of this method. + * @param method The underlying method implementation. + * @param nonYielding If this method is guaranteed to never yield, and will always return a + * {@linkplain MethodResult#of(Object...) basic result}. + * @param genericType The peripheral type of this method. This is only set if this is a method on a + * {@link GenericPeripheral}. + * @param The type of method, either a {@link LuaMethod} or {@link PeripheralMethod}. + */ +public record NamedMethod(String name, T method, boolean nonYielding, @Nullable PeripheralType genericType) { +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/methods/ObjectSource.java b/projects/core/src/main/java/dan200/computercraft/core/methods/ObjectSource.java new file mode 100644 index 000000000..1ce62fe41 --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/methods/ObjectSource.java @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.methods; + +/** + * A Lua object which exposes additional methods. + *

+ * This can be used to merge multiple objects together into one. Ideally this'd be part of the API, but I'm not entirely + * happy with the interface - something I'd like to think about first. + */ +public interface ObjectSource { + Iterable getExtra(); +} diff --git a/projects/core/src/main/java/dan200/computercraft/core/methods/PeripheralMethod.java b/projects/core/src/main/java/dan200/computercraft/core/methods/PeripheralMethod.java new file mode 100644 index 000000000..0269146fe --- /dev/null +++ b/projects/core/src/main/java/dan200/computercraft/core/methods/PeripheralMethod.java @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2020 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.core.methods; + +import dan200.computercraft.api.lua.*; +import dan200.computercraft.api.peripheral.IComputerAccess; +import dan200.computercraft.api.peripheral.IDynamicPeripheral; +import dan200.computercraft.api.peripheral.IPeripheral; + +/** + * A Lua function associated with some peripheral. + *

+ * This interface is not typically implemented yourself, but instead generated from a {@link LuaFunction}-annotated + * method. + * + * @see NamedMethod + * @see IPeripheral + */ +@FunctionalInterface +public interface PeripheralMethod { + /** + * Apply this method. + * + * @param target The object instance that this method targets. + * @param context The Lua context for this function call. + * @param computer The interface to the computer that is making the call. + * @param args Arguments to this function. + * @return The return call of this function. + * @throws LuaException Thrown by the underlying method call. + * @see IDynamicPeripheral#callMethod(IComputerAccess, ILuaContext, int, IArguments) + */ + MethodResult apply(Object target, ILuaContext context, IComputerAccess computer, IArguments args) throws LuaException; +} diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/apis/settings.lua b/projects/core/src/main/resources/data/computercraft/lua/rom/apis/settings.lua index e4ebd7cff..d1481401b 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/apis/settings.lua +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/apis/settings.lua @@ -2,13 +2,32 @@ -- -- SPDX-License-Identifier: LicenseRef-CCPL ---- Read and write configuration options for CraftOS and your programs. --- --- By default, the settings API will load its configuration from the --- `/.settings` file. One can then use @{settings.save} to update the file. --- --- @module settings --- @since 1.78 +--[[- Read and write configuration options for CraftOS and your programs. + +When a computer starts, it reads the current value of settings from the +`/.settings` file. These values then may be @{settings.get|read} or +@{settings.set|modified}. + +:::caution +Calling @{settings.set} does _not_ update the settings file by default. You +_must_ call @{settings.save} to persist values. +::: + +@module settings +@since 1.78 +@usage Define an basic setting `123` and read its value. + + settings.define("my.setting", { + description = "An example setting", + default = 123, + type = number, + }) + print("my.setting = " .. settings.get("my.setting")) -- 123 + +You can then use the `set` program to change its value (e.g. `set my.setting 456`), +and then re-run the `example` program to check it has changed. + +]] local expect = dofile("rom/modules/main/cc/expect.lua") local type, expect, field = type, expect.expect, expect.field @@ -92,13 +111,19 @@ local function set_value(name, new) end end ---- Set the value of a setting. --- --- @tparam string name The name of the setting to set --- @param value The setting's value. This cannot be `nil`, and must be --- serialisable by @{textutils.serialize}. --- @throws If this value cannot be serialised --- @see settings.unset +--[[- Set the value of a setting. + +:::caution +Calling @{settings.set} does _not_ update the settings file by default. You +_must_ call @{settings.save} to persist values. +::: + +@tparam string name The name of the setting to set +@param value The setting's value. This cannot be `nil`, and must be +serialisable by @{textutils.serialize}. +@throws If this value cannot be serialised +@see settings.unset +]] function set(name, value) expect(1, name, "string") expect(2, value, "number", "string", "boolean", "table") diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/apis/window.lua b/projects/core/src/main/resources/data/computercraft/lua/rom/apis/window.lua index 302372a39..62c86d361 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/apis/window.lua +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/apis/window.lua @@ -131,11 +131,7 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) local sEmptyTextColor = tEmptyColorLines[nTextColor] local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor] for y = 1, nHeight do - tLines[y] = { - text = sEmptyText, - textColor = sEmptyTextColor, - backgroundColor = sEmptyBackgroundColor, - } + tLines[y] = { sEmptyText, sEmptyTextColor, sEmptyBackgroundColor } end for i = 0, 15 do @@ -165,7 +161,7 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) local function redrawLine(n) local tLine = tLines[n] parent.setCursorPos(nX, nY + n - 1) - parent.blit(tLine.text, tLine.textColor, tLine.backgroundColor) + parent.blit(tLine[1], tLine[2], tLine[3]) end local function redraw() @@ -188,9 +184,9 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) -- Modify line local tLine = tLines[nCursorY] if nStart == 1 and nEnd == nWidth then - tLine.text = sText - tLine.textColor = sTextColor - tLine.backgroundColor = sBackgroundColor + tLine[1] = sText + tLine[2] = sTextColor + tLine[3] = sBackgroundColor else local sClippedText, sClippedTextColor, sClippedBackgroundColor if nStart < 1 then @@ -210,9 +206,9 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) sClippedBackgroundColor = sBackgroundColor end - local sOldText = tLine.text - local sOldTextColor = tLine.textColor - local sOldBackgroundColor = tLine.backgroundColor + local sOldText = tLine[1] + local sOldTextColor = tLine[2] + local sOldBackgroundColor = tLine[3] local sNewText, sNewTextColor, sNewBackgroundColor if nStart > 1 then local nOldEnd = nStart - 1 @@ -231,9 +227,9 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) sNewBackgroundColor = sNewBackgroundColor .. string_sub(sOldBackgroundColor, nOldStart, nWidth) end - tLine.text = sNewText - tLine.textColor = sNewTextColor - tLine.backgroundColor = sNewBackgroundColor + tLine[1] = sNewText + tLine[2] = sNewTextColor + tLine[3] = sNewBackgroundColor end -- Redraw line @@ -280,11 +276,10 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) local sEmptyTextColor = tEmptyColorLines[nTextColor] local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor] for y = 1, nHeight do - tLines[y] = { - text = sEmptyText, - textColor = sEmptyTextColor, - backgroundColor = sEmptyBackgroundColor, - } + local line = tLines[y] + line[1] = sEmptyText + line[2] = sEmptyTextColor + line[3] = sEmptyBackgroundColor end if bVisible then redraw() @@ -295,14 +290,10 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) function window.clearLine() if nCursorY >= 1 and nCursorY <= nHeight then - local sEmptyText = sEmptySpaceLine - local sEmptyTextColor = tEmptyColorLines[nTextColor] - local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor] - tLines[nCursorY] = { - text = sEmptyText, - textColor = sEmptyTextColor, - backgroundColor = sEmptyBackgroundColor, - } + local line = tLines[nCursorY] + line[1] = sEmptySpaceLine + line[2] = tEmptyColorLines[nTextColor] + line[3] = tEmptyColorLines[nBackgroundColor] if bVisible then redrawLine(nCursorY) updateCursorColor() @@ -431,11 +422,7 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) if y >= 1 and y <= nHeight then tNewLines[newY] = tLines[y] else - tNewLines[newY] = { - text = sEmptyText, - textColor = sEmptyTextColor, - backgroundColor = sEmptyBackgroundColor, - } + tNewLines[newY] = { sEmptyText, sEmptyTextColor, sEmptyBackgroundColor } end end tLines = tNewLines @@ -478,7 +465,8 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) error("Line is out of range.", 2) end - return tLines[y].text, tLines[y].textColor, tLines[y].backgroundColor + local line = tLines[y] + return line[1], line[2], line[3] end -- Other functions @@ -574,26 +562,22 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) local sEmptyBackgroundColor = tEmptyColorLines[nBackgroundColor] for y = 1, new_height do if y > nHeight then - tNewLines[y] = { - text = sEmptyText, - textColor = sEmptyTextColor, - backgroundColor = sEmptyBackgroundColor, - } + tNewLines[y] = { sEmptyText, sEmptyTextColor, sEmptyBackgroundColor } else local tOldLine = tLines[y] if new_width == nWidth then tNewLines[y] = tOldLine elseif new_width < nWidth then tNewLines[y] = { - text = string_sub(tOldLine.text, 1, new_width), - textColor = string_sub(tOldLine.textColor, 1, new_width), - backgroundColor = string_sub(tOldLine.backgroundColor, 1, new_width), + string_sub(tOldLine[1], 1, new_width), + string_sub(tOldLine[2], 1, new_width), + string_sub(tOldLine[3], 1, new_width), } else tNewLines[y] = { - text = tOldLine.text .. string_sub(sEmptyText, nWidth + 1, new_width), - textColor = tOldLine.textColor .. string_sub(sEmptyTextColor, nWidth + 1, new_width), - backgroundColor = tOldLine.backgroundColor .. string_sub(sEmptyBackgroundColor, nWidth + 1, new_width), + tOldLine[1] .. string_sub(sEmptyText, nWidth + 1, new_width), + tOldLine[2] .. string_sub(sEmptyTextColor, nWidth + 1, new_width), + tOldLine[3] .. string_sub(sEmptyBackgroundColor, nWidth + 1, new_width), } end end diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/help/changelog.md b/projects/core/src/main/resources/data/computercraft/lua/rom/help/changelog.md index 098267351..ef0af61a8 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/help/changelog.md +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/help/changelog.md @@ -1,3 +1,23 @@ +# New features in CC: Tweaked 1.106.0 + +* Numerous documentation improvements (MCJack123, znepb, penguinencounter). +* Port `fs.find` to Lua. This also allows using `?` as a wildcard. +* Computers cursors now glow in the dark. +* Allow changing turtle upgrades from the GUI. +* Add option to serialize Unicode strings to JSON (MCJack123). +* Small optimisations to the `window` API. +* Turtle upgrades can now preserve NBT from upgrade item stack and when broken. +* Add support for tool enchantments and durability via datapacks. This is disabled for the built-in tools. + +Several bug fixes: +* Fix turtles rendering incorrectly when upside down. +* Fix misplaced calls to IArguments.escapes. +* Lua REPL no longer accepts `)(` as a valid expression. +* Fix several inconsistencies with `require`/`package.path` in the Lua REPL (Wojbie). +* Fix turtle being able to place water buckets outside its reach distance. +* Fix private several IP address ranges not being blocked by the `$private` rule. +* Improve permission checks in the `/computercraft` command. + # New features in CC: Tweaked 1.105.0 * Optimise JSON string parsing. diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/help/whatsnew.md b/projects/core/src/main/resources/data/computercraft/lua/rom/help/whatsnew.md index 1512a2ae6..172ac059e 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/help/whatsnew.md +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/help/whatsnew.md @@ -1,25 +1,21 @@ -New features in CC: Tweaked 1.105.0 +New features in CC: Tweaked 1.106.0 -* Optimise JSON string parsing. -* Add `colors.fromBlit` (Erb3). -* Upload file size limit is now configurable (khankul). -* Wired cables no longer have a distance limit. -* Java methods now coerce values to strings consistently with Lua. -* Add custom timeout support to the HTTP API. -* Support custom proxies for HTTP requests (Lemmmy). -* The `speaker` program now errors when playing HTML files. -* `edit` now shows an error message when editing read-only files. -* Update Ukranian translation (SirEdvin). +* Numerous documentation improvements (MCJack123, znepb, penguinencounter). +* Port `fs.find` to Lua. This also allows using `?` as a wildcard. +* Computers cursors now glow in the dark. +* Allow changing turtle upgrades from the GUI. +* Add option to serialize Unicode strings to JSON (MCJack123). +* Small optimisations to the `window` API. +* Turtle upgrades can now preserve NBT from upgrade item stack and when broken. +* Add support for tool enchantments and durability via datapacks. This is disabled for the built-in tools. Several bug fixes: -* Allow GPS hosts to only be 1 block apart. -* Fix "Turn On"/"Turn Off" buttons being inverted in the computer GUI (Erb3). -* Fix arrow keys not working in the printout UI. -* Several documentation fixes (zyxkad, Lupus590, Commandcracker). -* Fix monitor renderer debug text always being visible on Forge. -* Fix crash when another mod changes the LoggerContext. -* Fix the `monitor_renderer` option not being present in Fabric config files. -* Pasting on MacOS/OSX now uses Cmd+V rather than Ctrl+V. -* Fix turtles placing blocks upside down when at y<0. +* Fix turtles rendering incorrectly when upside down. +* Fix misplaced calls to IArguments.escapes. +* Lua REPL no longer accepts `)(` as a valid expression. +* Fix several inconsistencies with `require`/`package.path` in the Lua REPL (Wojbie). +* Fix turtle being able to place water buckets outside its reach distance. +* Fix private several IP address ranges not being blocked by the `$private` rule. +* Improve permission checks in the `/computercraft` command. Type "help changelog" to see the full version history. diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/init.lua b/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/init.lua index 7df278186..59125c945 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/init.lua +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/init.lua @@ -21,6 +21,8 @@ local error_printer = require "cc.internal.error_printer" local error_sentinel = {} local function make_context(input) + expect(1, input, "string") + local context = {} local lines = { 1 } @@ -73,8 +75,9 @@ local function parse(input, start_symbol) expect(2, start_symbol, "number") local context = make_context(input) - function context.report(msg) - expect(1, msg, "table") + function context.report(msg, ...) + expect(1, msg, "table", "function") + if type(msg) == "function" then msg = msg(...) end error_printer(context, msg) error(error_sentinel) end @@ -110,8 +113,9 @@ local function parse_repl(input) local context = make_context(input) local last_error = nil - function context.report(msg) - expect(1, msg, "table") + function context.report(msg, ...) + expect(1, msg, "table", "function") + if type(msg) == "function" then msg = msg(...) end last_error = msg error(error_sentinel) end diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/lexer.lua b/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/lexer.lua index 16436b3ea..e775d590b 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/lexer.lua +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/lexer.lua @@ -96,7 +96,7 @@ local function lex_number(context, str, start) local contents = sub(str, start, pos - 1) if not tonumber(contents) then -- TODO: Separate error for "2..3"? - context.report(errors.malformed_number(start, pos - 1)) + context.report(errors.malformed_number, start, pos - 1) end return tokens.NUMBER, pos - 1 @@ -118,14 +118,14 @@ local function lex_string(context, str, start_pos, quote) return tokens.STRING, pos elseif c == "\n" or c == "\r" or c == "" then -- We don't call newline here, as that's done for the next token. - context.report(errors.unfinished_string(start_pos, pos, quote)) + context.report(errors.unfinished_string, start_pos, pos, quote) return tokens.STRING, pos - 1 elseif c == "\\" then c = sub(str, pos + 1, pos + 1) if c == "\n" or c == "\r" then pos = newline(context, str, pos + 1, c) elseif c == "" then - context.report(errors.unfinished_string_escape(start_pos, pos, quote)) + context.report(errors.unfinished_string_escape, start_pos, pos, quote) return tokens.STRING, pos elseif c == "z" then pos = pos + 2 @@ -133,7 +133,7 @@ local function lex_string(context, str, start_pos, quote) local next_pos, _, c = find(str, "([%S\r\n])", pos) if not next_pos then - context.report(errors.unfinished_string(start_pos, #str, quote)) + context.report(errors.unfinished_string, start_pos, #str, quote) return tokens.STRING, #str end @@ -196,7 +196,7 @@ local function lex_long_str(context, str, start, len) elseif c == "[" then local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "[") if ok and boundary_pos - pos == len and len == 1 then - context.report(errors.nested_long_str(pos, boundary_pos)) + context.report(errors.nested_long_str, pos, boundary_pos) end pos = boundary_pos @@ -238,12 +238,12 @@ local function lex_token(context, str, pos) local end_pos = lex_long_str(context, str, boundary_pos + 1, boundary_pos - pos) if end_pos then return tokens.STRING, end_pos end - context.report(errors.unfinished_long_string(pos, boundary_pos, boundary_pos - pos)) + context.report(errors.unfinished_long_string, pos, boundary_pos, boundary_pos - pos) return tokens.ERROR, #str elseif pos + 1 == boundary_pos then -- Just a "[" return tokens.OSQUARE, pos else -- Malformed long string, for instance "[=" - context.report(errors.malformed_long_string(pos, boundary_pos, boundary_pos - pos)) + context.report(errors.malformed_long_string, pos, boundary_pos, boundary_pos - pos) return tokens.ERROR, boundary_pos end @@ -260,7 +260,7 @@ local function lex_token(context, str, pos) local end_pos = lex_long_str(context, str, boundary_pos + 1, boundary_pos - comment_pos) if end_pos then return tokens.COMMENT, end_pos end - context.report(errors.unfinished_long_comment(pos, boundary_pos, boundary_pos - comment_pos)) + context.report(errors.unfinished_long_comment, pos, boundary_pos, boundary_pos - comment_pos) return tokens.ERROR, #str end end @@ -317,18 +317,18 @@ local function lex_token(context, str, pos) if end_pos - pos <= 3 then local contents = sub(str, pos, end_pos) if contents == "&&" then - context.report(errors.wrong_and(pos, end_pos)) + context.report(errors.wrong_and, pos, end_pos) return tokens.AND, end_pos elseif contents == "||" then - context.report(errors.wrong_or(pos, end_pos)) + context.report(errors.wrong_or, pos, end_pos) return tokens.OR, end_pos elseif contents == "!=" or contents == "<>" then - context.report(errors.wrong_ne(pos, end_pos)) + context.report(errors.wrong_ne, pos, end_pos) return tokens.NE, end_pos end end - context.report(errors.unexpected_character(pos)) + context.report(errors.unexpected_character, pos) return tokens.ERROR, end_pos end end diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/parser.lua b/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/parser.lua index 2ee238c68..507f03928 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/parser.lua +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/modules/main/cc/internal/syntax/parser.lua @@ -244,7 +244,7 @@ local function handle_error(context, stack, stack_n, token, token_start, token_e end end - context.report(errors.unexpected_token(token, token_start, token_end)) + context.report(errors.unexpected_token, token, token_start, token_end) return false end diff --git a/projects/core/src/main/resources/data/computercraft/lua/rom/programs/lua.lua b/projects/core/src/main/resources/data/computercraft/lua/rom/programs/lua.lua index 7e00ead50..fd55dfe44 100644 --- a/projects/core/src/main/resources/data/computercraft/lua/rom/programs/lua.lua +++ b/projects/core/src/main/resources/data/computercraft/lua/rom/programs/lua.lua @@ -25,21 +25,13 @@ local tEnv = { } setmetatable(tEnv, { __index = _ENV }) --- Replace our package.path, so that it loads from the current directory, rather --- than from /rom/programs. This makes it a little more friendly to use and --- closer to what you'd expect. +-- Replace our require with new instance that loads from the current directory +-- rather than from /rom/programs. This makes it more friendly to use and closer +-- to what you'd expect. do + local make_package = require "cc.require".make local dir = shell.dir() - if dir:sub(1, 1) ~= "/" then dir = "/" .. dir end - if dir:sub(-1) ~= "/" then dir = dir .. "/" end - - local strip_path = "?;?.lua;?/init.lua;" - local path = package.path - if path:sub(1, #strip_path) == strip_path then - path = path:sub(#strip_path + 1) - end - - package.path = dir .. "?;" .. dir .. "?.lua;" .. dir .. "?/init.lua;" .. path + _ENV.require, _ENV.package = make_package(_ENV, dir) end if term.isColour() then @@ -82,18 +74,13 @@ while running do local name, offset = "=lua[" .. chunk_idx .. "]", 0 - local force_print = 0 local func, err = load(input, name, "t", tEnv) - - local expr_func = load("return _echo(" .. input .. ");", name, "t", tEnv) - if not func then - if expr_func then - func = expr_func - offset = 13 - force_print = 1 - end - elseif expr_func then - func = expr_func + if load("return " .. input) then + -- We wrap the expression with a call to _echo(...), which prevents tail + -- calls (and thus confusing errors). Note we check this is a valid + -- expression separately, to avoid accepting inputs like `)--` (which are + -- parsed as `_echo()--)`. + func = load("return _echo(" .. input .. "\n)", name, "t", tEnv) offset = 13 end @@ -103,9 +90,8 @@ while running do local results = table.pack(exception.try(func)) if results[1] then - local n = 1 - while n < results.n or n <= force_print do - local value = results[n + 1] + for i = 2, results.n do + local value = results[i] local ok, serialised = pcall(pretty.pretty, value, { function_args = settings.get("lua.function_args"), function_source = settings.get("lua.function_source"), @@ -115,7 +101,6 @@ while running do else print(tostring(value)) end - n = n + 1 end else printError(results[2]) diff --git a/projects/core/src/test/java/dan200/computercraft/core/ComputerTestDelegate.java b/projects/core/src/test/java/dan200/computercraft/core/ComputerTestDelegate.java index ce832e54b..962b683c2 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/ComputerTestDelegate.java +++ b/projects/core/src/test/java/dan200/computercraft/core/ComputerTestDelegate.java @@ -11,8 +11,6 @@ import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.core.computer.Computer; import dan200.computercraft.core.computer.ComputerSide; -import dan200.computercraft.core.computer.ComputerThread; -import dan200.computercraft.core.computer.mainthread.NoWorkMainThreadScheduler; import dan200.computercraft.core.filesystem.FileSystemException; import dan200.computercraft.core.filesystem.WritableFileMount; import dan200.computercraft.core.lua.CobaltLuaMachine; @@ -112,7 +110,7 @@ public class ComputerTestDelegate { } var environment = new BasicEnvironment(mount); - context = new ComputerContext(environment, new ComputerThread(1), new NoWorkMainThreadScheduler(), CoverageLuaMachine::new); + context = ComputerContext.builder(environment).luaFactory(CoverageLuaMachine::new).build(); computer = new Computer(context, environment, term, 0); computer.getEnvironment().setPeripheral(ComputerSide.TOP, new FakeModem()); computer.getEnvironment().setPeripheral(ComputerSide.BOTTOM, new FakePeripheralHub()); diff --git a/projects/core/src/test/java/dan200/computercraft/core/apis/ObjectWrapper.java b/projects/core/src/test/java/dan200/computercraft/core/apis/ObjectWrapper.java index e8370ed84..7c8ebedde 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/apis/ObjectWrapper.java +++ b/projects/core/src/test/java/dan200/computercraft/core/apis/ObjectWrapper.java @@ -4,32 +4,26 @@ package dan200.computercraft.core.apis; -import dan200.computercraft.api.lua.*; -import dan200.computercraft.core.asm.LuaMethod; +import dan200.computercraft.api.lua.ILuaContext; +import dan200.computercraft.api.lua.LuaException; +import dan200.computercraft.api.lua.LuaTask; +import dan200.computercraft.api.lua.ObjectArguments; +import dan200.computercraft.core.asm.LuaMethodSupplier; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.MethodSupplier; -import java.util.HashMap; +import java.util.List; import java.util.Map; -import java.util.Objects; public class ObjectWrapper implements ILuaContext { + private static final MethodSupplier LUA_METHODS = LuaMethodSupplier.create(List.of()); + private final Object object; private final Map methodMap; public ObjectWrapper(Object object) { this.object = object; - var dynamicMethods = object instanceof IDynamicLuaObject dynamic - ? Objects.requireNonNull(dynamic.getMethodNames(), "Methods cannot be null") - : LuaMethod.EMPTY_METHODS; - - var methods = LuaMethod.GENERATOR.getMethods(object.getClass()); - - var methodMap = this.methodMap = new HashMap<>(methods.size() + dynamicMethods.length); - for (var i = 0; i < dynamicMethods.length; i++) { - methodMap.put(dynamicMethods[i], LuaMethod.DYNAMIC.get(i)); - } - for (var method : methods) { - methodMap.put(method.getName(), method.getMethod()); - } + methodMap = LUA_METHODS.getSelfMethods(object); } public Object[] call(String name, Object... args) throws LuaException { diff --git a/projects/core/src/test/java/dan200/computercraft/core/apis/http/options/AddressRuleTest.java b/projects/core/src/test/java/dan200/computercraft/core/apis/http/options/AddressRuleTest.java index 4682d45da..a7a7bf488 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/apis/http/options/AddressRuleTest.java +++ b/projects/core/src/test/java/dan200/computercraft/core/apis/http/options/AddressRuleTest.java @@ -31,7 +31,14 @@ public class AddressRuleTest { @ValueSource(strings = { "0.0.0.0", "[::]", "localhost", "127.0.0.1.nip.io", "127.0.0.1", "[::1]", - "172.17.0.1", "192.168.1.114", "[0:0:0:0:0:ffff:c0a8:172]", "10.0.0.1" + "172.17.0.1", "192.168.1.114", "[0:0:0:0:0:ffff:c0a8:172]", "10.0.0.1", + // Multicast + "224.0.0.1", "ff02::1", + // Cloud metadata providers + "100.100.100.200", // Alibaba + "192.0.0.192", // Oracle + "fd00:ec2::254", // AWS + "169.254.169.254", // AWS, Digital Ocean, GCP, etc.. }) public void blocksLocalDomains(String domain) { assertEquals(apply(CoreConfig.httpRules, domain, 80).action, Action.DENY); diff --git a/projects/core/src/test/java/dan200/computercraft/core/asm/GeneratorTest.java b/projects/core/src/test/java/dan200/computercraft/core/asm/GeneratorTest.java index 94b33f0d3..9fc6620e5 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/asm/GeneratorTest.java +++ b/projects/core/src/test/java/dan200/computercraft/core/asm/GeneratorTest.java @@ -7,11 +7,14 @@ package dan200.computercraft.core.asm; import dan200.computercraft.api.lua.*; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.core.computer.ComputerSide; +import dan200.computercraft.core.methods.LuaMethod; +import dan200.computercraft.core.methods.NamedMethod; import org.hamcrest.Matcher; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Collection; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -21,9 +24,11 @@ import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertThrows; public class GeneratorTest { + private static final MethodSupplierImpl GENERATOR = (MethodSupplierImpl) LuaMethodSupplier.create(List.of()); + @Test public void testBasic() { - var methods = LuaMethod.GENERATOR.getMethods(Basic.class); + var methods = GENERATOR.getMethods(Basic.class); assertThat(methods, contains( allOf( named("go"), @@ -34,48 +39,48 @@ public class GeneratorTest { @Test public void testIdentical() { - var methods = LuaMethod.GENERATOR.getMethods(Basic.class); - var methods2 = LuaMethod.GENERATOR.getMethods(Basic.class); + var methods = GENERATOR.getMethods(Basic.class); + var methods2 = GENERATOR.getMethods(Basic.class); assertThat(methods, sameInstance(methods2)); } @Test public void testIdenticalMethods() { - var methods = LuaMethod.GENERATOR.getMethods(Basic.class); - var methods2 = LuaMethod.GENERATOR.getMethods(Basic2.class); + var methods = GENERATOR.getMethods(Basic.class); + var methods2 = GENERATOR.getMethods(Basic2.class); assertThat(methods, contains(named("go"))); - assertThat(methods.get(0).getMethod(), sameInstance(methods2.get(0).getMethod())); + assertThat(methods.get(0).method(), sameInstance(methods2.get(0).method())); } @Test public void testEmptyClass() { - assertThat(LuaMethod.GENERATOR.getMethods(Empty.class), is(empty())); + assertThat(GENERATOR.getMethods(Empty.class), is(empty())); } @Test public void testNonPublicClass() { - assertThat(LuaMethod.GENERATOR.getMethods(NonPublic.class), is(empty())); + assertThat(GENERATOR.getMethods(NonPublic.class), is(empty())); } @Test public void testNonInstance() { - assertThat(LuaMethod.GENERATOR.getMethods(NonInstance.class), is(empty())); + assertThat(GENERATOR.getMethods(NonInstance.class), is(empty())); } @Test public void testIllegalThrows() { - assertThat(LuaMethod.GENERATOR.getMethods(IllegalThrows.class), is(empty())); + assertThat(GENERATOR.getMethods(IllegalThrows.class), is(empty())); } @Test public void testCustomNames() { - var methods = LuaMethod.GENERATOR.getMethods(CustomNames.class); + var methods = GENERATOR.getMethods(CustomNames.class); assertThat(methods, contains(named("go1"), named("go2"))); } @Test public void testArgKinds() { - var methods = LuaMethod.GENERATOR.getMethods(ArgKinds.class); + var methods = GENERATOR.getMethods(ArgKinds.class); assertThat(methods, containsInAnyOrder( named("objectArg"), named("intArg"), named("optIntArg"), named("context"), named("arguments") @@ -84,7 +89,7 @@ public class GeneratorTest { @Test public void testEnum() throws LuaException { - var methods = LuaMethod.GENERATOR.getMethods(EnumMethods.class); + var methods = GENERATOR.getMethods(EnumMethods.class); assertThat(methods, containsInAnyOrder(named("getEnum"), named("optEnum"))); assertThat(apply(methods, new EnumMethods(), "getEnum", "front"), one(is("FRONT"))); @@ -95,7 +100,7 @@ public class GeneratorTest { @Test public void testMainThread() throws LuaException { - var methods = LuaMethod.GENERATOR.getMethods(MainThread.class); + var methods = GENERATOR.getMethods(MainThread.class); assertThat(methods, contains(allOf( named("go"), contramap(is(false), "non-yielding", NamedMethod::nonYielding) @@ -107,7 +112,7 @@ public class GeneratorTest { @Test public void testUnsafe() { - var methods = LuaMethod.GENERATOR.getMethods(Unsafe.class); + var methods = GENERATOR.getMethods(Unsafe.class); assertThat(methods, contains(named("withUnsafe"))); } @@ -217,8 +222,8 @@ public class GeneratorTest { private static T find(Collection> methods, String name) { return methods.stream() - .filter(x -> x.getName().equals(name)) - .map(NamedMethod::getMethod) + .filter(x -> x.name().equals(name)) + .map(NamedMethod::method) .findAny() .orElseThrow(NullPointerException::new); } @@ -235,7 +240,7 @@ public class GeneratorTest { } public static Matcher> named(String method) { - return contramap(is(method), "name", NamedMethod::getName); + return contramap(is(method), "name", NamedMethod::name); } private static final ILuaContext CONTEXT = new ILuaContext() { diff --git a/projects/core/src/test/java/dan200/computercraft/core/asm/MethodTest.java b/projects/core/src/test/java/dan200/computercraft/core/asm/MethodTest.java index bfff064e1..a61b15ec0 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/asm/MethodTest.java +++ b/projects/core/src/test/java/dan200/computercraft/core/asm/MethodTest.java @@ -10,6 +10,7 @@ import dan200.computercraft.api.peripheral.IDynamicPeripheral; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.core.computer.ComputerBootstrap; import dan200.computercraft.core.computer.ComputerSide; +import dan200.computercraft.core.methods.ObjectSource; import org.junit.jupiter.api.Test; import javax.annotation.Nullable; diff --git a/projects/core/src/test/java/dan200/computercraft/core/computer/ComputerBootstrap.java b/projects/core/src/test/java/dan200/computercraft/core/computer/ComputerBootstrap.java index e9975d0ca..42f0947af 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/computer/ComputerBootstrap.java +++ b/projects/core/src/test/java/dan200/computercraft/core/computer/ComputerBootstrap.java @@ -49,7 +49,7 @@ public class ComputerBootstrap { var term = new Terminal(51, 19, true); var mainThread = new MainThread(new MainThreadConfig.Basic(Integer.MAX_VALUE, Integer.MAX_VALUE)); var environment = new BasicEnvironment(mount); - var context = new ComputerContext(environment, 1, mainThread); + var context = ComputerContext.builder(environment).mainThreadScheduler(mainThread).build(); final var computer = new Computer(context, environment, term, 0); var api = new AssertApi(); diff --git a/projects/core/src/test/java/dan200/computercraft/core/lua/VarargArgumentsTest.java b/projects/core/src/test/java/dan200/computercraft/core/lua/VarargArgumentsTest.java index 7a76ea562..97a6aa36c 100644 --- a/projects/core/src/test/java/dan200/computercraft/core/lua/VarargArgumentsTest.java +++ b/projects/core/src/test/java/dan200/computercraft/core/lua/VarargArgumentsTest.java @@ -60,4 +60,12 @@ class VarargArgumentsTest { assertThrows(IllegalStateException.class, () -> args.get(0)); assertThrows(IllegalStateException.class, () -> args.getType(0)); } + + @Test + public void testEscapeAfterClose() { + var args = VarargArguments.of(tableWithCustomType()); + args.close(); + + assertThrows(IllegalStateException.class, args::escapes); + } } diff --git a/projects/core/src/test/resources/test-rom/spec/modules/cc/internal/syntax/syntax_helpers.lua b/projects/core/src/test/resources/test-rom/spec/modules/cc/internal/syntax/syntax_helpers.lua index 18b310d68..87022065d 100644 --- a/projects/core/src/test/resources/test-rom/spec/modules/cc/internal/syntax/syntax_helpers.lua +++ b/projects/core/src/test/resources/test-rom/spec/modules/cc/internal/syntax/syntax_helpers.lua @@ -49,8 +49,9 @@ local function capture_parser(input, print_tokens, start) end local context = make_context(input) - function context.report(message) - expect(3, message, "table") + function context.report(message, ...) + expect(3, message, "table", "function") + if type(message) == "function" then message = message(...) end for _, msg in ipairs(message) do if type(msg) == "table" and msg.tag == "annotate" then diff --git a/projects/core/src/testFixtures/kotlin/dan200/computercraft/test/core/computer/KotlinComputerManager.kt b/projects/core/src/testFixtures/kotlin/dan200/computercraft/test/core/computer/KotlinComputerManager.kt index a6fef3a26..8a93930e1 100644 --- a/projects/core/src/testFixtures/kotlin/dan200/computercraft/test/core/computer/KotlinComputerManager.kt +++ b/projects/core/src/testFixtures/kotlin/dan200/computercraft/test/core/computer/KotlinComputerManager.kt @@ -7,9 +7,7 @@ package dan200.computercraft.test.core.computer import dan200.computercraft.api.lua.ILuaAPI import dan200.computercraft.core.ComputerContext import dan200.computercraft.core.computer.Computer -import dan200.computercraft.core.computer.ComputerThread import dan200.computercraft.core.computer.TimeoutState -import dan200.computercraft.core.computer.mainthread.NoWorkMainThreadScheduler import dan200.computercraft.core.lua.MachineEnvironment import dan200.computercraft.core.lua.MachineResult import dan200.computercraft.core.terminal.Terminal @@ -27,11 +25,9 @@ typealias FakeComputerTask = (state: TimeoutState) -> MachineResult class KotlinComputerManager : AutoCloseable { private val machines: MutableMap> = HashMap() - private val context = ComputerContext( - BasicEnvironment(), - ComputerThread(1), - NoWorkMainThreadScheduler(), - ) { env, _ -> DummyLuaMachine(env) } + private val context = ComputerContext.builder(BasicEnvironment()) + .luaFactory { env, _ -> DummyLuaMachine(env) } + .build() private val errorLock: Lock = ReentrantLock() private val hasError = errorLock.newCondition() diff --git a/projects/fabric/build.gradle.kts b/projects/fabric/build.gradle.kts index 65881313f..2a2f3ced1 100644 --- a/projects/fabric/build.gradle.kts +++ b/projects/fabric/build.gradle.kts @@ -21,15 +21,25 @@ cct { } fun addRemappedConfiguration(name: String) { + // There was a regression in Loom 1.1 which means that targetConfigurationName doesn't do anything, and remap + // configurations just get added to the main source set (https://github.com/FabricMC/fabric-loom/issues/843). + // To get around that, we create our own source set and register a remap configuration with that. This does + // introduce a bit of noise, but it's not the end of the world. + val ourSourceSet = sourceSets.register(name) { + // Try to make this source set as much of a non-entity as possible. + listOf(allSource, java, resources, kotlin).forEach { it.setSrcDirs(emptyList()) } + } + val capitalName = name.replaceFirstChar { it.titlecase(Locale.ROOT) } + loom.addRemapConfiguration("mod$capitalName") { + onCompileClasspath.set(false) + onRuntimeClasspath.set(true) + sourceSet.set(ourSourceSet) + targetConfigurationName.set(name) + } configurations.create(name) { isCanBeConsumed = false isCanBeResolved = true - } - val capitalName = name.capitalize(Locale.ROOT) - loom.addRemapConfiguration("mod$capitalName") { - onCompileClasspath.set(false) - onRuntimeClasspath.set(false) - targetConfigurationName.set(name) + extendsFrom(configurations["${name}RuntimeClasspath"]) } } diff --git a/projects/fabric/src/client/java/dan200/computercraft/client/model/CompositeBakedModel.java b/projects/fabric/src/client/java/dan200/computercraft/client/model/CompositeBakedModel.java index aa22ac224..177094cdc 100644 --- a/projects/fabric/src/client/java/dan200/computercraft/client/model/CompositeBakedModel.java +++ b/projects/fabric/src/client/java/dan200/computercraft/client/model/CompositeBakedModel.java @@ -25,6 +25,10 @@ public class CompositeBakedModel extends CustomBakedModel { this.models = models; } + public static BakedModel of(List models) { + return models.size() == 1 ? models.get(0) : new CompositeBakedModel(models); + } + @Override public List getQuads(@Nullable BlockState blockState, @Nullable Direction face, RandomSource rand) { @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/projects/fabric/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java b/projects/fabric/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java index 28ba06bf2..704350b1a 100644 --- a/projects/fabric/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java +++ b/projects/fabric/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java @@ -14,8 +14,6 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; /** * The custom model for turtle items, which renders tools and overlays as part of the model. @@ -23,28 +21,22 @@ import java.util.Map; * @see TurtleModelParts */ public class TurtleModel extends ForwardingBakedModel { - private final TurtleModelParts parts; + private final TurtleModelParts parts; - private final Map cachedModels = new HashMap<>(); private final ItemOverrides overrides = new ItemOverrides() { @Override public BakedModel resolve(BakedModel model, ItemStack stack, @Nullable ClientLevel level, @Nullable LivingEntity entity, int seed) { - return cachedModels.computeIfAbsent(parts.getCombination(stack), TurtleModel.this::buildModel); + return parts.getModel(stack); } }; public TurtleModel(BakedModel familyModel, BakedModel colourModel) { wrapped = familyModel; - parts = new TurtleModelParts(familyModel, colourModel, TransformedBakedModel::new); + parts = new TurtleModelParts<>(familyModel, colourModel, TransformedBakedModel::new, CompositeBakedModel::of); } @Override public ItemOverrides getOverrides() { return overrides; } - - private BakedModel buildModel(TurtleModelParts.Combination combo) { - var models = parts.buildModel(combo); - return models.size() == 1 ? models.get(0) : new CompositeBakedModel(models); - } } diff --git a/projects/fabric/src/generated/resources/assets/computercraft/lang/en_us.json b/projects/fabric/src/generated/resources/assets/computercraft/lang/en_us.json index 845d71ec6..77fe60ee0 100644 --- a/projects/fabric/src/generated/resources/assets/computercraft/lang/en_us.json +++ b/projects/fabric/src/generated/resources/assets/computercraft/lang/en_us.json @@ -99,7 +99,7 @@ "gui.computercraft.config.http.bandwidth.global_upload.tooltip": "The number of bytes which can be uploaded in a second. This is shared across all computers. (bytes/s).\nRange: > 1", "gui.computercraft.config.http.bandwidth.tooltip": "Limits bandwidth used by computers.", "gui.computercraft.config.http.enabled": "Enable the HTTP API", - "gui.computercraft.config.http.enabled.tooltip": "Enable the \"http\" API on Computers. This also disables the \"pastebin\" and \"wget\"\nprograms, that many users rely on. It's recommended to leave this on and use the\n\"rules\" config option to impose more fine-grained control.", + "gui.computercraft.config.http.enabled.tooltip": "Enable the \"http\" API on Computers. Disabling this also disables the \"pastebin\" and\n\"wget\" programs, that many users rely on. It's recommended to leave this on and use\nthe \"rules\" config option to impose more fine-grained control.", "gui.computercraft.config.http.max_requests": "Maximum concurrent requests", "gui.computercraft.config.http.max_requests.tooltip": "The number of http requests a computer can make at one time. Additional requests\nwill be queued, and sent when the running requests have finished. Set to 0 for\nunlimited.\nRange: > 0", "gui.computercraft.config.http.max_websockets": "Maximum concurrent websockets", @@ -113,7 +113,7 @@ "gui.computercraft.config.http.proxy.type": "Proxy type", "gui.computercraft.config.http.proxy.type.tooltip": "The type of proxy to use.\nAllowed Values: HTTP, HTTPS, SOCKS4, SOCKS5", "gui.computercraft.config.http.rules": "Allow/deny rules", - "gui.computercraft.config.http.rules.tooltip": "A list of rules which control behaviour of the \"http\" API for specific domains or\nIPs. Each rule is an item with a 'host' to match against, and a series of\nproperties. Rules are evaluated in order, meaning earlier rules override later\nones.\nThe host may be a domain name (\"pastebin.com\"), wildcard (\"*.pastebin.com\") or\nCIDR notation (\"127.0.0.0/8\").\nIf no rules, the domain is blocked.", + "gui.computercraft.config.http.rules.tooltip": "A list of rules which control behaviour of the \"http\" API for specific domains or\nIPs. Each rule matches against a hostname and an optional port, and then sets several\nproperties for the request. Rules are evaluated in order, meaning earlier rules override\nlater ones.\n\nValid properties:\n - \"host\" (required): The domain or IP address this rule matches. This may be a domain name\n (\"pastebin.com\"), wildcard (\"*.pastebin.com\") or CIDR notation (\"127.0.0.0/8\").\n - \"port\" (optional): Only match requests for a specific port, such as 80 or 443.\n\n - \"action\" (optional): Whether to allow or deny this request.\n - \"max_download\" (optional): The maximum size (in bytes) that a computer can download in this\n request.\n - \"max_upload\" (optional): The maximum size (in bytes) that a computer can upload in a this request.\n - \"max_websocket_message\" (optional): The maximum size (in bytes) that a computer can send or\n receive in one websocket packet.\n - \"use_proxy\" (optional): Enable use of the HTTP/SOCKS proxy if it is configured.", "gui.computercraft.config.http.tooltip": "Controls the HTTP API", "gui.computercraft.config.http.websocket_enabled": "Enable websockets", "gui.computercraft.config.http.websocket_enabled.tooltip": "Enable use of http websockets. This requires the \"http_enable\" option to also be true.", diff --git a/projects/fabric/src/main/java/dan200/computercraft/mixin/ItemMixin.java b/projects/fabric/src/main/java/dan200/computercraft/mixin/ItemMixin.java new file mode 100644 index 000000000..b1b18593b --- /dev/null +++ b/projects/fabric/src/main/java/dan200/computercraft/mixin/ItemMixin.java @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2023 The CC: Tweaked Developers +// +// SPDX-License-Identifier: MPL-2.0 + +package dan200.computercraft.mixin; + +import dan200.computercraft.shared.platform.FakePlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.ModifyConstant; + +@Mixin(Item.class) +class ItemMixin { + /** + * Replace the reach distance in {@link Item#getPlayerPOVHitResult(Level, Player, ClipContext.Fluid)}. + * + * @param reach The original reach distance. + * @param level The current level. + * @param player The current player. + * @return The new reach distance. + * @see FakePlayer#getBlockReach() + */ + @ModifyConstant(method = "getPlayerPOVHitResult", constant = @Constant(doubleValue = 5)) + @SuppressWarnings("UnusedMethod") + private static double getReachDistance(double reach, Level level, Player player) { + return player instanceof FakePlayer fp ? fp.getBlockReach() : reach; + } +} diff --git a/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java b/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java index 4b36a5d84..ac0d54e92 100644 --- a/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java +++ b/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java @@ -5,22 +5,21 @@ package dan200.computercraft.shared.peripheral.generic; import dan200.computercraft.api.peripheral.IPeripheral; -import dan200.computercraft.core.asm.NamedMethod; -import dan200.computercraft.core.asm.PeripheralMethod; import dan200.computercraft.shared.peripheral.generic.methods.InventoryMethods; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; public class GenericPeripheralProvider { + private static final Logger LOG = LoggerFactory.getLogger(GenericPeripheralProvider.class); + interface Lookup { @Nullable T find(Level world, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, Direction context); @@ -31,53 +30,23 @@ public class GenericPeripheralProvider { ); @Nullable - public static IPeripheral getPeripheral(Level world, BlockPos pos, Direction side, @Nullable BlockEntity blockEntity) { + public static IPeripheral getPeripheral(Level level, BlockPos pos, Direction side, @Nullable BlockEntity blockEntity) { if (blockEntity == null) return null; - var saturated = new GenericPeripheralBuilder(); + var server = level.getServer(); + if (server == null) { + LOG.warn("Fetching peripherals on a non-server level {}.", level, new IllegalStateException("Fetching peripherals on a non-server level.")); + return null; + } - var tileMethods = PeripheralMethod.GENERATOR.getMethods(blockEntity.getClass()); - if (!tileMethods.isEmpty()) saturated.addMethods(blockEntity, tileMethods); + var builder = new GenericPeripheralBuilder(server); + builder.addMethods(blockEntity); for (var lookup : lookups) { - var contents = lookup.find(world, pos, blockEntity.getBlockState(), blockEntity, side); - if (contents == null) continue; - - var methods = PeripheralMethod.GENERATOR.getMethods(contents.getClass()); - if (!methods.isEmpty()) saturated.addMethods(contents, methods); + var contents = lookup.find(level, pos, blockEntity.getBlockState(), blockEntity, side); + if (contents != null) builder.addMethods(contents); } - return saturated.toPeripheral(blockEntity); - } - - private static class GenericPeripheralBuilder { - private @Nullable String name; - private final Set additionalTypes = new HashSet<>(0); - private final ArrayList methods = new ArrayList<>(0); - - @Nullable - IPeripheral toPeripheral(BlockEntity tile) { - if (methods.isEmpty()) return null; - - methods.trimToSize(); - return new GenericPeripheral(tile, name, additionalTypes, methods); - } - - void addMethods(Object target, List> methods) { - var saturatedMethods = this.methods; - saturatedMethods.ensureCapacity(saturatedMethods.size() + methods.size()); - for (var method : methods) { - saturatedMethods.add(new SaturatedMethod(target, method)); - - // If we have a peripheral type, use it. Always pick the smallest one, so it's consistent (assuming mods - // don't change). - var type = method.getGenericType(); - if (type != null && type.getPrimaryType() != null) { - var name = type.getPrimaryType(); - if (this.name == null || this.name.compareTo(name) > 0) this.name = name; - } - if (type != null) additionalTypes.addAll(type.getAdditionalTypes()); - } - } + return builder.toPeripheral(blockEntity, side); } } diff --git a/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/SidedGenericPeripheral.java b/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/SidedGenericPeripheral.java deleted file mode 100644 index b0aa1a351..000000000 --- a/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/SidedGenericPeripheral.java +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers -// -// SPDX-License-Identifier: MPL-2.0 - -package dan200.computercraft.shared.peripheral.generic; - -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.entity.BlockEntity; - -import javax.annotation.Nullable; -import java.util.List; -import java.util.Set; - -public class SidedGenericPeripheral extends GenericPeripheral { - private final Direction direction; - - SidedGenericPeripheral(BlockEntity tile, Direction direction, @Nullable String name, Set additionalTypes, List methods) { - super(tile, name, additionalTypes, methods); - this.direction = direction; - } - - public Direction direction() { - return direction; - } -} diff --git a/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java b/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java index 527e62dfe..dfbbdf5b7 100644 --- a/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java +++ b/projects/fabric/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java @@ -12,7 +12,6 @@ import dan200.computercraft.api.peripheral.GenericPeripheral; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.PeripheralType; -import dan200.computercraft.shared.peripheral.generic.SidedGenericPeripheral; import dan200.computercraft.shared.platform.FabricContainerTransfer; import net.fabricmc.fabric.api.transfer.v1.item.ItemStorage; import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant; @@ -157,7 +156,7 @@ public class InventoryMethods implements GenericPeripheral { @Nullable private static SlottedStorage extractHandler(IPeripheral peripheral) { var object = peripheral.getTarget(); - var direction = peripheral instanceof SidedGenericPeripheral sided ? sided.direction() : null; + var direction = peripheral instanceof dan200.computercraft.shared.peripheral.generic.GenericPeripheral sided ? sided.side() : null; if (object instanceof BlockEntity blockEntity) { if (blockEntity.isRemoved()) return null; diff --git a/projects/fabric/src/main/java/dan200/computercraft/shared/platform/FakePlayer.java b/projects/fabric/src/main/java/dan200/computercraft/shared/platform/FakePlayer.java index 5f2b0c412..4bce69373 100644 --- a/projects/fabric/src/main/java/dan200/computercraft/shared/platform/FakePlayer.java +++ b/projects/fabric/src/main/java/dan200/computercraft/shared/platform/FakePlayer.java @@ -6,12 +6,15 @@ package dan200.computercraft.shared.platform; import com.mojang.authlib.GameProfile; import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.EntityDimensions; import net.minecraft.world.entity.Pose; import net.minecraft.world.entity.player.Player; -final class FakePlayer extends net.fabricmc.fabric.api.entity.FakePlayer { +import static dan200.computercraft.shared.platform.FakePlayerConstants.MAX_REACH; + +public final class FakePlayer extends net.fabricmc.fabric.api.entity.FakePlayer { private FakePlayer(ServerLevel serverLevel, GameProfile gameProfile) { super(serverLevel, gameProfile); } @@ -33,4 +36,13 @@ final class FakePlayer extends net.fabricmc.fabric.api.entity.FakePlayer { public float getStandingEyeHeight(Pose pose, EntityDimensions dimensions) { return 0; } + + public double getBlockReach() { + return MAX_REACH; + } + + @Override + public boolean broadcastToPlayer(ServerPlayer player) { + return false; + } } diff --git a/projects/fabric/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java b/projects/fabric/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java index 4e84e8f1f..82b97a5f4 100644 --- a/projects/fabric/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java +++ b/projects/fabric/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java @@ -34,6 +34,7 @@ import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerType; import net.fabricmc.fabric.api.tag.convention.v1.ConventionalItemTags; import net.fabricmc.fabric.api.transfer.v1.item.InventoryStorage; import net.fabricmc.fabric.api.transfer.v1.item.ItemStorage; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.commands.synchronization.ArgumentTypeInfo; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -73,7 +74,6 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.Vec3; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -83,6 +83,11 @@ import java.util.function.*; @AutoService(dan200.computercraft.impl.PlatformHelper.class) public class PlatformHelperImpl implements PlatformHelper { + @Override + public boolean isDevelopmentEnvironment() { + return FabricLoader.getInstance().isDevelopmentEnvironment(); + } + @Override public ConfigFile.Builder createConfigBuilder() { return new FabricConfigFile.Builder(); @@ -290,7 +295,7 @@ public class PlatformHelperImpl implements PlatformHelper { public boolean hasToolUsage(ItemStack stack) { var item = stack.getItem(); return item instanceof ShovelItem || stack.is(ItemTags.SHOVELS) || - item instanceof HoeItem || stack.is(ItemTags.HOES); + item instanceof HoeItem || stack.is(ItemTags.HOES); } @Override @@ -356,7 +361,6 @@ public class PlatformHelperImpl implements PlatformHelper { return object; } - @Nonnull @Override public Iterator iterator() { return registry.iterator(); diff --git a/projects/fabric/src/main/resources/computercraft.fabric.mixins.json b/projects/fabric/src/main/resources/computercraft.fabric.mixins.json index 186ada5fe..0b6d01a0c 100644 --- a/projects/fabric/src/main/resources/computercraft.fabric.mixins.json +++ b/projects/fabric/src/main/resources/computercraft.fabric.mixins.json @@ -12,6 +12,7 @@ "EntityMixin", "ExplosionDamageCalculatorMixin", "ItemEntityMixin", + "ItemMixin", "ServerLevelMixin", "ShapedRecipeMixin", "TagEntryAccessor", diff --git a/projects/forge/build.gradle.kts b/projects/forge/build.gradle.kts index 589e44f0d..0437e531f 100644 --- a/projects/forge/build.gradle.kts +++ b/projects/forge/build.gradle.kts @@ -35,8 +35,6 @@ minecraft { property("forge.logging.markers", "REGISTRIES") property("forge.logging.console.level", "debug") - forceExit = false - mods.register("computercraft") { cct.sourceDirectories.get().forEach { if (it.classes) sources(it.sourceSet) @@ -262,11 +260,7 @@ val runGametest by tasks.registering(JavaExec::class) { dependsOn("cleanRunGametest") usesService(MinecraftRunnerService.get(gradle)) - // Copy from runGameTestServer. We do it in this slightly odd way as runGameTestServer - // isn't created until the task is configured (which is no good for us). - val exec = tasks.getByName("runGameTestServer") - dependsOn(exec.dependsOn) - exec.copyToFull(this) + setRunConfig(minecraft.runs["gameTestServer"]) systemProperty("cctest.gametest-report", project.buildDir.resolve("test-results/$name.xml").absolutePath) } @@ -275,7 +269,7 @@ tasks.check { dependsOn(runGametest) } val runGametestClient by tasks.registering(ClientJavaExec::class) { description = "Runs client-side gametests with no mods" - copyFrom("runTestClient") + setRunConfig(minecraft.runs["testClient"]) tags("client") } cct.jacoco(runGametestClient) diff --git a/projects/forge/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java b/projects/forge/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java index f4ebbe78d..257e48699 100644 --- a/projects/forge/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java +++ b/projects/forge/src/client/java/dan200/computercraft/client/model/turtle/TurtleModel.java @@ -11,9 +11,8 @@ import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraftforge.client.model.BakedModelWrapper; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.function.Function; /** * The custom model for turtle items, which renders tools and overlays as part of the model. @@ -21,12 +20,11 @@ import java.util.Map; * @see TurtleModelParts */ public class TurtleModel extends BakedModelWrapper { - private final TurtleModelParts parts; - private final Map> cachedModels = new HashMap<>(); + private final TurtleModelParts> parts; public TurtleModel(BakedModel familyModel, BakedModel colourModel) { super(familyModel); - parts = new TurtleModelParts(familyModel, colourModel, TransformedBakedModel::new); + parts = new TurtleModelParts<>(familyModel, colourModel, TransformedBakedModel::new, Function.identity()); } @Override @@ -37,6 +35,6 @@ public class TurtleModel extends BakedModelWrapper { @Override public List getRenderPasses(ItemStack stack, boolean fabulous) { - return cachedModels.computeIfAbsent(parts.getCombination(stack), parts::buildModel); + return parts.getModel(stack); } } diff --git a/projects/forge/src/generated/resources/assets/computercraft/lang/en_us.json b/projects/forge/src/generated/resources/assets/computercraft/lang/en_us.json index 845d71ec6..77fe60ee0 100644 --- a/projects/forge/src/generated/resources/assets/computercraft/lang/en_us.json +++ b/projects/forge/src/generated/resources/assets/computercraft/lang/en_us.json @@ -99,7 +99,7 @@ "gui.computercraft.config.http.bandwidth.global_upload.tooltip": "The number of bytes which can be uploaded in a second. This is shared across all computers. (bytes/s).\nRange: > 1", "gui.computercraft.config.http.bandwidth.tooltip": "Limits bandwidth used by computers.", "gui.computercraft.config.http.enabled": "Enable the HTTP API", - "gui.computercraft.config.http.enabled.tooltip": "Enable the \"http\" API on Computers. This also disables the \"pastebin\" and \"wget\"\nprograms, that many users rely on. It's recommended to leave this on and use the\n\"rules\" config option to impose more fine-grained control.", + "gui.computercraft.config.http.enabled.tooltip": "Enable the \"http\" API on Computers. Disabling this also disables the \"pastebin\" and\n\"wget\" programs, that many users rely on. It's recommended to leave this on and use\nthe \"rules\" config option to impose more fine-grained control.", "gui.computercraft.config.http.max_requests": "Maximum concurrent requests", "gui.computercraft.config.http.max_requests.tooltip": "The number of http requests a computer can make at one time. Additional requests\nwill be queued, and sent when the running requests have finished. Set to 0 for\nunlimited.\nRange: > 0", "gui.computercraft.config.http.max_websockets": "Maximum concurrent websockets", @@ -113,7 +113,7 @@ "gui.computercraft.config.http.proxy.type": "Proxy type", "gui.computercraft.config.http.proxy.type.tooltip": "The type of proxy to use.\nAllowed Values: HTTP, HTTPS, SOCKS4, SOCKS5", "gui.computercraft.config.http.rules": "Allow/deny rules", - "gui.computercraft.config.http.rules.tooltip": "A list of rules which control behaviour of the \"http\" API for specific domains or\nIPs. Each rule is an item with a 'host' to match against, and a series of\nproperties. Rules are evaluated in order, meaning earlier rules override later\nones.\nThe host may be a domain name (\"pastebin.com\"), wildcard (\"*.pastebin.com\") or\nCIDR notation (\"127.0.0.0/8\").\nIf no rules, the domain is blocked.", + "gui.computercraft.config.http.rules.tooltip": "A list of rules which control behaviour of the \"http\" API for specific domains or\nIPs. Each rule matches against a hostname and an optional port, and then sets several\nproperties for the request. Rules are evaluated in order, meaning earlier rules override\nlater ones.\n\nValid properties:\n - \"host\" (required): The domain or IP address this rule matches. This may be a domain name\n (\"pastebin.com\"), wildcard (\"*.pastebin.com\") or CIDR notation (\"127.0.0.0/8\").\n - \"port\" (optional): Only match requests for a specific port, such as 80 or 443.\n\n - \"action\" (optional): Whether to allow or deny this request.\n - \"max_download\" (optional): The maximum size (in bytes) that a computer can download in this\n request.\n - \"max_upload\" (optional): The maximum size (in bytes) that a computer can upload in a this request.\n - \"max_websocket_message\" (optional): The maximum size (in bytes) that a computer can send or\n receive in one websocket packet.\n - \"use_proxy\" (optional): Enable use of the HTTP/SOCKS proxy if it is configured.", "gui.computercraft.config.http.tooltip": "Controls the HTTP API", "gui.computercraft.config.http.websocket_enabled": "Enable websockets", "gui.computercraft.config.http.websocket_enabled.tooltip": "Enable use of http websockets. This requires the \"http_enable\" option to also be true.", diff --git a/projects/forge/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java b/projects/forge/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java index a2a26e65a..64c9333e1 100644 --- a/projects/forge/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java +++ b/projects/forge/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java @@ -5,20 +5,22 @@ package dan200.computercraft.shared.peripheral.generic; import dan200.computercraft.api.peripheral.IPeripheral; -import dan200.computercraft.core.asm.NamedMethod; -import dan200.computercraft.core.asm.PeripheralMethod; import dan200.computercraft.shared.util.CapabilityUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.NonNullConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Objects; public class GenericPeripheralProvider { + private static final Logger LOG = LoggerFactory.getLogger(GenericPeripheralProvider.class); + private static final ArrayList> capabilities = new ArrayList<>(); public static synchronized void addCapability(Capability capability) { @@ -27,57 +29,26 @@ public class GenericPeripheralProvider { } @Nullable - public static IPeripheral getPeripheral(Level world, BlockPos pos, Direction side, NonNullConsumer invalidate) { - var tile = world.getBlockEntity(pos); - if (tile == null) return null; + public static IPeripheral getPeripheral(Level level, BlockPos pos, Direction side, NonNullConsumer invalidate) { + var blockEntity = level.getBlockEntity(pos); + if (blockEntity == null) return null; - var saturated = new GenericPeripheralBuilder(); + var server = level.getServer(); + if (server == null) { + LOG.warn("Fetching peripherals on a non-server level {}.", level, new IllegalStateException("Fetching peripherals on a non-server level.")); + return null; + } - var tileMethods = PeripheralMethod.GENERATOR.getMethods(tile.getClass()); - if (!tileMethods.isEmpty()) saturated.addMethods(tile, tileMethods); + var builder = new GenericPeripheralBuilder(server); + builder.addMethods(blockEntity); for (var capability : capabilities) { - var wrapper = CapabilityUtil.getCapability(tile, capability, side); + var wrapper = CapabilityUtil.getCapability(blockEntity, capability, side); wrapper.ifPresent(contents -> { - var capabilityMethods = PeripheralMethod.GENERATOR.getMethods(contents.getClass()); - if (capabilityMethods.isEmpty()) return; - - saturated.addMethods(contents, capabilityMethods); - CapabilityUtil.addListener(wrapper, invalidate); + if (builder.addMethods(contents)) CapabilityUtil.addListener(wrapper, invalidate); }); } - return saturated.toPeripheral(tile); - } - - private static class GenericPeripheralBuilder { - private @Nullable String name; - private final Set additionalTypes = new HashSet<>(0); - private final ArrayList methods = new ArrayList<>(0); - - @Nullable - IPeripheral toPeripheral(BlockEntity tile) { - if (methods.isEmpty()) return null; - - methods.trimToSize(); - return new GenericPeripheral(tile, name, additionalTypes, methods); - } - - void addMethods(Object target, List> methods) { - var saturatedMethods = this.methods; - saturatedMethods.ensureCapacity(saturatedMethods.size() + methods.size()); - for (var method : methods) { - saturatedMethods.add(new SaturatedMethod(target, method)); - - // If we have a peripheral type, use it. Always pick the smallest one, so it's consistent (assuming mods - // don't change). - var type = method.getGenericType(); - if (type != null && type.getPrimaryType() != null) { - var name = type.getPrimaryType(); - if (this.name == null || this.name.compareTo(name) > 0) this.name = name; - } - if (type != null) additionalTypes.addAll(type.getAdditionalTypes()); - } - } + return builder.toPeripheral(blockEntity, side); } } diff --git a/projects/forge/src/main/java/dan200/computercraft/shared/platform/FakePlayerExt.java b/projects/forge/src/main/java/dan200/computercraft/shared/platform/FakePlayerExt.java index 060e080a4..ad32e9280 100644 --- a/projects/forge/src/main/java/dan200/computercraft/shared/platform/FakePlayerExt.java +++ b/projects/forge/src/main/java/dan200/computercraft/shared/platform/FakePlayerExt.java @@ -6,6 +6,7 @@ package dan200.computercraft.shared.platform; import com.mojang.authlib.GameProfile; import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityDimensions; @@ -16,6 +17,8 @@ import net.minecraftforge.common.util.FakePlayer; import javax.annotation.Nullable; import java.util.OptionalInt; +import static dan200.computercraft.shared.platform.FakePlayerConstants.MAX_REACH; + class FakePlayerExt extends FakePlayer { FakePlayerExt(ServerLevel serverLevel, GameProfile profile) { super(serverLevel, profile); @@ -45,4 +48,19 @@ class FakePlayerExt extends FakePlayer { public float getStandingEyeHeight(Pose pose, EntityDimensions dimensions) { return 0; } + + @Override + public double getBlockReach() { + return MAX_REACH; + } + + @Override + public double getEntityReach() { + return MAX_REACH; + } + + @Override + public boolean broadcastToPlayer(ServerPlayer player) { + return false; + } } diff --git a/projects/forge/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java b/projects/forge/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java index 8cd383bb6..52dd8b685 100644 --- a/projects/forge/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java +++ b/projects/forge/src/main/java/dan200/computercraft/shared/platform/PlatformHelperImpl.java @@ -63,6 +63,7 @@ import net.minecraftforge.common.util.NonNullConsumer; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.items.wrapper.InvWrapper; import net.minecraftforge.items.wrapper.SidedInvWrapper; import net.minecraftforge.network.NetworkHooks; @@ -77,6 +78,11 @@ import java.util.function.*; @AutoService(dan200.computercraft.impl.PlatformHelper.class) public class PlatformHelperImpl implements PlatformHelper { + @Override + public boolean isDevelopmentEnvironment() { + return !FMLLoader.isProduction(); + } + @Override public ConfigFile.Builder createConfigBuilder() { return new ForgeConfigFile.Builder();