diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index b69180785..014abc079 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -9,8 +9,8 @@ jobs: steps: - uses: actions/checkout@v2 - - name: Checkout submodules - run: git submodule update --init --recursive + with: + submodules: true - name: Set up Java 16 uses: actions/setup-java@v1 diff --git a/build.gradle b/build.gradle index 44ca32f99..dfc18de3a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,47 +1,68 @@ plugins { - id 'fabric-loom' version '0.9-SNAPSHOT' - id 'maven-publish' id "checkstyle" + id "jacoco" + id "maven-publish" id "com.github.hierynomus.license" version "0.16.1" + id "org.jetbrains.kotlin.jvm" version "1.5.21" + id 'fabric-loom' version '0.10-SNAPSHOT' } +def javaVersion = JavaLanguageVersion.of(16) java { toolchain { - languageVersion = JavaLanguageVersion.of(16) - vendor = JvmVendorSpec.ADOPTOPENJDK + languageVersion = javaVersion + } + + withSourcesJar() + withJavadocJar() +} + +tasks.withType(JavaExec).configureEach { + javaLauncher = javaToolchains.launcherFor { + languageVersion = javaVersion } } version = mod_version group = "dan200.computercraft" -archivesBaseName = "cc-restiched" +archivesBaseName = "cc-restitched" -repositories { - mavenCentral() - maven { url 'https://jitpack.io' } - maven { url 'https://api.modrinth.com/maven'} - maven { url "https://maven.shedaniel.me/" } - maven { url "https://maven.terraformersmc.com/" } - maven { - name "SquidDev" - url "https://squiddev.cc/maven" +sourceSets { + main.resources { + srcDir 'src/generated/resources' } + + testMod {} } loom { accessWidenerPath = file("src/main/resources/cc.accesswidener") } +repositories { + mavenCentral() + maven { + name "SquidDev" + url "https://squiddev.cc/maven" + } + + // TODO: Limit these to a set of groups. + maven { url "https://maven.shedaniel.me/" } + maven { url "https://maven.terraformersmc.com/" } +} + configurations { + shade implementation.extendsFrom shade + cctJavadoc } dependencies { - checkstyle 'com.puppycrawl.tools:checkstyle:8.45.1' + checkstyle "com.puppycrawl.tools:checkstyle:8.45" minecraft "com.mojang:minecraft:${mc_version}" - mappings "net.fabricmc:yarn:${mc_version}+build.${mappings_version}:v2" + mappings loom.officialMojangMappings() modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${fabric_api_version}" @@ -52,7 +73,8 @@ dependencies { modImplementation "me.shedaniel.cloth.api:cloth-utils-v1:${cloth_api_version}" implementation 'com.electronwill.night-config:toml:3.6.3' - implementation 'com.google.code.findbugs:jsr305:3.0.2' + + compileOnly 'com.google.code.findbugs:jsr305:3.0.2' shade 'org.squiddev:Cobalt:0.5.2-SNAPSHOT' @@ -61,39 +83,114 @@ dependencies { include 'com.electronwill.night-config:toml:3.6.3' include "me.shedaniel.cloth:cloth-config-fabric:${cloth_config_version}" - modRuntime "me.shedaniel:RoughlyEnoughItems-api-fabric:6.0.254-alpha" - modRuntime "me.shedaniel:RoughlyEnoughItems-fabric:6.0.254-alpha" + modRuntimeOnly "me.shedaniel:RoughlyEnoughItems-api-fabric:6.0.254-alpha" + modRuntimeOnly "me.shedaniel:RoughlyEnoughItems-fabric:6.0.254-alpha" + + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.0' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testImplementation 'org.hamcrest:hamcrest:2.2' + testImplementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.21' + testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1' + + cctJavadoc 'cc.tweaked:cct-javadoc:1.4.1' } processResources { inputs.property "version", project.version - filesMatching("fabric.mod.json") { - expand "version": project.version - } + def hash = 'none' + Set contributors = [] + try { + hash = ["git", "-C", projectDir, "rev-parse", "HEAD"].execute().text.trim() + + def blacklist = ['GitHub', 'dan200', 'Daniel Ratcliffe'] + ["git", "-C", projectDir, "log", "--format=tformat:%an%n%cn"].execute().text.split('\n').each { + if (!blacklist.contains(it)) contributors.add(it) + } + } catch (Exception e) { + e.printStackTrace() + } + inputs.property "commithash", hash + duplicatesStrategy = DuplicatesStrategy.INCLUDE + + filesMatching(["fabric.mod.json", "data/computercraft/lua/rom/help/credits.txt"]) { + expand( + 'version': mod_version, + 'mcversion': mc_version, + 'gitcontributors': contributors.sort(false, String.CASE_INSENSITIVE_ORDER).join('\n') + ) + } } -// ensure that the encoding is set to UTF-8, no matter what the system default is -// this fixes some edge cases with special characters not displaying correctly -// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html tasks.withType(JavaCompile) { options.encoding = "UTF-8" } -// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task -// if it is present. -// If you remove this task, sources will not be generated. -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = "sources" - from sourceSets.main.allSource +javadoc { + include "dan200/computercraft/api/**/*.java" +} + +task luaJavadoc(type: Javadoc) { + description "Generates documentation for Java-side Lua functions." + group "documentation" + + source = sourceSets.main.allJava + destinationDir = file("${project.docsDir}/luaJavadoc") + classpath = sourceSets.main.compileClasspath + + options.docletpath = configurations.cctJavadoc.files as List + options.doclet = "cc.tweaked.javadoc.LuaDoclet" + options.noTimestamp = false + + javadocTool = javaToolchains.javadocToolFor { + languageVersion = javaVersion + } } jar { from "LICENSE" + manifest { + attributes([ + "Specification-Title" : "computercraft", + "Specification-Version" : "1", + "Implementation-Title" : "CC: Restitched", + "Implementation-Version" : "${mod_version}", + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } from configurations.shade.collect { it.isDirectory() ? it : zipTree(it) } } +[compileJava, compileTestJava].forEach { + it.configure { + options.compilerArgs << "-Xlint" << "-Xlint:-processing" + } +} + +sourcesJar { + duplicatesStrategy = DuplicatesStrategy.INCLUDE +} + +// Check tasks + +test { + useJUnitPlatform() + testLogging { + events "skipped", "failed" + } +} + +jacocoTestReport { + dependsOn('test') + reports { + xml.required = true + html.required = true + } +} + +check.dependsOn jacocoTestReport import com.hierynomus.gradle.license.tasks.LicenseCheck import com.hierynomus.gradle.license.tasks.LicenseFormat @@ -113,7 +210,7 @@ license { } } -[licenseTest, licenseFormatTest].forEach { +[licenseTest, licenseFormatTest, licenseTestMod, licenseFormatTestMod].forEach { it.configure { include("**/*.java") header file('config/license/main.txt') @@ -126,9 +223,8 @@ gradle.projectsEvaluated { } } - -task licenseAPI(type: LicenseCheck); -task licenseFormatAPI(type: LicenseFormat); +task licenseAPI(type: LicenseCheck) +task licenseFormatAPI(type: LicenseFormat) [licenseAPI, licenseFormatAPI].forEach { it.configure { source = sourceSets.main.java diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index ebc62360c..580780514 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -58,13 +58,20 @@ - + + + + - + + + @@ -149,8 +156,13 @@ - + + + + + + diff --git a/config/pre-commit/config.yml b/config/pre-commit/config.yml index 6d16e1978..9fcbee67a 100644 --- a/config/pre-commit/config.yml +++ b/config/pre-commit/config.yml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.2.0 + rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -16,7 +16,7 @@ repos: exclude: "tsconfig\\.json$" - repo: https://github.com/editorconfig-checker/editorconfig-checker.python - rev: 2.3.5 + rev: 2.3.54 hooks: - id: editorconfig-checker args: ['-disable-indentation'] @@ -38,6 +38,13 @@ repos: entry: ./gradlew licenseFormat pass_filenames: false require_serial: true + - id: illuaminate + name: Check Lua code + files: ".*\\.(lua|java|md)" + language: script + entry: config/pre-commit/illuaminate-lint.sh + pass_filenames: false + require_serial: true exclude: | (?x)^( diff --git a/doc/events/alarm.md b/doc/events/alarm.md new file mode 100644 index 000000000..db7f04845 --- /dev/null +++ b/doc/events/alarm.md @@ -0,0 +1,21 @@ +--- +module: [kind=event] alarm +see: os.setAlarm To start an alarm. +--- + +The @{timer} event is fired when an alarm started with @{os.setAlarm} completes. + +## Return Values +1. @{string}: The event name. +2. @{number}: The ID of the alarm that finished. + +## Example +Starts a timer and then prints its ID: +```lua +local alarmID = os.setAlarm(os.time() + 0.05) +local event, id +repeat + event, id = os.pullEvent("alarm") +until id == alarmID +print("Alarm with ID " .. id .. " was fired") +``` diff --git a/doc/events/char.md b/doc/events/char.md new file mode 100644 index 000000000..473313702 --- /dev/null +++ b/doc/events/char.md @@ -0,0 +1,24 @@ +--- +module: [kind=event] char +see: key To listen to any key press. +--- + +The @{char} event is fired when a character is _typed_ on the keyboard. + +The @{char} event is different to a key press. Sometimes multiple key presses may result in one character being +typed (for instance, on some European keyboards). Similarly, some keys (e.g. Ctrl) do not have any +corresponding character. The @{key} should be used if you want to listen to key presses themselves. + +## Return values +1. @{string}: The event name. +2. @{string}: The string representing the character that was pressed. + + +## Example +Prints each character the user presses: +```lua +while true do + local event, character = os.pullEvent("char") + print(character .. " was pressed.") +end +``` diff --git a/doc/events/computer_command.md b/doc/events/computer_command.md new file mode 100644 index 000000000..245252399 --- /dev/null +++ b/doc/events/computer_command.md @@ -0,0 +1,18 @@ +--- +module: [kind=event] computer_command +--- + +The @{computer_command} event is fired when the `/computercraft queue` command is run for the current computer. + +## Return Values +1. @{string}: The event name. +... @{string}: The arguments passed to the command. + +## Example +Prints the contents of messages sent: +```lua +while true do + local event = {os.pullEvent("computer_command")} + print("Received message:", table.unpack(event, 2)) +end +``` diff --git a/doc/events/disk.md b/doc/events/disk.md new file mode 100644 index 000000000..2946d70c4 --- /dev/null +++ b/doc/events/disk.md @@ -0,0 +1,19 @@ +--- +module: [kind=event] disk +see: disk_eject For the event sent when a disk is removed. +--- + +The @{disk} event is fired when a disk is inserted into an adjacent or networked disk drive. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side of the disk drive that had a disk inserted. + +## Example +Prints a message when a disk is inserted: +```lua +while true do + local event, side = os.pullEvent("disk") + print("Inserted a disk on side " .. side) +end +``` diff --git a/doc/events/disk_eject.md b/doc/events/disk_eject.md new file mode 100644 index 000000000..71c3ede0a --- /dev/null +++ b/doc/events/disk_eject.md @@ -0,0 +1,19 @@ +--- +module: [kind=event] disk_eject +see: disk For the event sent when a disk is inserted. +--- + +The @{disk_eject} event is fired when a disk is removed from an adjacent or networked disk drive. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side of the disk drive that had a disk removed. + +## Example +Prints a message when a disk is removed: +```lua +while true do + local event, side = os.pullEvent("disk_eject") + print("Removed a disk on side " .. side) +end +``` diff --git a/doc/events/http_check.md b/doc/events/http_check.md new file mode 100644 index 000000000..9af5ea7ca --- /dev/null +++ b/doc/events/http_check.md @@ -0,0 +1,14 @@ +--- +module: [kind=event] http_check +see: http.checkURLAsync To check a URL asynchronously. +--- + +The @{http_check} event is fired when a URL check finishes. + +This event is normally handled inside @{http.checkURL}, but it can still be seen when using @{http.checkURLAsync}. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL requested to be checked. +3. @{boolean}: Whether the check succeeded. +4. @{string|nil}: If the check failed, a reason explaining why the check failed. diff --git a/doc/events/http_failure.md b/doc/events/http_failure.md new file mode 100644 index 000000000..dc10b40d7 --- /dev/null +++ b/doc/events/http_failure.md @@ -0,0 +1,39 @@ +--- +module: [kind=event] http_failure +see: http.request To send an HTTP request. +--- + +The @{http_failure} event is fired when an HTTP request fails. + +This event is normally handled inside @{http.get} and @{http.post}, but it can still be seen when using @{http.request}. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL of the site requested. +3. @{string}: An error describing the failure. +4. @{http.Response|nil}: A response handle if the connection succeeded, but the server's response indicated failure. + +## Example +Prints an error why the website cannot be contacted: +```lua +local myURL = "https://does.not.exist.tweaked.cc" +http.request(myURL) +local event, url, err +repeat + event, url, err = os.pullEvent("http_failure") +until url == myURL +print("The URL " .. url .. " could not be reached: " .. err) +``` + +Prints the contents of a webpage that does not exist: +```lua +local myURL = "https://tweaked.cc/this/does/not/exist" +http.request(myURL) +local event, url, err, handle +repeat + event, url, err, handle = os.pullEvent("http_failure") +until url == myURL +print("The URL " .. url .. " could not be reached: " .. err) +print(handle.getResponseCode()) +handle.close() +``` diff --git a/doc/events/http_success.md b/doc/events/http_success.md new file mode 100644 index 000000000..3700b9211 --- /dev/null +++ b/doc/events/http_success.md @@ -0,0 +1,27 @@ +--- +module: [kind=event] http_success +see: http.request To make an HTTP request. +--- + +The @{http_success} event is fired when an HTTP request returns successfully. + +This event is normally handled inside @{http.get} and @{http.post}, but it can still be seen when using @{http.request}. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL of the site requested. +3. @{http.Response}: The handle for the response text. + +## Example +Prints the content of a website (this may fail if the request fails): +```lua +local myURL = "https://tweaked.cc/" +http.request(myURL) +local event, url, handle +repeat + event, url, handle = os.pullEvent("http_success") +until url == myURL +print("Contents of " .. url .. ":") +print(handle.readAll()) +handle.close() +``` diff --git a/doc/events/key.md b/doc/events/key.md new file mode 100644 index 000000000..1f11e443b --- /dev/null +++ b/doc/events/key.md @@ -0,0 +1,26 @@ +--- +module: [kind=event] key +--- + +This event is fired when any key is pressed while the terminal is focused. + +This event returns a numerical "key code" (for instance, F1 is 290). This value may vary between versions and +so it is recommended to use the constants in the @{keys} API rather than hard coding numeric values. + +If the button pressed represented a printable character, then the @{key} event will be followed immediately by a @{char} +event. If you are consuming text input, use a @{char} event instead! + +## Return values +1. @{string}: The event name. +2. @{number}: The numerical key value of the key pressed. +3. @{boolean}: Whether the key event was generated while holding the key (@{true}), rather than pressing it the first time (@{false}). + +## Example +Prints each key when the user presses it, and if the key is being held. + +```lua +while true do + local event, key, is_held = os.pullEvent("key") + print(("%s held=%s"):format(keys.getName(key), is_held)) +end +``` diff --git a/doc/events/key_up.md b/doc/events/key_up.md new file mode 100644 index 000000000..e957cae6b --- /dev/null +++ b/doc/events/key_up.md @@ -0,0 +1,24 @@ +--- +module: [kind=event] key_up +see: keys For a lookup table of the given keys. +--- + +Fired whenever a key is released (or the terminal is closed while a key was being pressed). + +This event returns a numerical "key code" (for instance, F1 is 290). This value may vary between versions and +so it is recommended to use the constants in the @{keys} API rather than hard coding numeric values. + +## Return values +1. @{string}: The event name. +2. @{number}: The numerical key value of the key pressed. + +## Example +Prints each key released on the keyboard whenever a @{key_up} event is fired. + +```lua +while true do + local event, key = os.pullEvent("key_up") + local name = keys.getName(key) or "unknown key" + print(name .. " was released.") +end +``` diff --git a/doc/events/modem_message.md b/doc/events/modem_message.md new file mode 100644 index 000000000..ec619f3d4 --- /dev/null +++ b/doc/events/modem_message.md @@ -0,0 +1,22 @@ +--- +module: [kind=event] modem_message +--- + +The @{modem_message} event is fired when a message is received on an open channel on any modem. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side of the modem that received the message. +3. @{number}: The channel that the message was sent on. +4. @{number}: The reply channel set by the sender. +5. @{any}: The message as sent by the sender. +6. @{number}: The distance between the sender and the receiver, in blocks (decimal). + +## Example +Prints a message when one is sent: +```lua +while true do + local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message") + print(("Message received on side %s on channel %d (reply to %d) from %f blocks away with message %s"):format(side, channel, replyChannel, distance, tostring(message))) +end +``` diff --git a/doc/events/monitor_resize.md b/doc/events/monitor_resize.md new file mode 100644 index 000000000..03de804e7 --- /dev/null +++ b/doc/events/monitor_resize.md @@ -0,0 +1,18 @@ +--- +module: [kind=event] monitor_resize +--- + +The @{monitor_resize} event is fired when an adjacent or networked monitor's size is changed. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side or network ID of the monitor that resized. + +## Example +Prints a message when a monitor is resized: +```lua +while true do + local event, side = os.pullEvent("monitor_resize") + print("The monitor on side " .. side .. " was resized.") +end +``` diff --git a/doc/events/monitor_touch.md b/doc/events/monitor_touch.md new file mode 100644 index 000000000..0f27a9cc1 --- /dev/null +++ b/doc/events/monitor_touch.md @@ -0,0 +1,20 @@ +--- +module: [kind=event] monitor_touch +--- + +The @{monitor_touch} event is fired when an adjacent or networked Advanced Monitor is right-clicked. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side or network ID of the monitor that was touched. +3. @{number}: The X coordinate of the touch, in characters. +4. @{number}: The Y coordinate of the touch, in characters. + +## Example +Prints a message when a monitor is touched: +```lua +while true do + local event, side, x, y = os.pullEvent("monitor_touch") + print("The monitor on side " .. side .. " was touched at (" .. x .. ", " .. y .. ")") +end +``` diff --git a/doc/events/mouse_click.md b/doc/events/mouse_click.md new file mode 100644 index 000000000..83d371260 --- /dev/null +++ b/doc/events/mouse_click.md @@ -0,0 +1,34 @@ +--- +module: [kind=event] mouse_click +--- + +This event is fired when the terminal is clicked with a mouse. This event is only fired on advanced computers (including +advanced turtles and pocket computers). + +## Return values +1. @{string}: The event name. +2. @{number}: The mouse button that was clicked. +3. @{number}: The X-coordinate of the click. +4. @{number}: The Y-coordinate of the click. + +## Mouse buttons +Several mouse events (@{mouse_click}, @{mouse_up}, @{mouse_scroll}) contain a "mouse button" code. This takes a +numerical value depending on which button on your mouse was last pressed when this event occurred. + + + + + + + +
Button codeMouse button
1Left button
2Middle button
3Right button
+ +## Example +Print the button and the coordinates whenever the mouse is clicked. + +```lua +while true do + local event, button, x, y = os.pullEvent("mouse_click") + print(("The mouse button %s was pressed at %d, %d"):format(button, x, y)) +end +``` diff --git a/doc/events/mouse_drag.md b/doc/events/mouse_drag.md new file mode 100644 index 000000000..15451c9f8 --- /dev/null +++ b/doc/events/mouse_drag.md @@ -0,0 +1,22 @@ +--- +module: [kind=event] mouse_drag +see: mouse_click For when a mouse button is initially pressed. +--- + +This event is fired every time the mouse is moved while a mouse button is being held. + +## Return values +1. @{string}: The event name. +2. @{number}: The [mouse button](mouse_click.html#Mouse_buttons) that is being pressed. +3. @{number}: The X-coordinate of the mouse. +4. @{number}: The Y-coordinate of the mouse. + +## Example +Print the button and the coordinates whenever the mouse is dragged. + +```lua +while true do + local event, button, x, y = os.pullEvent("mouse_drag") + print(("The mouse button %s was dragged at %d, %d"):format(button, x, y)) +end +``` diff --git a/doc/events/mouse_scroll.md b/doc/events/mouse_scroll.md new file mode 100644 index 000000000..6248220a5 --- /dev/null +++ b/doc/events/mouse_scroll.md @@ -0,0 +1,21 @@ +--- +module: [kind=event] mouse_scroll +--- + +This event is fired when a mouse wheel is scrolled in the terminal. + +## Return values +1. @{string}: The event name. +2. @{number}: The direction of the scroll. (-1 = up, 1 = down) +3. @{number}: The X-coordinate of the mouse when scrolling. +4. @{number}: The Y-coordinate of the mouse when scrolling. + +## Example +Prints the direction of each scroll, and the position of the mouse at the time. + +```lua +while true do + local event, dir, x, y = os.pullEvent("mouse_scroll") + print(("The mouse was scrolled in direction %s at %d, %d"):format(dir, x, y)) +end +``` diff --git a/doc/events/mouse_up.md b/doc/events/mouse_up.md new file mode 100644 index 000000000..886330a6d --- /dev/null +++ b/doc/events/mouse_up.md @@ -0,0 +1,21 @@ +--- +module: [kind=event] mouse_up +--- + +This event is fired when a mouse button is released or a held mouse leaves the computer's terminal. + +## Return values +1. @{string}: The event name. +2. @{number}: The [mouse button](mouse_click.html#Mouse_buttons) that was released. +3. @{number}: The X-coordinate of the mouse. +4. @{number}: The Y-coordinate of the mouse. + +## Example +Prints the coordinates and button number whenever the mouse is released. + +```lua +while true do + local event, button, x, y = os.pullEvent("mouse_up") + print(("The mouse button %s was released at %d, %d"):format(button, x, y)) +end +``` diff --git a/doc/events/paste.md b/doc/events/paste.md new file mode 100644 index 000000000..b4f8713c5 --- /dev/null +++ b/doc/events/paste.md @@ -0,0 +1,18 @@ +--- +module: [kind=event] paste +--- + +The @{paste} event is fired when text is pasted into the computer through Ctrl-V (or ⌘V on Mac). + +## Return values +1. @{string}: The event name. +2. @{string} The text that was pasted. + +## Example +Prints pasted text: +```lua +while true do + local event, text = os.pullEvent("paste") + print('"' .. text .. '" was pasted') +end +``` diff --git a/doc/events/peripheral.md b/doc/events/peripheral.md new file mode 100644 index 000000000..5769f3942 --- /dev/null +++ b/doc/events/peripheral.md @@ -0,0 +1,19 @@ +--- +module: [kind=event] peripheral +see: peripheral_detach For the event fired when a peripheral is detached. +--- + +The @{peripheral} event is fired when a peripheral is attached on a side or to a modem. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side the peripheral was attached to. + +## Example +Prints a message when a peripheral is attached: +```lua +while true do + local event, side = os.pullEvent("peripheral") + print("A peripheral was attached on side " .. side) +end +``` diff --git a/doc/events/peripheral_detach.md b/doc/events/peripheral_detach.md new file mode 100644 index 000000000..c8a462cf0 --- /dev/null +++ b/doc/events/peripheral_detach.md @@ -0,0 +1,19 @@ +--- +module: [kind=event] peripheral_detach +see: peripheral For the event fired when a peripheral is attached. +--- + +The @{peripheral_detach} event is fired when a peripheral is detached from a side or from a modem. + +## Return Values +1. @{string}: The event name. +2. @{string}: The side the peripheral was detached from. + +## Example +Prints a message when a peripheral is detached: +```lua +while true do + local event, side = os.pullEvent("peripheral_detach") + print("A peripheral was detached on side " .. side) +end +``` diff --git a/doc/events/rednet_message.md b/doc/events/rednet_message.md new file mode 100644 index 000000000..8d0bdf697 --- /dev/null +++ b/doc/events/rednet_message.md @@ -0,0 +1,30 @@ +--- +module: [kind=event] rednet_message +see: modem_message For raw modem messages sent outside of Rednet. +see: rednet.receive To wait for a Rednet message with an optional timeout and protocol filter. +--- + +The @{rednet_message} event is fired when a message is sent over Rednet. + +This event is usually handled by @{rednet.receive}, but it can also be pulled manually. + +@{rednet_message} events are sent by @{rednet.run} in the top-level coroutine in response to @{modem_message} events. A @{rednet_message} event is always preceded by a @{modem_message} event. They are generated inside CraftOS rather than being sent by the ComputerCraft machine. + +## Return Values +1. @{string}: The event name. +2. @{number}: The ID of the sending computer. +3. @{any}: The message sent. +4. @{string|nil}: The protocol of the message, if provided. + +## Example +Prints a message when one is sent: +```lua +while true do + local event, sender, message, protocol = os.pullEvent("rednet_message") + if protocol ~= nil then + print("Received message from " .. sender .. " with protocol " .. protocol .. " and message " .. tostring(message)) + else + print("Received message from " .. sender .. " with message " .. tostring(message)) + end +end +``` diff --git a/doc/events/redstone.md b/doc/events/redstone.md new file mode 100644 index 000000000..44eda304a --- /dev/null +++ b/doc/events/redstone.md @@ -0,0 +1,14 @@ +--- +module: [kind=event] redstone +--- + +The @{redstone} event is fired whenever any redstone inputs on the computer change. + +## Example +Prints a message when a redstone input changes: +```lua +while true do + os.pullEvent("redstone") + print("A redstone input has changed!") +end +``` diff --git a/doc/events/task_complete.md b/doc/events/task_complete.md new file mode 100644 index 000000000..eddec51d2 --- /dev/null +++ b/doc/events/task_complete.md @@ -0,0 +1,28 @@ +--- +module: [kind=event] task_complete +see: commands.execAsync To run a command which fires a task_complete event. +--- + +The @{task_complete} event is fired when an asynchronous task completes. This is usually handled inside the function call that queued the task; however, functions such as @{commands.execAsync} return immediately so the user can wait for completion. + +## Return Values +1. @{string}: The event name. +2. @{number}: The ID of the task that completed. +3. @{boolean}: Whether the command succeeded. +4. @{string}: If the command failed, an error message explaining the failure. (This is not present if the command succeeded.) +...: Any parameters returned from the command. + +## Example +Prints the results of an asynchronous command: +```lua +local taskID = commands.execAsync("say Hello") +local event +repeat + event = {os.pullEvent("task_complete")} +until event[2] == taskID +if event[3] == true then + print("Task " .. event[2] .. " succeeded:", table.unpack(event, 4)) +else + print("Task " .. event[2] .. " failed: " .. event[4]) +end +``` diff --git a/doc/events/term_resize.md b/doc/events/term_resize.md new file mode 100644 index 000000000..0eb503bad --- /dev/null +++ b/doc/events/term_resize.md @@ -0,0 +1,15 @@ +--- +module: [kind=event] term_resize +--- + +The @{term_resize} event is fired when the main terminal is resized, mainly when a new tab is opened or closed in @{multishell}. + +## Example +Prints : +```lua +while true do + os.pullEvent("term_resize") + local w, h = term.getSize() + print("The term was resized to (" .. w .. ", " .. h .. ")") +end +``` diff --git a/doc/events/terminate.md b/doc/events/terminate.md new file mode 100644 index 000000000..0760b8c3b --- /dev/null +++ b/doc/events/terminate.md @@ -0,0 +1,25 @@ +--- +module: [kind=event] terminate +--- + +The @{terminate} event is fired when Ctrl-T is held down. + +This event is normally handled by @{os.pullEvent}, and will not be returned. However, @{os.pullEventRaw} will return this event when fired. + +@{terminate} will be sent even when a filter is provided to @{os.pullEventRaw}. When using @{os.pullEventRaw} with a filter, make sure to check that the event is not @{terminate}. + +## Example +Prints a message when Ctrl-T is held: +```lua +while true do + local event = os.pullEventRaw("terminate") + if event == "terminate" then print("Terminate requested!") end +end +``` + +Exits when Ctrl-T is held: +```lua +while true do + os.pullEvent() +end +``` diff --git a/doc/events/timer.md b/doc/events/timer.md new file mode 100644 index 000000000..c359c37b4 --- /dev/null +++ b/doc/events/timer.md @@ -0,0 +1,21 @@ +--- +module: [kind=event] timer +see: os.startTimer To start a timer. +--- + +The @{timer} event is fired when a timer started with @{os.startTimer} completes. + +## Return Values +1. @{string}: The event name. +2. @{number}: The ID of the timer that finished. + +## Example +Starts a timer and then prints its ID: +```lua +local timerID = os.startTimer(2) +local event, id +repeat + event, id = os.pullEvent("timer") +until id == timerID +print("Timer with ID " .. id .. " was fired") +``` diff --git a/doc/events/turtle_inventory.md b/doc/events/turtle_inventory.md new file mode 100644 index 000000000..bc9392b6b --- /dev/null +++ b/doc/events/turtle_inventory.md @@ -0,0 +1,14 @@ +--- +module: [kind=event] turtle_inventory +--- + +The @{turtle_inventory} event is fired when a turtle's inventory is changed. + +## Example +Prints a message when the inventory is changed: +```lua +while true do + os.pullEvent("turtle_inventory") + print("The inventory was changed.") +end +``` diff --git a/doc/events/websocket_closed.md b/doc/events/websocket_closed.md new file mode 100644 index 000000000..9e3783d19 --- /dev/null +++ b/doc/events/websocket_closed.md @@ -0,0 +1,21 @@ +--- +module: [kind=event] websocket_closed +--- + +The @{websocket_closed} event is fired when an open WebSocket connection is closed. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL of the WebSocket that was closed. + +## Example +Prints a message when a WebSocket is closed (this may take a minute): +```lua +local myURL = "wss://example.tweaked.cc/echo" +local ws = http.websocket(myURL) +local event, url +repeat + event, url = os.pullEvent("websocket_closed") +until url == myURL +print("The WebSocket at " .. url .. " was closed.") +``` diff --git a/doc/events/websocket_failure.md b/doc/events/websocket_failure.md new file mode 100644 index 000000000..eef34e777 --- /dev/null +++ b/doc/events/websocket_failure.md @@ -0,0 +1,25 @@ +--- +module: [kind=event] websocket_failure +see: http.websocketAsync To send an HTTP request. +--- + +The @{websocket_failure} event is fired when a WebSocket connection request fails. + +This event is normally handled inside @{http.websocket}, but it can still be seen when using @{http.websocketAsync}. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL of the site requested. +3. @{string}: An error describing the failure. + +## Example +Prints an error why the website cannot be contacted: +```lua +local myURL = "wss://example.tweaked.cc/not-a-websocket" +http.websocketAsync(myURL) +local event, url, err +repeat + event, url, err = os.pullEvent("websocket_failure") +until url == myURL +print("The URL " .. url .. " could not be reached: " .. err) +``` diff --git a/doc/events/websocket_message.md b/doc/events/websocket_message.md new file mode 100644 index 000000000..839e214cc --- /dev/null +++ b/doc/events/websocket_message.md @@ -0,0 +1,27 @@ +--- +module: [kind=event] websocket_message +--- + +The @{websocket_message} event is fired when a message is received on an open WebSocket connection. + +This event is normally handled by @{http.Websocket.receive}, but it can also be pulled manually. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL of the WebSocket. +3. @{string}: The contents of the message. +4. @{boolean}: Whether this is a binary message. + +## Example +Prints a message sent by a WebSocket: +```lua +local myURL = "wss://example.tweaked.cc/echo" +local ws = http.websocket(myURL) +ws.send("Hello!") +local event, url, message +repeat + event, url, message = os.pullEvent("websocket_message") +until url == myURL +print("Received message from " .. url .. " with contents " .. message) +ws.close() +``` diff --git a/doc/events/websocket_success.md b/doc/events/websocket_success.md new file mode 100644 index 000000000..dcde934b3 --- /dev/null +++ b/doc/events/websocket_success.md @@ -0,0 +1,28 @@ +--- +module: [kind=event] websocket_success +see: http.websocketAsync To open a WebSocket asynchronously. +--- + +The @{websocket_success} event is fired when a WebSocket connection request returns successfully. + +This event is normally handled inside @{http.websocket}, but it can still be seen when using @{http.websocketAsync}. + +## Return Values +1. @{string}: The event name. +2. @{string}: The URL of the site. +3. @{http.Websocket}: The handle for the WebSocket. + +## Example +Prints the content of a website (this may fail if the request fails): +```lua +local myURL = "wss://example.tweaked.cc/echo" +http.websocketAsync(myURL) +local event, url, handle +repeat + event, url, handle = os.pullEvent("websocket_success") +until url == myURL +print("Connected to " .. url) +handle.send("Hello!") +print(handle.receive()) +handle.close() +``` diff --git a/doc/head.html b/doc/head.html new file mode 100644 index 000000000..efd18a401 --- /dev/null +++ b/doc/head.html @@ -0,0 +1 @@ + diff --git a/doc/images/basic-terminal.png b/doc/images/basic-terminal.png new file mode 100644 index 000000000..782b850cd Binary files /dev/null and b/doc/images/basic-terminal.png differ diff --git a/doc/images/peripherals.png b/doc/images/peripherals.png new file mode 100644 index 000000000..16c2e807d Binary files /dev/null and b/doc/images/peripherals.png differ diff --git a/doc/images/turtle.png b/doc/images/turtle.png new file mode 100644 index 000000000..7c58553a0 Binary files /dev/null and b/doc/images/turtle.png differ diff --git a/doc/index.md b/doc/index.md new file mode 100644 index 000000000..74d76434b --- /dev/null +++ b/doc/index.md @@ -0,0 +1,55 @@ +# ![CC: Tweaked](logo.png) +CC: Tweaked is a mod for Minecraft which adds programmable computers, turtles and more to the game. A fork of the +much-beloved [ComputerCraft], it continues its legacy with better performance, stability, and a wealth of new features. + +CC: Tweaked can be installed from [CurseForge] or [Modrinth]. It requires the [Minecraft Forge][forge] mod loader, but +[versions are available for Fabric][ccrestitched]. + +## Features +Controlled using the [Lua programming language][lua], CC: Tweaked's computers provides all the tools you need to start +writing code and automating your Minecraft world. + +![A ComputerCraft terminal open and ready to be programmed.](images/basic-terminal.png){.big-image} + +While computers are incredibly powerful, they're rather limited by their inability to move about. *Turtles* are the +solution here. They can move about the world, placing and breaking blocks, swinging a sword to protect you from zombies, +or whatever else you program them to! + +![A turtle tunneling in Minecraft.](images/turtle.png){.big-image} + +Not all problems can be solved with a pickaxe though, and so CC: Tweaked also provides a bunch of additional peripherals +for your computers. You can play a tune with speakers, display text or images on a monitor, connect all your +computers together with modems, and much more. + +Computers can now also interact with inventories such as chests, allowing you to build complex inventory and item +management systems. + +![A chest's contents being read by a computer and displayed on a monitor.](images/peripherals.png){.big-image} + +## Getting Started +While ComputerCraft is lovely for both experienced programmers and for people who have never coded before, it can be a +little daunting getting started. Thankfully, there's several fantastic tutorials out there: + + - [Direwolf20's ComputerCraft tutorials](https://www.youtube.com/watch?v=wrUHUhfCY5A "ComputerCraft Tutorial Episode 1 - HELP! and Hello World") + - [Sethbling's ComputerCraft series](https://www.youtube.com/watch?v=DSsx4VSe-Uk "Programming Tutorial with Minecraft Turtles -- Ep. 1: Intro to Turtles and If-Then-Else_End") + - [Lyqyd's Computer Basics 1](http://www.computercraft.info/forums2/index.php?/topic/15033-computer-basics-i/ "Computer Basics I") + +Once you're a little more familiar with the mod, the sidebar and links below provide more detailed documentation on the +various APIs and peripherals provided by the mod. + +If you get stuck, do pop in to the [Minecraft Computer Mod Discord guild][discord] or ComputerCraft's +[IRC channel][irc]. + +## Get Involved +CC: Tweaked lives on [GitHub]. If you've got any ideas, feedback or bugs please do [create an issue][bug]. + +[github]: https://github.com/cc-tweaked/CC-Tweaked/ "CC: Tweaked on GitHub" +[bug]: https://github.com/cc-tweaked/CC-Tweaked/issues/new/choose +[computercraft]: https://github.com/dan200/ComputerCraft "ComputerCraft on GitHub" +[curseforge]: https://minecraft.curseforge.com/projects/cc-tweaked "Download CC: Tweaked from CurseForge" +[modrinth]: https://modrinth.com/mod/gu7yAYhd "Download CC: Tweaked from Modrinth" +[forge]: https://files.minecraftforge.net/ "Download Minecraft Forge." +[ccrestitched]: https://www.curseforge.com/minecraft/mc-mods/cc-restitched "Download CC: Restitched from CurseForge" +[lua]: https://www.lua.org/ "Lua's main website" +[discord]: https://discord.computercraft.cc "The Minecraft Computer Mods Discord" +[irc]: http://webchat.esper.net/?channels=computercraft "IRC webchat on EsperNet" diff --git a/doc/logo.png b/doc/logo.png new file mode 100644 index 000000000..33b71f8b6 Binary files /dev/null and b/doc/logo.png differ diff --git a/doc/stub/fs.lua b/doc/stub/fs.lua new file mode 100644 index 000000000..aa40a30f3 --- /dev/null +++ b/doc/stub/fs.lua @@ -0,0 +1,36 @@ +--- The FS API allows you to manipulate files and the filesystem. +-- +-- @module fs + +--- Returns true if a path is mounted to the parent filesystem. +-- +-- The root filesystem "/" is considered a mount, along with disk folders and +-- the rom folder. Other programs (such as network shares) can exstend this to +-- make other mount types by correctly assigning their return value for getDrive. +-- +-- @tparam string path The path to check. +-- @treturn boolean If the path is mounted, rather than a normal file/folder. +-- @throws If the path does not exist. +-- @see getDrive +-- @since 1.87.0 +function isDriveRoot(path) end + +--[[- Provides completion for a file or directory name, suitable for use with +@{_G.read}. + +When a directory is a possible candidate for completion, two entries are +included - one with a trailing slash (indicating that entries within this +directory exist) and one without it (meaning this entry is an immediate +completion candidate). `include_dirs` can be set to @{false} to only include +those with a trailing slash. + +@tparam string path The path to complete. +@tparam string location The location where paths are resolved from. +@tparam[opt] boolean include_files When @{false}, only directories will be +included in the returned list. +@tparam[opt] boolean include_dirs When @{false}, "raw" directories will not be +included in the returned list. +@treturn { string... } A list of possible completion candidates. +@since 1.74 +]] +function complete(path, location, include_files, include_dirs) end diff --git a/doc/stub/global.lua b/doc/stub/global.lua new file mode 100644 index 000000000..a2d54fa12 --- /dev/null +++ b/doc/stub/global.lua @@ -0,0 +1,130 @@ +--[[- +Functions in the global environment, defined in `bios.lua`. This does not +include standard Lua functions. + +@module _G +]] + +--[[- Pauses execution for the specified number of seconds. + +As it waits for a fixed amount of world ticks, `time` will automatically be +rounded up to the nearest multiple of 0.05 seconds. If you are using coroutines +or the @{parallel|parallel API}, it will only pause execution of the current +thread, not the whole program. + +**Note** Because sleep internally uses timers, it is a function that yields. +This means that you can use it to prevent "Too long without yielding" errors, +however, as the minimum sleep time is 0.05 seconds, it will slow your program +down. + +**Warning** Internally, this function queues and waits for a timer event (using +@{os.startTimer}), however it does not listen for any other events. This means +that any event that occurs while sleeping will be entirely discarded. If you +need to receive events while sleeping, consider using @{os.startTimer|timers}, +or the @{parallel|parallel API}. + +@tparam number time The number of seconds to sleep for, rounded up to the +nearest multiple of 0.05. + +@see os.startTimer +@usage Sleep for three seconds. + + print("Sleeping for three seconds") + sleep(3) + print("Done!") +]] +function sleep(time) end + +--- Writes a line of text to the screen without a newline at the end, wrapping +-- text if necessary. +-- +-- @tparam string text The text to write to the string +-- @treturn number The number of lines written +-- @see print A wrapper around write that adds a newline and accepts multiple arguments +-- @usage write("Hello, world") +function write(text) end + +--- Prints the specified values to the screen separated by spaces, wrapping if +-- necessary. After printing, the cursor is moved to the next line. +-- +-- @param ... The values to print on the screen +-- @treturn number The number of lines written +-- @usage print("Hello, world!") +function print(...) end + +--- Prints the specified values to the screen in red, separated by spaces, +-- wrapping if necessary. After printing, the cursor is moved to the next line. +-- +-- @param ... The values to print on the screen +-- @usage printError("Something went wrong!") +function printError(...) end + +--[[- Reads user input from the terminal, automatically handling arrow keys, +pasting, character replacement, history scrollback, auto-completion, and +default values. + +@tparam[opt] string replaceChar A character to replace each typed character with. +This can be used for hiding passwords, for example. +@tparam[opt] table history A table holding history items that can be scrolled +back to with the up/down arrow keys. The oldest item is at index 1, while the +newest item is at the highest index. +@tparam[opt] function(partial: string):({ string... }|nil) completeFn A function +to be used for completion. This function should take the partial text typed so +far, and returns a list of possible completion options. +@tparam[opt] string default Default text which should already be entered into +the prompt. + +@treturn string The text typed in. + +@see cc.completion For functions to help with completion. +@usage Read a string and echo it back to the user + + write("> ") + local msg = read() + print(msg) + +@usage Prompt a user for a password. + + while true do + write("Password> ") + local pwd = read("*") + if pwd == "let me in" then break end + print("Incorrect password, try again.") + end + print("Logged in!") + +@usage A complete example with completion, history and a default value. + + local completion = require "cc.completion" + local history = { "potato", "orange", "apple" } + local choices = { "apple", "orange", "banana", "strawberry" } + write("> ") + local msg = read(nil, history, function(text) return completion.choice(text, choices) end, "app") + print(msg) + +@changed 1.74 Added `completeFn` parameter. +@changed 1.80pr1 Added `default` parameter. +]] +function read(replaceChar, history, completeFn, default) end + +--- The ComputerCraft and Minecraft version of the current computer environment. +-- +-- For example, `ComputerCraft 1.93.0 (Minecraft 1.15.2)`. +-- @usage _HOST +-- @since 1.76 +_HOST = _HOST + +--[[- The default computer settings as defined in the ComputerCraft +configuration. + +This is a comma-separated list of settings pairs defined by the mod +configuration or server owner. By default, it is empty. + +An example value to disable autocompletion: + + shell.autocomplete=false,lua.autocomplete=false,edit.autocomplete=false + +@usage _CC_DEFAULT_SETTINGS +@since 1.77 +]] +_CC_DEFAULT_SETTINGS = _CC_DEFAULT_SETTINGS diff --git a/doc/stub/http.lua b/doc/stub/http.lua new file mode 100644 index 000000000..81ba63753 --- /dev/null +++ b/doc/stub/http.lua @@ -0,0 +1,181 @@ +--- The http library allows communicating with web servers, sending and +-- receiving data from them. +-- +-- @module http +-- @since 1.1 + +--- Asynchronously make a HTTP request to the given url. +-- +-- This returns immediately, a [`http_success`](#http-success-event) or +-- [`http_failure`](#http-failure-event) will be queued once the request has +-- completed. +-- +-- @tparam string url The url to request +-- @tparam[opt] string body An optional string containing the body of the +-- request. If specified, a `POST` request will be made instead. +-- @tparam[opt] { [string] = string } headers Additional headers to send as part +-- of this request. +-- @tparam[opt] boolean binary Whether to make a binary HTTP request. If true, +-- the body will not be UTF-8 encoded, and the received response will not be +-- decoded. +-- +-- @tparam[2] { +-- url = string, body? = string, headers? = { [string] = string }, +-- binary? = boolean, method? = string, redirect? = boolean, +-- } request Options for the request. +-- +-- This table form is an expanded version of the previous syntax. All arguments +-- from above are passed in as fields instead (for instance, +-- `http.request("https://example.com")` becomes `http.request { url = +-- "https://example.com" }`). +-- +-- This table also accepts several additional options: +-- +-- - `method`: Which HTTP method to use, for instance `"PATCH"` or `"DELETE"`. +-- - `redirect`: Whether to follow HTTP redirects. Defaults to true. +-- +-- @see http.get For a synchronous way to make GET requests. +-- @see http.post For a synchronous way to make POST requests. +-- +-- @changed 1.63 Added argument for headers. +-- @changed 1.80pr1 Added argument for binary handles. +-- @changed 1.80pr1.6 Added support for table argument. +-- @changed 1.86.0 Added PATCH and TRACE methods. +function request(...) end + +--- Make a HTTP GET request to the given url. +-- +-- @tparam string url The url to request +-- @tparam[opt] { [string] = string } headers Additional headers to send as part +-- of this request. +-- @tparam[opt] boolean binary Whether to make a binary HTTP request. If true, +-- the body will not be UTF-8 encoded, and the received response will not be +-- decoded. +-- +-- @tparam[2] { +-- url = string, headers? = { [string] = string }, +-- binary? = boolean, method? = string, redirect? = boolean, +-- } request Options for the request. See @{http.request} for details on how +-- these options behave. +-- +-- @treturn Response The resulting http response, which can be read from. +-- @treturn[2] nil When the http request failed, such as in the event of a 404 +-- error or connection timeout. +-- @treturn string A message detailing why the request failed. +-- @treturn Response|nil The failing http response, if available. +-- +-- @changed 1.63 Added argument for headers. +-- @changed 1.80pr1 Response handles are now returned on error if available. +-- @changed 1.80pr1 Added argument for binary handles. +-- @changed 1.80pr1.6 Added support for table argument. +-- @changed 1.86.0 Added PATCH and TRACE methods. +-- +-- @usage Make a request to [example.tweaked.cc](https://example.tweaked.cc), +-- and print the returned page. +-- ```lua +-- local request = http.get("https://example.tweaked.cc") +-- print(request.readAll()) +-- -- => HTTP is working! +-- request.close() +-- ``` +function get(...) end + +--- Make a HTTP POST request to the given url. +-- +-- @tparam string url The url to request +-- @tparam string body The body of the POST request. +-- @tparam[opt] { [string] = string } headers Additional headers to send as part +-- of this request. +-- @tparam[opt] boolean binary Whether to make a binary HTTP request. If true, +-- the body will not be UTF-8 encoded, and the received response will not be +-- decoded. +-- +-- @tparam[2] { +-- url = string, body? = string, headers? = { [string] = string }, +-- binary? = boolean, method? = string, redirect? = boolean, +-- } request Options for the request. See @{http.request} for details on how +-- these options behave. +-- +-- @treturn Response The resulting http response, which can be read from. +-- @treturn[2] nil When the http request failed, such as in the event of a 404 +-- error or connection timeout. +-- @treturn string A message detailing why the request failed. +-- @treturn Response|nil The failing http response, if available. +-- +-- @since 1.31 +-- @changed 1.63 Added argument for headers. +-- @changed 1.80pr1 Response handles are now returned on error if available. +-- @changed 1.80pr1 Added argument for binary handles. +-- @changed 1.80pr1.6 Added support for table argument. +-- @changed 1.86.0 Added PATCH and TRACE methods. +function post(...) end + +--- Asynchronously determine whether a URL can be requested. +-- +-- If this returns `true`, one should also listen for [`http_check` +-- events](#http-check-event) which will container further information about +-- whether the URL is allowed or not. +-- +-- @tparam string url The URL to check. +-- @treturn true When this url is not invalid. This does not imply that it is +-- allowed - see the comment above. +-- @treturn[2] false When this url is invalid. +-- @treturn string A reason why this URL is not valid (for instance, if it is +-- malformed, or blocked). +-- +-- @see http.checkURL For a synchronous version. +function checkURLAsync(url) end + +--- Determine whether a URL can be requested. +-- +-- If this returns `true`, one should also listen for [`http_check` +-- events](#http-check-event) which will container further information about +-- whether the URL is allowed or not. +-- +-- @tparam string url The URL to check. +-- @treturn true When this url is valid and can be requested via @{http.request}. +-- @treturn[2] false When this url is invalid. +-- @treturn string A reason why this URL is not valid (for instance, if it is +-- malformed, or blocked). +-- +-- @see http.checkURLAsync For an asynchronous version. +-- +-- @usage +-- ```lua +-- print(http.checkURL("https://example.tweaked.cc/")) +-- -- => true +-- print(http.checkURL("http://localhost/")) +-- -- => false Domain not permitted +-- print(http.checkURL("not a url")) +-- -- => false URL malformed +-- ``` +function checkURL(url) end + +--- Open a websocket. +-- +-- @tparam string url The websocket url to connect to. This should have the +-- `ws://` or `wss://` protocol. +-- @tparam[opt] { [string] = string } headers Additional headers to send as part +-- of the initial websocket connection. +-- +-- @treturn Websocket The websocket connection. +-- @treturn[2] false If the websocket connection failed. +-- @treturn string An error message describing why the connection failed. +-- @since 1.80pr1.1 +-- @changed 1.80pr1.3 No longer asynchronous. +-- @changed 1.95.3 Added User-Agent to default headers. +function websocket(url, headers) end + +--- Asynchronously open a websocket. +-- +-- This returns immediately, a [`websocket_success`](#websocket-success-event) +-- or [`websocket_failure`](#websocket-failure-event) will be queued once the +-- request has completed. +-- +-- @tparam string url The websocket url to connect to. This should have the +-- `ws://` or `wss://` protocol. +-- @tparam[opt] { [string] = string } headers Additional headers to send as part +-- of the initial websocket connection. +-- @since 1.80pr1.3 +-- @changed 1.95.3 Added User-Agent to default headers. +function websocketAsync(url, headers) end diff --git a/doc/stub/os.lua b/doc/stub/os.lua new file mode 100644 index 000000000..39c051ceb --- /dev/null +++ b/doc/stub/os.lua @@ -0,0 +1,128 @@ +-- Defined in bios.lua + +--[[- Loads the given API into the global environment. + +This function loads and executes the file at the given path, and all global +variables and functions exported by it will by available through the use of +`myAPI.`, where `myAPI` is the base name of the API file. + +@tparam string path The path of the API to load. +@treturn boolean Whether or not the API was successfully loaded. +@since 1.2 + +@deprecated When possible it's best to avoid using this function. It pollutes +the global table and can mask errors. + +@{require} should be used to load libraries instead. +]] +function loadAPI(path) end + +--- Unloads an API which was loaded by @{os.loadAPI}. +-- +-- This effectively removes the specified table from `_G`. +-- +-- @tparam string name The name of the API to unload. +-- @since 1.2 +-- @deprecated See @{os.loadAPI} for why. +function unloadAPI(name) end + +--[[- Pause execution of the current thread and waits for any events matching +`filter`. + +This function @{coroutine.yield|yields} the current process and waits for it +to be resumed with a vararg list where the first element matches `filter`. +If no `filter` is supplied, this will match all events. + +Unlike @{os.pullEventRaw}, it will stop the application upon a "terminate" +event, printing the error "Terminated". + +@tparam[opt] string filter Event to filter for. +@treturn string event The name of the event that fired. +@treturn any param... Optional additional parameters of the event. +@usage Listen for `mouse_click` events. + + while true do + local event, button, x, y = os.pullEvent("mouse_click") + print("Button", button, "was clicked at", x, ",", y) + end + +@usage Listen for multiple events. + + while true do + local eventData = {os.pullEvent()} + local event = eventData[1] + + if event == "mouse_click" then + print("Button", eventData[2], "was clicked at", eventData[3], ",", eventData[4]) + elseif event == "key" then + print("Key code", eventData[2], "was pressed") + end + end + +@see os.pullEventRaw To pull the terminate event. +@changed 1.3 Added filter argument. +]] +function pullEvent(filter) end + +--[[- Pause execution of the current thread and waits for events, including the +`terminate` event. + +This behaves almost the same as @{os.pullEvent}, except it allows you to handle +the `terminate` event yourself - the program will not stop execution when +Ctrl+T is pressed. + +@tparam[opt] string filter Event to filter for. +@treturn string event The name of the event that fired. +@treturn any param... Optional additional parameters of the event. +@usage Listen for `terminate` events. + + while true do + local event = os.pullEventRaw() + if event == "terminate" then + print("Caught terminate event!") + end + end + +@see os.pullEvent To pull events normally. +]] +function pullEventRaw(filter) end + +--- Pauses execution for the specified number of seconds, alias of @{_G.sleep}. +-- +-- @tparam number time The number of seconds to sleep for, rounded up to the +-- nearest multiple of 0.05. +function sleep(time) end + +--- Get the current CraftOS version (for example, `CraftOS 1.8`). +-- +-- This is defined by `bios.lua`. For the current version of CC:Tweaked, this +-- should return `CraftOS 1.8`. +-- +-- @treturn string The current CraftOS version. +-- @usage os.version() +function version() end + +--[[- Run the program at the given path with the specified environment and +arguments. + +This function does not resolve program names like the shell does. This means +that, for example, `os.run("edit")` will not work. As well as this, it does not +provide access to the @{shell} API in the environment. For this behaviour, use +@{shell.run} instead. + +If the program cannot be found, or failed to run, it will print the error and +return `false`. If you want to handle this more gracefully, use an alternative +such as @{loadfile}. + +@tparam table env The environment to run the program with. +@tparam string path The exact path of the program to run. +@param ... The arguments to pass to the program. +@treturn boolean Whether or not the program ran successfully. +@usage Run the default shell from within your program: + + os.run({}, "/rom/programs/shell.lua") + +@see shell.run +@see loadfile +]] +function run(env, path, ...) end diff --git a/doc/stub/turtle.lua b/doc/stub/turtle.lua new file mode 100644 index 000000000..10ae68df7 --- /dev/null +++ b/doc/stub/turtle.lua @@ -0,0 +1,14 @@ +--[[- Craft a recipe based on the turtle's inventory. + +The turtle's inventory should set up like a crafting grid. For instance, to +craft sticks, slots 1 and 5 should contain planks. _All_ other slots should be +empty, including those outside the crafting "grid". + +@tparam[opt=64] number limit The maximum number of crafting steps to run. +@throws When limit is less than 1 or greater than 64. +@treturn[1] true If crafting succeeds. +@treturn[2] false If crafting fails. +@treturn string A string describing why crafting failed. +@since 1.4 +]] +function craft(limit) end diff --git a/gradle.properties b/gradle.properties index efe800f9d..149a41402 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,12 +6,10 @@ mod_version=1.97.2 # Minecraft properties mc_version=1.17.1 -mappings_version=61 - -# Dependencies -cloth_config_version=5.0.34 -fabric_loader_version=0.11.7 fabric_api_version=0.40.1+1.17 +fabric_loader_version=0.12.0 + +cloth_api_version=2.0.54 +cloth_config_version=5.0.34 jankson_version=1.2.0 modmenu_version=2.0.2 -cloth_api_version=2.0.54 diff --git a/illuaminate.sexp b/illuaminate.sexp new file mode 100644 index 000000000..ac3ae44e4 --- /dev/null +++ b/illuaminate.sexp @@ -0,0 +1,115 @@ +; -*- mode: Lisp;-*- + +(sources + /doc/stub/ + /doc/events/ + /build/docs/luaJavadoc/ + /src/main/resources/*/computercraft/lua/bios.lua + /src/main/resources/*/computercraft/lua/rom/ + /src/test/resources/test-rom + /src/web/mount) + + +(doc + (destination build/docs/lua) + (index doc/index.md) + + (site + (title "CC: Tweaked") + (logo src/main/resources/pack.png) + (url https://tweaked.cc/) + (source-link https://github.com/cc-tweaked/CC-Tweaked/blob/${commit}/${path}#L${line}) + + (styles src/web/styles.css) + (scripts build/rollup/index.js) + (head doc/head.html)) + + (module-kinds + (peripheral Peripherals) + (generic_peripheral "Generic Peripherals") + (event Events)) + + (library-path + /doc/stub/ + /build/docs/luaJavadoc/ + + /src/main/resources/*/computercraft/lua/rom/apis/ + /src/main/resources/*/computercraft/lua/rom/apis/command/ + /src/main/resources/*/computercraft/lua/rom/apis/turtle/ + + /src/main/resources/*/computercraft/lua/rom/modules/main/ + /src/main/resources/*/computercraft/lua/rom/modules/command/ + /src/main/resources/*/computercraft/lua/rom/modules/turtle/)) + +(at / + (linters + syntax:string-index + + ;; It'd be nice to avoid this, but right now there's a lot of instances of + ;; it. + -var:set-loop + + ;; It's useful to name arguments for documentation, so we allow this. It'd + ;; be good to find a compromise in the future, but this works for now. + -var:unused-arg) + + (lint + (bracket-spaces + (call no-space) + (function-args no-space) + (parens no-space) + (table space) + (index no-space)) + + (allow-clarifying-parens true) + + ;; colours imports from colors, and we don't handle that right now. + ;; keys is entirely dynamic, so we skip it. + (dynamic-modules colours keys _G) + + (globals + :max + _CC_DEFAULT_SETTINGS + _CC_DISABLE_LUA51_FEATURES + _HOST + ;; Ideally we'd pick these up from bios.lua, but illuaminate currently + ;; isn't smart enough. + sleep write printError read rs))) + +;; We disable the unused global linter in bios.lua and the APIs. In the future +;; hopefully we'll get illuaminate to handle this. +(at + (/src/main/resources/*/computercraft/lua/bios.lua + /src/main/resources/*/computercraft/lua/rom/apis/) + (linters -var:unused-global) + (lint (allow-toplevel-global true))) + +;; Silence some variable warnings in documentation stubs. +(at (/doc/stub/ /build/docs/luaJavadoc/) + (linters -var:unused-global) + (lint (allow-toplevel-global true))) + +;; Suppress warnings for currently undocumented modules. +(at + (; Lua APIs + /src/main/resources/*/computercraft/lua/rom/apis/io.lua + /src/main/resources/*/computercraft/lua/rom/apis/window.lua) + + (linters -doc:undocumented -doc:undocumented-arg -doc:undocumented-return)) + +;; Suppress warnings for various APIs using its own deprecated members. +(at + (/src/main/resources/*/computercraft/lua/bios.lua + /src/main/resources/*/computercraft/lua/rom/apis/turtle/turtle.lua) + (linters -var:deprecated)) + +(at /src/test/resources/test-rom + ; We should still be able to test deprecated members. + (linters -var:deprecated) + + (lint + (globals + :max sleep write + cct_test describe expect howlci fail it pending stub))) + +(at /src/web/mount/expr_template.lua (lint (globals :max __expr__))) diff --git a/src/main/java/dan200/computercraft/ComputerCraft.java b/src/main/java/dan200/computercraft/ComputerCraft.java index c79489d7d..00f116d64 100644 --- a/src/main/java/dan200/computercraft/ComputerCraft.java +++ b/src/main/java/dan200/computercraft/ComputerCraft.java @@ -6,7 +6,6 @@ package dan200.computercraft; -import dan200.computercraft.api.turtle.event.TurtleAction; import dan200.computercraft.core.apis.http.options.Action; import dan200.computercraft.core.apis.http.options.AddressRule; import dan200.computercraft.shared.ComputerCraftRegistry.ModBlocks; @@ -31,16 +30,15 @@ import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.fabric.api.resource.ResourcePackActivationType; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Arrays; import java.util.Collections; -import java.util.EnumSet; import java.util.List; import java.util.concurrent.TimeUnit; @@ -91,7 +89,6 @@ public final class ComputerCraft implements ModInitializer public static int advancedTurtleFuelLimit = 100000; public static boolean turtlesObeyBlockProtection = true; public static boolean turtlesCanPush = true; - public static EnumSet turtleDisabledActions = EnumSet.noneOf( TurtleAction.class ); public static int computerTermWidth = 51; public static int computerTermHeight = 19; @@ -111,30 +108,30 @@ public final class ComputerCraft implements ModInitializer // Logging public static final Logger log = LogManager.getLogger( MOD_ID ); - public static ItemGroup MAIN_GROUP = FabricItemGroupBuilder.build( new Identifier( MOD_ID, "main" ), () -> new ItemStack( ModBlocks.COMPUTER_NORMAL ) ); + public static CreativeModeTab MAIN_GROUP = FabricItemGroupBuilder.build( new ResourceLocation( MOD_ID, "main" ), () -> new ItemStack( ModBlocks.COMPUTER_NORMAL ) ); @Override public void onInitialize() { ComputerCraftProxyCommon.init(); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "colour" ), ColourableRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "computer_upgrade" ), ComputerUpgradeRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "colour" ), ColourableRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "computer_upgrade" ), ComputerUpgradeRecipe.SERIALIZER ); Registry.register( Registry.RECIPE_SERIALIZER, - new Identifier( ComputerCraft.MOD_ID, "pocket_computer_upgrade" ), + new ResourceLocation( ComputerCraft.MOD_ID, "pocket_computer_upgrade" ), PocketComputerUpgradeRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "disk" ), DiskRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "printout" ), PrintoutRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "turtle" ), TurtleRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "turtle_upgrade" ), TurtleUpgradeRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "impostor_shaped" ), ImpostorRecipe.SERIALIZER ); - Registry.register( Registry.RECIPE_SERIALIZER, new Identifier( ComputerCraft.MOD_ID, "impostor_shapeless" ), ImpostorShapelessRecipe.SERIALIZER ); - Registry.register( Registry.LOOT_CONDITION_TYPE, new Identifier( ComputerCraft.MOD_ID, "block_named" ), BlockNamedEntityLootCondition.TYPE ); - Registry.register( Registry.LOOT_CONDITION_TYPE, new Identifier( ComputerCraft.MOD_ID, "player_creative" ), PlayerCreativeLootCondition.TYPE ); - Registry.register( Registry.LOOT_CONDITION_TYPE, new Identifier( ComputerCraft.MOD_ID, "has_id" ), HasComputerIdLootCondition.TYPE ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "disk" ), DiskRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "printout" ), PrintoutRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "turtle" ), TurtleRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "turtle_upgrade" ), TurtleUpgradeRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "impostor_shaped" ), ImpostorRecipe.SERIALIZER ); + Registry.register( Registry.RECIPE_SERIALIZER, new ResourceLocation( ComputerCraft.MOD_ID, "impostor_shapeless" ), ImpostorShapelessRecipe.SERIALIZER ); + Registry.register( Registry.LOOT_CONDITION_TYPE, new ResourceLocation( ComputerCraft.MOD_ID, "block_named" ), BlockNamedEntityLootCondition.TYPE ); + Registry.register( Registry.LOOT_CONDITION_TYPE, new ResourceLocation( ComputerCraft.MOD_ID, "player_creative" ), PlayerCreativeLootCondition.TYPE ); + Registry.register( Registry.LOOT_CONDITION_TYPE, new ResourceLocation( ComputerCraft.MOD_ID, "has_id" ), HasComputerIdLootCondition.TYPE ); init(); FabricLoader.getInstance().getModContainer( MOD_ID ).ifPresent( modContainer -> { - ResourceManagerHelper.registerBuiltinResourcePack( new Identifier( MOD_ID, "classic" ), modContainer, ResourcePackActivationType.NORMAL ); - ResourceManagerHelper.registerBuiltinResourcePack( new Identifier( MOD_ID, "overhaul" ), modContainer, ResourcePackActivationType.NORMAL ); + ResourceManagerHelper.registerBuiltinResourcePack( new ResourceLocation( MOD_ID, "classic" ), modContainer, ResourcePackActivationType.NORMAL ); + ResourceManagerHelper.registerBuiltinResourcePack( new ResourceLocation( MOD_ID, "overhaul" ), modContainer, ResourcePackActivationType.NORMAL ); } ); } } diff --git a/src/main/java/dan200/computercraft/ComputerCraftAPIImpl.java b/src/main/java/dan200/computercraft/ComputerCraftAPIImpl.java index 5e8128645..068114705 100644 --- a/src/main/java/dan200/computercraft/ComputerCraftAPIImpl.java +++ b/src/main/java/dan200/computercraft/ComputerCraftAPIImpl.java @@ -32,14 +32,14 @@ import dan200.computercraft.shared.util.IDAssigner; import dan200.computercraft.shared.wired.WiredNode; import me.shedaniel.cloth.api.utils.v1.GameInstanceUtils; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.resource.ReloadableResourceManager; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; +import net.minecraft.server.packs.resources.ReloadableResourceManager; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -62,10 +62,10 @@ public final class ComputerCraftAPIImpl implements IComputerCraftAPI MinecraftServer server = GameInstanceUtils.getServer(); if( server != null ) { - ReloadableResourceManager manager = (ReloadableResourceManager) ((MinecraftServerAccess) server).getServerResourceManager().getResourceManager(); + ReloadableResourceManager manager = (ReloadableResourceManager) ((MinecraftServerAccess) server).callGetResourceManager(); try { - return manager.getResource( new Identifier( domain, subPath ) ) + return manager.getResource( new ResourceLocation( domain, subPath ) ) .getInputStream(); } catch( IOException ignored ) @@ -93,13 +93,13 @@ public final class ComputerCraftAPIImpl implements IComputerCraftAPI } @Override - public int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath ) + public int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath ) { return IDAssigner.getNextId( parentSubPath ); } @Override - public IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity ) + public IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity ) { try { @@ -117,7 +117,7 @@ public final class ComputerCraftAPIImpl implements IComputerCraftAPI MinecraftServer server = GameInstanceUtils.getServer(); if( server != null ) { - ReloadableResourceManager manager = (ReloadableResourceManager) ((MinecraftServerAccess) server).getServerResourceManager().getResourceManager(); + ReloadableResourceManager manager = (ReloadableResourceManager) ((MinecraftServerAccess) server).callGetResourceManager(); ResourceMount mount = ResourceMount.get( domain, subPath, manager ); return mount.exists( "" ) ? mount : null; } @@ -143,7 +143,7 @@ public final class ComputerCraftAPIImpl implements IComputerCraftAPI } @Override - public int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) { return BundledRedstone.getDefaultOutput( world, pos, side ); } @@ -188,7 +188,7 @@ public final class ComputerCraftAPIImpl implements IComputerCraftAPI @Nullable @Override - public IWiredElement getWiredElementAt( @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public IWiredElement getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side ) { BlockEntity tile = world.getBlockEntity( pos ); if( tile instanceof TileCable ) diff --git a/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java b/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java index c1f8ed540..bef9f90d7 100644 --- a/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java +++ b/src/main/java/dan200/computercraft/api/ComputerCraftAPI.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api; import dan200.computercraft.api.filesystem.IMount; @@ -21,10 +20,10 @@ import dan200.computercraft.api.peripheral.IPeripheralProvider; import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.redstone.IBundledRedstoneProvider; import dan200.computercraft.api.turtle.ITurtleUpgrade; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -32,19 +31,11 @@ import javax.annotation.Nullable; /** * The static entry point to the ComputerCraft API. * - * Members in this class must be called after mod_ComputerCraft has been initialised, but may be called before it is fully loaded. + * Members in this class must be called after mod_ComputerCraft has been initialised, but may be called before it is + * fully loaded. */ public final class ComputerCraftAPI { - private static IComputerCraftAPI instance; - - @Nonnull - @Deprecated - public static String getAPIVersion() - { - return getInstalledVersion(); - } - @Nonnull public static String getInstalledVersion() { @@ -52,23 +43,10 @@ public final class ComputerCraftAPI } @Nonnull - private static IComputerCraftAPI getInstance() + @Deprecated + public static String getAPIVersion() { - if( instance != null ) - { - return instance; - } - - try - { - return instance = (IComputerCraftAPI) Class.forName( "dan200.computercraft.ComputerCraftAPIImpl" ) - .getField( "INSTANCE" ) - .get( null ); - } - catch( ReflectiveOperationException e ) - { - throw new IllegalStateException( "Cannot find ComputerCraft API", e ); - } + return getInstalledVersion(); } /** @@ -80,10 +58,11 @@ public final class ComputerCraftAPI * @param parentSubPath The folder path within the save directory where the new directory should be created. eg: "computercraft/disk" * @return The numerical value of the name of the new folder, or -1 if the folder could not be created for some reason. * - * eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now available for writing. - * @see #createSaveDirMount(World, String, long) + * eg: if createUniqueNumberedSaveDir( world, "computer/disk" ) was called returns 42, then "computer/disk/42" is now + * available for writing. + * @see #createSaveDirMount(Level, String, long) */ - public static int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath ) + public static int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath ) { return getInstance().createUniqueNumberedSaveDir( world, parentSubPath ); } @@ -91,23 +70,23 @@ public final class ComputerCraftAPI /** * Creates a file system mount that maps to a subfolder of the save directory for a given world, and returns it. * - * Use in conjunction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the users save directory onto a computers - * file system. + * Use in conjunction with IComputerAccess.mount() or IComputerAccess.mountWritable() to mount a folder from the + * users save directory onto a computers file system. * * @param world The world for which the save dir can be found. This should be the server side world object. - * @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42". Use createUniqueNumberedSaveDir() - * to create a new numbered folder to use. + * @param subPath The folder path within the save directory that the mount should map to. eg: "computer/disk/42". + * Use createUniqueNumberedSaveDir() to create a new numbered folder to use. * @param capacity The amount of data that can be stored in the directory before it fills up, in bytes. - * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() to mount this on a - * Computers' file system. - * @see #createUniqueNumberedSaveDir(World, String) + * @return The mount, or null if it could be created for some reason. Use IComputerAccess.mount() or IComputerAccess.mountWritable() + * to mount this on a Computers' file system. + * @see #createUniqueNumberedSaveDir(Level, String) * @see IComputerAccess#mount(String, IMount) * @see IComputerAccess#mountWritable(String, IWritableMount) * @see IMount * @see IWritableMount */ @Nullable - public static IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity ) + public static IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity ) { return getInstance().createSaveDirMount( world, subPath, capacity ); } @@ -115,8 +94,8 @@ public final class ComputerCraftAPI /** * Creates a file system mount to a resource folder, and returns it. * - * Use in conjunction with {@link IComputerAccess#mount} or {@link IComputerAccess#mountWritable} to mount a resource folder onto a computer's file - * system. + * Use in conjunction with {@link IComputerAccess#mount} or {@link IComputerAccess#mountWritable} to mount a + * resource folder onto a computer's file system. * * The files in this mount will be a combination of files in all mod jar, and data packs that contain * resources with the same domain and path. For instance, ComputerCraft's resources are stored in @@ -137,7 +116,7 @@ public final class ComputerCraftAPI } /** - * Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations. + * rers a peripheral provider to convert blocks into {@link IPeripheral} implementations. * * @param provider The peripheral provider to register. * @see IPeripheral @@ -160,8 +139,9 @@ public final class ComputerCraftAPI } /** - * Registers a new turtle turtle for use in ComputerCraft. After calling this, users should be able to craft Turtles with your new turtle. It is - * recommended to call this during the load() method of your mod. + * Registers a new turtle turtle for use in ComputerCraft. After calling this, + * users should be able to craft Turtles with your new turtle. It is recommended to call + * this during the load() method of your mod. * * @param upgrade The turtle upgrade to register. * @see ITurtleUpgrade @@ -188,11 +168,11 @@ public final class ComputerCraftAPI * @param world The world this block is in. * @param pos The position this block is at. * @param side The side to extract the bundled redstone output from. - * @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned. If there is no block - * capable of emitting bundled redstone at the location, -1 will be returned. + * @return If there is a block capable of emitting bundled redstone at the location, it's signal (0-65535) will be returned. + * If there is no block capable of emitting bundled redstone at the location, -1 will be returned. * @see IBundledRedstoneProvider */ - public static int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public static int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) { return getInstance().getBundledRedstoneOutput( world, pos, side ); } @@ -251,20 +231,38 @@ public final class ComputerCraftAPI * @see IWiredElement#getNode() */ @Nullable - public static IWiredElement getWiredElementAt( @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public static IWiredElement getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side ) { return getInstance().getWiredElementAt( world, pos, side ); } + private static IComputerCraftAPI instance; + + @Nonnull + private static IComputerCraftAPI getInstance() + { + if( instance != null ) return instance; + + try + { + return instance = (IComputerCraftAPI) Class.forName( "dan200.computercraft.ComputerCraftAPIImpl" ) + .getField( "INSTANCE" ).get( null ); + } + catch( ReflectiveOperationException e ) + { + throw new IllegalStateException( "Cannot find ComputerCraft API", e ); + } + } + public interface IComputerCraftAPI { @Nonnull String getInstalledVersion(); - int createUniqueNumberedSaveDir( @Nonnull World world, @Nonnull String parentSubPath ); + int createUniqueNumberedSaveDir( @Nonnull Level world, @Nonnull String parentSubPath ); @Nullable - IWritableMount createSaveDirMount( @Nonnull World world, @Nonnull String subPath, long capacity ); + IWritableMount createSaveDirMount( @Nonnull Level world, @Nonnull String subPath, long capacity ); @Nullable IMount createResourceMount( @Nonnull String domain, @Nonnull String subPath ); @@ -277,7 +275,7 @@ public final class ComputerCraftAPI void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider ); - int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ); + int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ); void registerMediaProvider( @Nonnull IMediaProvider provider ); @@ -292,6 +290,6 @@ public final class ComputerCraftAPI IWiredNode createWiredNodeForElement( @Nonnull IWiredElement element ); @Nullable - IWiredElement getWiredElementAt( @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction side ); + IWiredElement getWiredElementAt( @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction side ); } } diff --git a/src/main/java/dan200/computercraft/api/IUpgradeBase.java b/src/main/java/dan200/computercraft/api/IUpgradeBase.java index ee9b6e500..d87c404bb 100644 --- a/src/main/java/dan200/computercraft/api/IUpgradeBase.java +++ b/src/main/java/dan200/computercraft/api/IUpgradeBase.java @@ -7,9 +7,9 @@ package dan200.computercraft.api; import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.api.turtle.ITurtleUpgrade; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.Identifier; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -28,7 +28,7 @@ public interface IUpgradeBase * @return The unique ID for this upgrade. */ @Nonnull - Identifier getUpgradeID(); + ResourceLocation getUpgradeID(); /** * Return an unlocalised string to describe this type of computer in item names. @@ -67,8 +67,6 @@ public interface IUpgradeBase * @param stack The stack to check. This is guaranteed to be non-empty and have the same item as * {@link #getCraftingItem()}. * @return If this stack may be used to equip this upgrade. - * @see net.minecraftforge.common.crafting.NBTIngredient#test(ItemStack) For the implementation of the default - * check. */ default boolean isItemSuitable( @Nonnull ItemStack stack ) { @@ -76,8 +74,8 @@ public interface IUpgradeBase // A more expanded form of ItemStack.areShareTagsEqual, but allowing an empty tag to be equal to a // null one. - NbtCompound shareTag = stack.getNbt(); - NbtCompound craftingShareTag = crafting.getNbt(); + CompoundTag shareTag = stack.getTag(); + CompoundTag craftingShareTag = crafting.getTag(); if( shareTag == craftingShareTag ) return true; if( shareTag == null ) return craftingShareTag.isEmpty(); if( craftingShareTag == null ) return shareTag.isEmpty(); diff --git a/src/main/java/dan200/computercraft/api/client/TransformedModel.java b/src/main/java/dan200/computercraft/api/client/TransformedModel.java index 201d53333..5a439da61 100644 --- a/src/main/java/dan200/computercraft/api/client/TransformedModel.java +++ b/src/main/java/dan200/computercraft/api/client/TransformedModel.java @@ -6,16 +6,16 @@ package dan200.computercraft.api.client; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Transformation; +import com.mojang.math.Vector3f; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.BakedModelManager; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.util.math.AffineTransformation; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.Vec3f; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelManager; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import java.util.Objects; @@ -27,9 +27,9 @@ import java.util.Objects; public final class TransformedModel { private final BakedModel model; - private final AffineTransformation matrix; + private final Transformation matrix; - public TransformedModel( @Nonnull BakedModel model, @Nonnull AffineTransformation matrix ) + public TransformedModel( @Nonnull BakedModel model, @Nonnull Transformation matrix ) { this.model = Objects.requireNonNull( model ); this.matrix = Objects.requireNonNull( matrix ); @@ -38,22 +38,18 @@ public final class TransformedModel public TransformedModel( @Nonnull BakedModel model ) { this.model = Objects.requireNonNull( model ); - matrix = AffineTransformation.identity(); + matrix = Transformation.identity(); } - public static TransformedModel of( @Nonnull ModelIdentifier location ) + public static TransformedModel of( @Nonnull ModelResourceLocation location ) { - BakedModelManager modelManager = MinecraftClient.getInstance() - .getBakedModelManager(); + ModelManager modelManager = Minecraft.getInstance().getModelManager(); return new TransformedModel( modelManager.getModel( location ) ); } - public static TransformedModel of( @Nonnull ItemStack item, @Nonnull AffineTransformation transform ) + public static TransformedModel of( @Nonnull ItemStack item, @Nonnull Transformation transform ) { - BakedModel model = MinecraftClient.getInstance() - .getItemRenderer() - .getModels() - .getModel( item ); + BakedModel model = Minecraft.getInstance().getItemRenderer().getItemModelShaper().getItemModel( item ); return new TransformedModel( model, transform ); } @@ -64,23 +60,23 @@ public final class TransformedModel } @Nonnull - public AffineTransformation getMatrix() + public Transformation getMatrix() { return matrix; } - public void push( MatrixStack matrixStack ) + public void push( PoseStack matrixStack ) { - matrixStack.push(); + matrixStack.pushPose(); - Vec3f translation = matrix.getTranslation(); - matrixStack.translate( translation.getX(), translation.getY(), translation.getZ() ); + Vector3f translation = matrix.getTranslation(); + matrixStack.translate( translation.x(), translation.y(), translation.z() ); - matrixStack.multiply( matrix.getRotation2() ); + matrixStack.mulPose( matrix.getLeftRotation() ); - Vec3f scale = matrix.getScale(); - matrixStack.scale( scale.getX(), scale.getY(), scale.getZ() ); + Vector3f scale = matrix.getScale(); + matrixStack.scale( scale.x(), scale.y(), scale.z() ); - matrixStack.multiply( matrix.getRotation1() ); + matrixStack.mulPose( matrix.getRightRotation() ); } } diff --git a/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java b/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java index 20db37caa..82aa83686 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java +++ b/src/main/java/dan200/computercraft/api/filesystem/FileAttributes.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.filesystem; import java.nio.file.attribute.BasicFileAttributes; diff --git a/src/main/java/dan200/computercraft/api/filesystem/FileOperationException.java b/src/main/java/dan200/computercraft/api/filesystem/FileOperationException.java index dc08e0268..638c61486 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/FileOperationException.java +++ b/src/main/java/dan200/computercraft/api/filesystem/FileOperationException.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.filesystem; import javax.annotation.Nonnull; diff --git a/src/main/java/dan200/computercraft/api/filesystem/IFileSystem.java b/src/main/java/dan200/computercraft/api/filesystem/IFileSystem.java index 8c74731e3..7ce152db7 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/IFileSystem.java +++ b/src/main/java/dan200/computercraft/api/filesystem/IFileSystem.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.filesystem; import java.io.IOException; diff --git a/src/main/java/dan200/computercraft/api/filesystem/IMount.java b/src/main/java/dan200/computercraft/api/filesystem/IMount.java index 9634cbb57..680f6fac3 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/IMount.java +++ b/src/main/java/dan200/computercraft/api/filesystem/IMount.java @@ -3,12 +3,11 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.filesystem; import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.peripheral.IComputerAccess; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import java.io.IOException; @@ -17,55 +16,20 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.List; /** - * Represents a read only part of a virtual filesystem that can be mounted onto a computer using {@link IComputerAccess#mount(String, IMount)}. + * Represents a read only part of a virtual filesystem that can be mounted onto a computer using + * {@link IComputerAccess#mount(String, IMount)}. * - * Ready made implementations of this interface can be created using {@link ComputerCraftAPI#createSaveDirMount(World, String, long)} or {@link - * ComputerCraftAPI#createResourceMount(String, String)}, or you're free to implement it yourselves! + * Ready made implementations of this interface can be created using + * {@link ComputerCraftAPI#createSaveDirMount(Level, String, long)} or + * {@link ComputerCraftAPI#createResourceMount(String, String)}, or you're free to implement it yourselves! * - * @see ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see ComputerCraftAPI#createResourceMount(String, String) * @see IComputerAccess#mount(String, IMount) * @see IWritableMount */ public interface IMount { - /** - * Returns the file names of all the files in a directory. - * - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms". - * @param contents A list of strings. Add all the file names to this list. - * @throws IOException If the file was not a directory, or could not be listed. - */ - void list( @Nonnull String path, @Nonnull List contents ) throws IOException; - - /** - * Opens a file with a given path, and returns an {@link ReadableByteChannel} representing its contents. - * - * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". - * @return A channel representing the contents of the file. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one will be able to - * seek to arbitrary positions when using binary mode. - * @throws IOException If the file does not exist, or could not be opened. - */ - @Nonnull - ReadableByteChannel openForRead( @Nonnull String path ) throws IOException; - - /** - * Get attributes about the given file. - * - * @param path The path to query. - * @return File attributes for the given file. - * @throws IOException If the file does not exist, or attributes could not be fetched. - */ - @Nonnull - default BasicFileAttributes getAttributes( @Nonnull String path ) throws IOException - { - if( !exists( path ) ) - { - throw new FileOperationException( path, "No such file" ); - } - return new FileAttributes( isDirectory( path ), getSize( path ) ); - } - /** * Returns whether a file with a given path exists or not. * @@ -84,6 +48,15 @@ public interface IMount */ boolean isDirectory( @Nonnull String path ) throws IOException; + /** + * Returns the file names of all the files in a directory. + * + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprograms". + * @param contents A list of strings. Add all the file names to this list. + * @throws IOException If the file was not a directory, or could not be listed. + */ + void list( @Nonnull String path, @Nonnull List contents ) throws IOException; + /** * Returns the size of a file with a given path, in bytes. * @@ -92,4 +65,30 @@ public interface IMount * @throws IOException If the file does not exist, or its size could not be determined. */ long getSize( @Nonnull String path ) throws IOException; + + /** + * Opens a file with a given path, and returns an {@link ReadableByteChannel} representing its contents. + * + * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". + * @return A channel representing the contents of the file. If the channel implements + * {@link java.nio.channels.SeekableByteChannel}, one will be able to seek to arbitrary positions when using binary + * mode. + * @throws IOException If the file does not exist, or could not be opened. + */ + @Nonnull + ReadableByteChannel openForRead( @Nonnull String path ) throws IOException; + + /** + * Get attributes about the given file. + * + * @param path The path to query. + * @return File attributes for the given file. + * @throws IOException If the file does not exist, or attributes could not be fetched. + */ + @Nonnull + default BasicFileAttributes getAttributes( @Nonnull String path ) throws IOException + { + if( !exists( path ) ) throw new FileOperationException( path, "No such file" ); + return new FileAttributes( isDirectory( path ), getSize( path ) ); + } } diff --git a/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java b/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java index d39eec86c..b1d7ca8ee 100644 --- a/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java +++ b/src/main/java/dan200/computercraft/api/filesystem/IWritableMount.java @@ -3,12 +3,11 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.filesystem; import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.peripheral.IComputerAccess; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import java.io.IOException; @@ -17,13 +16,13 @@ import java.nio.channels.WritableByteChannel; import java.util.OptionalLong; /** - * Represents a part of a virtual filesystem that can be mounted onto a computer using {@link IComputerAccess#mount(String, IMount)} or {@link - * IComputerAccess#mountWritable(String, IWritableMount)}, that can also be written to. + * Represents a part of a virtual filesystem that can be mounted onto a computer using {@link IComputerAccess#mount(String, IMount)} + * or {@link IComputerAccess#mountWritable(String, IWritableMount)}, that can also be written to. * - * Ready made implementations of this interface can be created using {@link ComputerCraftAPI#createSaveDirMount(World, String, long)}, or you're free to - * implement it yourselves! + * Ready made implementations of this interface can be created using + * {@link ComputerCraftAPI#createSaveDirMount(Level, String, long)}, or you're free to implement it yourselves! * - * @see ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see IComputerAccess#mount(String, IMount) * @see IComputerAccess#mountWritable(String, IWritableMount) * @see IMount @@ -50,8 +49,8 @@ public interface IWritableMount extends IMount * Opens a file with a given path, and returns an {@link OutputStream} for writing to it. * * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". - * @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one will be able to seek to arbitrary - * positions when using binary mode. + * @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one + * will be able to seek to arbitrary positions when using binary mode. * @throws IOException If the file could not be opened for writing. */ @Nonnull @@ -61,16 +60,16 @@ public interface IWritableMount extends IMount * Opens a file with a given path, and returns an {@link OutputStream} for appending to it. * * @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram". - * @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one will be able to seek to arbitrary - * positions when using binary mode. + * @return A stream for writing to. If the channel implements {@link java.nio.channels.SeekableByteChannel}, one + * will be able to seek to arbitrary positions when using binary mode. * @throws IOException If the file could not be opened for writing. */ @Nonnull WritableByteChannel openForAppend( @Nonnull String path ) throws IOException; /** - * Get the amount of free space on the mount, in bytes. You should decrease this value as the user writes to the mount, and write operations should fail - * once it reaches zero. + * Get the amount of free space on the mount, in bytes. You should decrease this value as the user writes to the + * mount, and write operations should fail once it reaches zero. * * @return The amount of free space, in bytes. * @throws IOException If the remaining space could not be computed. @@ -78,7 +77,8 @@ public interface IWritableMount extends IMount long getRemainingSpace() throws IOException; /** - * Get the capacity of this mount. This should be equal to the size of all files/directories on this mount, minus the {@link #getRemainingSpace()}. + * Get the capacity of this mount. This should be equal to the size of all files/directories on this mount, minus + * the {@link #getRemainingSpace()}. * * @return The capacity of this mount, in bytes. */ diff --git a/src/main/java/dan200/computercraft/api/lua/GenericSource.java b/src/main/java/dan200/computercraft/api/lua/GenericSource.java index f109f9d37..c29cf4991 100644 --- a/src/main/java/dan200/computercraft/api/lua/GenericSource.java +++ b/src/main/java/dan200/computercraft/api/lua/GenericSource.java @@ -9,7 +9,8 @@ import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.IPeripheralProvider; import dan200.computercraft.core.asm.LuaMethod; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.Container; import javax.annotation.Nonnull; @@ -18,20 +19,19 @@ import javax.annotation.Nonnull; * * Unlike normal objects ({@link IDynamicLuaObject} or {@link IPeripheral}), methods do not target this object but * instead are defined as {@code static} and accept their target as the first parameter. This allows you to inject - * methods onto objects you do not own, as well as declaring methods for a specific "trait" (for instance, a - * {@link Capability}). + * methods onto objects you do not own, as well as declaring methods for a specific "trait" (well, interface). * * Currently the "generic peripheral" system is incompatible with normal peripherals. Normal {@link IPeripheralProvider} * or {@link IPeripheral} implementations take priority. Tile entities which use this system are given a peripheral name * determined by their id, rather than any peripheral provider. This will hopefully change in the future, once a suitable * design has been established. * - * For example, the main CC: Tweaked mod defines a generic source for inventories, which works on {@link IItemHandler}s: + * For example, the main CC: Tweaked mod defines a generic source for inventories, which works on {@link Container}s: * *
{@code
  * public class InventoryMethods implements GenericSource {
  *     \@LuaFunction( mainThread = true )
- *     public static int size(IItemHandler inventory) {
+ *     public static int size(Container inventory) {
  *         return inventory.getSlots();
  *     }
  *
@@ -40,8 +40,6 @@ import javax.annotation.Nonnull;
  * }
* * @see ComputerCraftAPI#registerGenericSource(GenericSource) - * @see ComputerCraftAPI#registerGenericCapability(Capability) New capabilities (those not built into Forge) must be - * explicitly given to the generic peripheral system, as there is no way to enumerate all capabilities. */ public interface GenericSource { @@ -54,5 +52,5 @@ public interface GenericSource * @return This source's identifier. */ @Nonnull - Identifier id(); + ResourceLocation id(); } diff --git a/src/main/java/dan200/computercraft/api/lua/IArguments.java b/src/main/java/dan200/computercraft/api/lua/IArguments.java index 5546176ca..02e8b659d 100644 --- a/src/main/java/dan200/computercraft/api/lua/IArguments.java +++ b/src/main/java/dan200/computercraft/api/lua/IArguments.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nonnull; @@ -19,25 +18,6 @@ import static dan200.computercraft.api.lua.LuaValues.checkFinite; */ public interface IArguments { - /** - * Drop a number of arguments. The returned arguments instance will access arguments at position {@code i + count}, rather than {@code i}. However, - * errors will still use the given argument index. - * - * @param count The number of arguments to drop. - * @return The new {@link IArguments} instance. - */ - IArguments drop( int count ); - - default Object[] getAll() - { - Object[] result = new Object[count()]; - for( int i = 0; i < result.length; i++ ) - { - result[i] = get( i ); - } - return result; - } - /** * Get the number of arguments passed to this function. * @@ -62,6 +42,37 @@ public interface IArguments @Nullable Object get( int index ); + /** + * Drop a number of arguments. The returned arguments instance will access arguments at position {@code i + count}, + * rather than {@code i}. However, errors will still use the given argument index. + * + * @param count The number of arguments to drop. + * @return The new {@link IArguments} instance. + */ + IArguments drop( int count ); + + default Object[] getAll() + { + Object[] result = new Object[count()]; + for( int i = 0; i < result.length; i++ ) result[i] = get( i ); + return result; + } + + /** + * Get an argument as a double. + * + * @param index The argument number. + * @return The argument's value. + * @throws LuaException If the value is not a number. + * @see #getFiniteDouble(int) if you require this to be finite (i.e. not infinite or NaN). + */ + default double getDouble( int index ) throws LuaException + { + Object value = get( index ); + if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return ((Number) value).doubleValue(); + } + /** * Get an argument as an integer. * @@ -84,12 +95,8 @@ public interface IArguments default long getLong( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof Number) ) - { - throw LuaValues.badArgumentOf( index, "number", value ); - } - return LuaValues.checkFiniteNum( index, (Number) value ) - .longValue(); + if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return LuaValues.checkFiniteNum( index, (Number) value ).longValue(); } /** @@ -104,24 +111,6 @@ public interface IArguments return checkFinite( index, getDouble( index ) ); } - /** - * Get an argument as a double. - * - * @param index The argument number. - * @return The argument's value. - * @throws LuaException If the value is not a number. - * @see #getFiniteDouble(int) if you require this to be finite (i.e. not infinite or NaN). - */ - default double getDouble( int index ) throws LuaException - { - Object value = get( index ); - if( !(value instanceof Number) ) - { - throw LuaValues.badArgumentOf( index, "number", value ); - } - return ((Number) value).doubleValue(); - } - /** * Get an argument as a boolean. * @@ -132,26 +121,10 @@ public interface IArguments default boolean getBoolean( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof Boolean) ) - { - throw LuaValues.badArgumentOf( index, "boolean", value ); - } + if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); return (Boolean) value; } - /** - * Get a string argument as a byte array. - * - * @param index The argument number. - * @return The argument's value. This is a read only buffer. - * @throws LuaException If the value is not a string. - */ - @Nonnull - default ByteBuffer getBytes( int index ) throws LuaException - { - return LuaValues.encode( getString( index ) ); - } - /** * Get an argument as a string. * @@ -163,13 +136,23 @@ public interface IArguments default String getString( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof String) ) - { - throw LuaValues.badArgumentOf( index, "string", value ); - } + if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); return (String) value; } + /** + * Get a string argument as a byte array. + * + * @param index The argument number. + * @return The argument's value. This is a read only buffer. + * @throws LuaException If the value is not a string. + */ + @Nonnull + default ByteBuffer getBytes( int index ) throws LuaException + { + return LuaValues.encode( getString( index ) ); + } + /** * Get a string argument as an enum value. * @@ -196,75 +179,10 @@ public interface IArguments default Map getTable( int index ) throws LuaException { Object value = get( index ); - if( !(value instanceof Map) ) - { - throw LuaValues.badArgumentOf( index, "table", value ); - } + if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "table", value ); return (Map) value; } - /** - * Get a string argument as a byte array. - * - * @param index The argument number. - * @return The argument's value, or {@link Optional#empty()} if not present. This is a read only buffer. - * @throws LuaException If the value is not a string. - */ - default Optional optBytes( int index ) throws LuaException - { - return optString( index ).map( LuaValues::encode ); - } - - /** - * Get an argument as a string. - * - * @param index The argument number. - * @return The argument's value, or {@link Optional#empty()} if not present. - * @throws LuaException If the value is not a string. - */ - default Optional optString( int index ) throws LuaException - { - Object value = get( index ); - if( value == null ) - { - return Optional.empty(); - } - if( !(value instanceof String) ) - { - throw LuaValues.badArgumentOf( index, "string", value ); - } - return Optional.of( (String) value ); - } - - /** - * Get a string argument as an enum value. - * - * @param index The argument number. - * @param klass The type of enum to parse. - * @param The type of enum to parse. - * @return The argument's value. - * @throws LuaException If the value is not a string or not a valid option for this enum. - */ - @Nonnull - default > Optional optEnum( int index, Class klass ) throws LuaException - { - Optional str = optString( index ); - return str.isPresent() ? Optional.of( LuaValues.checkEnum( index, klass, str.get() ) ) : Optional.empty(); - } - - /** - * Get an argument as a double. - * - * @param index The argument number. - * @param def The default value, if this argument is not given. - * @return The argument's value, or {@code def} if none was provided. - * @throws LuaException If the value is not a number. - */ - default double optDouble( int index, double def ) throws LuaException - { - return optDouble( index ).orElse( def ); - } - /** * Get an argument as a double. * @@ -276,30 +194,11 @@ public interface IArguments default Optional optDouble( int index ) throws LuaException { Object value = get( index ); - if( value == null ) - { - return Optional.empty(); - } - if( !(value instanceof Number) ) - { - throw LuaValues.badArgumentOf( index, "number", value ); - } + if( value == null ) return Optional.empty(); + if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); return Optional.of( ((Number) value).doubleValue() ); } - /** - * Get an argument as an int. - * - * @param index The argument number. - * @param def The default value, if this argument is not given. - * @return The argument's value, or {@code def} if none was provided. - * @throws LuaException If the value is not a number. - */ - default int optInt( int index, int def ) throws LuaException - { - return optInt( index ).orElse( def ); - } - /** * Get an argument as an int. * @@ -323,16 +222,122 @@ public interface IArguments default Optional optLong( int index ) throws LuaException { Object value = get( index ); - if( value == null ) - { - return Optional.empty(); - } - if( !(value instanceof Number) ) - { - throw LuaValues.badArgumentOf( index, "number", value ); - } - return Optional.of( LuaValues.checkFiniteNum( index, (Number) value ) - .longValue() ); + if( value == null ) return Optional.empty(); + if( !(value instanceof Number) ) throw LuaValues.badArgumentOf( index, "number", value ); + return Optional.of( LuaValues.checkFiniteNum( index, (Number) value ).longValue() ); + } + + /** + * Get an argument as a finite number (not infinite or NaN). + * + * @param index The argument number. + * @return The argument's value, or {@link Optional#empty()} if not present. + * @throws LuaException If the value is not finite. + */ + default Optional optFiniteDouble( int index ) throws LuaException + { + Optional value = optDouble( index ); + if( value.isPresent() ) LuaValues.checkFiniteNum( index, value.get() ); + return value; + } + + /** + * Get an argument as a boolean. + * + * @param index The argument number. + * @return The argument's value, or {@link Optional#empty()} if not present. + * @throws LuaException If the value is not a boolean. + */ + default Optional optBoolean( int index ) throws LuaException + { + Object value = get( index ); + if( value == null ) return Optional.empty(); + if( !(value instanceof Boolean) ) throw LuaValues.badArgumentOf( index, "boolean", value ); + return Optional.of( (Boolean) value ); + } + + /** + * Get an argument as a string. + * + * @param index The argument number. + * @return The argument's value, or {@link Optional#empty()} if not present. + * @throws LuaException If the value is not a string. + */ + default Optional optString( int index ) throws LuaException + { + Object value = get( index ); + if( value == null ) return Optional.empty(); + if( !(value instanceof String) ) throw LuaValues.badArgumentOf( index, "string", value ); + return Optional.of( (String) value ); + } + + /** + * Get a string argument as a byte array. + * + * @param index The argument number. + * @return The argument's value, or {@link Optional#empty()} if not present. This is a read only buffer. + * @throws LuaException If the value is not a string. + */ + default Optional optBytes( int index ) throws LuaException + { + return optString( index ).map( LuaValues::encode ); + } + + /** + * Get a string argument as an enum value. + * + * @param index The argument number. + * @param klass The type of enum to parse. + * @param The type of enum to parse. + * @return The argument's value. + * @throws LuaException If the value is not a string or not a valid option for this enum. + */ + @Nonnull + default > Optional optEnum( int index, Class klass ) throws LuaException + { + Optional str = optString( index ); + return str.isPresent() ? Optional.of( LuaValues.checkEnum( index, klass, str.get() ) ) : Optional.empty(); + } + + /** + * Get an argument as a table. + * + * @param index The argument number. + * @return The argument's value, or {@link Optional#empty()} if not present. + * @throws LuaException If the value is not a table. + */ + default Optional> optTable( int index ) throws LuaException + { + Object value = get( index ); + if( value == null ) return Optional.empty(); + if( !(value instanceof Map) ) throw LuaValues.badArgumentOf( index, "map", value ); + return Optional.of( (Map) value ); + } + + /** + * Get an argument as a double. + * + * @param index The argument number. + * @param def The default value, if this argument is not given. + * @return The argument's value, or {@code def} if none was provided. + * @throws LuaException If the value is not a number. + */ + default double optDouble( int index, double def ) throws LuaException + { + return optDouble( index ).orElse( def ); + } + + /** + * Get an argument as an int. + * + * @param index The argument number. + * @param def The default value, if this argument is not given. + * @return The argument's value, or {@code def} if none was provided. + * @throws LuaException If the value is not a number. + */ + default int optInt( int index, int def ) throws LuaException + { + return optInt( index ).orElse( def ); } /** @@ -361,23 +366,6 @@ public interface IArguments return optFiniteDouble( index ).orElse( def ); } - /** - * Get an argument as a finite number (not infinite or NaN). - * - * @param index The argument number. - * @return The argument's value, or {@link Optional#empty()} if not present. - * @throws LuaException If the value is not finite. - */ - default Optional optFiniteDouble( int index ) throws LuaException - { - Optional value = optDouble( index ); - if( value.isPresent() ) - { - LuaValues.checkFiniteNum( index, value.get() ); - } - return value; - } - /** * Get an argument as a boolean. * @@ -391,27 +379,6 @@ public interface IArguments return optBoolean( index ).orElse( def ); } - /** - * Get an argument as a boolean. - * - * @param index The argument number. - * @return The argument's value, or {@link Optional#empty()} if not present. - * @throws LuaException If the value is not a boolean. - */ - default Optional optBoolean( int index ) throws LuaException - { - Object value = get( index ); - if( value == null ) - { - return Optional.empty(); - } - if( !(value instanceof Boolean) ) - { - throw LuaValues.badArgumentOf( index, "boolean", value ); - } - return Optional.of( (Boolean) value ); - } - /** * Get an argument as a string. * @@ -437,25 +404,4 @@ public interface IArguments { return optTable( index ).orElse( def ); } - - /** - * Get an argument as a table. - * - * @param index The argument number. - * @return The argument's value, or {@link Optional#empty()} if not present. - * @throws LuaException If the value is not a table. - */ - default Optional> optTable( int index ) throws LuaException - { - Object value = get( index ); - if( value == null ) - { - return Optional.empty(); - } - if( !(value instanceof Map) ) - { - throw LuaValues.badArgumentOf( index, "map", value ); - } - return Optional.of( (Map) value ); - } } diff --git a/src/main/java/dan200/computercraft/api/lua/IComputerSystem.java b/src/main/java/dan200/computercraft/api/lua/IComputerSystem.java index d9069b52a..fb76aceb4 100644 --- a/src/main/java/dan200/computercraft/api/lua/IComputerSystem.java +++ b/src/main/java/dan200/computercraft/api/lua/IComputerSystem.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import dan200.computercraft.api.filesystem.IFileSystem; @@ -12,7 +11,8 @@ import dan200.computercraft.api.peripheral.IComputerAccess; import javax.annotation.Nullable; /** - * An interface passed to {@link ILuaAPIFactory} in order to provide additional information about a computer. + * An interface passed to {@link ILuaAPIFactory} in order to provide additional information + * about a computer. */ public interface IComputerSystem extends IComputerAccess { diff --git a/src/main/java/dan200/computercraft/api/lua/IDynamicLuaObject.java b/src/main/java/dan200/computercraft/api/lua/IDynamicLuaObject.java index 49c4d6a47..ac3d3ce15 100644 --- a/src/main/java/dan200/computercraft/api/lua/IDynamicLuaObject.java +++ b/src/main/java/dan200/computercraft/api/lua/IDynamicLuaObject.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import dan200.computercraft.api.peripheral.IDynamicPeripheral; @@ -13,13 +12,15 @@ import javax.annotation.Nonnull; /** * An interface for representing custom objects returned by peripherals or other Lua objects. * - * Generally, one does not need to implement this type - it is sufficient to return an object with some methods annotated with {@link LuaFunction}. {@link - * IDynamicLuaObject} is useful when you wish your available methods to change at runtime. + * Generally, one does not need to implement this type - it is sufficient to return an object with some methods + * annotated with {@link LuaFunction}. {@link IDynamicLuaObject} is useful when you wish your available methods to + * change at runtime. */ public interface IDynamicLuaObject { /** - * Get the names of the methods that this object implements. This should not change over the course of the object's lifetime. + * Get the names of the methods that this object implements. This should not change over the course of the object's + * lifetime. * * @return The method names this object provides. * @see IDynamicPeripheral#getMethodNames() @@ -30,10 +31,13 @@ public interface IDynamicLuaObject /** * Called when a user calls one of the methods that this object implements. * - * @param context The context of the currently running lua thread. This can be used to wait for events or otherwise yield. - * @param method An integer identifying which method index from {@link #getMethodNames()} the computer wishes to call. + * @param context The context of the currently running lua thread. This can be used to wait for events + * or otherwise yield. + * @param method An integer identifying which method index from {@link #getMethodNames()} the computer wishes + * to call. * @param arguments The arguments for this method. - * @return The result of this function. Either an immediate value ({@link MethodResult#of(Object...)} or an instruction to yield. + * @return The result of this function. Either an immediate value ({@link MethodResult#of(Object...)} or an + * instruction to yield. * @throws LuaException If the function threw an exception. */ @Nonnull diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaAPI.java b/src/main/java/dan200/computercraft/api/lua/ILuaAPI.java index ca33136dc..e1a1d4a54 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaAPI.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaAPI.java @@ -3,17 +3,16 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import dan200.computercraft.api.ComputerCraftAPI; /** - * Represents a Lua object which is stored as a global variable on computer startup. This must either provide {@link LuaFunction} annotated functions or - * implement {@link IDynamicLuaObject}. + * Represents a Lua object which is stored as a global variable on computer startup. This must either provide + * {@link LuaFunction} annotated functions or implement {@link IDynamicLuaObject}. * - * Before implementing this interface, consider alternative methods of providing methods. It is generally preferred to use peripherals to provide - * functionality to users. + * Before implementing this interface, consider alternative methods of providing methods. It is generally preferred + * to use peripherals to provide functionality to users. * * @see ILuaAPIFactory * @see ComputerCraftAPI#registerAPIFactory(ILuaAPIFactory) diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaAPIFactory.java b/src/main/java/dan200/computercraft/api/lua/ILuaAPIFactory.java index 9b4fbbc47..7db976eb9 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaAPIFactory.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaAPIFactory.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import dan200.computercraft.api.ComputerCraftAPI; diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaCallback.java b/src/main/java/dan200/computercraft/api/lua/ILuaCallback.java index b24e4b25e..e999042af 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaCallback.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaCallback.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nonnull; @@ -18,7 +17,8 @@ public interface ILuaCallback /** * Resume this coroutine. * - * @param args The result of resuming this coroutine. These will have the same form as described in {@link LuaFunction}. + * @param args The result of resuming this coroutine. These will have the same form as described in + * {@link LuaFunction}. * @return The result of this continuation. Either the result to return to the callee, or another yield. * @throws LuaException On an error. */ diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaContext.java b/src/main/java/dan200/computercraft/api/lua/ILuaContext.java index 6d1aba949..4d29b57d1 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaContext.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaContext.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nonnull; @@ -41,5 +40,8 @@ public interface ILuaContext * @throws LuaException If the task could not be queued, or if the task threw an exception. */ @Nonnull - MethodResult executeMainThreadTask( @Nonnull ILuaTask task ) throws LuaException; + default MethodResult executeMainThreadTask( @Nonnull ILuaTask task ) throws LuaException + { + return TaskCallback.make( this, task ); + } } diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaFunction.java b/src/main/java/dan200/computercraft/api/lua/ILuaFunction.java index 70d900c2c..7813cbbdc 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaFunction.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaFunction.java @@ -3,14 +3,13 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nonnull; /** - * A function, which can be called from Lua. If you need to return a table of functions, it is recommended to use an object with {@link LuaFunction} - * methods, or implement {@link IDynamicLuaObject}. + * A function, which can be called from Lua. If you need to return a table of functions, it is recommended to use + * an object with {@link LuaFunction} methods, or implement {@link IDynamicLuaObject}. * * @see MethodResult#of(Object) */ @@ -18,8 +17,8 @@ import javax.annotation.Nonnull; public interface ILuaFunction { /** - * Call this function with a series of arguments. Note, this will always be called on the computer thread, and so its implementation must be - * thread-safe. + * Call this function with a series of arguments. Note, this will always be called on the computer thread, + * and so its implementation must be thread-safe. * * @param arguments The arguments for this function * @return The result of calling this function. diff --git a/src/main/java/dan200/computercraft/api/lua/ILuaTask.java b/src/main/java/dan200/computercraft/api/lua/ILuaTask.java index 44a429ed4..808e635b5 100644 --- a/src/main/java/dan200/computercraft/api/lua/ILuaTask.java +++ b/src/main/java/dan200/computercraft/api/lua/ILuaTask.java @@ -3,14 +3,14 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nullable; /** - * A task which can be executed via {@link ILuaContext#issueMainThreadTask(ILuaTask)} This will be run on the main thread, at the beginning of the next - * tick. + * A task which can be executed via {@link ILuaContext#issueMainThreadTask(ILuaTask)} This will be run on the main + * thread, at the beginning of the + * next tick. * * @see ILuaContext#issueMainThreadTask(ILuaTask) */ @@ -21,8 +21,9 @@ public interface ILuaTask * Execute this task. * * @return The arguments to add to the {@code task_completed} event. - * @throws LuaException If you throw any exception from this function, a lua error will be raised with the same message as your exception. Use this - * to throw appropriate errors if the wrong arguments are supplied to your method. + * @throws LuaException If you throw any exception from this function, a lua error will be raised with the + * same message as your exception. Use this to throw appropriate errors if the wrong + * arguments are supplied to your method. */ @Nullable Object[] execute() throws LuaException; diff --git a/src/main/java/dan200/computercraft/api/lua/LuaException.java b/src/main/java/dan200/computercraft/api/lua/LuaException.java index df97ed0fa..e2738ea91 100644 --- a/src/main/java/dan200/computercraft/api/lua/LuaException.java +++ b/src/main/java/dan200/computercraft/api/lua/LuaException.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nullable; @@ -42,7 +41,8 @@ public class LuaException extends Exception } /** - * The level this error is raised at. Level 1 is the function's caller, level 2 is that function's caller, and so on. + * The level this error is raised at. Level 1 is the function's caller, level 2 is that function's caller, and so + * on. * * @return The level to raise the error at. */ diff --git a/src/main/java/dan200/computercraft/api/lua/LuaFunction.java b/src/main/java/dan200/computercraft/api/lua/LuaFunction.java index 064149466..5558b153c 100644 --- a/src/main/java/dan200/computercraft/api/lua/LuaFunction.java +++ b/src/main/java/dan200/computercraft/api/lua/LuaFunction.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import dan200.computercraft.api.peripheral.IComputerAccess; @@ -16,8 +15,8 @@ import java.util.Optional; /** * Used to mark a Java function which is callable from Lua. * - * Methods annotated with {@link LuaFunction} must be public final instance methods. They can have any number of parameters, but they must be of the - * following types: + * Methods annotated with {@link LuaFunction} must be public final instance methods. They can have any number of + * parameters, but they must be of the following types: * *
    *
  • {@link ILuaContext} (and {@link IComputerAccess} if on a {@link IPeripheral})
  • @@ -49,7 +48,8 @@ public @interface LuaFunction String[] value() default {}; /** - * Run this function on the main server thread. This should be specified for any method which interacts with Minecraft in a thread-unsafe manner. + * Run this function on the main server thread. This should be specified for any method which interacts with + * Minecraft in a thread-unsafe manner. * * @return Whether this functi * @see ILuaContext#issueMainThreadTask(ILuaTask) diff --git a/src/main/java/dan200/computercraft/api/lua/LuaValues.java b/src/main/java/dan200/computercraft/api/lua/LuaValues.java index a78091060..8eec784ff 100644 --- a/src/main/java/dan200/computercraft/api/lua/LuaValues.java +++ b/src/main/java/dan200/computercraft/api/lua/LuaValues.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nonnull; @@ -38,8 +37,41 @@ public final class LuaValues chars[i] = c < 256 ? (byte) c : 63; } - return ByteBuffer.wrap( chars ) - .asReadOnlyBuffer(); + return ByteBuffer.wrap( chars ).asReadOnlyBuffer(); + } + + /** + * Returns a more detailed representation of this number's type. If this is finite, it will just return "number", + * otherwise it returns whether it is infinite or NaN. + * + * @param value The value to extract the type for. + * @return This value's numeric type. + */ + @Nonnull + public static String getNumericType( double value ) + { + if( Double.isNaN( value ) ) return "nan"; + if( value == Double.POSITIVE_INFINITY ) return "inf"; + if( value == Double.NEGATIVE_INFINITY ) return "-inf"; + return "number"; + } + + /** + * Get a string representation of the given value's type. + * + * @param value The value whose type we are trying to compute. + * @return A string representation of the given value's type, in a similar format to that provided by Lua's + * {@code type} function. + */ + @Nonnull + public static String getType( @Nullable Object value ) + { + if( value == null ) return "nil"; + if( value instanceof String ) return "string"; + if( value instanceof Boolean ) return "boolean"; + if( value instanceof Number ) return "number"; + if( value instanceof Map ) return "table"; + return "userdata"; } /** @@ -70,38 +102,6 @@ public final class LuaValues return new LuaException( "bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")" ); } - /** - * Get a string representation of the given value's type. - * - * @param value The value whose type we are trying to compute. - * @return A string representation of the given value's type, in a similar format to that provided by Lua's {@code type} function. - */ - @Nonnull - public static String getType( @Nullable Object value ) - { - if( value == null ) - { - return "nil"; - } - if( value instanceof String ) - { - return "string"; - } - if( value instanceof Boolean ) - { - return "boolean"; - } - if( value instanceof Number ) - { - return "number"; - } - if( value instanceof Map ) - { - return "table"; - } - return "userdata"; - } - /** * Ensure a numeric argument is finite (i.e. not infinite or {@link Double#NaN}. * @@ -126,38 +126,10 @@ public final class LuaValues */ public static double checkFinite( int index, double value ) throws LuaException { - if( !Double.isFinite( value ) ) - { - throw badArgument( index, "number", getNumericType( value ) ); - } + if( !Double.isFinite( value ) ) throw badArgument( index, "number", getNumericType( value ) ); return value; } - /** - * Returns a more detailed representation of this number's type. If this is finite, it will just return "number", otherwise it returns whether it is - * infinite or NaN. - * - * @param value The value to extract the type for. - * @return This value's numeric type. - */ - @Nonnull - public static String getNumericType( double value ) - { - if( Double.isNaN( value ) ) - { - return "nan"; - } - if( value == Double.POSITIVE_INFINITY ) - { - return "inf"; - } - if( value == Double.NEGATIVE_INFINITY ) - { - return "-inf"; - } - return "number"; - } - /** * Ensure a string is a valid enum value. * @@ -172,11 +144,7 @@ public final class LuaValues { for( T possibility : klass.getEnumConstants() ) { - if( possibility.name() - .equalsIgnoreCase( value ) ) - { - return possibility; - } + if( possibility.name().equalsIgnoreCase( value ) ) return possibility; } throw new LuaException( "bad argument #" + (index + 1) + " (unknown option " + value + ")" ); diff --git a/src/main/java/dan200/computercraft/api/lua/MethodResult.java b/src/main/java/dan200/computercraft/api/lua/MethodResult.java index 8787bf911..7d15d60b7 100644 --- a/src/main/java/dan200/computercraft/api/lua/MethodResult.java +++ b/src/main/java/dan200/computercraft/api/lua/MethodResult.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import dan200.computercraft.api.peripheral.IComputerAccess; @@ -18,8 +17,8 @@ import java.util.Objects; /** * The result of invoking a Lua method. * - * Method results either return a value immediately ({@link #of(Object...)} or yield control to the parent coroutine. When the current coroutine is resumed, - * we invoke the provided {@link ILuaCallback#resume(Object[])} callback. + * Method results either return a value immediately ({@link #of(Object...)} or yield control to the parent coroutine. + * When the current coroutine is resumed, we invoke the provided {@link ILuaCallback#resume(Object[])} callback. */ public final class MethodResult { @@ -57,11 +56,12 @@ public final class MethodResult /** * Return a single value immediately. * - * Integers, doubles, floats, strings, booleans, {@link Map}, {@link Collection}s, arrays and {@code null} will be converted to their corresponding Lua - * type. {@code byte[]} and {@link ByteBuffer} will be treated as binary strings. {@link ILuaFunction} will be treated as a function. + * Integers, doubles, floats, strings, booleans, {@link Map}, {@link Collection}s, arrays and {@code null} will be + * converted to their corresponding Lua type. {@code byte[]} and {@link ByteBuffer} will be treated as binary + * strings. {@link ILuaFunction} will be treated as a function. * - * In order to provide a custom object with methods, one may return a {@link IDynamicLuaObject}, or an arbitrary class with {@link LuaFunction} - * annotations. Anything else will be converted to {@code nil}. + * In order to provide a custom object with methods, one may return a {@link IDynamicLuaObject}, or an arbitrary + * class with {@link LuaFunction} annotations. Anything else will be converted to {@code nil}. * * @param value The value to return to the calling Lua function. * @return A method result which returns immediately with the given value. @@ -85,8 +85,8 @@ public final class MethodResult } /** - * Wait for an event to occur on the computer, suspending the thread until it arises. This method is exactly equivalent to {@code os.pullEvent()} in - * lua. + * Wait for an event to occur on the computer, suspending the thread until it arises. This method is exactly + * equivalent to {@code os.pullEvent()} in lua. * * @param filter A specific event to wait for, or null to wait for any event. * @param callback The callback to resume with the name of the event that occurred, and any event parameters. @@ -98,17 +98,15 @@ public final class MethodResult { Objects.requireNonNull( callback, "callback cannot be null" ); return new MethodResult( new Object[] { filter }, results -> { - if( results.length >= 1 && results[0].equals( "terminate" ) ) - { - throw new LuaException( "Terminated", 0 ); - } + if( results.length >= 1 && results[0].equals( "terminate" ) ) throw new LuaException( "Terminated", 0 ); return callback.resume( results ); } ); } /** - * The same as {@link #pullEvent(String, ILuaCallback)}, except "terminated" events are ignored. Only use this if you want to prevent program - * termination, which is not recommended. This method is exactly equivalent to {@code os.pullEventRaw()} in Lua. + * The same as {@link #pullEvent(String, ILuaCallback)}, except "terminated" events are ignored. Only use this if + * you want to prevent program termination, which is not recommended. This method is exactly equivalent to + * {@code os.pullEventRaw()} in Lua. * * @param filter A specific event to wait for, or null to wait for any event. * @param callback The callback to resume with the name of the event that occurred, and any event parameters. @@ -123,8 +121,8 @@ public final class MethodResult } /** - * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to {@code coroutine.yield()} in lua. Use - * {@code pullEvent()} if you wish to wait for events. + * Yield the current coroutine with some arguments until it is resumed. This method is exactly equivalent to + * {@code coroutine.yield()} in lua. Use {@code pullEvent()} if you wish to wait for events. * * @param arguments An object array containing the arguments to pass to coroutine.yield() * @param callback The callback to resume with an array containing the return values from coroutine.yield() @@ -156,7 +154,8 @@ public final class MethodResult } /** - * Increase the Lua error by a specific amount. One should never need to use this function - it largely exists for some CC internal code. + * Increase the Lua error by a specific amount. One should never need to use this function - it largely exists for + * some CC internal code. * * @param adjust The amount to increase the level by. * @return The new {@link MethodResult} with an adjusted error. This has no effect on immediate results. @@ -164,14 +163,8 @@ public final class MethodResult @Nonnull public MethodResult adjustError( int adjust ) { - if( adjust < 0 ) - { - throw new IllegalArgumentException( "cannot adjust by a negative amount" ); - } - if( adjust == 0 || callback == null ) - { - return this; - } + if( adjust < 0 ) throw new IllegalArgumentException( "cannot adjust by a negative amount" ); + if( adjust == 0 || callback == null ) return this; return new MethodResult( result, callback, this.adjust + adjust ); } } diff --git a/src/main/java/dan200/computercraft/api/lua/ObjectArguments.java b/src/main/java/dan200/computercraft/api/lua/ObjectArguments.java index d800d0ac6..6dd7e3c0f 100644 --- a/src/main/java/dan200/computercraft/api/lua/ObjectArguments.java +++ b/src/main/java/dan200/computercraft/api/lua/ObjectArguments.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.lua; import javax.annotation.Nullable; @@ -36,41 +35,32 @@ public final class ObjectArguments implements IArguments this.args = Objects.requireNonNull( args ); } - @Override - public IArguments drop( int count ) - { - if( count < 0 ) - { - throw new IllegalStateException( "count cannot be negative" ); - } - if( count == 0 ) - { - return this; - } - if( count >= args.size() ) - { - return EMPTY; - } - - return new ObjectArguments( args.subList( count, args.size() ) ); - } - - @Override - public Object[] getAll() - { - return args.toArray(); - } - @Override public int count() { return args.size(); } + @Override + public IArguments drop( int count ) + { + if( count < 0 ) throw new IllegalStateException( "count cannot be negative" ); + if( count == 0 ) return this; + if( count >= args.size() ) return EMPTY; + + return new ObjectArguments( args.subList( count, args.size() ) ); + } + @Nullable @Override public Object get( int index ) { return index >= args.size() ? null : args.get( index ); } + + @Override + public Object[] getAll() + { + return args.toArray(); + } } diff --git a/src/main/java/dan200/computercraft/api/lua/TaskCallback.java b/src/main/java/dan200/computercraft/api/lua/TaskCallback.java new file mode 100644 index 000000000..85870a221 --- /dev/null +++ b/src/main/java/dan200/computercraft/api/lua/TaskCallback.java @@ -0,0 +1,53 @@ +/* + * This file is part of the public ComputerCraft API - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. + * For help using the API, and posting your mods, visit the forums at computercraft.info. + */ +package dan200.computercraft.api.lua; + +import javax.annotation.Nonnull; +import java.util.Arrays; + +final class TaskCallback implements ILuaCallback +{ + private final MethodResult pull = MethodResult.pullEvent( "task_complete", this ); + private final long task; + + private TaskCallback( long task ) + { + this.task = task; + } + + @Nonnull + @Override + public MethodResult resume( Object[] response ) throws LuaException + { + if( response.length < 3 || !(response[1] instanceof Number) || !(response[2] instanceof Boolean) ) + { + return pull; + } + + if( ((Number) response[1]).longValue() != task ) return pull; + + if( (Boolean) response[2] ) + { + // Extract the return values from the event and return them + return MethodResult.of( Arrays.copyOfRange( response, 3, response.length ) ); + } + else if( response.length >= 4 && response[3] instanceof String ) + { + // Extract the error message from the event and raise it + throw new LuaException( (String) response[3] ); + } + else + { + throw new LuaException( "error" ); + } + } + + static MethodResult make( ILuaContext context, ILuaTask func ) throws LuaException + { + long task = context.issueMainThreadTask( func ); + return new TaskCallback( task ).pull; + } +} diff --git a/src/main/java/dan200/computercraft/api/media/IMedia.java b/src/main/java/dan200/computercraft/api/media/IMedia.java index 986da717e..da0be8da7 100644 --- a/src/main/java/dan200/computercraft/api/media/IMedia.java +++ b/src/main/java/dan200/computercraft/api/media/IMedia.java @@ -3,14 +3,13 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.media; import dan200.computercraft.api.filesystem.IMount; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.sound.SoundEvent; -import net.minecraft.world.World; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -18,7 +17,8 @@ import javax.annotation.Nullable; /** * Represents an item that can be placed in a disk drive and used by a Computer. * - * Implement this interface on your {@link Item} class to allow it to be used in the drive. Alternatively, register a {@link IMediaProvider}. + * Implement this interface on your {@link Item} class to allow it to be used in the drive. Alternatively, register + * a {@link IMediaProvider}. */ public interface IMedia { @@ -44,7 +44,8 @@ public interface IMedia } /** - * If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: "Jonathan Coulton - Still Alive" + * If this disk represents an item with audio (like a record), get the readable name of the audio track. ie: + * "Jonathan Coulton - Still Alive" * * @param stack The {@link ItemStack} to modify. * @return The name, or null if this item does not represent an item with audio. @@ -68,20 +69,20 @@ public interface IMedia } /** - * If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will be mounted onto the filesystem of - * the computer while the media is in the disk drive. + * If this disk represents an item with data (like a floppy disk), get a mount representing it's contents. This will + * be mounted onto the filesystem of the computer while the media is in the disk drive. * * @param stack The {@link ItemStack} to modify. * @param world The world in which the item and disk drive reside. - * @return The mount, or null if this item does not represent an item with data. If the mount returned also implements {@link - * dan200.computercraft.api.filesystem.IWritableMount}, it will mounted using mountWritable() + * @return The mount, or null if this item does not represent an item with data. If the mount returned also + * implements {@link dan200.computercraft.api.filesystem.IWritableMount}, it will mounted using mountWritable() * @see IMount * @see dan200.computercraft.api.filesystem.IWritableMount - * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see dan200.computercraft.api.ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see dan200.computercraft.api.ComputerCraftAPI#createResourceMount(String, String) */ @Nullable - default IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world ) + default IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world ) { return null; } diff --git a/src/main/java/dan200/computercraft/api/media/IMediaProvider.java b/src/main/java/dan200/computercraft/api/media/IMediaProvider.java index 7afa1e632..04ec9f9d6 100644 --- a/src/main/java/dan200/computercraft/api/media/IMediaProvider.java +++ b/src/main/java/dan200/computercraft/api/media/IMediaProvider.java @@ -3,10 +3,9 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.media; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/src/main/java/dan200/computercraft/api/network/IPacketNetwork.java b/src/main/java/dan200/computercraft/api/network/IPacketNetwork.java index b897717c6..277150156 100644 --- a/src/main/java/dan200/computercraft/api/network/IPacketNetwork.java +++ b/src/main/java/dan200/computercraft/api/network/IPacketNetwork.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network; import javax.annotation.Nonnull; @@ -38,8 +37,8 @@ public interface IPacketNetwork boolean isWireless(); /** - * Submit a packet for transmitting across the network. This will route the packet through the network, sending it to all receivers within range (or any - * interdimensional ones). + * Submit a packet for transmitting across the network. This will route the packet through the network, sending it + * to all receivers within range (or any interdimensional ones). * * @param packet The packet to send. * @param range The maximum distance this packet will be sent. @@ -49,8 +48,8 @@ public interface IPacketNetwork void transmitSameDimension( @Nonnull Packet packet, double range ); /** - * Submit a packet for transmitting across the network. This will route the packet through the network, sending it to all receivers across all - * dimensions. + * Submit a packet for transmitting across the network. This will route the packet through the network, sending it + * to all receivers across all dimensions. * * @param packet The packet to send. * @see #transmitSameDimension(Packet, double) diff --git a/src/main/java/dan200/computercraft/api/network/IPacketReceiver.java b/src/main/java/dan200/computercraft/api/network/IPacketReceiver.java index 660344a2b..b8a639828 100644 --- a/src/main/java/dan200/computercraft/api/network/IPacketReceiver.java +++ b/src/main/java/dan200/computercraft/api/network/IPacketReceiver.java @@ -3,11 +3,10 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; @@ -22,7 +21,7 @@ public interface IPacketReceiver * @return The receivers's world. */ @Nonnull - World getWorld(); + Level getLevel(); /** * Get the position in the world at which this receiver exists. @@ -30,13 +29,14 @@ public interface IPacketReceiver * @return The receiver's position. */ @Nonnull - Vec3d getPosition(); + Vec3 getPosition(); /** * Get the maximum distance this receiver can send and receive messages. * - * When determining whether a receiver can receive a message, the largest distance of the packet and receiver is used - ensuring it is within range. If - * the packet or receiver is inter-dimensional, then the packet will always be received. + * When determining whether a receiver can receive a message, the largest distance of the packet and receiver is + * used - ensuring it is within range. If the packet or receiver is inter-dimensional, then the packet will always + * be received. * * @return The maximum distance this device can send and receive messages. * @see #isInterdimensional() @@ -60,8 +60,8 @@ public interface IPacketReceiver /** * Receive a network packet from the same dimension. * - * @param packet The packet to receive. Generally you should check that you are listening on the given channel and, if so, queue the appropriate - * modem event. + * @param packet The packet to receive. Generally you should check that you are listening on the given channel and, + * if so, queue the appropriate modem event. * @param distance The distance this packet has travelled from the source. * @see Packet * @see #getRange() @@ -73,8 +73,8 @@ public interface IPacketReceiver /** * Receive a network packet from a different dimension. * - * @param packet The packet to receive. Generally you should check that you are listening on the given channel and, if so, queue the appropriate - * modem event. + * @param packet The packet to receive. Generally you should check that you are listening on the given channel and, + * if so, queue the appropriate modem event. * @see Packet * @see IPacketNetwork#transmitInterdimensional(Packet) * @see IPacketNetwork#transmitSameDimension(Packet, double) diff --git a/src/main/java/dan200/computercraft/api/network/IPacketSender.java b/src/main/java/dan200/computercraft/api/network/IPacketSender.java index f3c06a397..b6346952a 100644 --- a/src/main/java/dan200/computercraft/api/network/IPacketSender.java +++ b/src/main/java/dan200/computercraft/api/network/IPacketSender.java @@ -3,11 +3,10 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; @@ -22,7 +21,7 @@ public interface IPacketSender * @return The sender's world. */ @Nonnull - World getWorld(); + Level getLevel(); /** * Get the position in the world at which this sender exists. @@ -30,11 +29,11 @@ public interface IPacketSender * @return The sender's position. */ @Nonnull - Vec3d getPosition(); + Vec3 getPosition(); /** - * Get some sort of identification string for this sender. This does not strictly need to be unique, but you should be able to extract some identifiable - * information from it. + * Get some sort of identification string for this sender. This does not strictly need to be unique, but you + * should be able to extract some identifiable information from it. * * @return This device's id. */ diff --git a/src/main/java/dan200/computercraft/api/network/Packet.java b/src/main/java/dan200/computercraft/api/network/Packet.java index 34b2bd41f..5d1854120 100644 --- a/src/main/java/dan200/computercraft/api/network/Packet.java +++ b/src/main/java/dan200/computercraft/api/network/Packet.java @@ -3,128 +3,28 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.Objects; - /** * Represents a packet which may be sent across a {@link IPacketNetwork}. * + * @param channel The channel to send the packet along. Receiving devices should only process packets from on + * channels they are listening to. + * @param replyChannel The channel to reply on. + * @param payload The contents of this packet. This should be a "valid" Lua object, safe for queuing as an + * event or returning from a peripheral call. + * @param sender The object which sent this packet. * @see IPacketSender * @see IPacketNetwork#transmitSameDimension(Packet, double) * @see IPacketNetwork#transmitInterdimensional(Packet) * @see IPacketReceiver#receiveDifferentDimension(Packet) * @see IPacketReceiver#receiveSameDimension(Packet, double) */ -public class Packet +public record Packet( + int channel, + int replyChannel, + Object payload, + IPacketSender sender +) { - private final int channel; - private final int replyChannel; - private final Object payload; - - private final IPacketSender sender; - - /** - * Create a new packet, ready for transmitting across the network. - * - * @param channel The channel to send the packet along. Receiving devices should only process packets from on channels they are listening to. - * @param replyChannel The channel to reply on. - * @param payload The contents of this packet. This should be a "valid" Lua object, safe for queuing as an event or returning from a peripheral - * call. - * @param sender The object which sent this packet. - */ - public Packet( int channel, int replyChannel, @Nullable Object payload, @Nonnull IPacketSender sender ) - { - Objects.requireNonNull( sender, "sender cannot be null" ); - - this.channel = channel; - this.replyChannel = replyChannel; - this.payload = payload; - this.sender = sender; - } - - /** - * Get the channel this packet is sent along. Receivers should generally only process packets from on channels they are listening to. - * - * @return This packet's channel. - */ - public int getChannel() - { - return channel; - } - - /** - * The channel to reply on. Objects which will reply should send it along this channel. - * - * @return This channel to reply on. - */ - public int getReplyChannel() - { - return replyChannel; - } - - /** - * The actual data of this packet. This should be a "valid" Lua object, safe for queuing as an event or returning from a peripheral call. - * - * @return The packet's payload - */ - @Nullable - public Object getPayload() - { - return payload; - } - - /** - * The object which sent this message. - * - * @return The sending object. - */ - @Nonnull - public IPacketSender getSender() - { - return sender; - } - - @Override - public int hashCode() - { - int result; - result = channel; - result = 31 * result + replyChannel; - result = 31 * result + (payload != null ? payload.hashCode() : 0); - result = 31 * result + sender.hashCode(); - return result; - } - - @Override - public boolean equals( Object o ) - { - if( this == o ) - { - return true; - } - if( o == null || getClass() != o.getClass() ) - { - return false; - } - - Packet packet = (Packet) o; - - if( channel != packet.channel ) - { - return false; - } - if( replyChannel != packet.replyChannel ) - { - return false; - } - if( !Objects.equals( payload, packet.payload ) ) - { - return false; - } - return sender.equals( packet.sender ); - } } diff --git a/src/main/java/dan200/computercraft/api/network/wired/IWiredElement.java b/src/main/java/dan200/computercraft/api/network/wired/IWiredElement.java index 5ca0ddb9f..390bd91e9 100644 --- a/src/main/java/dan200/computercraft/api/network/wired/IWiredElement.java +++ b/src/main/java/dan200/computercraft/api/network/wired/IWiredElement.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network.wired; import dan200.computercraft.api.ComputerCraftAPI; @@ -13,16 +12,18 @@ import javax.annotation.Nonnull; /** * An object which may be part of a wired network. * - * Elements should construct a node using {@link ComputerCraftAPI#createWiredNodeForElement(IWiredElement)}. This acts as a proxy for all network objects. - * Whilst the node may change networks, an element's node should remain constant for its lifespan. + * Elements should construct a node using {@link ComputerCraftAPI#createWiredNodeForElement(IWiredElement)}. This acts + * as a proxy for all network objects. Whilst the node may change networks, an element's node should remain constant + * for its lifespan. * - * Elements are generally tied to a block or tile entity in world. In such as case, one should provide the {@link IWiredElement} capability for the - * appropriate sides. + * Elements are generally tied to a block or tile entity in world. In such as case, one should provide the + * {@link IWiredElement} capability for the appropriate sides. */ public interface IWiredElement extends IWiredSender { /** - * Called when objects on the network change. This may occur when network nodes are added or removed, or when peripherals change. + * Called when objects on the network change. This may occur when network nodes are added or removed, or when + * peripherals change. * * @param change The change which occurred. * @see IWiredNetworkChange diff --git a/src/main/java/dan200/computercraft/api/network/wired/IWiredNetwork.java b/src/main/java/dan200/computercraft/api/network/wired/IWiredNetwork.java index fa44c4d1b..ae18cb691 100644 --- a/src/main/java/dan200/computercraft/api/network/wired/IWiredNetwork.java +++ b/src/main/java/dan200/computercraft/api/network/wired/IWiredNetwork.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network.wired; import dan200.computercraft.api.peripheral.IPeripheral; @@ -12,14 +11,16 @@ import javax.annotation.Nonnull; import java.util.Map; /** - * A wired network is composed of one of more {@link IWiredNode}s, a set of connections between them, and a series of peripherals. + * A wired network is composed of one of more {@link IWiredNode}s, a set of connections between them, and a series + * of peripherals. * - * Networks from a connected graph. This means there is some path between all nodes on the network. Further more, if there is some path between two nodes - * then they must be on the same network. {@link IWiredNetwork} will automatically handle the merging and splitting of networks (and thus changing of - * available nodes and peripherals) as connections change. + * Networks from a connected graph. This means there is some path between all nodes on the network. Further more, if + * there is some path between two nodes then they must be on the same network. {@link IWiredNetwork} will automatically + * handle the merging and splitting of networks (and thus changing of available nodes and peripherals) as connections + * change. * - * This does mean one can not rely on the network remaining consistent between subsequent operations. Consequently, it is generally preferred to use the - * methods provided by {@link IWiredNode}. + * This does mean one can not rely on the network remaining consistent between subsequent operations. Consequently, + * it is generally preferred to use the methods provided by {@link IWiredNode}. * * @see IWiredNode#getNetwork() */ @@ -58,10 +59,12 @@ public interface IWiredNetwork /** * Sever all connections this node has, removing it from this network. * - * This should only be used on the server thread. You should only call this on nodes that your network element owns. + * This should only be used on the server thread. You should only call this on nodes + * that your network element owns. * * @param node The node to remove - * @return Whether this node was removed from the network. One cannot remove a node from a network where it is the only element. + * @return Whether this node was removed from the network. One cannot remove a node from a network where it is the + * only element. * @throws IllegalArgumentException If the node is not in the network. * @see IWiredNode#remove() */ @@ -70,7 +73,8 @@ public interface IWiredNetwork /** * Update the peripherals a node provides. * - * This should only be used on the server thread. You should only call this on nodes that your network element owns. + * This should only be used on the server thread. You should only call this on nodes + * that your network element owns. * * @param node The node to attach peripherals for. * @param peripherals The new peripherals for this node. diff --git a/src/main/java/dan200/computercraft/api/network/wired/IWiredNetworkChange.java b/src/main/java/dan200/computercraft/api/network/wired/IWiredNetworkChange.java index bef4b1048..0663509a6 100644 --- a/src/main/java/dan200/computercraft/api/network/wired/IWiredNetworkChange.java +++ b/src/main/java/dan200/computercraft/api/network/wired/IWiredNetworkChange.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network.wired; import dan200.computercraft.api.peripheral.IPeripheral; @@ -19,8 +18,8 @@ import java.util.Map; public interface IWiredNetworkChange { /** - * A set of peripherals which have been removed. Note that there may be entries with the same name in the added and removed set, but with a different - * peripheral. + * A set of peripherals which have been removed. Note that there may be entries with the same name + * in the added and removed set, but with a different peripheral. * * @return The set of removed peripherals. */ @@ -28,8 +27,8 @@ public interface IWiredNetworkChange Map peripheralsRemoved(); /** - * A set of peripherals which have been added. Note that there may be entries with the same name in the added and removed set, but with a different - * peripheral. + * A set of peripherals which have been added. Note that there may be entries with the same name + * in the added and removed set, but with a different peripheral. * * @return The set of added peripherals. */ diff --git a/src/main/java/dan200/computercraft/api/network/wired/IWiredNode.java b/src/main/java/dan200/computercraft/api/network/wired/IWiredNode.java index 73afe2fd7..e72f25a62 100644 --- a/src/main/java/dan200/computercraft/api/network/wired/IWiredNode.java +++ b/src/main/java/dan200/computercraft/api/network/wired/IWiredNode.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network.wired; import dan200.computercraft.api.network.IPacketNetwork; @@ -15,14 +14,15 @@ import java.util.Map; /** * Wired nodes act as a layer between {@link IWiredElement}s and {@link IWiredNetwork}s. * - * Firstly, a node acts as a packet network, capable of sending and receiving modem messages to connected nodes. These methods may be safely used on any - * thread. + * Firstly, a node acts as a packet network, capable of sending and receiving modem messages to connected nodes. These + * methods may be safely used on any thread. * - * When sending a packet, the system will attempt to find the shortest path between the two nodes based on their element's position. Note that packet - * senders and receivers can have different locations from their associated element: the distance between the two will be added to the total packet's - * distance. + * When sending a packet, the system will attempt to find the shortest path between the two nodes based on their + * element's position. Note that packet senders and receivers can have different locations from their associated + * element: the distance between the two will be added to the total packet's distance. * - * Wired nodes also provide several convenience methods for interacting with a wired network. These should only ever be used on the main server thread. + * Wired nodes also provide several convenience methods for interacting with a wired network. These should only ever + * be used on the main server thread. */ public interface IWiredNode extends IPacketNetwork { @@ -34,6 +34,17 @@ public interface IWiredNode extends IPacketNetwork @Nonnull IWiredElement getElement(); + /** + * The network this node is currently connected to. Note that this may change + * after any network operation, so it should not be cached. + * + * This should only be used on the server thread. + * + * @return This node's network. + */ + @Nonnull + IWiredNetwork getNetwork(); + /** * Create a connection from this node to another. * @@ -49,16 +60,6 @@ public interface IWiredNode extends IPacketNetwork return getNetwork().connect( this, node ); } - /** - * The network this node is currently connected to. Note that this may change after any network operation, so it should not be cached. - * - * This should only be used on the server thread. - * - * @return This node's network. - */ - @Nonnull - IWiredNetwork getNetwork(); - /** * Destroy a connection between this node and another. * @@ -78,9 +79,11 @@ public interface IWiredNode extends IPacketNetwork /** * Sever all connections this node has, removing it from this network. * - * This should only be used on the server thread. You should only call this on nodes that your network element owns. + * This should only be used on the server thread. You should only call this on nodes + * that your network element owns. * - * @return Whether this node was removed from the network. One cannot remove a node from a network where it is the only element. + * @return Whether this node was removed from the network. One cannot remove a node from a network where it is the + * only element. * @throws IllegalArgumentException If the node is not in the network. * @see IWiredNetwork#remove(IWiredNode) */ @@ -92,7 +95,8 @@ public interface IWiredNode extends IPacketNetwork /** * Mark this node's peripherals as having changed. * - * This should only be used on the server thread. You should only call this on nodes that your network element owns. + * This should only be used on the server thread. You should only call this on nodes + * that your network element owns. * * @param peripherals The new peripherals for this node. * @see IWiredNetwork#updatePeripherals(IWiredNode, Map) diff --git a/src/main/java/dan200/computercraft/api/network/wired/IWiredSender.java b/src/main/java/dan200/computercraft/api/network/wired/IWiredSender.java index c306b0a6b..f2795eced 100644 --- a/src/main/java/dan200/computercraft/api/network/wired/IWiredSender.java +++ b/src/main/java/dan200/computercraft/api/network/wired/IWiredSender.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.network.wired; import dan200.computercraft.api.network.IPacketSender; @@ -13,14 +12,16 @@ import javax.annotation.Nonnull; /** * An object on a {@link IWiredNetwork} capable of sending packets. * - * Unlike a regular {@link IPacketSender}, this must be associated with the node you are attempting to to send the packet from. + * Unlike a regular {@link IPacketSender}, this must be associated with the node you are attempting to + * to send the packet from. */ public interface IWiredSender extends IPacketSender { /** * The node in the network representing this object. * - * This should be used as a proxy for the main network. One should send packets and register receivers through this object. + * This should be used as a proxy for the main network. One should send packets + * and register receivers through this object. * * @return The node for this element. */ diff --git a/src/main/java/dan200/computercraft/api/peripheral/GenericPeripheral.java b/src/main/java/dan200/computercraft/api/peripheral/GenericPeripheral.java new file mode 100644 index 000000000..15988b3d3 --- /dev/null +++ b/src/main/java/dan200/computercraft/api/peripheral/GenericPeripheral.java @@ -0,0 +1,45 @@ +/* + * This file is part of the public ComputerCraft API - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. + * For help using the API, and posting your mods, visit the forums at computercraft.info. + */ +package dan200.computercraft.api.peripheral; + +import dan200.computercraft.api.lua.GenericSource; +import net.minecraft.world.Container; +import net.minecraft.world.level.block.entity.BlockEntity; + +import javax.annotation.Nonnull; + +/** + * A {@link GenericSource} which provides methods for a peripheral. + * + * Unlike a {@link GenericSource}, all methods should target the same type, for instance a + * {@link BlockEntity} subclass or a capability interface. This is not currently enforced. + */ +public interface GenericPeripheral extends GenericSource +{ + /** + * Get the type of the exposed peripheral. + * + * Unlike normal {@link IPeripheral}s, {@link GenericPeripheral} do not have to have a type. By default, the + * resulting peripheral uses the resource name of the wrapped {@link BlockEntity} (for instance {@literal minecraft:chest}). + * + * However, in some cases it may be more appropriate to specify a more readable name. Overriding this method allows + * you to do so. + * + * When multiple {@link GenericPeripheral}s return a non-empty peripheral type for a single tile entity, the + * lexicographically smallest will be chosen. In order to avoid this conflict, this method should only be + * implemented when your peripheral targets a single tile entity AND it's likely that you're the + * only mod to do so. Similarly this should NOT be implemented when your methods target an + * interface (i.e. {@link Container}). + * + * @return The type of this peripheral or {@link PeripheralType#untyped()}. + * @see IPeripheral#getType() + */ + @Nonnull + default PeripheralType getType() + { + return PeripheralType.untyped(); + } +} diff --git a/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java b/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java index 0514ea509..11c9dec1a 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IComputerAccess.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.peripheral; import dan200.computercraft.api.ComputerCraftAPI; @@ -13,15 +12,16 @@ import dan200.computercraft.api.lua.ILuaCallback; import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaTask; import dan200.computercraft.api.lua.MethodResult; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; /** - * The interface passed to peripherals by computers or turtles, providing methods that they can call. This should not be implemented by your classes. Do not - * interact with computers except via this interface. + * The interface passed to peripherals by computers or turtles, providing methods + * that they can call. This should not be implemented by your classes. Do not interact + * with computers except via this interface. */ public interface IComputerAccess { @@ -30,10 +30,10 @@ public interface IComputerAccess * * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. * @param mount The mount object to mount on the computer. - * @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a file in the desired location. - * Store this value if you wish to unmount the mount later. + * @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a + * file in the desired location. Store this value if you wish to unmount the mount later. * @throws NotAttachedException If the peripheral has been detached. - * @see ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see ComputerCraftAPI#createResourceMount(String, String) * @see #mount(String, IMount, String) * @see #mountWritable(String, IWritableMount) @@ -52,10 +52,10 @@ public interface IComputerAccess * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. * @param mount The mount object to mount on the computer. * @param driveName A custom name to give for this mount location, as returned by {@code fs.getDrive()}. - * @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a file in the desired location. - * Store this value if you wish to unmount the mount later. + * @return The location on the computer's file system where you the mount mounted, or {@code null} if there was already a + * file in the desired location. Store this value if you wish to unmount the mount later. * @throws NotAttachedException If the peripheral has been detached. - * @see ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see ComputerCraftAPI#createResourceMount(String, String) * @see #mount(String, IMount) * @see #mountWritable(String, IWritableMount) @@ -65,26 +65,15 @@ public interface IComputerAccess @Nullable String mount( @Nonnull String desiredLocation, @Nonnull IMount mount, @Nonnull String driveName ); - /** - * Get a string, unique to the computer, by which the computer refers to this peripheral. For directly attached peripherals this will be - * "left","right","front","back",etc, but for peripherals attached remotely it will be different. It is good practice to supply this string when raising - * events to the computer, so that the computer knows from which peripheral the event came. - * - * @return A string unique to the computer, but not globally. - * @throws NotAttachedException If the peripheral has been detached. - */ - @Nonnull - String getAttachmentName(); - /** * Mount a mount onto the computer's file system in a writable mode. * * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. * @param mount The mount object to mount on the computer. - * @return The location on the computer's file system where you the mount mounted, or null if there was already a file in the desired location. Store - * this value if you wish to unmount the mount later. + * @return The location on the computer's file system where you the mount mounted, or null if there was already a + * file in the desired location. Store this value if you wish to unmount the mount later. * @throws NotAttachedException If the peripheral has been detached. - * @see ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see ComputerCraftAPI#createResourceMount(String, String) * @see #mount(String, IMount) * @see #unmount(String) @@ -102,10 +91,10 @@ public interface IComputerAccess * @param desiredLocation The location on the computer's file system where you would like the mount to be mounted. * @param mount The mount object to mount on the computer. * @param driveName A custom name to give for this mount location, as returned by {@code fs.getDrive()}. - * @return The location on the computer's file system where you the mount mounted, or null if there was already a file in the desired location. Store - * this value if you wish to unmount the mount later. + * @return The location on the computer's file system where you the mount mounted, or null if there was already a + * file in the desired location. Store this value if you wish to unmount the mount later. * @throws NotAttachedException If the peripheral has been detached. - * @see ComputerCraftAPI#createSaveDirMount(World, String, long) + * @see ComputerCraftAPI#createSaveDirMount(Level, String, long) * @see ComputerCraftAPI#createResourceMount(String, String) * @see #mount(String, IMount) * @see #unmount(String) @@ -114,16 +103,18 @@ public interface IComputerAccess String mountWritable( @Nonnull String desiredLocation, @Nonnull IWritableMount mount, @Nonnull String driveName ); /** - * Unmounts a directory previously mounted onto the computers file system by {@link #mount(String, IMount)} or {@link #mountWritable(String, - * IWritableMount)}. + * Unmounts a directory previously mounted onto the computers file system by {@link #mount(String, IMount)} + * or {@link #mountWritable(String, IWritableMount)}. * - * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be able to access it. All directories - * mounted by a mount or mountWritable are automatically unmounted when the peripheral is attached if they have not been explicitly unmounted. + * When a directory is unmounted, it will disappear from the computers file system, and the user will no longer be + * able to access it. All directories mounted by a mount or mountWritable are automatically unmounted when the + * peripheral is attached if they have not been explicitly unmounted. * * Note that you cannot unmount another peripheral's mounts. * - * @param location The desired location in the computers file system of the directory to unmount. This must be the location of a directory - * previously mounted by {@link #mount(String, IMount)} or {@link #mountWritable(String, IWritableMount)}, as indicated by their return value. + * @param location The desired location in the computers file system of the directory to unmount. + * This must be the location of a directory previously mounted by {@link #mount(String, IMount)} or + * {@link #mountWritable(String, IWritableMount)}, as indicated by their return value. * @throws NotAttachedException If the peripheral has been detached. * @throws IllegalStateException If the mount does not exist, or was mounted by another peripheral. * @see #mount(String, IMount) @@ -134,22 +125,26 @@ public interface IComputerAccess /** * Returns the numerical ID of this computer. * - * This is the same number obtained by calling {@code os.getComputerID()} or running the "id" program from lua, and is guaranteed unique. This number - * will be positive. + * This is the same number obtained by calling {@code os.getComputerID()} or running the "id" program from lua, + * and is guaranteed unique. This number will be positive. * * @return The identifier. */ int getID(); /** - * Causes an event to be raised on this computer, which the computer can respond to by calling {@code os.pullEvent()}. This can be used to notify the - * computer when things happen in the world or to this peripheral. + * Causes an event to be raised on this computer, which the computer can respond to by calling + * {@code os.pullEvent()}. This can be used to notify the computer when things happen in the world or to + * this peripheral. * - * @param event A string identifying the type of event that has occurred, this will be returned as the first value from {@code os.pullEvent()}. It - * is recommended that you you choose a name that is unique, and recognisable as originating from your peripheral. eg: If your peripheral type is - * "button", a suitable event would be "button_pressed". - * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will be supplied as extra return values to - * os.pullEvent(). Objects in the array will be converted to lua data types in the same fashion as the return values of IPeripheral.callMethod(). + * @param event A string identifying the type of event that has occurred, this will be + * returned as the first value from {@code os.pullEvent()}. It is recommended that you + * you choose a name that is unique, and recognisable as originating from your + * peripheral. eg: If your peripheral type is "button", a suitable event would be + * "button_pressed". + * @param arguments In addition to a name, you may pass an array of extra arguments to the event, that will + * be supplied as extra return values to os.pullEvent(). Objects in the array will be converted + * to lua data types in the same fashion as the return values of IPeripheral.callMethod(). * * You may supply {@code null} to indicate that no arguments are to be supplied. * @throws NotAttachedException If the peripheral has been detached. @@ -157,6 +152,19 @@ public interface IComputerAccess */ void queueEvent( @Nonnull String event, @Nullable Object... arguments ); + /** + * Get a string, unique to the computer, by which the computer refers to this peripheral. + * For directly attached peripherals this will be "left","right","front","back",etc, but + * for peripherals attached remotely it will be different. It is good practice to supply + * this string when raising events to the computer, so that the computer knows from + * which peripheral the event came. + * + * @return A string unique to the computer, but not globally. + * @throws NotAttachedException If the peripheral has been detached. + */ + @Nonnull + String getAttachmentName(); + /** * Get a set of peripherals that this computer access can "see", along with their attachment name. * @@ -171,8 +179,8 @@ public interface IComputerAccess Map getAvailablePeripherals(); /** - * Get a reachable peripheral with the given attachment name. This is a equivalent to {@link #getAvailablePeripherals()}{@code .get(name)}, though may - * be more efficient. + * Get a reachable peripheral with the given attachment name. This is a equivalent to + * {@link #getAvailablePeripherals()}{@code .get(name)}, though may be more efficient. * * @param name The peripheral's attached name * @return The reachable peripheral, or {@code null} if none can be found. @@ -184,11 +192,13 @@ public interface IComputerAccess /** * Get a {@link IWorkMonitor} for tasks your peripheral might execute on the main (server) thread. * - * This should be used to ensure your peripheral integrates with ComputerCraft's monitoring and limiting of how much server time each computer consumes. - * You should not need to use this if you use {@link ILuaContext#issueMainThreadTask(ILuaTask)} - this is intended for mods with their own system for - * running work on the main thread. + * This should be used to ensure your peripheral integrates with ComputerCraft's monitoring and limiting of how much + * server time each computer consumes. You should not need to use this if you use + * {@link ILuaContext#issueMainThreadTask(ILuaTask)} - this is intended for mods with their own system for running + * work on the main thread. * - * Please note that the returned implementation is not thread-safe, and should only be used from the main thread. + * Please note that the returned implementation is not thread-safe, and should only be used from the main + * thread. * * @return The work monitor for the main thread, or {@code null} if this computer does not have one. * @throws NotAttachedException If the peripheral has been detached. diff --git a/src/main/java/dan200/computercraft/api/peripheral/IDynamicPeripheral.java b/src/main/java/dan200/computercraft/api/peripheral/IDynamicPeripheral.java index e06c14096..695680b94 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IDynamicPeripheral.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IDynamicPeripheral.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.peripheral; import dan200.computercraft.api.lua.*; @@ -13,14 +12,14 @@ import javax.annotation.Nonnull; /** * A peripheral whose methods are not known at runtime. * - * This behaves similarly to {@link IDynamicLuaObject}, though also accepting the current {@link IComputerAccess}. Generally one may use {@link LuaFunction} - * instead of implementing this interface. + * This behaves similarly to {@link IDynamicLuaObject}, though also accepting the current {@link IComputerAccess}. + * Generally one may use {@link LuaFunction} instead of implementing this interface. */ public interface IDynamicPeripheral extends IPeripheral { /** - * Should return an array of strings that identify the methods that this peripheral exposes to Lua. This will be called once before each attachment, and - * should not change when called multiple times. + * Should return an array of strings that identify the methods that this peripheral exposes to Lua. This will be + * called once before each attachment, and should not change when called multiple times. * * @return An array of strings representing method names. * @see #callMethod @@ -29,19 +28,24 @@ public interface IDynamicPeripheral extends IPeripheral String[] getMethodNames(); /** - * This is called when a lua program on an attached computer calls {@code peripheral.call()} with one of the methods exposed by {@link - * #getMethodNames()}. + * This is called when a lua program on an attached computer calls {@code peripheral.call()} with + * one of the methods exposed by {@link #getMethodNames()}. * - * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe when interacting with Minecraft objects. + * Be aware that this will be called from the ComputerCraft Lua thread, and must be thread-safe when interacting + * with Minecraft objects. * - * @param computer The interface to the computer that is making the call. Remember that multiple computers can be attached to a peripheral at once. - * @param context The context of the currently running lua thread. This can be used to wait for events or otherwise yield. - * @param method An integer identifying which of the methods from getMethodNames() the computercraft wishes to call. The integer indicates the index - * into the getMethodNames() table that corresponds to the string passed into peripheral.call() + * @param computer The interface to the computer that is making the call. Remember that multiple + * computers can be attached to a peripheral at once. + * @param context The context of the currently running lua thread. This can be used to wait for events + * or otherwise yield. + * @param method An integer identifying which of the methods from getMethodNames() the computercraft + * wishes to call. The integer indicates the index into the getMethodNames() table + * that corresponds to the string passed into peripheral.call() * @param arguments The arguments for this method. * @return A {@link MethodResult} containing the values to return or the action to perform. - * @throws LuaException If you throw any exception from this function, a lua error will be raised with the same message as your exception. Use this - * to throw appropriate errors if the wrong arguments are supplied to your method. + * @throws LuaException If you throw any exception from this function, a lua error will be raised with the + * same message as your exception. Use this to throw appropriate errors if the wrong + * arguments are supplied to your method. * @see #getMethodNames() */ @Nonnull diff --git a/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java b/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java index 09a63c64d..eddc30861 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IPeripheral.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.peripheral; import dan200.computercraft.api.lua.LuaFunction; @@ -17,12 +16,14 @@ import javax.annotation.Nullable; * In order to expose a peripheral for your block or tile entity, you register a {@link IPeripheralProvider}. This cannot be implemented {@link * IPeripheral} directly on the tile. * - * Peripherals should provide a series of methods to the user, either using {@link LuaFunction} or by implementing {@link IDynamicPeripheral}. + * Peripherals should provide a series of methods to the user, either using {@link LuaFunction} or by implementing + * {@link IDynamicPeripheral}. */ public interface IPeripheral { /** - * Should return a string that uniquely identifies this type of peripheral. This can be queried from lua by calling {@code peripheral.getType()} + * Should return a string that uniquely identifies this type of peripheral. + * This can be queried from lua by calling {@code peripheral.getType()} * * @return A string identifying the type of peripheral. */ @@ -32,15 +33,19 @@ public interface IPeripheral /** * Is called when when a computer is attaching to the peripheral. * - * This will occur when a peripheral is placed next to an active computer, when a computer is turned on next to a peripheral, when a turtle travels into - * a square next to a peripheral, or when a wired modem adjacent to this peripheral is does any of the above. + * This will occur when a peripheral is placed next to an active computer, when a computer is turned on next to a + * peripheral, when a turtle travels into a square next to a peripheral, or when a wired modem adjacent to this + * peripheral is does any of the above. * - * Between calls to attach and {@link #detach}, the attached computer can make method calls on the peripheral using {@code peripheral.call()}. This - * method can be used to keep track of which computers are attached to the peripheral, or to take action when attachment occurs. + * Between calls to attach and {@link #detach}, the attached computer can make method calls on the peripheral using + * {@code peripheral.call()}. This method can be used to keep track of which computers are attached to the + * peripheral, or to take action when attachment occurs. * - * Be aware that will be called from both the server thread and ComputerCraft Lua thread, and so must be thread-safe and reentrant. + * Be aware that will be called from both the server thread and ComputerCraft Lua thread, and so must be thread-safe + * and reentrant. * - * @param computer The interface to the computer that is being attached. Remember that multiple computers can be attached to a peripheral at once. + * @param computer The interface to the computer that is being attached. Remember that multiple computers can be + * attached to a peripheral at once. * @see #detach */ default void attach( @Nonnull IComputerAccess computer ) @@ -50,14 +55,18 @@ public interface IPeripheral /** * Called when a computer is detaching from the peripheral. * - * This will occur when a computer shuts down, when the peripheral is removed while attached to computers, when a turtle moves away from a block - * attached to a peripheral, or when a wired modem adjacent to this peripheral is detached. + * This will occur when a computer shuts down, when the peripheral is removed while attached to computers, when a + * turtle moves away from a block attached to a peripheral, or when a wired modem adjacent to this peripheral is + * detached. * - * This method can be used to keep track of which computers are attached to the peripheral, or to take action when detachment occurs. + * This method can be used to keep track of which computers are attached to the peripheral, or to take action when + * detachment occurs. * - * Be aware that this will be called from both the server and ComputerCraft Lua thread, and must be thread-safe and reentrant. + * Be aware that this will be called from both the server and ComputerCraft Lua thread, and must be thread-safe + * and reentrant. * - * @param computer The interface to the computer that is being detached. Remember that multiple computers can be attached to a peripheral at once. + * @param computer The interface to the computer that is being detached. Remember that multiple computers can be + * attached to a peripheral at once. * @see #attach */ default void detach( @Nonnull IComputerAccess computer ) @@ -65,7 +74,8 @@ public interface IPeripheral } /** - * Get the object that this peripheral provides methods for. This will generally be the tile entity or block, but may be an inventory, entity, etc... + * Get the object that this peripheral provides methods for. This will generally be the tile entity + * or block, but may be an inventory, entity, etc... * * @return The object this peripheral targets */ @@ -78,8 +88,8 @@ public interface IPeripheral /** * Determine whether this peripheral is equivalent to another one. * - * The minimal example should at least check whether they are the same object. However, you may wish to check if they point to the same block or tile - * entity. + * The minimal example should at least check whether they are the same object. However, you may wish to check if + * they point to the same block or tile entity. * * @param other The peripheral to compare against. This may be {@code null}. * @return Whether these peripherals are equivalent. diff --git a/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java b/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java index ae704dfc7..98e97d628 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IPeripheralProvider.java @@ -3,22 +3,18 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.peripheral; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; -import java.util.Optional; +import javax.annotation.Nullable; /** * This interface is used to create peripheral implementations for blocks. * - * If you have a {@link BlockEntity} which acts as a peripheral, you may alternatively expose the {@link IPeripheral} capability. - * * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) */ @FunctionalInterface @@ -30,9 +26,9 @@ public interface IPeripheralProvider * @param world The world the block is in. * @param pos The position the block is at. * @param side The side to get the peripheral from. - * @return A peripheral, or {@link Optional#empty()} if there is not a peripheral here you'd like to handle. + * @return A peripheral or {@literal null} if there is not a peripheral here you'd like to handle. * @see dan200.computercraft.api.ComputerCraftAPI#registerPeripheralProvider(IPeripheralProvider) */ - @Nonnull - IPeripheral getPeripheral( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ); + @Nullable + IPeripheral getPeripheral( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ); } diff --git a/src/main/java/dan200/computercraft/api/peripheral/IPeripheralTile.java b/src/main/java/dan200/computercraft/api/peripheral/IPeripheralTile.java index b12d7f5c0..683ee64cc 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IPeripheralTile.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IPeripheralTile.java @@ -5,15 +5,15 @@ */ package dan200.computercraft.api.peripheral; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** - * A {@link net.minecraft.block.entity.BlockEntity} which may act as a peripheral. + * A {@link net.minecraft.world.level.block.entity.BlockEntity} which may act as a peripheral. * * If you need more complex capabilities (such as handling TEs not belonging to your mod), you should use {@link IPeripheralProvider}. */ @@ -24,7 +24,7 @@ public interface IPeripheralTile * * @param side The side to get the peripheral from. * @return A peripheral, or {@code null} if there is not a peripheral here. - * @see IPeripheralProvider#getPeripheral(World, BlockPos, Direction) + * @see IPeripheralProvider#getPeripheral(Level, BlockPos, Direction) */ @Nullable IPeripheral getPeripheral( @Nonnull Direction side ); diff --git a/src/main/java/dan200/computercraft/api/peripheral/IWorkMonitor.java b/src/main/java/dan200/computercraft/api/peripheral/IWorkMonitor.java index 21ae59438..2ec3f3df9 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/IWorkMonitor.java +++ b/src/main/java/dan200/computercraft/api/peripheral/IWorkMonitor.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.peripheral; import javax.annotation.Nonnull; @@ -11,14 +10,15 @@ import java.util.Objects; import java.util.concurrent.TimeUnit; /** - * Monitors "work" associated with a computer, keeping track of how much a computer has done, and ensuring every computer receives a fair share of any - * processing time. + * Monitors "work" associated with a computer, keeping track of how much a computer has done, and ensuring every + * computer receives a fair share of any processing time. * - * This is primarily intended for work done by peripherals on the main thread (such as on a tile entity's tick), but could be used for other purposes (such - * as complex computations done on another thread). + * This is primarily intended for work done by peripherals on the main thread (such as on a tile entity's tick), but + * could be used for other purposes (such as complex computations done on another thread). * - * Before running a task, one should call {@link #canWork()} to determine if the computer is currently allowed to execute work. If that returns true, you - * should execute the task and use {@link #trackWork(long, TimeUnit)} to inform the monitor how long that task took. + * Before running a task, one should call {@link #canWork()} to determine if the computer is currently allowed to + * execute work. If that returns true, you should execute the task and use {@link #trackWork(long, TimeUnit)} to inform + * the monitor how long that task took. * * Alternatively, use {@link #runWork(Runnable)} to run and keep track of work. * @@ -26,16 +26,31 @@ import java.util.concurrent.TimeUnit; */ public interface IWorkMonitor { + /** + * If the owning computer is currently allowed to execute work. + * + * @return If we can execute work right now. + */ + boolean canWork(); + /** * If the owning computer is currently allowed to execute work, and has ample time to do so. * - * This is effectively a more restrictive form of {@link #canWork()}. One should use that in order to determine if you may do an initial piece of work, - * and shouldWork to determine if any additional task may be performed. + * This is effectively a more restrictive form of {@link #canWork()}. One should use that in order to determine if + * you may do an initial piece of work, and shouldWork to determine if any additional task may be performed. * * @return If we should execute work right now. */ boolean shouldWork(); + /** + * Inform the monitor how long some piece of work took to execute. + * + * @param time The time some task took to run + * @param unit The unit that {@code time} was measured in. + */ + void trackWork( long time, @Nonnull TimeUnit unit ); + /** * Run a task if possible, and inform the monitor of how long it took. * @@ -45,10 +60,7 @@ public interface IWorkMonitor default boolean runWork( @Nonnull Runnable runnable ) { Objects.requireNonNull( runnable, "runnable should not be null" ); - if( !canWork() ) - { - return false; - } + if( !canWork() ) return false; long start = System.nanoTime(); try @@ -62,19 +74,4 @@ public interface IWorkMonitor return true; } - - /** - * If the owning computer is currently allowed to execute work. - * - * @return If we can execute work right now. - */ - boolean canWork(); - - /** - * Inform the monitor how long some piece of work took to execute. - * - * @param time The time some task took to run - * @param unit The unit that {@code time} was measured in. - */ - void trackWork( long time, @Nonnull TimeUnit unit ); } diff --git a/src/main/java/dan200/computercraft/api/peripheral/NotAttachedException.java b/src/main/java/dan200/computercraft/api/peripheral/NotAttachedException.java index 335841cfb..96ebd11ac 100644 --- a/src/main/java/dan200/computercraft/api/peripheral/NotAttachedException.java +++ b/src/main/java/dan200/computercraft/api/peripheral/NotAttachedException.java @@ -3,11 +3,11 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.peripheral; /** - * Thrown when performing operations on {@link IComputerAccess} when the current peripheral is no longer attached to the computer. + * Thrown when performing operations on {@link IComputerAccess} when the current peripheral is no longer attached to + * the computer. */ public class NotAttachedException extends IllegalStateException { diff --git a/src/main/java/dan200/computercraft/api/peripheral/PeripheralType.java b/src/main/java/dan200/computercraft/api/peripheral/PeripheralType.java new file mode 100644 index 000000000..2780534c2 --- /dev/null +++ b/src/main/java/dan200/computercraft/api/peripheral/PeripheralType.java @@ -0,0 +1,62 @@ +/* + * This file is part of the public ComputerCraft API - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. + * For help using the API, and posting your mods, visit the forums at computercraft.info. + */ +package dan200.computercraft.api.peripheral; + +import com.google.common.base.Strings; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * The type of a {@link GenericPeripheral}. + * + * When determining the final type of the resulting peripheral, the union of all types is taken, with the + * lexicographically smallest non-empty name being chosen. + */ +public final class PeripheralType +{ + private static final PeripheralType UNTYPED = new PeripheralType( null ); + + private final String type; + + public PeripheralType( String type ) + { + this.type = type; + } + + /** + * An empty peripheral type, used when a {@link GenericPeripheral} does not have an explicit type. + * + * @return The empty peripheral type. + */ + public static PeripheralType untyped() + { + return UNTYPED; + } + + /** + * Create a new non-empty peripheral type. + * + * @param type The name of the type. + * @return The constructed peripheral type. + */ + public static PeripheralType ofType( @Nonnull String type ) + { + if( Strings.isNullOrEmpty( type ) ) throw new IllegalArgumentException( "type cannot be null or empty" ); + return new PeripheralType( type ); + } + + /** + * Get the name of this peripheral type. This may be {@literal null}. + * + * @return The type of this peripheral. + */ + @Nullable + public String getPrimaryType() + { + return type; + } +} diff --git a/src/main/java/dan200/computercraft/api/pocket/AbstractPocketUpgrade.java b/src/main/java/dan200/computercraft/api/pocket/AbstractPocketUpgrade.java index 6599d7e90..ccb68d834 100644 --- a/src/main/java/dan200/computercraft/api/pocket/AbstractPocketUpgrade.java +++ b/src/main/java/dan200/computercraft/api/pocket/AbstractPocketUpgrade.java @@ -3,15 +3,14 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.pocket; import dan200.computercraft.shared.util.NonNullSupplier; -import net.minecraft.item.Item; -import net.minecraft.item.ItemConvertible; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ItemLike; import javax.annotation.Nonnull; import java.util.function.Supplier; @@ -23,55 +22,55 @@ import java.util.function.Supplier; */ public abstract class AbstractPocketUpgrade implements IPocketUpgrade { - private final Identifier id; + private final ResourceLocation id; private final String adjective; private final NonNullSupplier stack; - protected AbstractPocketUpgrade( Identifier id, String adjective, NonNullSupplier stack ) + protected AbstractPocketUpgrade( ResourceLocation id, String adjective, NonNullSupplier stack ) { this.id = id; this.adjective = adjective; this.stack = stack; } - protected AbstractPocketUpgrade( Identifier id, NonNullSupplier item ) + protected AbstractPocketUpgrade( ResourceLocation id, NonNullSupplier item ) { - this( id, Util.createTranslationKey( "upgrade", id ) + ".adjective", item ); + this( id, Util.makeDescriptionId( "upgrade", id ) + ".adjective", item ); } - protected AbstractPocketUpgrade( Identifier id, String adjective, ItemStack stack ) + protected AbstractPocketUpgrade( ResourceLocation id, String adjective, ItemStack stack ) { this( id, adjective, () -> stack ); } - protected AbstractPocketUpgrade( Identifier id, ItemStack stack ) + protected AbstractPocketUpgrade( ResourceLocation id, ItemStack stack ) { this( id, () -> stack ); } - protected AbstractPocketUpgrade( Identifier id, String adjective, ItemConvertible item ) + protected AbstractPocketUpgrade( ResourceLocation id, String adjective, ItemLike item ) { this( id, adjective, new CachedStack( () -> item ) ); } - protected AbstractPocketUpgrade( Identifier id, ItemConvertible item ) + protected AbstractPocketUpgrade( ResourceLocation id, ItemLike item ) { this( id, new CachedStack( () -> item ) ); } - protected AbstractPocketUpgrade( Identifier id, String adjective, Supplier item ) + protected AbstractPocketUpgrade( ResourceLocation id, String adjective, Supplier item ) { this( id, adjective, new CachedStack( item ) ); } - protected AbstractPocketUpgrade( Identifier id, Supplier item ) + protected AbstractPocketUpgrade( ResourceLocation id, Supplier item ) { this( id, new CachedStack( item ) ); } @Nonnull @Override - public final Identifier getUpgradeID() + public final ResourceLocation getUpgradeID() { return id; } @@ -97,11 +96,11 @@ public abstract class AbstractPocketUpgrade implements IPocketUpgrade */ private static final class CachedStack implements NonNullSupplier { - private final Supplier provider; + private final Supplier provider; private Item item; private ItemStack stack; - CachedStack( Supplier provider ) + CachedStack( Supplier provider ) { this.provider = provider; } diff --git a/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java b/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java index 0638f6c5c..2fa939153 100644 --- a/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java +++ b/src/main/java/dan200/computercraft/api/pocket/IPocketAccess.java @@ -3,13 +3,12 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.pocket; import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.entity.Entity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.Identifier; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.Entity; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,7 +32,8 @@ public interface IPocketAccess /** * Get the colour of this pocket computer as a RGB number. * - * @return The colour this pocket computer is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or -1 if it has no colour. + * @return The colour this pocket computer is. This will be a RGB colour between {@code 0x000000} and + * {@code 0xFFFFFF} or -1 if it has no colour. * @see #setColour(int) */ int getColour(); @@ -41,8 +41,8 @@ public interface IPocketAccess /** * Set the colour of the pocket computer to a RGB number. * - * @param colour The colour this pocket computer should be changed to. This should be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or - * -1 to reset to the default colour. + * @param colour The colour this pocket computer should be changed to. This should be a RGB colour between + * {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour. * @see #getColour() */ void setColour( int colour ); @@ -50,7 +50,8 @@ public interface IPocketAccess /** * Get the colour of this pocket computer's light as a RGB number. * - * @return The colour this light is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or -1 if it has no colour. + * @return The colour this light is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or + * -1 if it has no colour. * @see #setLight(int) */ int getLight(); @@ -58,8 +59,8 @@ public interface IPocketAccess /** * Set the colour of the pocket computer's light to a RGB number. * - * @param colour The colour this modem's light will be changed to. This should be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or -1 - * to reset to the default colour. + * @param colour The colour this modem's light will be changed to. This should be a RGB colour between + * {@code 0x000000} and {@code 0xFFFFFF} or -1 to reset to the default colour. * @see #getLight() */ void setLight( int colour ); @@ -73,7 +74,7 @@ public interface IPocketAccess * @see #updateUpgradeNBTData() */ @Nonnull - NbtCompound getUpgradeNBTData(); + CompoundTag getUpgradeNBTData(); /** * Mark the upgrade-specific NBT as dirty. @@ -93,5 +94,5 @@ public interface IPocketAccess * @return A collection of all upgrade names. */ @Nonnull - Map getUpgrades(); + Map getUpgrades(); } diff --git a/src/main/java/dan200/computercraft/api/pocket/IPocketUpgrade.java b/src/main/java/dan200/computercraft/api/pocket/IPocketUpgrade.java index d8b9d0c13..4e39f0b38 100644 --- a/src/main/java/dan200/computercraft/api/pocket/IPocketUpgrade.java +++ b/src/main/java/dan200/computercraft/api/pocket/IPocketUpgrade.java @@ -3,13 +3,12 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.pocket; import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.IUpgradeBase; import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -24,8 +23,9 @@ public interface IPocketUpgrade extends IUpgradeBase /** * Creates a peripheral for the pocket computer. * - * The peripheral created will be stored for the lifetime of the upgrade, will be passed an argument to {@link #update(IPocketAccess, IPeripheral)} and - * will be attached, detached and have methods called in the same manner as an ordinary peripheral. + * The peripheral created will be stored for the lifetime of the upgrade, will be passed an argument to + * {@link #update(IPocketAccess, IPeripheral)} and will be attached, detached and have methods called in the same + * manner as an ordinary peripheral. * * @param access The access object for the pocket item stack. * @return The newly created peripheral. @@ -51,11 +51,12 @@ public interface IPocketUpgrade extends IUpgradeBase * @param world The world the computer is in. * @param access The access object for the pocket item stack. * @param peripheral The peripheral for this upgrade. - * @return {@code true} to stop the GUI from opening, otherwise false. You should always provide some code path which returns {@code false}, such as - * requiring the player to be sneaking - otherwise they will be unable to access the GUI. + * @return {@code true} to stop the GUI from opening, otherwise false. You should always provide some code path + * which returns {@code false}, such as requiring the player to be sneaking - otherwise they will be unable to + * access the GUI. * @see #createPeripheral(IPocketAccess) */ - default boolean onRightClick( @Nonnull World world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ) + default boolean onRightClick( @Nonnull Level world, @Nonnull IPocketAccess access, @Nullable IPeripheral peripheral ) { return false; } diff --git a/src/main/java/dan200/computercraft/api/redstone/IBundledRedstoneProvider.java b/src/main/java/dan200/computercraft/api/redstone/IBundledRedstoneProvider.java index ad92f3903..1f2f4f4ad 100644 --- a/src/main/java/dan200/computercraft/api/redstone/IBundledRedstoneProvider.java +++ b/src/main/java/dan200/computercraft/api/redstone/IBundledRedstoneProvider.java @@ -3,12 +3,11 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.redstone; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; @@ -26,8 +25,9 @@ public interface IBundledRedstoneProvider * @param world The world this block is in. * @param pos The position this block is at. * @param side The side to extract the bundled redstone output from. - * @return A number in the range 0-65535 to indicate this block is providing output, or -1 if you do not wish to handle this block. + * @return A number in the range 0-65535 to indicate this block is providing output, or -1 if you do not wish to + * handle this block. * @see dan200.computercraft.api.ComputerCraftAPI#registerBundledRedstoneProvider(IBundledRedstoneProvider) */ - int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ); + int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ); } diff --git a/src/main/java/dan200/computercraft/api/turtle/AbstractTurtleUpgrade.java b/src/main/java/dan200/computercraft/api/turtle/AbstractTurtleUpgrade.java index 7046cc808..6d075b5fc 100644 --- a/src/main/java/dan200/computercraft/api/turtle/AbstractTurtleUpgrade.java +++ b/src/main/java/dan200/computercraft/api/turtle/AbstractTurtleUpgrade.java @@ -7,11 +7,11 @@ package dan200.computercraft.api.turtle; import dan200.computercraft.shared.util.NonNullSupplier; -import net.minecraft.item.Item; -import net.minecraft.item.ItemConvertible; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ItemLike; import javax.annotation.Nonnull; import java.util.function.Supplier; @@ -23,12 +23,12 @@ import java.util.function.Supplier; */ public abstract class AbstractTurtleUpgrade implements ITurtleUpgrade { - private final Identifier id; + private final ResourceLocation id; private final TurtleUpgradeType type; private final String adjective; private final NonNullSupplier stack; - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, NonNullSupplier stack ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, String adjective, NonNullSupplier stack ) { this.id = id; this.type = type; @@ -36,44 +36,44 @@ public abstract class AbstractTurtleUpgrade implements ITurtleUpgrade this.stack = stack; } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, NonNullSupplier stack ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, NonNullSupplier stack ) { - this( id, type, Util.createTranslationKey( "upgrade", id ) + ".adjective", stack ); + this( id, type, Util.makeDescriptionId( "upgrade", id ) + ".adjective", stack ); } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, ItemStack stack ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, String adjective, ItemStack stack ) { this( id, type, adjective, () -> stack ); } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, ItemStack stack ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, ItemStack stack ) { this( id, type, () -> stack ); } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, ItemConvertible item ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, String adjective, ItemLike item ) { this( id, type, adjective, new CachedStack( () -> item ) ); } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, ItemConvertible item ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, ItemLike item ) { this( id, type, new CachedStack( () -> item ) ); } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, String adjective, Supplier item ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, String adjective, Supplier item ) { this( id, type, adjective, new CachedStack( item ) ); } - protected AbstractTurtleUpgrade( Identifier id, TurtleUpgradeType type, Supplier item ) + protected AbstractTurtleUpgrade( ResourceLocation id, TurtleUpgradeType type, Supplier item ) { this( id, type, new CachedStack( item ) ); } @Nonnull @Override - public final Identifier getUpgradeID() + public final ResourceLocation getUpgradeID() { return id; } @@ -106,11 +106,11 @@ public abstract class AbstractTurtleUpgrade implements ITurtleUpgrade */ private static final class CachedStack implements NonNullSupplier { - private final Supplier provider; + private final Supplier provider; private Item item; private ItemStack stack; - CachedStack( Supplier provider ) + CachedStack( Supplier provider ) { this.provider = provider; } diff --git a/src/main/java/dan200/computercraft/api/turtle/FakePlayer.java b/src/main/java/dan200/computercraft/api/turtle/FakePlayer.java index e534e648e..b1481f5c3 100644 --- a/src/main/java/dan200/computercraft/api/turtle/FakePlayer.java +++ b/src/main/java/dan200/computercraft/api/turtle/FakePlayer.java @@ -9,30 +9,34 @@ import com.mojang.authlib.GameProfile; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; -import net.minecraft.block.entity.CommandBlockBlockEntity; -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.command.argument.EntityAnchorArgumentType; -import net.minecraft.entity.Entity; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.effect.StatusEffectInstance; -import net.minecraft.entity.passive.HorseBaseEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.network.*; -import net.minecraft.network.packet.c2s.play.RequestCommandCompletionsC2SPacket; -import net.minecraft.network.packet.c2s.play.VehicleMoveC2SPacket; -import net.minecraft.recipe.Recipe; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.sound.SoundCategory; -import net.minecraft.sound.SoundEvent; -import net.minecraft.text.Text; -import net.minecraft.util.Hand; -import net.minecraft.util.math.ChunkPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.village.TradeOfferList; +import net.minecraft.commands.arguments.EntityAnchorArgument; +import net.minecraft.network.Connection; +import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.chat.ChatType; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.game.ServerboundCommandSuggestionPacket; +import net.minecraft.network.protocol.game.ServerboundMoveVehiclePacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.Container; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.animal.horse.AbstractHorse; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.trading.MerchantOffers; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.block.entity.CommandBlockEntity; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nullable; import javax.crypto.Cipher; @@ -41,26 +45,26 @@ import java.util.OptionalInt; import java.util.UUID; /** - * A wrapper for {@link ServerPlayerEntity} which denotes a "fake" player. + * A wrapper for {@link ServerPlayer} which denotes a "fake" player. * * Please note that this does not implement any of the traditional fake player behaviour. It simply exists to prevent me passing in normal players. */ -public class FakePlayer extends ServerPlayerEntity +public class FakePlayer extends ServerPlayer { - public FakePlayer( ServerWorld world, GameProfile gameProfile ) + public FakePlayer( ServerLevel world, GameProfile gameProfile ) { super( world.getServer(), world, gameProfile ); - networkHandler = new FakeNetHandler( this ); + connection = new FakeNetHandler( this ); } // region Direct networkHandler access @Override - public void enterCombat() + public void onEnterCombat() { } @Override - public void endCombat() + public void onLeaveCombat() { } @@ -70,23 +74,23 @@ public class FakePlayer extends ServerPlayerEntity } @Override - public void playerTick() + public void doTick() { } @Override - public void onDeath( DamageSource damage ) + public void die( DamageSource damage ) { } @Override - public Entity moveToWorld( ServerWorld destination ) + public Entity changeDimension( ServerLevel destination ) { return this; } @Override - public void wakeUp( boolean bl, boolean updateSleepingPlayers ) + public void stopSleepInBed( boolean bl, boolean updateSleepingPlayers ) { } @@ -103,33 +107,33 @@ public class FakePlayer extends ServerPlayerEntity } @Override - public void openEditSignScreen( SignBlockEntity tile ) + public void openTextEdit( SignBlockEntity tile ) { } @Override - public OptionalInt openHandledScreen( @Nullable NamedScreenHandlerFactory container ) + public OptionalInt openMenu( @Nullable MenuProvider container ) { return OptionalInt.empty(); } @Override - public void sendTradeOffers( int id, TradeOfferList list, int level, int experience, boolean levelled, boolean refreshable ) + public void sendMerchantOffers( int id, MerchantOffers list, int level, int experience, boolean levelled, boolean refreshable ) { } @Override - public void openHorseInventory( HorseBaseEntity horse, Inventory inventory ) + public void openHorseInventory( AbstractHorse horse, Container inventory ) { } @Override - public void useBook( ItemStack stack, Hand hand ) + public void openItemGui( ItemStack stack, InteractionHand hand ) { } @Override - public void openCommandBlockScreen( CommandBlockBlockEntity block ) + public void openCommandBlock( CommandBlockEntity block ) { } @@ -149,7 +153,7 @@ public class FakePlayer extends ServerPlayerEntity // } @Override - public void closeHandledScreen() + public void closeContainer() { } @@ -159,55 +163,55 @@ public class FakePlayer extends ServerPlayerEntity // } @Override - public int unlockRecipes( Collection> recipes ) + public int awardRecipes( Collection> recipes ) { return 0; } // Indirect @Override - public int lockRecipes( Collection> recipes ) + public int resetRecipes( Collection> recipes ) { return 0; } @Override - public void sendMessage( Text textComponent, boolean status ) + public void displayClientMessage( Component textComponent, boolean status ) { } @Override - protected void consumeItem() + protected void completeUsingItem() { } @Override - public void lookAt( EntityAnchorArgumentType.EntityAnchor anchor, Vec3d vec3d ) + public void lookAt( EntityAnchorArgument.Anchor anchor, Vec3 vec3d ) { } @Override - public void lookAtEntity( EntityAnchorArgumentType.EntityAnchor self, Entity entity, EntityAnchorArgumentType.EntityAnchor target ) + public void lookAt( EntityAnchorArgument.Anchor self, Entity entity, EntityAnchorArgument.Anchor target ) { } @Override - protected void onStatusEffectApplied( StatusEffectInstance statusEffectInstance, @Nullable Entity source ) + protected void onEffectAdded( MobEffectInstance statusEffectInstance, @Nullable Entity source ) { } @Override - protected void onStatusEffectUpgraded( StatusEffectInstance statusEffectInstance, boolean particles, @Nullable Entity source ) + protected void onEffectUpdated( MobEffectInstance statusEffectInstance, boolean particles, @Nullable Entity source ) { } @Override - protected void onStatusEffectRemoved( StatusEffectInstance statusEffectInstance ) + protected void onEffectRemoved( MobEffectInstance statusEffectInstance ) { } @Override - public void requestTeleport( double x, double y, double z ) + public void teleportTo( double x, double y, double z ) { } @@ -217,13 +221,13 @@ public class FakePlayer extends ServerPlayerEntity // } @Override - public void sendMessage( Text message, MessageType type, UUID senderUuid ) + public void sendMessage( Component message, ChatType type, UUID senderUuid ) { } @Override - public String getIp() + public String getIpAddress() { return "[Fake Player]"; } @@ -239,63 +243,63 @@ public class FakePlayer extends ServerPlayerEntity // } @Override - public void setCameraEntity( Entity entity ) + public void setCamera( Entity entity ) { } @Override - public void teleport( ServerWorld serverWorld, double x, double y, double z, float pitch, float yaw ) + public void teleportTo( ServerLevel serverWorld, double x, double y, double z, float pitch, float yaw ) { } @Override - public void sendInitialChunkPackets( ChunkPos chunkPos, Packet packet, Packet packet2 ) + public void trackChunk( ChunkPos chunkPos, Packet packet, Packet packet2 ) { } @Override - public void sendUnloadChunkPacket( ChunkPos chunkPos ) + public void untrackChunk( ChunkPos chunkPos ) { } @Override - public void playSound( SoundEvent soundEvent, SoundCategory soundCategory, float volume, float pitch ) + public void playNotifySound( SoundEvent soundEvent, SoundSource soundCategory, float volume, float pitch ) { } - private static class FakeNetHandler extends ServerPlayNetworkHandler + private static class FakeNetHandler extends ServerGamePacketListenerImpl { - FakeNetHandler( ServerPlayerEntity player ) + FakeNetHandler( ServerPlayer player ) { super( player.server, new FakeConnection(), player ); } @Override - public void disconnect( Text message ) + public void disconnect( Component message ) { } @Override - public void onVehicleMove( VehicleMoveC2SPacket move ) + public void handleMoveVehicle( ServerboundMoveVehiclePacket move ) { } @Override - public void onRequestCommandCompletions( RequestCommandCompletionsC2SPacket packet ) + public void handleCustomCommandSuggestions( ServerboundCommandSuggestionPacket packet ) { } @Override - public void sendPacket( Packet packet, @Nullable GenericFutureListener> listener ) + public void send( Packet packet, @Nullable GenericFutureListener> listener ) { } } - private static class FakeConnection extends ClientConnection + private static class FakeConnection extends Connection { FakeConnection() { - super( NetworkSide.CLIENTBOUND ); + super( PacketFlow.CLIENTBOUND ); } @Override @@ -304,7 +308,7 @@ public class FakePlayer extends ServerPlayerEntity } @Override - public void setState( NetworkState state ) + public void setProtocol( ConnectionProtocol state ) { } @@ -329,18 +333,18 @@ public class FakePlayer extends ServerPlayerEntity } @Override - public void disconnect( Text message ) + public void disconnect( Component message ) { } @Override - public void setupEncryption( Cipher cipher, Cipher cipher2 ) + public void setEncryptionKey( Cipher cipher, Cipher cipher2 ) { - super.setupEncryption( cipher, cipher2 ); + super.setEncryptionKey( cipher, cipher2 ); } @Override - public void disableAutoRead() + public void setReadOnly() { } } diff --git a/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java b/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java index c50b83eb3..d9de8062a 100644 --- a/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java +++ b/src/main/java/dan200/computercraft/api/turtle/ITurtleAccess.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; import com.mojang.authlib.GameProfile; @@ -11,12 +10,12 @@ import dan200.computercraft.api.lua.ILuaCallback; import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.util.ItemStorage; -import net.minecraft.inventory.Inventory; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.Container; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -24,7 +23,8 @@ import javax.annotation.Nullable; /** * The interface passed to turtle by turtles, providing methods that they can call. * - * This should not be implemented by your classes. Do not interact with turtles except via this interface and {@link ITurtleUpgrade}. + * This should not be implemented by your classes. Do not interact with turtles except via this interface and + * {@link ITurtleUpgrade}. */ public interface ITurtleAccess { @@ -34,7 +34,7 @@ public interface ITurtleAccess * @return the world in which the turtle resides. */ @Nonnull - World getWorld(); + Level getLevel(); /** * Returns a vector containing the integer co-ordinates at which the turtle resides. @@ -47,25 +47,27 @@ public interface ITurtleAccess /** * Attempt to move this turtle to a new position. * - * This will preserve the turtle's internal state, such as it's inventory, computer and upgrades. It should be used before playing a movement animation - * using {@link #playAnimation(TurtleAnimation)}. + * This will preserve the turtle's internal state, such as it's inventory, computer and upgrades. It should + * be used before playing a movement animation using {@link #playAnimation(TurtleAnimation)}. * * @param world The new world to move it to * @param pos The new position to move it to. - * @return Whether the movement was successful. It may fail if the block was not loaded or the block placement was cancelled. + * @return Whether the movement was successful. It may fail if the block was not loaded or the block placement + * was cancelled. * @throws UnsupportedOperationException When attempting to teleport on the client side. */ - boolean teleportTo( @Nonnull World world, @Nonnull BlockPos pos ); + boolean teleportTo( @Nonnull Level world, @Nonnull BlockPos pos ); /** - * Returns a vector containing the floating point co-ordinates at which the turtle is rendered. This will shift when the turtle is moving. + * Returns a vector containing the floating point co-ordinates at which the turtle is rendered. + * This will shift when the turtle is moving. * * @param f The subframe fraction. * @return A vector containing the floating point co-ordinates at which the turtle resides. * @see #getVisualYaw(float) */ @Nonnull - Vec3d getVisualPosition( float f ); + Vec3 getVisualPosition( float f ); /** * Returns the yaw the turtle is facing when it is rendered. @@ -86,8 +88,8 @@ public interface ITurtleAccess Direction getDirection(); /** - * Set the direction the turtle is facing. Note that this will not play a rotation animation, you will also need to call {@link - * #playAnimation(TurtleAnimation)} to do so. + * Set the direction the turtle is facing. Note that this will not play a rotation animation, you will also need to + * call {@link #playAnimation(TurtleAnimation)} to do so. * * @param dir The new direction to set. This should be on either the x or z axis (so north, south, east or west). * @see #getDirection() @@ -106,30 +108,32 @@ public interface ITurtleAccess /** * Set the currently selected slot in the turtle's inventory. * - * @param slot The slot to set. This must be greater or equal to 0 and less than the inventory size. Otherwise no action will be taken. + * @param slot The slot to set. This must be greater or equal to 0 and less than the inventory size. Otherwise no + * action will be taken. * @throws UnsupportedOperationException When attempting to change the slot on the client side. * @see #getInventory() * @see #getSelectedSlot() */ void setSelectedSlot( int slot ); - /** - * Get the colour of this turtle as a RGB number. - * - * @return The colour this turtle is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or -1 if it has no colour. - * @see #setColour(int) - */ - int getColour(); - /** * Set the colour of the turtle to a RGB number. * - * @param colour The colour this turtle should be changed to. This should be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or -1 to - * reset to the default colour. + * @param colour The colour this turtle should be changed to. This should be a RGB colour between {@code 0x000000} + * and {@code 0xFFFFFF} or -1 to reset to the default colour. * @see #getColour() */ void setColour( int colour ); + /** + * Get the colour of this turtle as a RGB number. + * + * @return The colour this turtle is. This will be a RGB colour between {@code 0x000000} and {@code 0xFFFFFF} or + * -1 if it has no colour. + * @see #setColour(int) + */ + int getColour(); + /** * Get the player who owns this turtle, namely whoever placed it. * @@ -138,6 +142,32 @@ public interface ITurtleAccess @Nullable GameProfile getOwningPlayer(); + /** + * Get the inventory of this turtle. + * + * Note: this inventory should only be accessed and modified on the server thread. + * + * @return This turtle's inventory + * @see #getItemHandler() + */ + @Nonnull + Container getInventory(); + + /** + * Get the inventory of this turtle as an {@link ItemStorage}. + * + * Note: this inventory should only be accessed and modified on the server thread. + * + * @return This turtle's inventory + * @see #getInventory() + * @see ItemStorage + */ + @Nonnull + default ItemStorage getItemHandler() + { + return ItemStorage.wrap( getInventory() ); + } + /** * Determine whether this turtle will require fuel when performing actions. * @@ -157,7 +187,8 @@ public interface ITurtleAccess int getFuelLevel(); /** - * Set the fuel level to a new value. It is generally preferred to use {@link #consumeFuel(int)}} or {@link #addFuel(int)} instead. + * Set the fuel level to a new value. It is generally preferred to use {@link #consumeFuel(int)}} or {@link #addFuel(int)} + * instead. * * @param fuel The new amount of fuel. This must be between 0 and the fuel limit. * @see #getFuelLevel() @@ -178,8 +209,8 @@ public interface ITurtleAccess * Removes some fuel from the turtles fuel supply. Negative numbers can be passed in to INCREASE the fuel level of the turtle. * * @param fuel The amount of fuel to consume. - * @return Whether the turtle was able to consume the amount of fuel specified. Will return false if you supply a number greater than the current fuel - * level of the turtle. No fuel will be consumed if {@code false} is returned. + * @return Whether the turtle was able to consume the amount of fuel specified. Will return false if you supply a number + * greater than the current fuel level of the turtle. No fuel will be consumed if {@code false} is returned. * @throws UnsupportedOperationException When attempting to consume fuel on the client side. */ boolean consumeFuel( int fuel ); @@ -193,13 +224,15 @@ public interface ITurtleAccess void addFuel( int fuel ); /** - * Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed on the main thread, so are - * guaranteed to be able to access Minecraft objects safely, and will be queued up with the turtles standard movement and tool commands. An issued - * command will return an unique integer, which will be supplied as a parameter to a "turtle_response" event issued to the turtle after the command has - * completed. Look at the lua source code for "rom/apis/turtle" for how to build a lua wrapper around this functionality. + * Adds a custom command to the turtles command queue. Unlike peripheral methods, these custom commands will be executed + * on the main thread, so are guaranteed to be able to access Minecraft objects safely, and will be queued up + * with the turtles standard movement and tool commands. An issued command will return an unique integer, which will + * be supplied as a parameter to a "turtle_response" event issued to the turtle after the command has completed. Look at the + * lua source code for "rom/apis/turtle" for how to build a lua wrapper around this functionality. * * @param command An object which will execute the custom command when its point in the queue is reached - * @return The objects the command returned when executed. you should probably return these to the player unchanged if called from a peripheral method. + * @return The objects the command returned when executed. you should probably return these to the player + * unchanged if called from a peripheral method. * @throws UnsupportedOperationException When attempting to execute a command on the client side. * @see ITurtleCommand * @see MethodResult#pullEvent(String, ILuaCallback) @@ -208,7 +241,8 @@ public interface ITurtleAccess MethodResult executeCommand( @Nonnull ITurtleCommand command ); /** - * Start playing a specific animation. This will prevent other turtle commands from executing until it is finished. + * Start playing a specific animation. This will prevent other turtle commands from executing until + * it is finished. * * @param animation The animation to play. * @throws UnsupportedOperationException When attempting to execute play an animation on the client side. @@ -247,36 +281,22 @@ public interface ITurtleAccess /** * Get an upgrade-specific NBT compound, which can be used to store arbitrary data. * - * This will be persisted across turtle restarts and chunk loads, as well as being synced to the client. You must call {@link - * #updateUpgradeNBTData(TurtleSide)} after modifying it. + * This will be persisted across turtle restarts and chunk loads, as well as being synced to the client. You must + * call {@link #updateUpgradeNBTData(TurtleSide)} after modifying it. * * @param side The side to get the upgrade data for. * @return The upgrade-specific data. * @see #updateUpgradeNBTData(TurtleSide) */ @Nonnull - NbtCompound getUpgradeNBTData( @Nullable TurtleSide side ); + CompoundTag getUpgradeNBTData( @Nullable TurtleSide side ); /** - * Mark the upgrade-specific data as dirty on a specific side. This is required for the data to be synced to the client and persisted. + * Mark the upgrade-specific data as dirty on a specific side. This is required for the data to be synced to the + * client and persisted. * * @param side The side to mark dirty. * @see #updateUpgradeNBTData(TurtleSide) */ void updateUpgradeNBTData( @Nonnull TurtleSide side ); - - default ItemStorage getItemHandler() - { - return ItemStorage.wrap( getInventory() ); - } - - /** - * Get the inventory of this turtle. - * - * Note: this inventory should only be accessed and modified on the server thread. - * - * @return This turtle's inventory - */ - @Nonnull - Inventory getInventory(); } diff --git a/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java b/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java index 134bb346d..e7300a02c 100644 --- a/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java +++ b/src/main/java/dan200/computercraft/api/turtle/ITurtleCommand.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; import javax.annotation.Nonnull; @@ -19,8 +18,8 @@ public interface ITurtleCommand /** * Will be called by the turtle on the main thread when it is time to execute the custom command. * - * The handler should either perform the work of the command, and return success, or return failure with an error message to indicate the command cannot - * be executed at this time. + * The handler should either perform the work of the command, and return success, or return + * failure with an error message to indicate the command cannot be executed at this time. * * @param turtle Access to the turtle for whom the command was issued. * @return A result, indicating whether this action succeeded or not. diff --git a/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java b/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java index bc9d9e018..52acab992 100644 --- a/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java +++ b/src/main/java/dan200/computercraft/api/turtle/ITurtleUpgrade.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; import dan200.computercraft.api.ComputerCraftAPI; @@ -12,13 +11,14 @@ import dan200.computercraft.api.client.TransformedModel; import dan200.computercraft.api.peripheral.IPeripheral; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** - * The primary interface for defining an update for Turtles. A turtle update can either be a new tool, or a new peripheral. + * The primary interface for defining an update for Turtles. A turtle update + * can either be a new tool, or a new peripheral. * * @see ComputerCraftAPI#registerTurtleUpgrade(ITurtleUpgrade) */ @@ -36,12 +36,14 @@ public interface ITurtleUpgrade extends IUpgradeBase /** * Will only be called for peripheral upgrades. Creates a peripheral for a turtle being placed using this upgrade. * - * The peripheral created will be stored for the lifetime of the upgrade and will be passed as an argument to {@link #update(ITurtleAccess, - * TurtleSide)}. It will be attached, detached and have methods called in the same manner as a Computer peripheral. + * The peripheral created will be stored for the lifetime of the upgrade and will be passed as an argument to + * {@link #update(ITurtleAccess, TurtleSide)}. It will be attached, detached and have methods called in the same + * manner as a Computer peripheral. * * @param turtle Access to the turtle that the peripheral is being created for. * @param side Which side of the turtle (left or right) that the upgrade resides on. - * @return The newly created peripheral. You may return {@code null} if this upgrade is a Tool and this method is not expected to be called. + * @return The newly created peripheral. You may return {@code null} if this upgrade is a Tool + * and this method is not expected to be called. */ @Nullable default IPeripheral createPeripheral( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ) @@ -50,16 +52,19 @@ public interface ITurtleUpgrade extends IUpgradeBase } /** - * Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called by the turtle, and the tool is required to do some work. + * Will only be called for Tool turtle. Called when turtle.dig() or turtle.attack() is called + * by the turtle, and the tool is required to do some work. * * @param turtle Access to the turtle that the tool resides on. * @param side Which side of the turtle (left or right) the tool resides on. * @param verb Which action (dig or attack) the turtle is being called on to perform. - * @param direction Which world direction the action should be performed in, relative to the turtles position. This will either be up, down, or the - * direction the turtle is facing, depending on whether dig, digUp or digDown was called. - * @return Whether the turtle was able to perform the action, and hence whether the {@code turtle.dig()} or {@code turtle.attack()} lua method should - * return true. If true is returned, the tool will perform a swinging animation. You may return {@code null} if this turtle is a Peripheral and - * this method is not expected to be called. + * @param direction Which world direction the action should be performed in, relative to the turtles + * position. This will either be up, down, or the direction the turtle is facing, depending on + * whether dig, digUp or digDown was called. + * @return Whether the turtle was able to perform the action, and hence whether the {@code turtle.dig()} + * or {@code turtle.attack()} lua method should return true. If true is returned, the tool will perform + * a swinging animation. You may return {@code null} if this turtle is a Peripheral and this method is not expected + * to be called. */ @Nonnull default TurtleCommandResult useTool( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side, @Nonnull TurtleVerb verb, @Nonnull Direction direction ) @@ -70,6 +75,10 @@ public interface ITurtleUpgrade extends IUpgradeBase /** * Called to obtain the model to be used when rendering a turtle peripheral. * + * This can be obtained from {@link net.minecraft.client.renderer.ItemModelShaper#getItemModel(ItemStack)}, + * {@link net.minecraft.client.resources.model.ModelManager#getModel(ModelResourceLocation)} or any other + * source. + * * @param turtle Access to the turtle that the upgrade resides on. This will be null when getting item models! * @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. diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleAnimation.java b/src/main/java/dan200/computercraft/api/turtle/TurtleAnimation.java index f4468b5c9..dd67a044a 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleAnimation.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleAnimation.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; /** @@ -24,34 +23,38 @@ public enum TurtleAnimation NONE, /** - * Make the turtle move forward. Note that the animation starts from the block behind it, and moves into this one. + * Make the turtle move forward. Note that the animation starts from the block behind it, and + * moves into this one. */ MOVE_FORWARD, /** - * Make the turtle move backwards. Note that the animation starts from the block in front it, and moves into this one. + * Make the turtle move backwards. Note that the animation starts from the block in front it, and + * moves into this one. */ MOVE_BACK, /** - * Make the turtle move backwards. Note that the animation starts from the block above it, and moves into this one. + * Make the turtle move backwards. Note that the animation starts from the block above it, and + * moves into this one. */ MOVE_UP, /** - * Make the turtle move backwards. Note that the animation starts from the block below it, and moves into this one. + * Make the turtle move backwards. Note that the animation starts from the block below it, and + * moves into this one. */ MOVE_DOWN, /** - * Turn the turtle to the left. Note that the animation starts with the turtle facing right, and the turtle turns to face in the current - * direction. + * Turn the turtle to the left. Note that the animation starts with the turtle facing right, and + * the turtle turns to face in the current direction. */ TURN_LEFT, /** - * Turn the turtle to the left. Note that the animation starts with the turtle facing right, and the turtle turns to face in the current - * direction. + * Turn the turtle to the left. Note that the animation starts with the turtle facing right, and + * the turtle turns to face in the current direction. */ TURN_RIGHT, diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleCommandResult.java b/src/main/java/dan200/computercraft/api/turtle/TurtleCommandResult.java index 17f42bb85..eccd976e5 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleCommandResult.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleCommandResult.java @@ -3,9 +3,10 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; +import net.minecraft.core.Direction; + import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -19,16 +20,6 @@ public final class TurtleCommandResult { private static final TurtleCommandResult EMPTY_SUCCESS = new TurtleCommandResult( true, null, null ); private static final TurtleCommandResult EMPTY_FAILURE = new TurtleCommandResult( false, null, null ); - private final boolean success; - private final String errorMessage; - private final Object[] results; - - private TurtleCommandResult( boolean success, String errorMessage, Object[] results ) - { - this.success = success; - this.errorMessage = errorMessage; - this.results = results; - } /** * Create a successful command result with no result. @@ -50,10 +41,7 @@ public final class TurtleCommandResult @Nonnull public static TurtleCommandResult success( @Nullable Object[] results ) { - if( results == null || results.length == 0 ) - { - return EMPTY_SUCCESS; - } + if( results == null || results.length == 0 ) return EMPTY_SUCCESS; return new TurtleCommandResult( true, null, results ); } @@ -77,13 +65,21 @@ public final class TurtleCommandResult @Nonnull public static TurtleCommandResult failure( @Nullable String errorMessage ) { - if( errorMessage == null ) - { - return EMPTY_FAILURE; - } + if( errorMessage == null ) return EMPTY_FAILURE; return new TurtleCommandResult( false, errorMessage, null ); } + private final boolean success; + private final String errorMessage; + private final Object[] results; + + private TurtleCommandResult( boolean success, String errorMessage, Object[] results ) + { + this.success = success; + this.errorMessage = errorMessage; + this.results = results; + } + /** * Determine whether the command executed successfully. * diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java b/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java index 86edade62..e944cfe43 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleSide.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; /** diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java b/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java index a6c6fede4..daa036a8a 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleUpgradeType.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; /** @@ -14,20 +13,21 @@ package dan200.computercraft.api.turtle; public enum TurtleUpgradeType { /** - * A tool is rendered as an item on the side of the turtle, and responds to the {@code turtle.dig()} and {@code turtle.attack()} methods (Such as - * pickaxe or sword on Mining and Melee turtles). + * A tool is rendered as an item on the side of the turtle, and responds to the {@code turtle.dig()} + * and {@code turtle.attack()} methods (Such as pickaxe or sword on Mining and Melee turtles). */ TOOL, /** - * A peripheral adds a special peripheral which is attached to the side of the turtle, and can be interacted with the {@code peripheral} API (Such as - * the modem on Wireless Turtles). + * A peripheral adds a special peripheral which is attached to the side of the turtle, + * and can be interacted with the {@code peripheral} API (Such as the modem on Wireless Turtles). */ PERIPHERAL, /** - * An upgrade which provides both a tool and a peripheral. This can be used when you wish your upgrade to also provide methods. For example, a pickaxe - * could provide methods determining whether it can break the given block or not. + * An upgrade which provides both a tool and a peripheral. This can be used when you wish + * your upgrade to also provide methods. For example, a pickaxe could provide methods + * determining whether it can break the given block or not. */ BOTH; diff --git a/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java b/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java index d4622b1a0..53a2b0ceb 100644 --- a/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java +++ b/src/main/java/dan200/computercraft/api/turtle/TurtleVerb.java @@ -3,11 +3,13 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle; +import net.minecraft.core.Direction; + /** - * An enum representing the different actions that an {@link ITurtleUpgrade} of type Tool may be called on to perform by a turtle. + * An enum representing the different actions that an {@link ITurtleUpgrade} of type Tool may be called on to perform by + * a turtle. * * @see ITurtleUpgrade#getType() * @see ITurtleUpgrade#useTool(ITurtleAccess, TurtleSide, TurtleVerb, Direction) diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleAction.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleAction.java deleted file mode 100644 index ca5ccecf6..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleAction.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -/** - * A basic action that a turtle may perform, as accessed by the {@code turtle} API. - * - * @see TurtleActionEvent - */ -public enum TurtleAction -{ - /** - * A turtle moves to a new position. - * - * @see TurtleBlockEvent.Move - */ - MOVE, - - /** - * A turtle turns in a specific direction. - */ - TURN, - - /** - * A turtle attempts to dig a block. - * - * @see TurtleBlockEvent.Dig - */ - DIG, - - /** - * A turtle attempts to place a block or item in the world. - * - * @see TurtleBlockEvent.Place - */ - PLACE, - - /** - * A turtle attempts to attack an entity. - * - * @see TurtleActionEvent - */ - ATTACK, - - /** - * Drop an item into an inventory/the world. - * - * @see TurtleInventoryEvent.Drop - */ - DROP, - - /** - * Suck an item from an inventory or the world. - * - * @see TurtleInventoryEvent.Suck - */ - SUCK, - - /** - * Refuel the turtle's fuel levels. - */ - REFUEL, - - /** - * Equip or unequip an item. - */ - EQUIP, - - /** - * Inspect a block in world. - * - * @see TurtleBlockEvent.Inspect - */ - INSPECT, - - /** - * Gather metdata about an item in the turtle's inventory. - */ - INSPECT_ITEM, -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleActionEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleActionEvent.java deleted file mode 100644 index b6c129855..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleActionEvent.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -import dan200.computercraft.api.turtle.ITurtleAccess; -import dan200.computercraft.api.turtle.TurtleCommandResult; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.Objects; - -/** - * An event fired when a turtle is performing a known action. - */ -public class TurtleActionEvent extends TurtleEvent -{ - private final TurtleAction action; - private String failureMessage; - private boolean cancelled = false; - - public TurtleActionEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action ) - { - super( turtle ); - - Objects.requireNonNull( action, "action cannot be null" ); - this.action = action; - } - - public TurtleAction getAction() - { - return action; - } - - /** - * Sets the cancellation state of this action. - * - * If {@code cancel} is {@code true}, this action will not be carried out. - * - * @param cancel The new canceled value. - * @see TurtleCommandResult#failure() - * @deprecated Use {@link #setCanceled(boolean, String)} instead. - */ - @Deprecated - public void setCanceled( boolean cancel ) - { - setCanceled( cancel, null ); - } - - /** - * Set the cancellation state of this action, setting a failure message if required. - * - * If {@code cancel} is {@code true}, this action will not be carried out. - * - * @param cancel The new canceled value. - * @param failureMessage The message to return to the user explaining the failure. - * @see TurtleCommandResult#failure(String) - */ - public void setCanceled( boolean cancel, @Nullable String failureMessage ) - { - cancelled = true; - this.failureMessage = cancel ? failureMessage : null; - } - - /** - * Get the message with which this will fail. - * - * @return The failure message. - * @see TurtleCommandResult#failure() - * @see #setCanceled(boolean, String) - */ - @Nullable - public String getFailureMessage() - { - return failureMessage; - } - - public boolean isCancelled() - { - return cancelled; - } -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleAttackEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleAttackEvent.java deleted file mode 100644 index fa8c492cc..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleAttackEvent.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -import dan200.computercraft.api.turtle.FakePlayer; -import dan200.computercraft.api.turtle.ITurtleAccess; -import dan200.computercraft.api.turtle.ITurtleUpgrade; -import dan200.computercraft.api.turtle.TurtleSide; -import net.minecraft.entity.Entity; - -import javax.annotation.Nonnull; -import java.util.Objects; - -/** - * Fired when a turtle attempts to attack an entity. - * - * @see TurtleAction#ATTACK - */ -public class TurtleAttackEvent extends TurtlePlayerEvent -{ - private final Entity target; - private final ITurtleUpgrade upgrade; - private final TurtleSide side; - - public TurtleAttackEvent( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull Entity target, @Nonnull ITurtleUpgrade upgrade, - @Nonnull TurtleSide side ) - { - super( turtle, TurtleAction.ATTACK, player ); - Objects.requireNonNull( target, "target cannot be null" ); - Objects.requireNonNull( upgrade, "upgrade cannot be null" ); - Objects.requireNonNull( side, "side cannot be null" ); - this.target = target; - this.upgrade = upgrade; - this.side = side; - } - - /** - * Get the entity being attacked by this turtle. - * - * @return The entity being attacked. - */ - @Nonnull - public Entity getTarget() - { - return target; - } - - /** - * Get the upgrade responsible for attacking. - * - * @return The upgrade responsible for attacking. - */ - @Nonnull - public ITurtleUpgrade getUpgrade() - { - return upgrade; - } - - /** - * Get the side the attacking upgrade is on. - * - * @return The upgrade's side. - */ - @Nonnull - public TurtleSide getSide() - { - return side; - } -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleBlockEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleBlockEvent.java deleted file mode 100644 index 2a195e62a..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleBlockEvent.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -import dan200.computercraft.api.lua.MethodResult; -import dan200.computercraft.api.turtle.FakePlayer; -import dan200.computercraft.api.turtle.ITurtleAccess; -import dan200.computercraft.api.turtle.ITurtleUpgrade; -import dan200.computercraft.api.turtle.TurtleSide; -import net.minecraft.block.BlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import javax.annotation.Nonnull; -import java.util.Map; -import java.util.Objects; - -/** - * A general event for when a turtle interacts with a block or region. - * - * You should generally listen to one of the sub-events instead, cancelling them where appropriate. - * - * Note that you are not guaranteed to receive this event, if it has been cancelled by other mechanisms, such as block protection systems. - * - * Be aware that some events (such as {@link TurtleInventoryEvent}) do not necessarily interact with a block, simply objects within that block space. - */ -public abstract class TurtleBlockEvent extends TurtlePlayerEvent -{ - private final World world; - private final BlockPos pos; - - protected TurtleBlockEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player, @Nonnull World world, - @Nonnull BlockPos pos ) - { - super( turtle, action, player ); - - Objects.requireNonNull( world, "world cannot be null" ); - Objects.requireNonNull( pos, "pos cannot be null" ); - this.world = world; - this.pos = pos; - } - - /** - * Get the world the turtle is interacting in. - * - * @return The world the turtle is interacting in. - */ - public World getWorld() - { - return world; - } - - /** - * Get the position the turtle is interacting with. Note that this is different to {@link ITurtleAccess#getPosition()}. - * - * @return The position the turtle is interacting with. - */ - public BlockPos getPos() - { - return pos; - } - - /** - * Fired when a turtle attempts to dig a block. - * - * @see TurtleAction#DIG - */ - public static class Dig extends TurtleBlockEvent - { - private final BlockState block; - private final ITurtleUpgrade upgrade; - private final TurtleSide side; - - public Dig( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState block, - @Nonnull ITurtleUpgrade upgrade, @Nonnull TurtleSide side ) - { - super( turtle, TurtleAction.DIG, player, world, pos ); - - Objects.requireNonNull( block, "block cannot be null" ); - Objects.requireNonNull( upgrade, "upgrade cannot be null" ); - Objects.requireNonNull( side, "side cannot be null" ); - this.block = block; - this.upgrade = upgrade; - this.side = side; - } - - /** - * Get the block which is about to be broken. - * - * @return The block which is going to be broken. - */ - @Nonnull - public BlockState getBlock() - { - return block; - } - - /** - * Get the upgrade doing the digging. - * - * @return The upgrade doing the digging. - */ - @Nonnull - public ITurtleUpgrade getUpgrade() - { - return upgrade; - } - - /** - * Get the side the upgrade doing the digging is on. - * - * @return The upgrade's side. - */ - @Nonnull - public TurtleSide getSide() - { - return side; - } - } - - /** - * Fired when a turtle attempts to move into a block. - * - * @see TurtleAction#MOVE - */ - public static class Move extends TurtleBlockEvent - { - public Move( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos ) - { - super( turtle, TurtleAction.MOVE, player, world, pos ); - } - } - - /** - * Fired when a turtle attempts to place a block in the world. - * - * @see TurtleAction#PLACE - */ - public static class Place extends TurtleBlockEvent - { - private final ItemStack stack; - - public Place( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull ItemStack stack ) - { - super( turtle, TurtleAction.PLACE, player, world, pos ); - - Objects.requireNonNull( stack, "stack cannot be null" ); - this.stack = stack; - } - - /** - * Get the item stack that will be placed. This should not be modified. - * - * @return The item stack to be placed. - */ - @Nonnull - public ItemStack getStack() - { - return stack; - } - } - - /** - * Fired when a turtle gathers data on a block in world. - * - * You may prevent blocks being inspected, or add additional information to the result. - * - * @see TurtleAction#INSPECT - */ - public static class Inspect extends TurtleBlockEvent - { - private final BlockState state; - private final Map data; - - public Inspect( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, - @Nonnull Map data ) - { - super( turtle, TurtleAction.INSPECT, player, world, pos ); - - Objects.requireNonNull( state, "state cannot be null" ); - Objects.requireNonNull( data, "data cannot be null" ); - this.data = data; - this.state = state; - } - - /** - * Get the block state which is being inspected. - * - * @return The inspected block state. - */ - @Nonnull - public BlockState getState() - { - return state; - } - - /** - * Get the "inspection data" from this block, which will be returned to the user. - * - * @return This block's inspection data. - */ - @Nonnull - public Map getData() - { - return data; - } - - /** - * Add new information to the inspection result. Note this will override fields with the same name. - * - * @param newData The data to add. Note all values should be convertible to Lua (see {@link MethodResult#of(Object)}). - */ - public void addData( @Nonnull Map newData ) - { - Objects.requireNonNull( newData, "newData cannot be null" ); - data.putAll( newData ); - } - } -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleEvent.java index 726a059ae..6557efc12 100644 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleEvent.java +++ b/src/main/java/dan200/computercraft/api/turtle/event/TurtleEvent.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle.event; import com.google.common.eventbus.EventBus; @@ -13,12 +12,10 @@ import javax.annotation.Nonnull; import java.util.Objects; /** - * A base class for all events concerning a turtle. This will only ever constructed and fired on the server side, so sever specific methods on {@link - * ITurtleAccess} are safe to use. + * A base class for all events concerning a turtle. This will only ever constructed and fired on the server side, + * so sever specific methods on {@link ITurtleAccess} are safe to use. * * You should generally not need to subscribe to this event, preferring one of the more specific classes. - * - * @see TurtleActionEvent */ public abstract class TurtleEvent { @@ -32,12 +29,6 @@ public abstract class TurtleEvent this.turtle = turtle; } - public static boolean post( TurtleActionEvent event ) - { - EVENT_BUS.post( event ); - return event.isCancelled(); - } - /** * Get the turtle which is performing this action. * @@ -48,5 +39,4 @@ public abstract class TurtleEvent { return turtle; } - } diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleInspectItemEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleInspectItemEvent.java deleted file mode 100644 index d22b6673d..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleInspectItemEvent.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -import dan200.computercraft.api.lua.MethodResult; -import dan200.computercraft.api.turtle.ITurtleAccess; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; -import java.util.Map; -import java.util.Objects; - -/** - * Fired when a turtle gathers data on an item in its inventory. - * - * You may prevent items being inspected, or add additional information to the result. Be aware that this may be fired on the computer thread, and so any - * operations on it must be thread safe. - * - * @see TurtleAction#INSPECT_ITEM - */ -public class TurtleInspectItemEvent extends TurtleActionEvent -{ - private final ItemStack stack; - private final Map data; - private final boolean mainThread; - - @Deprecated - public TurtleInspectItemEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, @Nonnull Map data ) - { - this( turtle, stack, data, false ); - } - - public TurtleInspectItemEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, @Nonnull Map data, boolean mainThread ) - { - super( turtle, TurtleAction.INSPECT_ITEM ); - - Objects.requireNonNull( stack, "stack cannot be null" ); - Objects.requireNonNull( data, "data cannot be null" ); - this.stack = stack; - this.data = data; - this.mainThread = mainThread; - } - - /** - * The item which is currently being inspected. - * - * @return The item stack which is being inspected. This should not be modified. - */ - @Nonnull - public ItemStack getStack() - { - return stack; - } - - /** - * Get the "inspection data" from this item, which will be returned to the user. - * - * @return This items's inspection data. - */ - @Nonnull - public Map getData() - { - return data; - } - - /** - * If this event is being fired on the server thread. When true, information which relies on server state may be exposed. - * - * @return If this is run on the main thread. - */ - public boolean onMainThread() - { - return mainThread; - } - - /** - * Add new information to the inspection result. Note this will override fields with the same name. - * - * @param newData The data to add. Note all values should be convertible to Lua (see {@link MethodResult#of(Object)}). - */ - public void addData( @Nonnull Map newData ) - { - Objects.requireNonNull( newData, "newData cannot be null" ); - data.putAll( newData ); - } -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleInventoryEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleInventoryEvent.java deleted file mode 100644 index 37b01ecb5..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleInventoryEvent.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -import dan200.computercraft.api.turtle.FakePlayer; -import dan200.computercraft.api.turtle.ITurtleAccess; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.Objects; - -/** - * Fired when a turtle attempts to interact with an inventory. - */ -public abstract class TurtleInventoryEvent extends TurtleBlockEvent -{ - private final Inventory handler; - - protected TurtleInventoryEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player, @Nonnull World world, - @Nonnull BlockPos pos, @Nullable Inventory handler ) - { - super( turtle, action, player, world, pos ); - this.handler = handler; - } - - /** - * Get the inventory being interacted with. - * - * @return The inventory being interacted with, {@code null} if the item will be dropped to/sucked from the world. - */ - @Nullable - public Inventory getItemHandler() - { - return handler; - } - - /** - * Fired when a turtle attempts to suck from an inventory. - * - * @see TurtleAction#SUCK - */ - public static class Suck extends TurtleInventoryEvent - { - public Suck( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable Inventory handler ) - { - super( turtle, TurtleAction.SUCK, player, world, pos, handler ); - } - } - - /** - * Fired when a turtle attempts to drop an item into an inventory. - * - * @see TurtleAction#DROP - */ - public static class Drop extends TurtleInventoryEvent - { - private final ItemStack stack; - - public Drop( @Nonnull ITurtleAccess turtle, @Nonnull FakePlayer player, @Nonnull World world, @Nonnull BlockPos pos, @Nullable Inventory handler, - @Nonnull ItemStack stack ) - { - super( turtle, TurtleAction.DROP, player, world, pos, handler ); - - Objects.requireNonNull( stack, "stack cannot be null" ); - this.stack = stack; - } - - /** - * The item which will be inserted into the inventory/dropped on the ground. - * - * @return The item stack which will be dropped. This should not be modified. - */ - @Nonnull - public ItemStack getStack() - { - return stack; - } - } -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtlePlayerEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtlePlayerEvent.java deleted file mode 100644 index 463a6602c..000000000 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtlePlayerEvent.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of the public ComputerCraft API - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. - * For help using the API, and posting your mods, visit the forums at computercraft.info. - */ - -package dan200.computercraft.api.turtle.event; - -import dan200.computercraft.api.turtle.FakePlayer; -import dan200.computercraft.api.turtle.ITurtleAccess; - -import javax.annotation.Nonnull; -import java.util.Objects; - -/** - * An action done by a turtle which is normally done by a player. - * - * {@link #getPlayer()} may be used to modify the player's attributes or perform permission checks. - */ -public abstract class TurtlePlayerEvent extends TurtleActionEvent -{ - private final FakePlayer player; - - protected TurtlePlayerEvent( @Nonnull ITurtleAccess turtle, @Nonnull TurtleAction action, @Nonnull FakePlayer player ) - { - super( turtle, action ); - - Objects.requireNonNull( player, "player cannot be null" ); - this.player = player; - } - - /** - * A fake player, representing this turtle. - * - * This may be used for triggering permission checks. - * - * @return A {@link FakePlayer} representing this turtle. - */ - @Nonnull - public FakePlayer getPlayer() - { - return player; - } -} diff --git a/src/main/java/dan200/computercraft/api/turtle/event/TurtleRefuelEvent.java b/src/main/java/dan200/computercraft/api/turtle/event/TurtleRefuelEvent.java index a5374d684..ec7f41244 100644 --- a/src/main/java/dan200/computercraft/api/turtle/event/TurtleRefuelEvent.java +++ b/src/main/java/dan200/computercraft/api/turtle/event/TurtleRefuelEvent.java @@ -3,11 +3,10 @@ * Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only. * For help using the API, and posting your mods, visit the forums at computercraft.info. */ - package dan200.computercraft.api.turtle.event; import dan200.computercraft.api.turtle.ITurtleAccess; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -16,17 +15,16 @@ import java.util.Objects; /** * Fired when a turtle attempts to refuel from an item. * - * One may use {@link #setCanceled(boolean, String)} to prevent refueling from this specific item. Additionally, you may use {@link #setHandler(Handler)} to - * register a custom fuel provider. + * One may use {@link #setHandler(Handler)} to register a custom fuel provider for a given item. */ -public class TurtleRefuelEvent extends TurtleActionEvent +public class TurtleRefuelEvent extends TurtleEvent { private final ItemStack stack; private Handler handler; public TurtleRefuelEvent( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack ) { - super( turtle, TurtleAction.REFUEL ); + super( turtle ); Objects.requireNonNull( turtle, "turtle cannot be null" ); this.stack = stack; @@ -59,7 +57,8 @@ public class TurtleRefuelEvent extends TurtleActionEvent /** * Set the refuel handler for this stack. * - * You should call this if you can actually refuel from this item, and ideally only if there are no existing handlers. + * You should call this if you can actually refuel from this item, and ideally only if there are no existing + * handlers. * * @param handler The new refuel handler. * @see #getHandler() @@ -81,7 +80,8 @@ public class TurtleRefuelEvent extends TurtleActionEvent * @param turtle The turtle to refuel. * @param stack The stack to refuel with. * @param slot The slot the stack resides within. This may be used to modify the inventory afterwards. - * @param limit The maximum number of refuel operations to perform. This will often correspond to the number of items to consume. + * @param limit The maximum number of refuel operations to perform. This will often correspond to the number of + * items to consume. * @return The amount of fuel gained. */ int refuel( @Nonnull ITurtleAccess turtle, @Nonnull ItemStack stack, int slot, int limit ); diff --git a/src/main/java/dan200/computercraft/client/ClientRegistry.java b/src/main/java/dan200/computercraft/client/ClientRegistry.java index 25ac05541..2e1b3074a 100644 --- a/src/main/java/dan200/computercraft/client/ClientRegistry.java +++ b/src/main/java/dan200/computercraft/client/ClientRegistry.java @@ -15,15 +15,11 @@ import dan200.computercraft.shared.pocket.items.ItemPocketComputer; import dan200.computercraft.shared.util.Colour; import net.fabricmc.fabric.api.client.rendering.v1.ColorProviderRegistry; import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.ModelLoader; -import net.minecraft.client.render.model.ModelRotation; -import net.minecraft.client.render.model.UnbakedModel; -import net.minecraft.client.texture.SpriteAtlasTexture; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.resource.ResourceManager; -import net.minecraft.util.Identifier; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.resources.model.*; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; import java.util.HashSet; import java.util.function.Consumer; @@ -68,20 +64,20 @@ public final class ClientRegistry private ClientRegistry() {} - public static void onTextureStitchEvent( SpriteAtlasTexture atlasTexture, ClientSpriteRegistryCallback.Registry registry ) + public static void onTextureStitchEvent( TextureAtlas atlasTexture, ClientSpriteRegistryCallback.Registry registry ) { for( String extra : EXTRA_TEXTURES ) { - registry.register( new Identifier( ComputerCraft.MOD_ID, extra ) ); + registry.register( new ResourceLocation( ComputerCraft.MOD_ID, extra ) ); } } @SuppressWarnings( "NewExpressionSideOnly" ) - public static void onModelBakeEvent( ResourceManager manager, Consumer out ) + public static void onModelBakeEvent( ResourceManager manager, Consumer out ) { for( String model : EXTRA_MODELS ) { - out.accept( new ModelIdentifier( new Identifier( ComputerCraft.MOD_ID, model ), "inventory" ) ); + out.accept( new ModelResourceLocation( new ResourceLocation( ComputerCraft.MOD_ID, model ), "inventory" ) ); } } @@ -114,14 +110,14 @@ public final class ClientRegistry ComputerCraftRegistry.ModBlocks.TURTLE_ADVANCED ); } - private static BakedModel bake( ModelLoader loader, UnbakedModel model, Identifier identifier ) + private static BakedModel bake( ModelBakery loader, UnbakedModel model, ResourceLocation identifier ) { - model.getTextureDependencies( loader::getOrLoadModel, new HashSet<>() ); + model.getMaterials( loader::getModel, new HashSet<>() ); return model.bake( loader, - spriteIdentifier -> MinecraftClient.getInstance() - .getSpriteAtlas( spriteIdentifier.getAtlasId() ) - .apply( spriteIdentifier.getTextureId() ), - ModelRotation.X0_Y0, + spriteIdentifier -> Minecraft.getInstance() + .getTextureAtlas( spriteIdentifier.atlasLocation() ) + .apply( spriteIdentifier.texture() ), + BlockModelRotation.X0_Y0, identifier ); } } diff --git a/src/main/java/dan200/computercraft/client/ClientTableFormatter.java b/src/main/java/dan200/computercraft/client/ClientTableFormatter.java index 194c23689..d401e6566 100644 --- a/src/main/java/dan200/computercraft/client/ClientTableFormatter.java +++ b/src/main/java/dan200/computercraft/client/ClientTableFormatter.java @@ -6,17 +6,17 @@ package dan200.computercraft.client; -import dan200.computercraft.fabric.mixin.ChatHudAccess; +import dan200.computercraft.fabric.mixin.ChatComponentAccess; import dan200.computercraft.shared.command.text.ChatHelpers; import dan200.computercraft.shared.command.text.TableBuilder; import dan200.computercraft.shared.command.text.TableFormatter; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.font.TextRenderer; -import net.minecraft.client.gui.hud.ChatHud; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; -import net.minecraft.util.math.MathHelper; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.ChatComponent; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; @@ -29,7 +29,7 @@ public class ClientTableFormatter implements TableFormatter @Override @Nullable - public Text getPadding( Text component, int width ) + public Component getPadding( Component component, int width ) { int extraWidth = width - getWidth( component ); if( extraWidth <= 0 ) @@ -37,18 +37,18 @@ public class ClientTableFormatter implements TableFormatter return null; } - TextRenderer renderer = renderer(); + Font renderer = renderer(); - float spaceWidth = renderer.getWidth( " " ); - int spaces = MathHelper.floor( extraWidth / spaceWidth ); + float spaceWidth = renderer.width( " " ); + int spaces = Mth.floor( extraWidth / spaceWidth ); int extra = extraWidth - (int) (spaces * spaceWidth); - return ChatHelpers.coloured( StringUtils.repeat( ' ', spaces ) + StringUtils.repeat( (char) 712, extra ), Formatting.GRAY ); + return ChatHelpers.coloured( StringUtils.repeat( ' ', spaces ) + StringUtils.repeat( (char) 712, extra ), ChatFormatting.GRAY ); } - private static TextRenderer renderer() + private static Font renderer() { - return MinecraftClient.getInstance().textRenderer; + return Minecraft.getInstance().font; } @Override @@ -58,28 +58,28 @@ public class ClientTableFormatter implements TableFormatter } @Override - public int getWidth( Text component ) + public int getWidth( Component component ) { - return renderer().getWidth( component ); + return renderer().width( component ); } @Override - public void writeLine( int id, Text component ) + public void writeLine( int id, Component component ) { - MinecraftClient mc = MinecraftClient.getInstance(); - ChatHud chat = mc.inGameHud.getChatHud(); + Minecraft mc = Minecraft.getInstance(); + ChatComponent chat = mc.gui.getChat(); // TODO: Trim the text if it goes over the allowed length // int maxWidth = MathHelper.floor( chat.getChatWidth() / chat.getScale() ); // List list = RenderComponentsUtil.func_238505_a_( component, maxWidth, mc.fontRenderer ); // if( !list.isEmpty() ) chat.printChatMessageWithOptionalDeletion( list.get( 0 ), id ); - ((ChatHudAccess) chat).callAddMessage( component, id ); + ((ChatComponentAccess) chat).callAddMessage( component, id ); } @Override public int display( TableBuilder table ) { - ChatHud chat = MinecraftClient.getInstance().inGameHud.getChatHud(); + ChatComponent chat = Minecraft.getInstance().gui.getChat(); int lastHeight = lastHeights.get( table.getId() ); @@ -88,7 +88,7 @@ public class ClientTableFormatter implements TableFormatter for( int i = height; i < lastHeight; i++ ) { - ((ChatHudAccess) chat).callRemoveMessage( i + table.getId() ); + ((ChatComponentAccess) chat).callRemoveById( i + table.getId() ); } return height; } diff --git a/src/main/java/dan200/computercraft/client/SoundManager.java b/src/main/java/dan200/computercraft/client/SoundManager.java index fe452eb7d..d4ccf7cac 100644 --- a/src/main/java/dan200/computercraft/client/SoundManager.java +++ b/src/main/java/dan200/computercraft/client/SoundManager.java @@ -5,13 +5,13 @@ */ package dan200.computercraft.client; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.sound.AbstractSoundInstance; -import net.minecraft.client.sound.SoundInstance; -import net.minecraft.client.sound.TickableSoundInstance; -import net.minecraft.sound.SoundCategory; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.sounds.AbstractSoundInstance; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.resources.sounds.TickableSoundInstance; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.phys.Vec3; import java.util.HashMap; import java.util.Map; @@ -21,9 +21,9 @@ public class SoundManager { private static final Map sounds = new HashMap<>(); - public static void playSound( UUID source, Vec3d position, Identifier event, float volume, float pitch ) + public static void playSound( UUID source, Vec3 position, ResourceLocation event, float volume, float pitch ) { - var soundManager = MinecraftClient.getInstance().getSoundManager(); + var soundManager = Minecraft.getInstance().getSoundManager(); MoveableSound oldSound = sounds.get( source ); if( oldSound != null ) soundManager.stop( oldSound ); @@ -38,10 +38,10 @@ public class SoundManager SoundInstance sound = sounds.remove( source ); if( sound == null ) return; - MinecraftClient.getInstance().getSoundManager().stop( sound ); + Minecraft.getInstance().getSoundManager().stop( sound ); } - public static void moveSound( UUID source, Vec3d position ) + public static void moveSound( UUID source, Vec3 position ) { MoveableSound sound = sounds.get( source ); if( sound != null ) sound.setPosition( position ); @@ -54,24 +54,24 @@ public class SoundManager private static class MoveableSound extends AbstractSoundInstance implements TickableSoundInstance { - protected MoveableSound( Identifier sound, Vec3d position, float volume, float pitch ) + protected MoveableSound( ResourceLocation sound, Vec3 position, float volume, float pitch ) { - super( sound, SoundCategory.RECORDS ); + super( sound, SoundSource.RECORDS ); setPosition( position ); this.volume = volume; this.pitch = pitch; - attenuationType = SoundInstance.AttenuationType.LINEAR; + attenuation = Attenuation.LINEAR; } - void setPosition( Vec3d position ) + void setPosition( Vec3 position ) { - x = (float) position.getX(); - y = (float) position.getY(); - z = (float) position.getZ(); + x = (float) position.x(); + y = (float) position.y(); + z = (float) position.z(); } @Override - public boolean isDone() + public boolean isStopped() { return false; } diff --git a/src/main/java/dan200/computercraft/client/gui/ComputerScreenBase.java b/src/main/java/dan200/computercraft/client/gui/ComputerScreenBase.java index fdab4ce8e..e9c54163d 100644 --- a/src/main/java/dan200/computercraft/client/gui/ComputerScreenBase.java +++ b/src/main/java/dan200/computercraft/client/gui/ComputerScreenBase.java @@ -5,6 +5,7 @@ */ package dan200.computercraft.client.gui; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.gui.widgets.ComputerSidebar; import dan200.computercraft.client.gui.widgets.WidgetTerminal; @@ -16,11 +17,10 @@ import dan200.computercraft.shared.computer.upload.UploadResult; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.network.server.ContinueUploadMessage; import dan200.computercraft.shared.network.server.UploadFileMessage; -import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.entity.player.Inventory; import org.lwjgl.glfw.GLFW; import javax.annotation.Nonnull; @@ -34,12 +34,12 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -public abstract class ComputerScreenBase extends HandledScreen +public abstract class ComputerScreenBase extends AbstractContainerScreen { - private static final Text OK = new TranslatableText( "gui.ok" ); - private static final Text CANCEL = new TranslatableText( "gui.cancel" ); - private static final Text OVERWRITE = new TranslatableText( "gui.computercraft.upload.overwrite_button" ); + private static final Component OK = new TranslatableComponent( "gui.ok" ); + private static final Component CANCEL = new TranslatableComponent( "gui.cancel" ); + private static final Component OVERWRITE = new TranslatableComponent( "gui.computercraft.upload.overwrite_button" ); protected WidgetTerminal terminal; protected final ClientComputer computer; @@ -47,7 +47,7 @@ public abstract class ComputerScreenBase extend protected final int sidebarYOffset; - public ComputerScreenBase( T container, PlayerInventory player, Text title, int sidebarYOffset ) + public ComputerScreenBase( T container, Inventory player, Component title, int sidebarYOffset ) { super( container, player, title ); computer = (ClientComputer) container.getComputer(); @@ -61,10 +61,10 @@ public abstract class ComputerScreenBase extend protected final void init() { super.init(); - client.keyboard.setRepeatEvents( true ); + minecraft.keyboardHandler.setSendRepeatsToGui( true ); - terminal = addDrawableChild( createTerminal() ); - ComputerSidebar.addButtons( this, computer, this::addDrawableChild, x, y + sidebarYOffset ); + terminal = addRenderableWidget( createTerminal() ); + ComputerSidebar.addButtons( this, computer, this::addRenderableWidget, leftPos, topPos + sidebarYOffset ); setFocused( terminal ); } @@ -72,13 +72,13 @@ public abstract class ComputerScreenBase extend public final void removed() { super.removed(); - client.keyboard.setRepeatEvents( false ); + minecraft.keyboardHandler.setSendRepeatsToGui( false ); } @Override - public final void handledScreenTick() + public final void containerTick() { - super.handledScreenTick(); + super.containerTick(); terminal.update(); } @@ -95,11 +95,11 @@ public abstract class ComputerScreenBase extend } @Override - public final void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) + public final void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) { renderBackground( stack ); super.render( stack, mouseX, mouseY, partialTicks ); - drawMouseoverTooltip( stack, mouseX, mouseY ); + renderTooltip( stack, mouseX, mouseY ); } @Override @@ -109,13 +109,13 @@ public abstract class ComputerScreenBase extend } @Override - protected void drawForeground( @Nonnull MatrixStack transform, int mouseX, int mouseY ) + protected void renderLabels( @Nonnull PoseStack transform, int mouseX, int mouseY ) { // Skip rendering labels. } @Override - public void filesDragged( @Nonnull List files ) + public void onFilesDrop( @Nonnull List files ) { if( files.isEmpty() ) return; @@ -145,7 +145,7 @@ public abstract class ComputerScreenBase extend String name = file.getFileName().toString(); if( name.length() > UploadFileMessage.MAX_FILE_NAME ) { - alert( UploadResult.FAILED_TITLE, new TranslatableText( "gui.computercraft.upload.failed.name_too_long" ) ); + alert( UploadResult.FAILED_TITLE, new TranslatableComponent( "gui.computercraft.upload.failed.name_too_long" ) ); return; } @@ -156,7 +156,7 @@ public abstract class ComputerScreenBase extend byte[] digest = FileUpload.getDigest( buffer ); if( digest == null ) { - alert( UploadResult.FAILED_TITLE, new TranslatableText( "gui.computercraft.upload.failed.corrupted" ) ); + alert( UploadResult.FAILED_TITLE, new TranslatableComponent( "gui.computercraft.upload.failed.corrupted" ) ); return; } @@ -166,13 +166,13 @@ public abstract class ComputerScreenBase extend catch( IOException e ) { ComputerCraft.log.error( "Failed uploading files", e ); - alert( UploadResult.FAILED_TITLE, new TranslatableText( "gui.computercraft.upload.failed.generic", "Cannot compute checksum" ) ); + alert( UploadResult.FAILED_TITLE, new TranslatableComponent( "gui.computercraft.upload.failed.generic", "Cannot compute checksum" ) ); } } if( toUpload.size() > UploadFileMessage.MAX_FILES ) { - alert( UploadResult.FAILED_TITLE, new TranslatableText( "gui.computercraft.upload.failed.too_many_files" ) ); + alert( UploadResult.FAILED_TITLE, new TranslatableComponent( "gui.computercraft.upload.failed.too_many_files" ) ); return; } @@ -182,7 +182,7 @@ public abstract class ComputerScreenBase extend } } - public void uploadResult( UploadResult result, Text message ) + public void uploadResult( UploadResult result, Component message ) { switch( result ) { @@ -194,7 +194,7 @@ public abstract class ComputerScreenBase extend break; case CONFIRM_OVERWRITE: OptionScreen.show( - client, UploadResult.UPLOAD_OVERWRITE, message, + minecraft, UploadResult.UPLOAD_OVERWRITE, message, Arrays.asList( OptionScreen.newButton( CANCEL, b -> cancelUpload() ), OptionScreen.newButton( OVERWRITE, b -> continueUpload() ) @@ -207,21 +207,21 @@ public abstract class ComputerScreenBase extend private void continueUpload() { - if( client.currentScreen instanceof OptionScreen ) ((OptionScreen) client.currentScreen).disable(); + if( minecraft.screen instanceof OptionScreen ) ((OptionScreen) minecraft.screen).disable(); NetworkHandler.sendToServer( new ContinueUploadMessage( computer.getInstanceID(), true ) ); } private void cancelUpload() { - client.setScreen( this ); + minecraft.setScreen( this ); NetworkHandler.sendToServer( new ContinueUploadMessage( computer.getInstanceID(), false ) ); } - private void alert( Text title, Text message ) + private void alert( Component title, Component message ) { - OptionScreen.show( client, title, message, - Collections.singletonList( OptionScreen.newButton( OK, b -> client.setScreen( this ) ) ), - () -> client.setScreen( this ) + OptionScreen.show( minecraft, title, message, + Collections.singletonList( OptionScreen.newButton( OK, b -> minecraft.setScreen( this ) ) ), + () -> minecraft.setScreen( this ) ); } diff --git a/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java b/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java index b0456bd69..d91b45ab1 100644 --- a/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java +++ b/src/main/java/dan200/computercraft/client/gui/FixedWidthFontRenderer.java @@ -6,18 +6,18 @@ package dan200.computercraft.client.gui; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.Matrix4f; +import com.mojang.math.Transformation; import dan200.computercraft.client.FrameInfo; import dan200.computercraft.client.render.RenderTypes; import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.core.terminal.TextBuffer; import dan200.computercraft.shared.util.Colour; import dan200.computercraft.shared.util.Palette; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.AffineTransformation; -import net.minecraft.util.math.Matrix4f; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -31,9 +31,9 @@ public final class FixedWidthFontRenderer public static final float WIDTH = 256.0f; public static final float BACKGROUND_START = (WIDTH - 6.0f) / WIDTH; public static final float BACKGROUND_END = (WIDTH - 4.0f) / WIDTH; - private static final Matrix4f IDENTITY = AffineTransformation.identity() + private static final Matrix4f IDENTITY = Transformation.identity() .getMatrix(); - public static final Identifier FONT = new Identifier( "computercraft", "textures/gui/term_font.png" ); + public static final ResourceLocation FONT = new ResourceLocation( "computercraft", "textures/gui/term_font.png" ); private FixedWidthFontRenderer() @@ -157,34 +157,34 @@ public final class FixedWidthFontRenderer buffer.vertex( transform, x, y, 0f ) .color( r, g, b, 1.0f ) - .texture( xStart / WIDTH, yStart / WIDTH ) - .light( light ) - .next(); + .uv( xStart / WIDTH, yStart / WIDTH ) + .uv2( light ) + .endVertex(); buffer.vertex( transform, x, y + FONT_HEIGHT, 0f ) .color( r, g, b, 1.0f ) - .texture( xStart / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ) - .light( light ) - .next(); + .uv( xStart / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ) + .uv2( light ) + .endVertex(); buffer.vertex( transform, x + FONT_WIDTH, y, 0f ) .color( r, g, b, 1.0f ) - .texture( (xStart + FONT_WIDTH) / WIDTH, yStart / WIDTH ) - .light( light ) - .next(); + .uv( (xStart + FONT_WIDTH) / WIDTH, yStart / WIDTH ) + .uv2( light ) + .endVertex(); buffer.vertex( transform, x + FONT_WIDTH, y, 0f ) .color( r, g, b, 1.0f ) - .texture( (xStart + FONT_WIDTH) / WIDTH, yStart / WIDTH ) - .light( light ) - .next(); + .uv( (xStart + FONT_WIDTH) / WIDTH, yStart / WIDTH ) + .uv2( light ) + .endVertex(); buffer.vertex( transform, x, y + FONT_HEIGHT, 0f ) .color( r, g, b, 1.0f ) - .texture( xStart / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ) - .light( light ) - .next(); + .uv( xStart / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ) + .uv2( light ) + .endVertex(); buffer.vertex( transform, x + FONT_WIDTH, y + FONT_HEIGHT, 0f ) .color( r, g, b, 1.0f ) - .texture( (xStart + FONT_WIDTH) / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ) - .light( light ) - .next(); + .uv( (xStart + FONT_WIDTH) / WIDTH, (yStart + FONT_HEIGHT) / WIDTH ) + .uv2( light ) + .endVertex(); } private static void drawQuad( Matrix4f transform, VertexConsumer buffer, float x, float y, float width, float height, Palette palette, @@ -210,28 +210,28 @@ public final class FixedWidthFontRenderer { buffer.vertex( transform, x, y, 0 ) .color( r, g, b, 1.0f ) - .texture( BACKGROUND_START, BACKGROUND_START ) - .next(); + .uv( BACKGROUND_START, BACKGROUND_START ) + .endVertex(); buffer.vertex( transform, x, y + height, 0 ) .color( r, g, b, 1.0f ) - .texture( BACKGROUND_START, BACKGROUND_END ) - .next(); + .uv( BACKGROUND_START, BACKGROUND_END ) + .endVertex(); buffer.vertex( transform, x + width, y, 0 ) .color( r, g, b, 1.0f ) - .texture( BACKGROUND_END, BACKGROUND_START ) - .next(); + .uv( BACKGROUND_END, BACKGROUND_START ) + .endVertex(); buffer.vertex( transform, x + width, y, 0 ) .color( r, g, b, 1.0f ) - .texture( BACKGROUND_END, BACKGROUND_START ) - .next(); + .uv( BACKGROUND_END, BACKGROUND_START ) + .endVertex(); buffer.vertex( transform, x, y + height, 0 ) .color( r, g, b, 1.0f ) - .texture( BACKGROUND_START, BACKGROUND_END ) - .next(); + .uv( BACKGROUND_START, BACKGROUND_END ) + .endVertex(); buffer.vertex( transform, x + width, y + height, 0 ) .color( r, g, b, 1.0f ) - .texture( BACKGROUND_END, BACKGROUND_END ) - .next(); + .uv( BACKGROUND_END, BACKGROUND_END ) + .endVertex(); } public static void drawTerminalWithoutCursor( @Nonnull Matrix4f transform, @Nonnull VertexConsumer buffer, float x, float y, @@ -319,12 +319,12 @@ public final class FixedWidthFontRenderer public static void drawTerminal( @Nonnull Matrix4f transform, float x, float y, @Nonnull Terminal terminal, boolean greyscale, float topMarginSize, float bottomMarginSize, float leftMarginSize, float rightMarginSize ) { - VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance() - .getBufferBuilders() - .getEntityVertexConsumers(); + MultiBufferSource.BufferSource renderer = Minecraft.getInstance() + .renderBuffers() + .bufferSource(); VertexConsumer buffer = renderer.getBuffer( RenderTypes.TERMINAL_WITH_DEPTH ); drawTerminal( transform, buffer, x, y, terminal, greyscale, topMarginSize, bottomMarginSize, leftMarginSize, rightMarginSize ); - renderer.draw(); + renderer.endBatch(); } public static void drawTerminal( float x, float y, @Nonnull Terminal terminal, boolean greyscale, float topMarginSize, float bottomMarginSize, @@ -341,21 +341,21 @@ public final class FixedWidthFontRenderer public static void drawEmptyTerminal( @Nonnull Matrix4f transform, float x, float y, float width, float height ) { - VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance() - .getBufferBuilders() - .getEntityVertexConsumers(); + MultiBufferSource.BufferSource renderer = Minecraft.getInstance() + .renderBuffers() + .bufferSource(); drawEmptyTerminal( transform, renderer, x, y, width, height ); - renderer.draw(); + renderer.endBatch(); } - public static void drawEmptyTerminal( @Nonnull Matrix4f transform, @Nonnull VertexConsumerProvider renderer, float x, float y, float width, + public static void drawEmptyTerminal( @Nonnull Matrix4f transform, @Nonnull MultiBufferSource renderer, float x, float y, float width, float height ) { Colour colour = Colour.BLACK; drawQuad( transform, renderer.getBuffer( RenderTypes.TERMINAL_WITH_DEPTH ), x, y, width, height, colour.getR(), colour.getG(), colour.getB() ); } - public static void drawBlocker( @Nonnull Matrix4f transform, @Nonnull VertexConsumerProvider renderer, float x, float y, float width, float height ) + public static void drawBlocker( @Nonnull Matrix4f transform, @Nonnull MultiBufferSource renderer, float x, float y, float width, float height ) { Colour colour = Colour.BLACK; drawQuad( transform, renderer.getBuffer( RenderTypes.TERMINAL_BLOCKER ), x, y, width, height, colour.getR(), colour.getG(), colour.getB() ); diff --git a/src/main/java/dan200/computercraft/client/gui/GuiComputer.java b/src/main/java/dan200/computercraft/client/gui/GuiComputer.java index 8d3eba876..b938d87f9 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiComputer.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiComputer.java @@ -6,6 +6,7 @@ package dan200.computercraft.client.gui; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.gui.widgets.ComputerSidebar; import dan200.computercraft.client.gui.widgets.WidgetTerminal; @@ -13,9 +14,8 @@ import dan200.computercraft.client.render.ComputerBorderRenderer; import dan200.computercraft.client.render.RenderTypes; import dan200.computercraft.shared.computer.inventory.ContainerComputerBase; import dan200.computercraft.shared.computer.inventory.ContainerViewComputer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; import javax.annotation.Nonnull; @@ -27,27 +27,27 @@ public final class GuiComputer extends Computer private final int termWidth; private final int termHeight; - private GuiComputer( T container, PlayerInventory player, Text title, int termWidth, int termHeight ) + private GuiComputer( T container, Inventory player, Component title, int termWidth, int termHeight ) { super( container, player, title, BORDER ); this.termWidth = termWidth; this.termHeight = termHeight; - backgroundWidth = WidgetTerminal.getWidth( termWidth ) + BORDER * 2 + ComputerSidebar.WIDTH; - backgroundHeight = WidgetTerminal.getHeight( termHeight ) + BORDER * 2; + imageWidth = WidgetTerminal.getWidth( termWidth ) + BORDER * 2 + ComputerSidebar.WIDTH; + imageHeight = WidgetTerminal.getHeight( termHeight ) + BORDER * 2; } - public static GuiComputer create( ContainerComputerBase container, PlayerInventory inventory, Text component ) + public static GuiComputer create( ContainerComputerBase container, Inventory inventory, Component component ) { return new GuiComputer<>( container, inventory, component, ComputerCraft.computerTermWidth, ComputerCraft.computerTermHeight ); } - public static GuiComputer createPocket( ContainerComputerBase container, PlayerInventory inventory, Text component ) + public static GuiComputer createPocket( ContainerComputerBase container, Inventory inventory, Component component ) { return new GuiComputer<>( container, inventory, component, ComputerCraft.pocketTermWidth, ComputerCraft.pocketTermHeight ); } - public static GuiComputer createView( ContainerViewComputer container, PlayerInventory inventory, Text component ) + public static GuiComputer createView( ContainerViewComputer container, Inventory inventory, Component component ) { return new GuiComputer<>( container, inventory, component, container.getWidth(), container.getHeight() ); } @@ -56,15 +56,16 @@ public final class GuiComputer extends Computer protected WidgetTerminal createTerminal() { return new WidgetTerminal( computer, - x + ComputerSidebar.WIDTH + BORDER, y + BORDER, termWidth, termHeight + leftPos + ComputerSidebar.WIDTH + BORDER, topPos + BORDER, termWidth, termHeight ); } + @Override - public void drawBackground( @Nonnull MatrixStack stack, float partialTicks, int mouseX, int mouseY ) + public void renderBg( @Nonnull PoseStack stack, float partialTicks, int mouseX, int mouseY ) { ComputerBorderRenderer.render( - getTexture( family ), terminal.x, terminal.y, getZOffset(), + getTexture( family ), terminal.x, terminal.y, getBlitOffset(), RenderTypes.FULL_BRIGHT_LIGHTMAP, terminal.getWidth(), terminal.getHeight() ); - ComputerSidebar.renderBackground( stack, x, y + sidebarYOffset ); + ComputerSidebar.renderBackground( stack, leftPos, topPos + sidebarYOffset ); } } diff --git a/src/main/java/dan200/computercraft/client/gui/GuiDiskDrive.java b/src/main/java/dan200/computercraft/client/gui/GuiDiskDrive.java index 0cfbc3daa..6c61b4021 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiDiskDrive.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiDiskDrive.java @@ -7,39 +7,39 @@ package dan200.computercraft.client.gui; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.shared.peripheral.diskdrive.ContainerDiskDrive; -import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.client.render.GameRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Inventory; import javax.annotation.Nonnull; -public class GuiDiskDrive extends HandledScreen +public class GuiDiskDrive extends AbstractContainerScreen { - private static final Identifier BACKGROUND = new Identifier( "computercraft", "textures/gui/disk_drive.png" ); + private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/disk_drive.png" ); - public GuiDiskDrive( ContainerDiskDrive container, PlayerInventory player, Text title ) + public GuiDiskDrive( ContainerDiskDrive container, Inventory player, Component title ) { super( container, player, title ); } @Override - public void render( @Nonnull MatrixStack transform, int mouseX, int mouseY, float partialTicks ) + public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks ) { renderBackground( transform ); super.render( transform, mouseX, mouseY, partialTicks ); - drawMouseoverTooltip( transform, mouseX, mouseY ); + renderTooltip( transform, mouseX, mouseY ); } @Override - protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) + protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) { RenderSystem.setShader( GameRenderer::getPositionTexShader ); RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F ); RenderSystem.setShaderTexture( 0, BACKGROUND ); - drawTexture( transform, x, y, 0, 0, backgroundWidth, backgroundHeight ); + blit( transform, leftPos, topPos, 0, 0, imageWidth, imageHeight ); } } diff --git a/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java b/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java index 917a6861a..67905dff3 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiPrinter.java @@ -7,42 +7,42 @@ package dan200.computercraft.client.gui; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.shared.peripheral.printer.ContainerPrinter; -import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Inventory; import javax.annotation.Nonnull; -public class GuiPrinter extends HandledScreen +public class GuiPrinter extends AbstractContainerScreen { - private static final Identifier BACKGROUND = new Identifier( "computercraft", "textures/gui/printer.png" ); + private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/printer.png" ); - public GuiPrinter( ContainerPrinter container, PlayerInventory player, Text title ) + public GuiPrinter( ContainerPrinter container, Inventory player, Component title ) { super( container, player, title ); } @Override - public void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) + public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) { renderBackground( stack ); super.render( stack, mouseX, mouseY, partialTicks ); - drawMouseoverTooltip( stack, mouseX, mouseY ); + renderTooltip( stack, mouseX, mouseY ); } @Override - protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) + protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) { RenderSystem.setShaderColor( 1.0F, 1.0F, 1.0F, 1.0F ); RenderSystem.setShaderTexture( 0, BACKGROUND ); - drawTexture( transform, x, y, 0, 0, backgroundWidth, backgroundHeight ); + blit( transform, leftPos, topPos, 0, 0, imageWidth, imageHeight ); - if( getScreenHandler().isPrinting() ) + if( getMenu().isPrinting() ) { - drawTexture( transform, x + 34, y + 21, 176, 0, 25, 45 ); + blit( transform, leftPos + 34, topPos + 21, 176, 0, 25, 45 ); } } } diff --git a/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java b/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java index 2163ef355..299971999 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiPrintout.java @@ -7,16 +7,16 @@ package dan200.computercraft.client.gui; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Matrix4f; import dan200.computercraft.core.terminal.TextBuffer; import dan200.computercraft.shared.common.ContainerHeldItem; import dan200.computercraft.shared.media.items.ItemPrintout; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.Text; -import net.minecraft.util.math.Matrix4f; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; import org.lwjgl.glfw.GLFW; import javax.annotation.Nonnull; @@ -24,7 +24,7 @@ import javax.annotation.Nonnull; import static dan200.computercraft.client.render.PrintoutRenderer.*; import static dan200.computercraft.client.render.RenderTypes.FULL_BRIGHT_LIGHTMAP; -public class GuiPrintout extends HandledScreen +public class GuiPrintout extends AbstractContainerScreen { private final boolean book; private final int pages; @@ -32,11 +32,11 @@ public class GuiPrintout extends HandledScreen private final TextBuffer[] colours; private int page; - public GuiPrintout( ContainerHeldItem container, PlayerInventory player, Text title ) + public GuiPrintout( ContainerHeldItem container, Inventory player, Component title ) { super( container, player, title ); - backgroundHeight = Y_SIZE; + imageHeight = Y_SIZE; String[] text = ItemPrintout.getText( container.getStack() ); this.text = new TextBuffer[text.length]; @@ -89,37 +89,37 @@ public class GuiPrintout extends HandledScreen } @Override - public void render( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) + public void render( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) { // We must take the background further back in order to not overlap with our printed pages. - setZOffset( getZOffset() - 1 ); + setBlitOffset( getBlitOffset() - 1 ); renderBackground( stack ); - setZOffset( getZOffset() + 1 ); + setBlitOffset( getBlitOffset() + 1 ); super.render( stack, mouseX, mouseY, partialTicks ); } @Override - protected void drawForeground( @Nonnull MatrixStack transform, int mouseX, int mouseY ) + protected void renderLabels( @Nonnull PoseStack transform, int mouseX, int mouseY ) { // Skip rendering labels. } @Override - protected void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) + protected void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) { // Draw the printout RenderSystem.setShaderColor( 1.0f, 1.0f, 1.0f, 1.0f ); RenderSystem.enableDepthTest(); - VertexConsumerProvider.Immediate renderer = MinecraftClient.getInstance() - .getBufferBuilders() - .getEntityVertexConsumers(); - Matrix4f matrix = transform.peek() - .getModel(); - drawBorder( matrix, renderer, x, y, getZOffset(), page, pages, book, FULL_BRIGHT_LIGHTMAP ); - drawText( matrix, renderer, x + X_TEXT_MARGIN, y + Y_TEXT_MARGIN, ItemPrintout.LINES_PER_PAGE * page, FULL_BRIGHT_LIGHTMAP, text, colours ); - renderer.draw(); + MultiBufferSource.BufferSource renderer = Minecraft.getInstance() + .renderBuffers() + .bufferSource(); + Matrix4f matrix = transform.last() + .pose(); + drawBorder( matrix, renderer, leftPos, topPos, getBlitOffset(), page, pages, book, FULL_BRIGHT_LIGHTMAP ); + drawText( matrix, renderer, leftPos + X_TEXT_MARGIN, topPos + Y_TEXT_MARGIN, ItemPrintout.LINES_PER_PAGE * page, FULL_BRIGHT_LIGHTMAP, text, colours ); + renderer.endBatch(); } @Override diff --git a/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java b/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java index 56dd0b1be..c2faa896f 100644 --- a/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java +++ b/src/main/java/dan200/computercraft/client/gui/GuiTurtle.java @@ -7,16 +7,16 @@ package dan200.computercraft.client.gui; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.gui.widgets.ComputerSidebar; import dan200.computercraft.client.gui.widgets.WidgetTerminal; import dan200.computercraft.client.render.ComputerBorderRenderer; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.turtle.inventory.ContainerTurtle; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Inventory; import javax.annotation.Nonnull; @@ -24,21 +24,21 @@ import static dan200.computercraft.shared.turtle.inventory.ContainerTurtle.BORDE public class GuiTurtle extends ComputerScreenBase { - private static final Identifier BACKGROUND_NORMAL = new Identifier( "computercraft", "textures/gui/turtle_normal.png" ); - private static final Identifier BACKGROUND_ADVANCED = new Identifier( "computercraft", "textures/gui/turtle_advanced.png" ); + private static final ResourceLocation BACKGROUND_NORMAL = new ResourceLocation( "computercraft", "textures/gui/turtle_normal.png" ); + private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation( "computercraft", "textures/gui/turtle_advanced.png" ); private static final int TEX_WIDTH = 254; private static final int TEX_HEIGHT = 217; private final ComputerFamily family; - public GuiTurtle( ContainerTurtle container, PlayerInventory player, Text title ) + public GuiTurtle( ContainerTurtle container, Inventory player, Component title ) { super( container, player, title, BORDER ); family = container.getFamily(); - backgroundWidth = TEX_WIDTH + ComputerSidebar.WIDTH; - backgroundHeight = TEX_HEIGHT; + imageWidth = TEX_WIDTH + ComputerSidebar.WIDTH; + imageHeight = TEX_HEIGHT; } @@ -46,25 +46,25 @@ public class GuiTurtle extends ComputerScreenBase protected WidgetTerminal createTerminal() { return new WidgetTerminal( - computer, x + BORDER + ComputerSidebar.WIDTH, y + BORDER, + computer, leftPos + BORDER + ComputerSidebar.WIDTH, topPos + BORDER, ComputerCraft.turtleTermWidth, ComputerCraft.turtleTermHeight ); } @Override - public void drawBackground( @Nonnull MatrixStack transform, float partialTicks, int mouseX, int mouseY ) + public void renderBg( @Nonnull PoseStack transform, float partialTicks, int mouseX, int mouseY ) { boolean advanced = family == ComputerFamily.ADVANCED; RenderSystem.setShaderTexture( 0, advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL ); - drawTexture( transform, x + ComputerSidebar.WIDTH, y, 0, 0, TEX_WIDTH, TEX_HEIGHT ); + blit( transform, leftPos + ComputerSidebar.WIDTH, topPos, 0, 0, TEX_WIDTH, TEX_HEIGHT ); // Draw selection slot - int slot = getScreenHandler().getSelectedSlot(); + int slot = getMenu().getSelectedSlot(); if( slot >= 0 ) { int slotX = slot % 4; int slotY = slot / 4; - drawTexture( transform, x + ContainerTurtle.TURTLE_START_X - 2 + slotX * 18, y + ContainerTurtle.PLAYER_START_Y - 2 + slotY * 18, + blit( transform, leftPos + ContainerTurtle.TURTLE_START_X - 2 + slotX * 18, topPos + ContainerTurtle.PLAYER_START_Y - 2 + slotY * 18, 0, 217, 24, @@ -72,6 +72,6 @@ public class GuiTurtle extends ComputerScreenBase } RenderSystem.setShaderTexture( 0, advanced ? ComputerBorderRenderer.BACKGROUND_ADVANCED : ComputerBorderRenderer.BACKGROUND_NORMAL ); - ComputerSidebar.renderBackground( transform, x, y + sidebarYOffset ); + ComputerSidebar.renderBackground( transform, leftPos, topPos + sidebarYOffset ); } } diff --git a/src/main/java/dan200/computercraft/client/gui/NoTermComputerScreen.java b/src/main/java/dan200/computercraft/client/gui/NoTermComputerScreen.java index 5ea1642a5..300dd7def 100644 --- a/src/main/java/dan200/computercraft/client/gui/NoTermComputerScreen.java +++ b/src/main/java/dan200/computercraft/client/gui/NoTermComputerScreen.java @@ -5,29 +5,29 @@ */ package dan200.computercraft.client.gui; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.gui.widgets.WidgetTerminal; import dan200.computercraft.shared.computer.core.ClientComputer; import dan200.computercraft.shared.computer.inventory.ContainerComputerBase; -import net.minecraft.client.font.TextRenderer; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.screen.ingame.ScreenHandlerProvider; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.text.OrderedText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.entity.player.Inventory; import org.lwjgl.glfw.GLFW; import javax.annotation.Nonnull; import java.util.List; -public class NoTermComputerScreen extends Screen implements ScreenHandlerProvider +public class NoTermComputerScreen extends Screen implements MenuAccess { private final T menu; private WidgetTerminal terminal; - public NoTermComputerScreen( T menu, PlayerInventory player, Text title ) + public NoTermComputerScreen( T menu, Inventory player, Component title ) { super( title ); this.menu = menu; @@ -35,7 +35,7 @@ public class NoTermComputerScreen extends Scree @Nonnull @Override - public T getScreenHandler() + public T getMenu() { return menu; } @@ -44,12 +44,12 @@ public class NoTermComputerScreen extends Scree protected void init() { this.passEvents = true; - client.mouse.lockCursor(); - client.currentScreen = this; + minecraft.mouseHandler.grabMouse(); + minecraft.screen = this; super.init(); - client.keyboard.setRepeatEvents( true ); + minecraft.keyboardHandler.setSendRepeatsToGui( true ); - terminal = addSelectableChild( new WidgetTerminal( (ClientComputer) menu.getComputer(), 0, 0, ComputerCraft.pocketTermWidth, ComputerCraft.pocketTermHeight ) ); + terminal = addWidget( new WidgetTerminal( (ClientComputer) menu.getComputer(), 0, 0, ComputerCraft.pocketTermWidth, ComputerCraft.pocketTermHeight ) ); terminal.visible = false; terminal.active = false; setFocused( terminal ); @@ -59,7 +59,7 @@ public class NoTermComputerScreen extends Scree public final void removed() { super.removed(); - client.keyboard.setRepeatEvents( false ); + minecraft.keyboardHandler.setSendRepeatsToGui( false ); } @Override @@ -72,14 +72,14 @@ public class NoTermComputerScreen extends Scree @Override public boolean mouseScrolled( double pMouseX, double pMouseY, double pDelta ) { - client.player.getInventory().scrollInHotbar( pDelta ); + minecraft.player.getInventory().swapPaint( pDelta ); return super.mouseScrolled( pMouseX, pMouseY, pDelta ); } @Override public void onClose() { - client.player.closeHandledScreen(); + minecraft.player.closeContainer(); super.onClose(); } @@ -102,16 +102,16 @@ public class NoTermComputerScreen extends Scree } @Override - public void render( MatrixStack transform, int mouseX, int mouseY, float partialTicks ) + public void render( PoseStack transform, int mouseX, int mouseY, float partialTicks ) { super.render( transform, mouseX, mouseY, partialTicks ); - TextRenderer font = client.textRenderer; - List lines = font.wrapLines( new TranslatableText( "gui.computercraft.pocket_computer_overlay" ), (int) (width * 0.8) ); + Font font = minecraft.font; + List lines = font.split( new TranslatableComponent( "gui.computercraft.pocket_computer_overlay" ), (int) (width * 0.8) ); float y = 10.0f; - for( OrderedText line : lines ) + for( FormattedCharSequence line : lines ) { - font.drawWithShadow( transform, line, (float) ((width / 2) - (client.textRenderer.getWidth( line ) / 2)), y, 0xFFFFFF ); + font.drawShadow( transform, line, (float) ((width / 2) - (minecraft.font.width( line ) / 2)), y, 0xFFFFFF ); y += 9.0f; } } diff --git a/src/main/java/dan200/computercraft/client/gui/OptionScreen.java b/src/main/java/dan200/computercraft/client/gui/OptionScreen.java index 23de17f2a..532c08b94 100644 --- a/src/main/java/dan200/computercraft/client/gui/OptionScreen.java +++ b/src/main/java/dan200/computercraft/client/gui/OptionScreen.java @@ -6,21 +6,21 @@ package dan200.computercraft.client.gui; import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.font.MultilineText; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.widget.ButtonWidget; -import net.minecraft.client.gui.widget.ClickableWidget; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; import java.util.List; public final class OptionScreen extends Screen { - private static final Identifier BACKGROUND = new Identifier( "computercraft", "textures/gui/blank_screen.png" ); + private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/blank_screen.png" ); public static final int BUTTON_WIDTH = 100; public static final int BUTTON_HEIGHT = 20; @@ -33,14 +33,14 @@ public final class OptionScreen extends Screen private int innerWidth; private int innerHeight; - private MultilineText messageRenderer; - private final Text message; - private final List buttons; + private MultiLineLabel messageRenderer; + private final Component message; + private final List buttons; private final Runnable exit; private final Screen originalScreen; - private OptionScreen( Text title, Text message, List buttons, Runnable exit, Screen originalScreen ) + private OptionScreen( Component title, Component message, List buttons, Runnable exit, Screen originalScreen ) { super( title ); this.message = message; @@ -49,9 +49,9 @@ public final class OptionScreen extends Screen this.originalScreen = originalScreen; } - public static void show( MinecraftClient client, Text title, Text message, List buttons, Runnable exit ) + public static void show( Minecraft client, Component title, Component message, List buttons, Runnable exit ) { - client.setScreen( new OptionScreen( title, message, buttons, exit, unwrap( client.currentScreen ) ) ); + client.setScreen( new OptionScreen( title, message, buttons, exit, unwrap( client.screen ) ) ); } public static Screen unwrap( Screen screen ) @@ -67,40 +67,40 @@ public final class OptionScreen extends Screen int buttonWidth = BUTTON_WIDTH * buttons.size() + PADDING * (buttons.size() - 1); int innerWidth = this.innerWidth = Math.max( 256, buttonWidth + PADDING * 2 ); - messageRenderer = MultilineText.create( textRenderer, message, innerWidth - PADDING * 2 ); + messageRenderer = MultiLineLabel.create( font, message, innerWidth - PADDING * 2 ); - int textHeight = messageRenderer.count() * FONT_HEIGHT + PADDING * 2; + int textHeight = messageRenderer.getLineCount() * FONT_HEIGHT + PADDING * 2; innerHeight = textHeight + (buttons.isEmpty() ? 0 : buttons.get( 0 ).getHeight()) + PADDING; x = (width - innerWidth) / 2; y = (height - innerHeight) / 2; int x = (width - buttonWidth) / 2; - for( ClickableWidget button : buttons ) + for( AbstractWidget button : buttons ) { button.x = x; button.y = y + textHeight; - addDrawableChild( button ); + addRenderableWidget( button ); x += BUTTON_WIDTH + PADDING; } } @Override - public void render( @Nonnull MatrixStack transform, int mouseX, int mouseY, float partialTicks ) + public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks ) { renderBackground( transform ); // Render the actual texture. RenderSystem.setShaderTexture( 0, BACKGROUND ); - drawTexture( transform, x, y, 0, 0, innerWidth, PADDING ); - drawTexture( transform, + blit( transform, x, y, 0, 0, innerWidth, PADDING ); + blit( transform, x, y + PADDING, 0, PADDING, innerWidth, innerHeight - PADDING * 2, innerWidth, PADDING ); - drawTexture( transform, x, y + innerHeight - PADDING, 0, 256 - PADDING, innerWidth, PADDING ); + blit( transform, x, y + innerHeight - PADDING, 0, 256 - PADDING, innerWidth, PADDING ); - messageRenderer.draw( transform, x + PADDING, y + PADDING, FONT_HEIGHT, 0x404040 ); + messageRenderer.renderLeftAlignedNoShadow( transform, x + PADDING, y + PADDING, FONT_HEIGHT, 0x404040 ); super.render( transform, mouseX, mouseY, partialTicks ); } @@ -110,14 +110,14 @@ public final class OptionScreen extends Screen exit.run(); } - public static ClickableWidget newButton( Text component, ButtonWidget.PressAction clicked ) + public static AbstractWidget newButton( Component component, Button.OnPress clicked ) { - return new ButtonWidget( 0, 0, BUTTON_WIDTH, BUTTON_HEIGHT, component, clicked ); + return new Button( 0, 0, BUTTON_WIDTH, BUTTON_HEIGHT, component, clicked ); } public void disable() { - for( ClickableWidget widget : buttons ) widget.active = false; + for( AbstractWidget widget : buttons ) widget.active = false; } @Nonnull diff --git a/src/main/java/dan200/computercraft/client/gui/widgets/ComputerSidebar.java b/src/main/java/dan200/computercraft/client/gui/widgets/ComputerSidebar.java index 25d87c8dc..afc8139ff 100644 --- a/src/main/java/dan200/computercraft/client/gui/widgets/ComputerSidebar.java +++ b/src/main/java/dan200/computercraft/client/gui/widgets/ComputerSidebar.java @@ -5,16 +5,16 @@ */ package dan200.computercraft.client.gui.widgets; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.render.ComputerBorderRenderer; import dan200.computercraft.shared.command.text.ChatHelpers; import dan200.computercraft.shared.computer.core.ClientComputer; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.widget.ClickableWidget; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.Formatting; -import net.minecraft.util.Identifier; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; import java.util.Arrays; import java.util.function.Consumer; @@ -24,7 +24,7 @@ import java.util.function.Consumer; */ public final class ComputerSidebar { - private static final Identifier TEXTURE = new Identifier( ComputerCraft.MOD_ID, "textures/gui/buttons.png" ); + private static final ResourceLocation TEXTURE = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/buttons.png" ); private static final int TEX_SIZE = 64; @@ -45,7 +45,7 @@ public final class ComputerSidebar { } - public static void addButtons( Screen screen, ClientComputer computer, Consumer add, int x, int y ) + public static void addButtons( Screen screen, ClientComputer computer, Consumer add, int x, int y ) { x += CORNERS_BORDER + 1; y += CORNERS_BORDER + ICON_MARGIN; @@ -54,11 +54,11 @@ public final class ComputerSidebar screen, x, y, ICON_WIDTH, ICON_HEIGHT, () -> computer.isOn() ? 15 : 1, 1, ICON_TEX_Y_DIFF, TEXTURE, TEX_SIZE, TEX_SIZE, b -> toggleComputer( computer ), () -> computer.isOn() ? Arrays.asList( - new TranslatableText( "gui.computercraft.tooltip.turn_off" ), - ChatHelpers.coloured( new TranslatableText( "gui.computercraft.tooltip.turn_off.key" ), Formatting.GRAY ) + new TranslatableComponent( "gui.computercraft.tooltip.turn_off" ), + ChatHelpers.coloured( new TranslatableComponent( "gui.computercraft.tooltip.turn_off.key" ), ChatFormatting.GRAY ) ) : Arrays.asList( - new TranslatableText( "gui.computercraft.tooltip.turn_on" ), - ChatHelpers.coloured( new TranslatableText( "gui.computercraft.tooltip.turn_off.key" ), Formatting.GRAY ) + new TranslatableComponent( "gui.computercraft.tooltip.turn_on" ), + ChatHelpers.coloured( new TranslatableComponent( "gui.computercraft.tooltip.turn_off.key" ), ChatFormatting.GRAY ) ) ) ); @@ -68,26 +68,26 @@ public final class ComputerSidebar screen, x, y, ICON_WIDTH, ICON_HEIGHT, 29, 1, ICON_TEX_Y_DIFF, TEXTURE, TEX_SIZE, TEX_SIZE, b -> computer.queueEvent( "terminate" ), Arrays.asList( - new TranslatableText( "gui.computercraft.tooltip.terminate" ), - ChatHelpers.coloured( new TranslatableText( "gui.computercraft.tooltip.terminate.key" ), Formatting.GRAY ) + new TranslatableComponent( "gui.computercraft.tooltip.terminate" ), + ChatHelpers.coloured( new TranslatableComponent( "gui.computercraft.tooltip.terminate.key" ), ChatFormatting.GRAY ) ) ) ); } - public static void renderBackground( MatrixStack transform, int x, int y ) + public static void renderBackground( PoseStack transform, int x, int y ) { - Screen.drawTexture( transform, + Screen.blit( transform, x, y, 0, 102, WIDTH, FULL_BORDER, ComputerBorderRenderer.TEX_SIZE, ComputerBorderRenderer.TEX_SIZE ); - Screen.drawTexture( transform, + Screen.blit( transform, x, y + FULL_BORDER, WIDTH, HEIGHT - FULL_BORDER * 2, 0, 107, WIDTH, 4, ComputerBorderRenderer.TEX_SIZE, ComputerBorderRenderer.TEX_SIZE ); - Screen.drawTexture( transform, + Screen.blit( transform, x, y + HEIGHT - FULL_BORDER, 0, 111, WIDTH, FULL_BORDER, ComputerBorderRenderer.TEX_SIZE, ComputerBorderRenderer.TEX_SIZE ); diff --git a/src/main/java/dan200/computercraft/client/gui/widgets/DynamicImageButton.java b/src/main/java/dan200/computercraft/client/gui/widgets/DynamicImageButton.java index 4e8751883..e14e0cde9 100644 --- a/src/main/java/dan200/computercraft/client/gui/widgets/DynamicImageButton.java +++ b/src/main/java/dan200/computercraft/client/gui/widgets/DynamicImageButton.java @@ -6,12 +6,12 @@ package dan200.computercraft.client.gui.widgets; import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.widget.ButtonWidget; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; import java.util.List; @@ -19,24 +19,24 @@ import java.util.function.IntSupplier; import java.util.function.Supplier; /** - * Version of {@link net.minecraft.client.gui.widget.TexturedButtonWidget} which allows changing some properties + * Version of {@link net.minecraft.client.gui.components.ImageButton} which allows changing some properties * dynamically. */ -public class DynamicImageButton extends ButtonWidget +public class DynamicImageButton extends Button { private final Screen screen; - private final Identifier texture; + private final ResourceLocation texture; private final IntSupplier xTexStart; private final int yTexStart; private final int yDiffTex; private final int textureWidth; private final int textureHeight; - private final Supplier> tooltip; + private final Supplier> tooltip; public DynamicImageButton( Screen screen, int x, int y, int width, int height, int xTexStart, int yTexStart, int yDiffTex, - Identifier texture, int textureWidth, int textureHeight, - PressAction onPress, List tooltip + ResourceLocation texture, int textureWidth, int textureHeight, + OnPress onPress, List tooltip ) { this( @@ -49,11 +49,11 @@ public class DynamicImageButton extends ButtonWidget public DynamicImageButton( Screen screen, int x, int y, int width, int height, IntSupplier xTexStart, int yTexStart, int yDiffTex, - Identifier texture, int textureWidth, int textureHeight, - PressAction onPress, Supplier> tooltip + ResourceLocation texture, int textureWidth, int textureHeight, + OnPress onPress, Supplier> tooltip ) { - super( x, y, width, height, LiteralText.EMPTY, onPress ); + super( x, y, width, height, TextComponent.EMPTY, onPress ); this.screen = screen; this.textureWidth = textureWidth; this.textureHeight = textureHeight; @@ -65,7 +65,7 @@ public class DynamicImageButton extends ButtonWidget } @Override - public void renderButton( @Nonnull MatrixStack stack, int mouseX, int mouseY, float partialTicks ) + public void renderButton( @Nonnull PoseStack stack, int mouseX, int mouseY, float partialTicks ) { RenderSystem.setShaderTexture( 0, texture ); RenderSystem.disableDepthTest(); @@ -73,7 +73,7 @@ public class DynamicImageButton extends ButtonWidget int yTex = yTexStart; if( isHovered() ) yTex += yDiffTex; - drawTexture( stack, x, y, xTexStart.getAsInt(), yTex, width, height, textureWidth, textureHeight ); + blit( stack, x, y, xTexStart.getAsInt(), yTex, width, height, textureWidth, textureHeight ); RenderSystem.enableDepthTest(); if( isHovered() ) renderToolTip( stack, mouseX, mouseY ); @@ -81,20 +81,20 @@ public class DynamicImageButton extends ButtonWidget @Nonnull @Override - public Text getMessage() + public Component getMessage() { - List tooltip = this.tooltip.get(); - return tooltip.isEmpty() ? LiteralText.EMPTY : tooltip.get( 0 ); + List tooltip = this.tooltip.get(); + return tooltip.isEmpty() ? TextComponent.EMPTY : tooltip.get( 0 ); } // @Override - public void renderToolTip( @Nonnull MatrixStack stack, int mouseX, int mouseY ) + public void renderToolTip( @Nonnull PoseStack stack, int mouseX, int mouseY ) { - List tooltip = this.tooltip.get(); + List tooltip = this.tooltip.get(); if( !tooltip.isEmpty() ) { - screen.renderTooltip( stack, tooltip, mouseX, mouseY ); + screen.renderComponentTooltip( stack, tooltip, mouseX, mouseY ); } } } diff --git a/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java b/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java index 62c3d8404..8eaac4d80 100644 --- a/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java +++ b/src/main/java/dan200/computercraft/client/gui/widgets/WidgetTerminal.java @@ -6,16 +6,16 @@ package dan200.computercraft.client.gui.widgets; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Matrix4f; import dan200.computercraft.client.gui.FixedWidthFontRenderer; import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.shared.computer.core.ClientComputer; import net.minecraft.SharedConstants; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; -import net.minecraft.client.gui.widget.ClickableWidget; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.text.LiteralText; -import net.minecraft.util.math.Matrix4f; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.network.chat.TextComponent; import org.lwjgl.glfw.GLFW; import javax.annotation.Nonnull; @@ -25,7 +25,7 @@ import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH; import static dan200.computercraft.client.render.ComputerBorderRenderer.MARGIN; -public class WidgetTerminal extends ClickableWidget +public class WidgetTerminal extends AbstractWidget { private static final float TERMINATE_TIME = 0.5f; @@ -49,7 +49,7 @@ public class WidgetTerminal extends ClickableWidget public WidgetTerminal( @Nonnull ClientComputer computer, int x, int y, int termWidth, int termHeight ) { - super( x, y, termWidth * FONT_WIDTH + MARGIN * 2, termHeight * FONT_HEIGHT + MARGIN * 2, LiteralText.EMPTY ); + super( x, y, termWidth * FONT_WIDTH + MARGIN * 2, termHeight * FONT_HEIGHT + MARGIN * 2, TextComponent.EMPTY ); this.computer = computer; @@ -207,7 +207,7 @@ public class WidgetTerminal extends ClickableWidget case GLFW.GLFW_KEY_V: // Ctrl+V for paste - String clipboard = MinecraftClient.getInstance().keyboard.getClipboard(); + String clipboard = Minecraft.getInstance().keyboardHandler.getClipboard(); if( clipboard != null ) { // Clip to the first occurrence of \r or \n @@ -227,7 +227,7 @@ public class WidgetTerminal extends ClickableWidget } // Filter the string - clipboard = SharedConstants.stripInvalidChars( clipboard ); + clipboard = SharedConstants.filterText( clipboard ); if( !clipboard.isEmpty() ) { // Clip to 512 characters and queue the event @@ -346,10 +346,10 @@ public class WidgetTerminal extends ClickableWidget } @Override - public void render( @Nonnull MatrixStack transform, int mouseX, int mouseY, float partialTicks ) + public void render( @Nonnull PoseStack transform, int mouseX, int mouseY, float partialTicks ) { if( !visible ) return; - Matrix4f matrix = transform.peek().getModel(); + Matrix4f matrix = transform.last().pose(); Terminal terminal = computer.getTerminal(); if( terminal != null ) { @@ -362,7 +362,7 @@ public class WidgetTerminal extends ClickableWidget } @Override - public void appendNarrations( NarrationMessageBuilder builder ) + public void updateNarration( NarrationElementOutput builder ) { } diff --git a/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java b/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java index 3d22b88ef..11dd8f378 100644 --- a/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java +++ b/src/main/java/dan200/computercraft/client/proxy/ComputerCraftProxyClient.java @@ -39,11 +39,11 @@ import net.fabricmc.fabric.api.client.rendering.v1.EntityRendererRegistry; import net.fabricmc.fabric.api.client.screenhandler.v1.ScreenRegistry; import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback; import net.fabricmc.fabric.api.object.builder.v1.client.model.FabricModelPredicateProviderRegistry; -import net.minecraft.client.item.UnclampedModelPredicateProvider; -import net.minecraft.client.render.RenderLayer; -import net.minecraft.item.Item; -import net.minecraft.screen.PlayerScreenHandler; -import net.minecraft.util.Identifier; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.item.ClampedItemPropertyFunction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.InventoryMenu; +import net.minecraft.world.item.Item; import java.util.function.Supplier; @@ -73,11 +73,11 @@ public final class ComputerCraftProxyClient implements ClientModInitializer registerContainers(); // While turtles themselves are not transparent, their upgrades may be. - BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.TURTLE_NORMAL, RenderLayer.getTranslucent() ); - BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.TURTLE_ADVANCED, RenderLayer.getTranslucent() ); + BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.TURTLE_NORMAL, RenderType.translucent() ); + BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.TURTLE_ADVANCED, RenderType.translucent() ); // Monitors' textures have transparent fronts and so count as cutouts. - BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.MONITOR_NORMAL, RenderLayer.getCutout() ); - BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.MONITOR_ADVANCED, RenderLayer.getCutout() ); + BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.MONITOR_NORMAL, RenderType.cutout() ); + BlockRenderLayerMap.INSTANCE.putBlock( ComputerCraftRegistry.ModBlocks.MONITOR_ADVANCED, RenderType.cutout() ); // Setup TESRs BlockEntityRendererRegistry.register( ComputerCraftRegistry.ModTiles.MONITOR_NORMAL, TileEntityMonitorRenderer::new ); @@ -85,7 +85,7 @@ public final class ComputerCraftProxyClient implements ClientModInitializer BlockEntityRendererRegistry.register( ComputerCraftRegistry.ModTiles.TURTLE_NORMAL, TileEntityTurtleRenderer::new ); BlockEntityRendererRegistry.register( ComputerCraftRegistry.ModTiles.TURTLE_ADVANCED, TileEntityTurtleRenderer::new ); - ClientSpriteRegistryCallback.event( PlayerScreenHandler.BLOCK_ATLAS_TEXTURE ) + ClientSpriteRegistryCallback.event( InventoryMenu.BLOCK_ATLAS ) .register( ClientRegistry::onTextureStitchEvent ); ModelLoadingRegistry.INSTANCE.registerModelProvider( ClientRegistry::onModelBakeEvent ); ModelLoadingRegistry.INSTANCE.registerResourceProvider( loader -> ( name, context ) -> TurtleModelLoader.INSTANCE.accepts( name ) ? @@ -127,9 +127,9 @@ public final class ComputerCraftProxyClient implements ClientModInitializer } @SafeVarargs - private static void registerItemProperty( String name, UnclampedModelPredicateProvider getter, Supplier... items ) + private static void registerItemProperty( String name, ClampedItemPropertyFunction getter, Supplier... items ) { - Identifier id = new Identifier( ComputerCraft.MOD_ID, name ); + ResourceLocation id = new ResourceLocation( ComputerCraft.MOD_ID, name ); for( Supplier item : items ) { FabricModelPredicateProviderRegistry.register( item.get(), id, getter ); diff --git a/src/main/java/dan200/computercraft/client/render/CableHighlightRenderer.java b/src/main/java/dan200/computercraft/client/render/CableHighlightRenderer.java index ee0a1e93a..1f9935a78 100644 --- a/src/main/java/dan200/computercraft/client/render/CableHighlightRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/CableHighlightRenderer.java @@ -6,21 +6,25 @@ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.Matrix3f; +import com.mojang.math.Matrix4f; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.peripheral.modem.wired.BlockCable; import dan200.computercraft.shared.peripheral.modem.wired.CableShapes; import dan200.computercraft.shared.util.WorldUtil; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.block.BlockState; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.Camera; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.Entity; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.*; -import net.minecraft.util.shape.VoxelShape; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.VoxelShape; @Environment( EnvType.CLIENT ) public final class CableHighlightRenderer @@ -29,21 +33,21 @@ public final class CableHighlightRenderer { } - public static boolean drawHighlight( MatrixStack stack, VertexConsumer consumer, Entity entity, double d, double e, double f, BlockPos pos, + public static boolean drawHighlight( PoseStack stack, VertexConsumer consumer, Entity entity, double d, double e, double f, BlockPos pos, BlockState state ) { - Camera info = MinecraftClient.getInstance().gameRenderer.getCamera(); + Camera info = Minecraft.getInstance().gameRenderer.getMainCamera(); // We only care about instances with both cable and modem. - if( state.getBlock() != ComputerCraftRegistry.ModBlocks.CABLE || state.get( BlockCable.MODEM ) - .getFacing() == null || !state.get( BlockCable.CABLE ) ) + if( state.getBlock() != ComputerCraftRegistry.ModBlocks.CABLE || state.getValue( BlockCable.MODEM ) + .getFacing() == null || !state.getValue( BlockCable.CABLE ) ) { return false; } - HitResult hitResult = MinecraftClient.getInstance().crosshairTarget; + HitResult hitResult = Minecraft.getInstance().hitResult; - Vec3d hitPos = hitResult != null ? hitResult.getPos() : new Vec3d( d, e, f ); + Vec3 hitPos = hitResult != null ? hitResult.getLocation() : new Vec3( d, e, f ); VoxelShape shape = WorldUtil.isVecInside( CableShapes.getModemShape( state ), hitPos.subtract( pos.getX(), @@ -51,19 +55,19 @@ public final class CableHighlightRenderer pos.getZ() ) ) ? CableShapes.getModemShape( state ) : CableShapes.getCableShape( state ); - Vec3d cameraPos = info.getPos(); + Vec3 cameraPos = info.getPosition(); - double xOffset = pos.getX() - cameraPos.getX(); - double yOffset = pos.getY() - cameraPos.getY(); - double zOffset = pos.getZ() - cameraPos.getZ(); - Matrix4f matrix4f = stack.peek() - .getModel(); - Matrix3f normal = stack.peek().getNormal(); - shape.forEachEdge( ( x1, y1, z1, x2, y2, z2 ) -> { + double xOffset = pos.getX() - cameraPos.x(); + double yOffset = pos.getY() - cameraPos.y(); + double zOffset = pos.getZ() - cameraPos.z(); + Matrix4f matrix4f = stack.last() + .pose(); + Matrix3f normal = stack.last().normal(); + shape.forAllEdges( ( x1, y1, z1, x2, y2, z2 ) -> { float xDelta = (float) (x2 - x1); float yDelta = (float) (y2 - y1); float zDelta = (float) (z2 - z1); - float len = MathHelper.sqrt( xDelta * xDelta + yDelta * yDelta + zDelta * zDelta ); + float len = Mth.sqrt( xDelta * xDelta + yDelta * yDelta + zDelta * zDelta ); xDelta = xDelta / len; yDelta = yDelta / len; zDelta = zDelta / len; @@ -71,11 +75,11 @@ public final class CableHighlightRenderer consumer.vertex( matrix4f, (float) (x1 + xOffset), (float) (y1 + yOffset), (float) (z1 + zOffset) ) .color( 0, 0, 0, 0.4f ) .normal( normal, xDelta, yDelta, zDelta ) - .next(); + .endVertex(); consumer.vertex( matrix4f, (float) (x2 + xOffset), (float) (y2 + yOffset), (float) (z2 + zOffset) ) .color( 0, 0, 0, 0.4f ) .normal( normal, xDelta, yDelta, zDelta ) - .next(); + .endVertex(); } ); return true; diff --git a/src/main/java/dan200/computercraft/client/render/ComputerBorderRenderer.java b/src/main/java/dan200/computercraft/client/render/ComputerBorderRenderer.java index c36acd10e..b5f58d77a 100644 --- a/src/main/java/dan200/computercraft/client/render/ComputerBorderRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/ComputerBorderRenderer.java @@ -5,23 +5,23 @@ */ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.Matrix4f; import dan200.computercraft.ComputerCraft; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.client.render.RenderLayer; -import net.minecraft.client.render.Tessellator; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Matrix4f; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; public class ComputerBorderRenderer { - public static final Identifier BACKGROUND_NORMAL = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_normal.png" ); - public static final Identifier BACKGROUND_ADVANCED = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_advanced.png" ); - public static final Identifier BACKGROUND_COMMAND = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_command.png" ); - public static final Identifier BACKGROUND_COLOUR = new Identifier( ComputerCraft.MOD_ID, "textures/gui/corners_colour.png" ); + public static final ResourceLocation BACKGROUND_NORMAL = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/corners_normal.png" ); + public static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/corners_advanced.png" ); + public static final ResourceLocation BACKGROUND_COMMAND = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/corners_command.png" ); + public static final ResourceLocation BACKGROUND_COLOUR = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/corners_colour.png" ); /** * The margin between the terminal and its border. */ @@ -45,7 +45,7 @@ public class ComputerBorderRenderer static { - IDENTITY.loadIdentity(); + IDENTITY.setIdentity(); } private final Matrix4f transform; @@ -68,7 +68,7 @@ public class ComputerBorderRenderer @Nonnull - public static Identifier getTexture( @Nonnull ComputerFamily family ) + public static ResourceLocation getTexture( @Nonnull ComputerFamily family ) { switch( family ) { @@ -82,11 +82,11 @@ public class ComputerBorderRenderer } } - public static void render( Identifier location, int x, int y, int z, int light, int width, int height ) + public static void render( ResourceLocation location, int x, int y, int z, int light, int width, int height ) { - VertexConsumerProvider.Immediate source = VertexConsumerProvider.immediate( Tessellator.getInstance().getBuffer() ); - render( IDENTITY, source.getBuffer( RenderLayer.getText( location ) ), x, y, z, light, width, height, false, 1, 1, 1 ); - source.draw(); + MultiBufferSource.BufferSource source = MultiBufferSource.immediate( Tesselator.getInstance().getBuilder() ); + render( IDENTITY, source.getBuffer( RenderType.text( location ) ), x, y, z, light, width, height, false, 1, 1, 1 ); + source.endBatch(); } @@ -144,23 +144,23 @@ public class ComputerBorderRenderer { builder.vertex( transform, x, y + height, z ) .color( r, g, b, 1.0f ) - .texture( u * TEX_SCALE, (v + textureHeight) * TEX_SCALE ) - .light( light ) - .next(); + .uv( u * TEX_SCALE, (v + textureHeight) * TEX_SCALE ) + .uv2( light ) + .endVertex(); builder.vertex( transform, x + width, y + height, z ) .color( r, g, b, 1.0f ) - .texture( (u + textureWidth) * TEX_SCALE, (v + textureHeight) * TEX_SCALE ) - .light( light ) - .next(); + .uv( (u + textureWidth) * TEX_SCALE, (v + textureHeight) * TEX_SCALE ) + .uv2( light ) + .endVertex(); builder.vertex( transform, x + width, y, z ) .color( r, g, b, 1.0f ) - .texture( (u + textureWidth) * TEX_SCALE, v * TEX_SCALE ) - .light( light ) - .next(); + .uv( (u + textureWidth) * TEX_SCALE, v * TEX_SCALE ) + .uv2( light ) + .endVertex(); builder.vertex( transform, x, y, z ) .color( r, g, b, 1.0f ) - .texture( u * TEX_SCALE, v * TEX_SCALE ) - .light( light ) - .next(); + .uv( u * TEX_SCALE, v * TEX_SCALE ) + .uv2( light ) + .endVertex(); } } diff --git a/src/main/java/dan200/computercraft/client/render/ItemMapLikeRenderer.java b/src/main/java/dan200/computercraft/client/render/ItemMapLikeRenderer.java index f1ef584c5..62f3069f3 100644 --- a/src/main/java/dan200/computercraft/client/render/ItemMapLikeRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/ItemMapLikeRenderer.java @@ -6,32 +6,32 @@ package dan200.computercraft.client.render; -import dan200.computercraft.fabric.mixin.HeldItemRendererAccess; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Vector3f; +import dan200.computercraft.fabric.mixin.ItemInHandRendererAccess; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.item.HeldItemRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Arm; -import net.minecraft.util.Hand; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3f; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; @Environment( EnvType.CLIENT ) public abstract class ItemMapLikeRenderer { public void renderItemFirstPerson( - MatrixStack transform, VertexConsumerProvider render, int lightTexture, Hand hand, float pitch, float equipProgress, + PoseStack transform, MultiBufferSource render, int lightTexture, InteractionHand hand, float pitch, float equipProgress, float swingProgress, ItemStack stack ) { - PlayerEntity player = MinecraftClient.getInstance().player; + Player player = Minecraft.getInstance().player; - transform.push(); - if( hand == Hand.MAIN_HAND && player.getOffHandStack().isEmpty() ) + transform.pushPose(); + if( hand == InteractionHand.MAIN_HAND && player.getOffhandItem().isEmpty() ) { renderItemFirstPersonCenter( transform, render, lightTexture, pitch, equipProgress, swingProgress, stack ); } @@ -40,12 +40,12 @@ public abstract class ItemMapLikeRenderer renderItemFirstPersonSide( transform, render, lightTexture, - hand == Hand.MAIN_HAND ? player.getMainArm() : player.getMainArm().getOpposite(), + hand == InteractionHand.MAIN_HAND ? player.getMainArm() : player.getMainArm().getOpposite(), equipProgress, swingProgress, stack ); } - transform.pop(); + transform.popPose(); } /** @@ -59,34 +59,34 @@ public abstract class ItemMapLikeRenderer * @param swingProgress The swing progress of this item * @param stack The stack to render */ - private void renderItemFirstPersonCenter( MatrixStack transform, VertexConsumerProvider render, int combinedLight, float pitch, float equipProgress, + private void renderItemFirstPersonCenter( PoseStack transform, MultiBufferSource render, int combinedLight, float pitch, float equipProgress, float swingProgress, ItemStack stack ) { - MinecraftClient minecraft = MinecraftClient.getInstance(); - HeldItemRenderer renderer = minecraft.getHeldItemRenderer(); + Minecraft minecraft = Minecraft.getInstance(); + ItemInHandRenderer renderer = minecraft.getItemInHandRenderer(); // Setup the appropriate transformations. This is just copied from the // corresponding method in ItemRenderer. - float swingRt = MathHelper.sqrt( swingProgress ); - float tX = -0.2f * MathHelper.sin( swingProgress * (float) Math.PI ); - float tZ = -0.4f * MathHelper.sin( swingRt * (float) Math.PI ); + float swingRt = Mth.sqrt( swingProgress ); + float tX = -0.2f * Mth.sin( swingProgress * (float) Math.PI ); + float tZ = -0.4f * Mth.sin( swingRt * (float) Math.PI ); transform.translate( 0, -tX / 2, tZ ); - HeldItemRendererAccess access = (HeldItemRendererAccess) renderer; - float pitchAngle = access.callGetMapAngle( pitch ); + ItemInHandRendererAccess access = (ItemInHandRendererAccess) renderer; + float pitchAngle = access.callCalculateMapTilt( pitch ); transform.translate( 0, 0.04F + equipProgress * -1.2f + pitchAngle * -0.5f, -0.72f ); - transform.multiply( Vec3f.POSITIVE_X.getDegreesQuaternion( pitchAngle * -85.0f ) ); + transform.mulPose( Vector3f.XP.rotationDegrees( pitchAngle * -85.0f ) ); if( !minecraft.player.isInvisible() ) { - transform.push(); - transform.multiply( Vec3f.POSITIVE_Y.getDegreesQuaternion( 90.0F ) ); - access.callRenderArm( transform, render, combinedLight, Arm.RIGHT ); - access.callRenderArm( transform, render, combinedLight, Arm.LEFT ); - transform.pop(); + transform.pushPose(); + transform.mulPose( Vector3f.YP.rotationDegrees( 90.0F ) ); + access.callRenderMapHand( transform, render, combinedLight, HumanoidArm.RIGHT ); + access.callRenderMapHand( transform, render, combinedLight, HumanoidArm.LEFT ); + transform.popPose(); } - float rX = MathHelper.sin( swingRt * (float) Math.PI ); - transform.multiply( Vec3f.POSITIVE_X.getDegreesQuaternion( rX * 20.0F ) ); + float rX = Mth.sin( swingRt * (float) Math.PI ); + transform.mulPose( Vector3f.XP.rotationDegrees( rX * 20.0F ) ); transform.scale( 2.0F, 2.0F, 2.0F ); renderItem( transform, render, stack, combinedLight ); @@ -103,39 +103,39 @@ public abstract class ItemMapLikeRenderer * @param swingProgress The swing progress of this item * @param stack The stack to render */ - private void renderItemFirstPersonSide( MatrixStack transform, VertexConsumerProvider render, int combinedLight, Arm side, float equipProgress, + private void renderItemFirstPersonSide( PoseStack transform, MultiBufferSource render, int combinedLight, HumanoidArm side, float equipProgress, float swingProgress, ItemStack stack ) { - MinecraftClient minecraft = MinecraftClient.getInstance(); - float offset = side == Arm.RIGHT ? 1f : -1f; + Minecraft minecraft = Minecraft.getInstance(); + float offset = side == HumanoidArm.RIGHT ? 1f : -1f; transform.translate( offset * 0.125f, -0.125f, 0f ); // If the player is not invisible then render a single arm if( !minecraft.player.isInvisible() ) { - transform.push(); - transform.multiply( Vec3f.POSITIVE_Z.getDegreesQuaternion( offset * 10f ) ); - ((HeldItemRendererAccess) minecraft.getHeldItemRenderer()) - .callRenderArmHoldingItem( transform, render, combinedLight, equipProgress, swingProgress, side ); - transform.pop(); + transform.pushPose(); + transform.mulPose( Vector3f.ZP.rotationDegrees( offset * 10f ) ); + ((ItemInHandRendererAccess) minecraft.getItemInHandRenderer()) + .callRenderPlayerArm( transform, render, combinedLight, equipProgress, swingProgress, side ); + transform.popPose(); } // Setup the appropriate transformations. This is just copied from the // corresponding method in ItemRenderer. - transform.push(); + transform.pushPose(); transform.translate( offset * 0.51f, -0.08f + equipProgress * -1.2f, -0.75f ); - float f1 = MathHelper.sqrt( swingProgress ); - float f2 = MathHelper.sin( f1 * (float) Math.PI ); + float f1 = Mth.sqrt( swingProgress ); + float f2 = Mth.sin( f1 * (float) Math.PI ); float f3 = -0.5f * f2; - float f4 = 0.4f * MathHelper.sin( f1 * ((float) Math.PI * 2f) ); - float f5 = -0.3f * MathHelper.sin( swingProgress * (float) Math.PI ); + float f4 = 0.4f * Mth.sin( f1 * ((float) Math.PI * 2f) ); + float f5 = -0.3f * Mth.sin( swingProgress * (float) Math.PI ); transform.translate( offset * f3, f4 - 0.3f * f2, f5 ); - transform.multiply( Vec3f.POSITIVE_X.getDegreesQuaternion( f2 * -45f ) ); - transform.multiply( Vec3f.POSITIVE_Y.getDegreesQuaternion( offset * f2 * -30f ) ); + transform.mulPose( Vector3f.XP.rotationDegrees( f2 * -45f ) ); + transform.mulPose( Vector3f.YP.rotationDegrees( offset * f2 * -30f ) ); renderItem( transform, render, stack, combinedLight ); - transform.pop(); + transform.popPose(); } /** @@ -146,5 +146,5 @@ public abstract class ItemMapLikeRenderer * @param stack The stack to render * @param light TODO rebase */ - protected abstract void renderItem( MatrixStack transform, VertexConsumerProvider render, ItemStack stack, int light ); + protected abstract void renderItem( PoseStack transform, MultiBufferSource render, ItemStack stack, int light ); } diff --git a/src/main/java/dan200/computercraft/client/render/ItemPocketRenderer.java b/src/main/java/dan200/computercraft/client/render/ItemPocketRenderer.java index 23982f3a9..993c922f2 100644 --- a/src/main/java/dan200/computercraft/client/render/ItemPocketRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/ItemPocketRenderer.java @@ -7,6 +7,9 @@ package dan200.computercraft.client.render; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.*; +import com.mojang.math.Matrix4f; +import com.mojang.math.Vector3f; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.gui.FixedWidthFontRenderer; import dan200.computercraft.core.terminal.Terminal; @@ -14,13 +17,11 @@ import dan200.computercraft.shared.computer.core.ClientComputer; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.pocket.items.ItemPocketComputer; import dan200.computercraft.shared.util.Colour; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.*; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Matrix4f; -import net.minecraft.util.math.Vec3f; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH; @@ -38,7 +39,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer } @Override - protected void renderItem( MatrixStack transform, VertexConsumerProvider render, ItemStack stack, int light ) + protected void renderItem( PoseStack transform, MultiBufferSource render, ItemStack stack, int light ) { ClientComputer computer = ItemPocketComputer.createClientComputer( stack ); Terminal terminal = computer == null ? null : computer.getTerminal(); @@ -60,9 +61,9 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer // Setup various transformations. Note that these are partially adapted from the corresponding method // in ItemRenderer - transform.push(); - transform.multiply( Vec3f.POSITIVE_Y.getDegreesQuaternion( 180f ) ); - transform.multiply( Vec3f.POSITIVE_Z.getDegreesQuaternion( 180f ) ); + transform.pushPose(); + transform.mulPose( Vector3f.YP.rotationDegrees( 180f ) ); + transform.mulPose( Vector3f.ZP.rotationDegrees( 180f ) ); transform.scale( 0.5f, 0.5f, 0.5f ); float scale = 0.75f / Math.max( width + BORDER * 2, height + BORDER * 2 + LIGHT_HEIGHT ); @@ -74,8 +75,8 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer ComputerFamily family = item.getFamily(); int frameColour = item.getColour( stack ); - Matrix4f matrix = transform.peek() - .getModel(); + Matrix4f matrix = transform.last() + .pose(); renderFrame( matrix, render, family, frameColour, light, width, height ); // Render the light @@ -92,7 +93,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer matrix, render.getBuffer( RenderTypes.TERMINAL_WITHOUT_DEPTH ), MARGIN, MARGIN, terminal, !computer.isColour(), MARGIN, MARGIN, MARGIN, MARGIN ); - FixedWidthFontRenderer.drawBlocker( transform.peek().getModel(), render, 0, 0, width, height ); + FixedWidthFontRenderer.drawBlocker( transform.last().pose(), render, 0, 0, width, height ); } else @@ -100,23 +101,23 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer FixedWidthFontRenderer.drawEmptyTerminal( matrix, 0, 0, width, height ); } - transform.pop(); + transform.popPose(); } - private static void renderFrame( Matrix4f transform, VertexConsumerProvider render, ComputerFamily family, int colour, int light, int width, int height ) + private static void renderFrame( Matrix4f transform, MultiBufferSource render, ComputerFamily family, int colour, int light, int width, int height ) { RenderSystem.enableBlend(); - MinecraftClient.getInstance() + Minecraft.getInstance() .getTextureManager() - .bindTexture( colour != -1 ? ComputerBorderRenderer.BACKGROUND_COLOUR : ComputerBorderRenderer.getTexture( family ) ); + .bindForSetup( colour != -1 ? ComputerBorderRenderer.BACKGROUND_COLOUR : ComputerBorderRenderer.getTexture( family ) ); - Identifier texture = colour != -1 ? ComputerBorderRenderer.BACKGROUND_COLOUR : ComputerBorderRenderer.getTexture( family ); + ResourceLocation texture = colour != -1 ? ComputerBorderRenderer.BACKGROUND_COLOUR : ComputerBorderRenderer.getTexture( family ); float r = ((colour >>> 16) & 0xFF) / 255.0f; float g = ((colour >>> 8) & 0xFF) / 255.0f; float b = (colour & 0xFF) / 255.0f; - ComputerBorderRenderer.render( transform, render.getBuffer( RenderLayer.getText( texture ) ), 0, 0, 0, light, width, height, true, r, g, b ); + ComputerBorderRenderer.render( transform, render.getBuffer( RenderType.text( texture ) ), 0, 0, 0, light, width, height, true, r, g, b ); } private static void renderLight( Matrix4f transform, int colour, int width, int height ) @@ -127,23 +128,23 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer float g = ((colour >>> 8) & 0xFF) / 255.0f; float b = (colour & 0xFF) / 255.0f; - Tessellator tessellator = Tessellator.getInstance(); - BufferBuilder buffer = tessellator.getBuffer(); - buffer.begin( VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR ); + Tesselator tessellator = Tesselator.getInstance(); + BufferBuilder buffer = tessellator.getBuilder(); + buffer.begin( VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR ); buffer.vertex( transform, width - LIGHT_HEIGHT * 2, height + LIGHT_HEIGHT + BORDER / 2.0f, 0 ) .color( r, g, b, 1.0f ) - .next(); + .endVertex(); buffer.vertex( transform, width, height + LIGHT_HEIGHT + BORDER / 2.0f, 0 ) .color( r, g, b, 1.0f ) - .next(); + .endVertex(); buffer.vertex( transform, width, height + BORDER / 2.0f, 0 ) .color( r, g, b, 1.0f ) - .next(); + .endVertex(); buffer.vertex( transform, width - LIGHT_HEIGHT * 2, height + BORDER / 2.0f, 0 ) .color( r, g, b, 1.0f ) - .next(); + .endVertex(); - tessellator.draw(); + tessellator.end(); RenderSystem.enableTexture(); } } diff --git a/src/main/java/dan200/computercraft/client/render/ItemPrintoutRenderer.java b/src/main/java/dan200/computercraft/client/render/ItemPrintoutRenderer.java index e432af8c3..d7f3ca2a6 100644 --- a/src/main/java/dan200/computercraft/client/render/ItemPrintoutRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/ItemPrintoutRenderer.java @@ -6,12 +6,12 @@ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Matrix4f; +import com.mojang.math.Vector3f; import dan200.computercraft.shared.media.items.ItemPrintout; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.Matrix4f; -import net.minecraft.util.math.Vec3f; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.world.item.ItemStack; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH; @@ -31,16 +31,16 @@ public final class ItemPrintoutRenderer extends ItemMapLikeRenderer } @Override - protected void renderItem( MatrixStack transform, VertexConsumerProvider render, ItemStack stack, int light ) + protected void renderItem( PoseStack transform, MultiBufferSource render, ItemStack stack, int light ) { - transform.multiply( Vec3f.POSITIVE_X.getDegreesQuaternion( 180f ) ); + transform.mulPose( Vector3f.XP.rotationDegrees( 180f ) ); transform.scale( 0.42f, 0.42f, -0.42f ); transform.translate( -0.5f, -0.48f, 0.0f ); drawPrintout( transform, render, stack, light ); } - private static void drawPrintout( MatrixStack transform, VertexConsumerProvider render, ItemStack stack, int light ) + private static void drawPrintout( PoseStack transform, MultiBufferSource render, ItemStack stack, int light ) { int pages = ItemPrintout.getPageCount( stack ); boolean book = ((ItemPrintout) stack.getItem()).getType() == ItemPrintout.Type.BOOK; @@ -70,13 +70,13 @@ public final class ItemPrintoutRenderer extends ItemMapLikeRenderer transform.scale( scale, scale, scale ); transform.translate( (max - width) / 2.0, (max - height) / 2.0, 0.0 ); - Matrix4f matrix = transform.peek() - .getModel(); + Matrix4f matrix = transform.last() + .pose(); drawBorder( matrix, render, 0, 0, -0.01f, 0, pages, book, light ); drawText( matrix, render, X_TEXT_MARGIN, Y_TEXT_MARGIN, 0, light, ItemPrintout.getText( stack ), ItemPrintout.getColours( stack ) ); } - public boolean renderInFrame( MatrixStack matrixStack, VertexConsumerProvider consumerProvider, ItemStack stack, int light ) + public boolean renderInFrame( PoseStack matrixStack, MultiBufferSource consumerProvider, ItemStack stack, int light ) { if( !(stack.getItem() instanceof ItemPrintout) ) { @@ -85,7 +85,7 @@ public final class ItemPrintoutRenderer extends ItemMapLikeRenderer // Move a little bit forward to ensure we're not clipping with the frame matrixStack.translate( 0.0f, 0.0f, -0.001f ); - matrixStack.multiply( Vec3f.POSITIVE_Z.getDegreesQuaternion( 180f ) ); + matrixStack.mulPose( Vector3f.ZP.rotationDegrees( 180f ) ); matrixStack.scale( 0.95f, 0.95f, -0.95f ); matrixStack.translate( -0.5f, -0.5f, 0.0f ); diff --git a/src/main/java/dan200/computercraft/client/render/ModelTransformer.java b/src/main/java/dan200/computercraft/client/render/ModelTransformer.java index a14ae9e07..44e44f307 100644 --- a/src/main/java/dan200/computercraft/client/render/ModelTransformer.java +++ b/src/main/java/dan200/computercraft/client/render/ModelTransformer.java @@ -5,14 +5,14 @@ */ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import com.mojang.math.Matrix4f; +import com.mojang.math.Vector4f; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.render.VertexFormat; -import net.minecraft.client.render.VertexFormatElement; -import net.minecraft.client.render.VertexFormats; -import net.minecraft.client.render.model.BakedQuad; -import net.minecraft.util.math.Matrix4f; -import net.minecraft.util.math.Vector4f; +import net.minecraft.client.renderer.block.model.BakedQuad; import java.util.List; @@ -27,7 +27,7 @@ public final class ModelTransformer static { identity = new Matrix4f(); - identity.loadIdentity(); + identity.setIdentity(); } private ModelTransformer() @@ -36,7 +36,7 @@ public final class ModelTransformer public static void transformQuadsTo( List output, List input, Matrix4f transform ) { - transformQuadsTo( VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, output, input, transform ); + transformQuadsTo( DefaultVertexFormat.BLOCK, output, input, transform ); } public static void transformQuadsTo( VertexFormat format, List output, List input, Matrix4f transform ) @@ -56,8 +56,8 @@ public final class ModelTransformer private static BakedQuad doTransformQuad( VertexFormat format, BakedQuad quad, Matrix4f transform ) { - int[] vertexData = quad.getVertexData().clone(); - BakedQuad copy = new BakedQuad( vertexData, -1, quad.getFace(), quad.getSprite(), true ); + int[] vertexData = quad.getVertices().clone(); + BakedQuad copy = new BakedQuad( vertexData, -1, quad.getDirection(), quad.getSprite(), true ); int offsetBytes = 0; for( int v = 0; v < 4; ++v ) @@ -65,7 +65,7 @@ public final class ModelTransformer for( VertexFormatElement element : format.getElements() ) // For each vertex element { int start = offsetBytes / Integer.BYTES; - if( element.getType() == VertexFormatElement.Type.POSITION && element.getDataType() == VertexFormatElement.DataType.FLOAT ) // When we find a position element + if( element.getUsage() == VertexFormatElement.Usage.POSITION && element.getType() == VertexFormatElement.Type.FLOAT ) // When we find a position element { Vector4f pos = new Vector4f( Float.intBitsToFloat( vertexData[start] ), Float.intBitsToFloat( vertexData[start + 1] ), @@ -76,11 +76,11 @@ public final class ModelTransformer pos.transform( transform ); // Insert the position - vertexData[start] = Float.floatToRawIntBits( pos.getX() ); - vertexData[start + 1] = Float.floatToRawIntBits( pos.getY() ); - vertexData[start + 2] = Float.floatToRawIntBits( pos.getZ() ); + vertexData[start] = Float.floatToRawIntBits( pos.x() ); + vertexData[start + 1] = Float.floatToRawIntBits( pos.y() ); + vertexData[start + 2] = Float.floatToRawIntBits( pos.z() ); } - offsetBytes += element.getByteLength(); + offsetBytes += element.getByteSize(); } } return copy; diff --git a/src/main/java/dan200/computercraft/client/render/MonitorHighlightRenderer.java b/src/main/java/dan200/computercraft/client/render/MonitorHighlightRenderer.java index d4083c67f..491b4514d 100644 --- a/src/main/java/dan200/computercraft/client/render/MonitorHighlightRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/MonitorHighlightRenderer.java @@ -6,20 +6,25 @@ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.Matrix3f; +import com.mojang.math.Matrix4f; import dan200.computercraft.shared.peripheral.monitor.TileMonitor; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.*; -import net.minecraft.world.World; +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; import java.util.EnumSet; -import static net.minecraft.util.math.Direction.*; + +import static net.minecraft.core.Direction.*; /** * Overrides monitor highlighting to only render the outline of the whole monitor, rather than the current block. This means you do not get an @@ -32,15 +37,15 @@ public final class MonitorHighlightRenderer { } - public static boolean drawHighlight( MatrixStack matrixStack, VertexConsumer vertexConsumer, Entity entity, double d, double e, double f, BlockPos pos, BlockState blockState ) + public static boolean drawHighlight( PoseStack matrixStack, VertexConsumer vertexConsumer, Entity entity, double d, double e, double f, BlockPos pos, BlockState blockState ) { // Preserve normal behaviour when crouching. - if( entity.isInSneakingPose() ) + if( entity.isCrouching() ) { return false; } - World world = entity.getEntityWorld(); + Level world = entity.getCommandSenderWorld(); BlockEntity tile = world.getBlockEntity( pos ); if( !(tile instanceof TileMonitor monitor) ) @@ -71,15 +76,15 @@ public final class MonitorHighlightRenderer faces.remove( monitor.getDown() ); } - Vec3d cameraPos = MinecraftClient.getInstance().gameRenderer.getCamera() - .getPos(); - matrixStack.push(); - matrixStack.translate( pos.getX() - cameraPos.getX(), pos.getY() - cameraPos.getY(), pos.getZ() - cameraPos.getZ() ); + Vec3 cameraPos = Minecraft.getInstance().gameRenderer.getMainCamera() + .getPosition(); + matrixStack.pushPose(); + matrixStack.translate( pos.getX() - cameraPos.x(), pos.getY() - cameraPos.y(), pos.getZ() - cameraPos.z() ); // I wish I could think of a better way to do this - Matrix4f transform = matrixStack.peek() - .getModel(); - Matrix3f normal = matrixStack.peek().getNormal(); + Matrix4f transform = matrixStack.last() + .pose(); + Matrix3f normal = matrixStack.last().normal(); if( faces.contains( NORTH ) || faces.contains( WEST ) ) { line( vertexConsumer, transform, normal, 0, 0, 0, UP ); @@ -129,7 +134,7 @@ public final class MonitorHighlightRenderer line( vertexConsumer, transform, normal, 1, 1, 0, SOUTH ); } - matrixStack.pop(); + matrixStack.popPose(); return true; } @@ -138,11 +143,11 @@ public final class MonitorHighlightRenderer { buffer.vertex( transform, x, y, z ) .color( 0, 0, 0, 0.4f ) - .normal( normal, direction.getOffsetX(), direction.getOffsetY(), direction.getOffsetZ() ) - .next(); - buffer.vertex( transform, x + direction.getOffsetX(), y + direction.getOffsetY(), z + direction.getOffsetZ() ) + .normal( normal, direction.getStepX(), direction.getStepY(), direction.getStepZ() ) + .endVertex(); + buffer.vertex( transform, x + direction.getStepX(), y + direction.getStepY(), z + direction.getStepZ() ) .color( 0, 0, 0, 0.4f ) - .normal( normal, direction.getOffsetX(), direction.getOffsetY(), direction.getOffsetZ() ) - .next(); + .normal( normal, direction.getStepX(), direction.getStepY(), direction.getStepZ() ) + .endVertex(); } } diff --git a/src/main/java/dan200/computercraft/client/render/MonitorTextureBufferShader.java b/src/main/java/dan200/computercraft/client/render/MonitorTextureBufferShader.java index bd14234a0..3602574ec 100644 --- a/src/main/java/dan200/computercraft/client/render/MonitorTextureBufferShader.java +++ b/src/main/java/dan200/computercraft/client/render/MonitorTextureBufferShader.java @@ -5,12 +5,12 @@ */ package dan200.computercraft.client.render; +import com.mojang.blaze3d.shaders.Uniform; +import com.mojang.blaze3d.vertex.VertexFormat; import dan200.computercraft.client.gui.FixedWidthFontRenderer; import dan200.computercraft.shared.util.Palette; -import net.minecraft.client.gl.GlUniform; -import net.minecraft.client.render.Shader; -import net.minecraft.client.render.VertexFormat; -import net.minecraft.resource.ResourceFactory; +import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.server.packs.resources.ResourceProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.GL13; @@ -19,26 +19,26 @@ import javax.annotation.Nullable; import java.io.IOException; import java.nio.FloatBuffer; -public class MonitorTextureBufferShader extends Shader +public class MonitorTextureBufferShader extends ShaderInstance { static final int TEXTURE_INDEX = GL13.GL_TEXTURE3; private static final Logger LOGGER = LogManager.getLogger(); - private final GlUniform palette; - private final GlUniform width; - private final GlUniform height; + private final Uniform palette; + private final Uniform width; + private final Uniform height; - public MonitorTextureBufferShader( ResourceFactory factory, String name, VertexFormat format ) throws IOException + public MonitorTextureBufferShader( ResourceProvider factory, String name, VertexFormat format ) throws IOException { super( factory, name, format ); width = getUniformChecked( "Width" ); height = getUniformChecked( "Height" ); - palette = new GlUniform( "Palette", GlUniform.field_32044 /* UT_FLOAT3 */, 16 * 3, this ); + palette = new Uniform( "Palette", Uniform.UT_FLOAT3 /* UT_FLOAT3 */, 16 * 3, this ); updateUniformLocation( palette ); - GlUniform tbo = getUniformChecked( "Tbo" ); + Uniform tbo = getUniformChecked( "Tbo" ); if( tbo != null ) tbo.set( TEXTURE_INDEX - GL13.GL_TEXTURE0 ); } @@ -53,7 +53,7 @@ public class MonitorTextureBufferShader extends Shader { if( this.palette == null ) return; - FloatBuffer paletteBuffer = this.palette.getFloatData(); + FloatBuffer paletteBuffer = this.palette.getFloatBuffer(); paletteBuffer.rewind(); for( int i = 0; i < 16; i++ ) { @@ -71,9 +71,9 @@ public class MonitorTextureBufferShader extends Shader } @Override - public void bind() + public void apply() { - super.bind(); + super.apply(); palette.upload(); } @@ -84,23 +84,23 @@ public class MonitorTextureBufferShader extends Shader super.close(); } - private void updateUniformLocation( GlUniform uniform ) + private void updateUniformLocation( Uniform uniform ) { - int id = GlUniform.getUniformLocation( getProgramRef(), uniform.getName() ); + int id = Uniform.glGetUniformLocation( getId(), uniform.getName() ); if( id == -1 ) { LOGGER.warn( "Shader {} could not find uniform named {} in the specified shader program.", getName(), uniform.getName() ); } else { - uniform.setLoc( id ); + uniform.setLocation( id ); } } @Nullable - private GlUniform getUniformChecked( String name ) + private Uniform getUniformChecked( String name ) { - GlUniform uniform = getUniform( name ); + Uniform uniform = getUniform( name ); if( uniform == null ) { LOGGER.warn( "Monitor shader {} should have uniform {}, but it was not present.", getName(), name ); diff --git a/src/main/java/dan200/computercraft/client/render/PrintoutRenderer.java b/src/main/java/dan200/computercraft/client/render/PrintoutRenderer.java index 7b8c809a5..2d9e49afa 100644 --- a/src/main/java/dan200/computercraft/client/render/PrintoutRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/PrintoutRenderer.java @@ -6,12 +6,12 @@ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.math.Matrix4f; import dan200.computercraft.client.gui.FixedWidthFontRenderer; import dan200.computercraft.core.terminal.TextBuffer; import dan200.computercraft.shared.util.Palette; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.util.math.Matrix4f; +import net.minecraft.client.renderer.MultiBufferSource; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT; import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAGE; @@ -48,7 +48,7 @@ public final class PrintoutRenderer private PrintoutRenderer() {} - public static void drawText( Matrix4f transform, VertexConsumerProvider renderer, int x, int y, int start, int light, TextBuffer[] text, TextBuffer[] colours ) + public static void drawText( Matrix4f transform, MultiBufferSource renderer, int x, int y, int start, int light, TextBuffer[] text, TextBuffer[] colours ) { VertexConsumer buffer = renderer.getBuffer( RenderTypes.PRINTOUT_TEXT ); for( int line = 0; line < LINES_PER_PAGE && line < text.length; line++ ) @@ -68,7 +68,7 @@ public final class PrintoutRenderer } } - public static void drawText( Matrix4f transform, VertexConsumerProvider renderer, int x, int y, int start, int light, String[] text, String[] colours ) + public static void drawText( Matrix4f transform, MultiBufferSource renderer, int x, int y, int start, int light, String[] text, String[] colours ) { VertexConsumer buffer = renderer.getBuffer( RenderTypes.PRINTOUT_TEXT ); for( int line = 0; line < LINES_PER_PAGE && line < text.length; line++ ) @@ -88,7 +88,7 @@ public final class PrintoutRenderer } } - public static void drawBorder( Matrix4f transform, VertexConsumerProvider renderer, float x, float y, float z, int page, int pages, boolean isBook, int light ) + public static void drawBorder( Matrix4f transform, MultiBufferSource renderer, float x, float y, float z, int page, int pages, boolean isBook, int light ) { int leftPages = page; int rightPages = pages - page - 1; @@ -173,6 +173,6 @@ public final class PrintoutRenderer private static void vertex( VertexConsumer buffer, Matrix4f matrix, float x, float y, float z, float u, float v, int light ) { - buffer.vertex( matrix, x, y, z ).color( 255, 255, 255, 255 ).texture( u, v ).light( light ).next(); + buffer.vertex( matrix, x, y, z ).color( 255, 255, 255, 255 ).uv( u, v ).uv2( light ).endVertex(); } } diff --git a/src/main/java/dan200/computercraft/client/render/RenderTypes.java b/src/main/java/dan200/computercraft/client/render/RenderTypes.java index cabc1c870..857bbd74f 100644 --- a/src/main/java/dan200/computercraft/client/render/RenderTypes.java +++ b/src/main/java/dan200/computercraft/client/render/RenderTypes.java @@ -5,9 +5,13 @@ */ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; import dan200.computercraft.client.gui.FixedWidthFontRenderer; -import net.minecraft.client.render.*; -import net.minecraft.util.Identifier; +import net.minecraft.client.renderer.RenderStateShard; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -21,17 +25,17 @@ public class RenderTypes public static MonitorTextureBufferShader monitorTboShader; @Nullable - public static Shader terminalShader; + public static ShaderInstance terminalShader; - public static final RenderLayer TERMINAL_WITHOUT_DEPTH = Types.TERMINAL_WITHOUT_DEPTH; - public static final RenderLayer MONITOR_TBO = Types.MONITOR_TBO; - public static final RenderLayer TERMINAL_BLOCKER = Types.BLOCKER; - public static final RenderLayer TERMINAL_WITH_DEPTH = Types.TERMINAL_WITH_DEPTH; - public static final RenderLayer PRINTOUT_TEXT = Types.PRINTOUT_TEXT; + public static final RenderType TERMINAL_WITHOUT_DEPTH = Types.TERMINAL_WITHOUT_DEPTH; + public static final RenderType MONITOR_TBO = Types.MONITOR_TBO; + public static final RenderType TERMINAL_BLOCKER = Types.BLOCKER; + public static final RenderType TERMINAL_WITH_DEPTH = Types.TERMINAL_WITH_DEPTH; + public static final RenderType PRINTOUT_TEXT = Types.PRINTOUT_TEXT; - public static final RenderLayer PRINTOUT_BACKGROUND = RenderLayer.getText( new Identifier( "computercraft", "textures/gui/printout.png" ) ); + public static final RenderType PRINTOUT_BACKGROUND = RenderType.text( new ResourceLocation( "computercraft", "textures/gui/printout.png" ) ); - public static final RenderLayer POSITION_COLOR = Types.POSITION_COLOR; + public static final RenderType POSITION_COLOR = Types.POSITION_COLOR; @Nonnull static MonitorTextureBufferShader getMonitorTextureBufferShader() @@ -41,72 +45,72 @@ public class RenderTypes } @Nonnull - static Shader getTerminalShader() + static ShaderInstance getTerminalShader() { if( terminalShader == null ) throw new NullPointerException( "MonitorTboShader has not been registered" ); return terminalShader; } - private static final class Types extends RenderPhase + private static final class Types extends RenderStateShard { - private static final VertexFormat.DrawMode GL_MODE = VertexFormat.DrawMode.TRIANGLES; - private static final VertexFormat FORMAT = VertexFormats.POSITION_COLOR_TEXTURE; - private static final Shader TERM_SHADER = new Shader( RenderTypes::getTerminalShader ); + private static final VertexFormat.Mode GL_MODE = VertexFormat.Mode.TRIANGLES; + private static final VertexFormat FORMAT = DefaultVertexFormat.POSITION_COLOR_TEX; + private static final ShaderStateShard TERM_SHADER = new ShaderStateShard( RenderTypes::getTerminalShader ); - private static final RenderPhase.Texture TERM_FONT_TEXTURE = new RenderPhase.Texture( + private static final RenderStateShard.TextureStateShard TERM_FONT_TEXTURE = new RenderStateShard.TextureStateShard( FixedWidthFontRenderer.FONT, false, false // blur, minimap ); - public static final RenderLayer MONITOR_TBO = RenderLayer.of( "monitor_tbo", VertexFormats.POSITION_TEXTURE, VertexFormat.DrawMode.TRIANGLE_STRIP, 128, false, false, // useDelegate, needsSorting - RenderLayer.MultiPhaseParameters.builder() - .texture( TERM_FONT_TEXTURE ) // blur, minimap - .shader( new RenderPhase.Shader( RenderTypes::getMonitorTextureBufferShader ) ) - .writeMaskState( RenderLayer.ALL_MASK ) - .build( false ) ); + public static final RenderType MONITOR_TBO = RenderType.create( "monitor_tbo", DefaultVertexFormat.POSITION_TEX, VertexFormat.Mode.TRIANGLE_STRIP, 128, false, false, // useDelegate, needsSorting + RenderType.CompositeState.builder() + .setTextureState( TERM_FONT_TEXTURE ) // blur, minimap + .setShaderState( new RenderStateShard.ShaderStateShard( RenderTypes::getMonitorTextureBufferShader ) ) + .setWriteMaskState( RenderType.COLOR_DEPTH_WRITE ) + .createCompositeState( false ) ); - static final RenderLayer TERMINAL_WITHOUT_DEPTH = RenderLayer.of( + static final RenderType TERMINAL_WITHOUT_DEPTH = RenderType.create( "terminal_without_depth", FORMAT, GL_MODE, 1024, false, false, // useDelegate, needsSorting - RenderLayer.MultiPhaseParameters.builder() - .texture( TERM_FONT_TEXTURE ) - .shader( TERM_SHADER ) - .writeMaskState( COLOR_MASK ) - .build( false ) + RenderType.CompositeState.builder() + .setTextureState( TERM_FONT_TEXTURE ) + .setShaderState( TERM_SHADER ) + .setWriteMaskState( COLOR_WRITE ) + .createCompositeState( false ) ); - static final RenderLayer BLOCKER = RenderLayer.of( "terminal_blocker", FORMAT, GL_MODE, 256, false, false, // useDelegate, needsSorting - RenderLayer.MultiPhaseParameters.builder() - .texture( TERM_FONT_TEXTURE ) - .shader( TERM_SHADER ) - .writeMaskState( DEPTH_MASK ) - .build( false ) ); + static final RenderType BLOCKER = RenderType.create( "terminal_blocker", FORMAT, GL_MODE, 256, false, false, // useDelegate, needsSorting + RenderType.CompositeState.builder() + .setTextureState( TERM_FONT_TEXTURE ) + .setShaderState( TERM_SHADER ) + .setWriteMaskState( DEPTH_WRITE ) + .createCompositeState( false ) ); - static final RenderLayer TERMINAL_WITH_DEPTH = RenderLayer.of( + static final RenderType TERMINAL_WITH_DEPTH = RenderType.create( "terminal_with_depth", FORMAT, GL_MODE, 1024, false, false, // useDelegate, needsSorting - RenderLayer.MultiPhaseParameters.builder() - .texture( TERM_FONT_TEXTURE ) - .shader( TERM_SHADER ) - .build( false ) + RenderType.CompositeState.builder() + .setTextureState( TERM_FONT_TEXTURE ) + .setShaderState( TERM_SHADER ) + .createCompositeState( false ) ); - static final RenderLayer PRINTOUT_TEXT = RenderLayer.of( - "printout_text", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT, GL_MODE, 1024, + static final RenderType PRINTOUT_TEXT = RenderType.create( + "printout_text", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, GL_MODE, 1024, false, false, // useDelegate, needsSorting - RenderLayer.MultiPhaseParameters.builder() - .texture( TERM_FONT_TEXTURE ) - .shader( RenderPhase.TEXT_SHADER ) - .lightmap( RenderPhase.ENABLE_LIGHTMAP ) - .build( false ) + RenderType.CompositeState.builder() + .setTextureState( TERM_FONT_TEXTURE ) + .setShaderState( RenderStateShard.RENDERTYPE_TEXT_SHADER ) + .setLightmapState( RenderStateShard.LIGHTMAP ) + .createCompositeState( false ) ); - static final RenderLayer POSITION_COLOR = RenderLayer.of( - "position_color", VertexFormats.POSITION_COLOR, VertexFormat.DrawMode.QUADS, 128, + static final RenderType POSITION_COLOR = RenderType.create( + "position_color", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 128, false, false, // useDelegate, needsSorting - RenderLayer.MultiPhaseParameters.builder() - .shader( COLOR_SHADER ) - .build( false ) + RenderType.CompositeState.builder() + .setShaderState( POSITION_COLOR_SHADER ) + .createCompositeState( false ) ); private Types( String name, Runnable setup, Runnable destroy ) diff --git a/src/main/java/dan200/computercraft/client/render/TileEntityMonitorRenderer.java b/src/main/java/dan200/computercraft/client/render/TileEntityMonitorRenderer.java index 6c8c0ab74..29c8ca657 100644 --- a/src/main/java/dan200/computercraft/client/render/TileEntityMonitorRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/TileEntityMonitorRenderer.java @@ -8,6 +8,10 @@ package dan200.computercraft.client.render; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.*; +import com.mojang.math.Matrix4f; +import com.mojang.math.Transformation; +import com.mojang.math.Vector3f; import dan200.computercraft.ComputerCraft; import dan200.computercraft.client.FrameInfo; import dan200.computercraft.client.gui.FixedWidthFontRenderer; @@ -18,12 +22,12 @@ import dan200.computercraft.shared.peripheral.monitor.MonitorRenderer; import dan200.computercraft.shared.peripheral.monitor.TileMonitor; import dan200.computercraft.shared.util.Colour; import dan200.computercraft.shared.util.DirectionUtil; -import net.minecraft.client.gl.VertexBuffer; -import net.minecraft.client.render.*; -import net.minecraft.client.render.block.entity.BlockEntityRenderer; -import net.minecraft.client.render.block.entity.BlockEntityRendererFactory; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.util.math.*; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL31; @@ -31,8 +35,8 @@ import org.lwjgl.opengl.GL31; import javax.annotation.Nonnull; import java.nio.ByteBuffer; +import static com.mojang.blaze3d.platform.MemoryTracker.create; import static dan200.computercraft.client.gui.FixedWidthFontRenderer.*; -import static net.minecraft.client.util.GlAllocationUtils.allocateByteBuffer; public class TileEntityMonitorRenderer implements BlockEntityRenderer { @@ -40,16 +44,17 @@ public class TileEntityMonitorRenderer implements BlockEntityRenderer { - private static final ModelIdentifier NORMAL_TURTLE_MODEL = new ModelIdentifier( "computercraft:turtle_normal", "inventory" ); - private static final ModelIdentifier ADVANCED_TURTLE_MODEL = new ModelIdentifier( "computercraft:turtle_advanced", "inventory" ); - private static final ModelIdentifier COLOUR_TURTLE_MODEL = new ModelIdentifier( "computercraft:turtle_colour", "inventory" ); - private static final ModelIdentifier ELF_OVERLAY_MODEL = new ModelIdentifier( "computercraft:turtle_elf_overlay", "inventory" ); + private static final ModelResourceLocation NORMAL_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_normal", "inventory" ); + private static final ModelResourceLocation ADVANCED_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_advanced", "inventory" ); + private static final ModelResourceLocation COLOUR_TURTLE_MODEL = new ModelResourceLocation( "computercraft:turtle_colour", "inventory" ); + private static final ModelResourceLocation ELF_OVERLAY_MODEL = new ModelResourceLocation( "computercraft:turtle_elf_overlay", "inventory" ); private final Random random = new Random( 0 ); BlockEntityRenderDispatcher renderer; - public TileEntityTurtleRenderer( BlockEntityRendererFactory.Context context ) + public TileEntityTurtleRenderer( BlockEntityRendererProvider.Context context ) { - renderer = context.getRenderDispatcher(); + renderer = context.getBlockEntityRenderDispatcher(); } - public static ModelIdentifier getTurtleModel( ComputerFamily family, boolean coloured ) + public static ModelResourceLocation getTurtleModel( ComputerFamily family, boolean coloured ) { switch( family ) { @@ -66,11 +66,11 @@ public class TileEntityTurtleRenderer implements BlockEntityRenderer } } - public static ModelIdentifier getTurtleOverlayModel( Identifier overlay, boolean christmas ) + public static ModelResourceLocation getTurtleOverlayModel( ResourceLocation overlay, boolean christmas ) { if( overlay != null ) { - return new ModelIdentifier( overlay, "inventory" ); + return new ModelResourceLocation( overlay, "inventory" ); } if( christmas ) { @@ -80,44 +80,44 @@ public class TileEntityTurtleRenderer implements BlockEntityRenderer } @Override - public void render( @Nonnull TileTurtle turtle, float partialTicks, @Nonnull MatrixStack transform, @Nonnull VertexConsumerProvider buffers, + public void render( @Nonnull TileTurtle turtle, float partialTicks, @Nonnull PoseStack transform, @Nonnull MultiBufferSource buffers, int lightmapCoord, int overlayLight ) { // Render the label String label = turtle.createProxy() .getLabel(); - HitResult hit = renderer.crosshairTarget; - if( label != null && hit.getType() == HitResult.Type.BLOCK && turtle.getPos() + HitResult hit = renderer.cameraHitResult; + if( label != null && hit.getType() == HitResult.Type.BLOCK && turtle.getBlockPos() .equals( ((BlockHitResult) hit).getBlockPos() ) ) { - MinecraftClient mc = MinecraftClient.getInstance(); - TextRenderer font = mc.textRenderer; + Minecraft mc = Minecraft.getInstance(); + Font font = mc.font; - transform.push(); + transform.pushPose(); transform.translate( 0.5, 1.2, 0.5 ); - transform.multiply( mc.getEntityRenderDispatcher() - .getRotation() ); + transform.mulPose( mc.getEntityRenderDispatcher() + .cameraOrientation() ); transform.scale( -0.025f, -0.025f, 0.025f ); - Matrix4f matrix = transform.peek() - .getModel(); - int opacity = (int) (mc.options.getTextBackgroundOpacity( 0.25f ) * 255) << 24; - float width = -font.getWidth( label ) / 2.0f; - font.draw( label, width, (float) 0, 0x20ffffff, false, matrix, buffers, true, opacity, lightmapCoord ); - font.draw( label, width, (float) 0, 0xffffffff, false, matrix, buffers, false, 0, lightmapCoord ); + Matrix4f matrix = transform.last() + .pose(); + int opacity = (int) (mc.options.getBackgroundOpacity( 0.25f ) * 255) << 24; + float width = -font.width( label ) / 2.0f; + font.drawInBatch( label, width, (float) 0, 0x20ffffff, false, matrix, buffers, true, opacity, lightmapCoord ); + font.drawInBatch( label, width, (float) 0, 0xffffffff, false, matrix, buffers, false, 0, lightmapCoord ); - transform.pop(); + transform.popPose(); } - transform.push(); + transform.pushPose(); // Setup the transform. - Vec3d offset = turtle.getRenderOffset( partialTicks ); + Vec3 offset = turtle.getRenderOffset( partialTicks ); float yaw = turtle.getRenderYaw( partialTicks ); transform.translate( offset.x, offset.y, offset.z ); transform.translate( 0.5f, 0.5f, 0.5f ); - transform.multiply( Vec3f.POSITIVE_Y.getDegreesQuaternion( 180.0f - yaw ) ); + transform.mulPose( Vector3f.YP.rotationDegrees( 180.0f - yaw ) ); if( label != null && (label.equals( "Dinnerbone" ) || label.equals( "Grumm" )) ) { // Flip the model @@ -128,13 +128,13 @@ public class TileEntityTurtleRenderer implements BlockEntityRenderer // Render the turtle int colour = turtle.getColour(); ComputerFamily family = turtle.getFamily(); - Identifier overlay = turtle.getOverlay(); + ResourceLocation overlay = turtle.getOverlay(); - VertexConsumer buffer = buffers.getBuffer( TexturedRenderLayers.getEntityTranslucentCull() ); + VertexConsumer buffer = buffers.getBuffer( Sheets.translucentCullBlockSheet() ); renderModel( transform, buffer, lightmapCoord, overlayLight, getTurtleModel( family, colour != -1 ), colour == -1 ? null : new int[] { colour } ); // Render the overlay - ModelIdentifier overlayModel = getTurtleOverlayModel( overlay, HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS ); + ModelResourceLocation overlayModel = getTurtleOverlayModel( overlay, HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS ); if( overlayModel != null ) { renderModel( transform, buffer, lightmapCoord, overlayLight, overlayModel, null ); @@ -144,44 +144,44 @@ public class TileEntityTurtleRenderer implements BlockEntityRenderer renderUpgrade( transform, buffer, lightmapCoord, overlayLight, turtle, TurtleSide.LEFT, partialTicks ); renderUpgrade( transform, buffer, lightmapCoord, overlayLight, turtle, TurtleSide.RIGHT, partialTicks ); - transform.pop(); + transform.popPose(); } - private void renderUpgrade( @Nonnull MatrixStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, TileTurtle turtle, - TurtleSide side, float f ) + private void renderUpgrade( @Nonnull PoseStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, TileTurtle turtle, + TurtleSide side, float f ) { ITurtleUpgrade upgrade = turtle.getUpgrade( side ); if( upgrade == null ) { return; } - transform.push(); + transform.pushPose(); float toolAngle = turtle.getToolRenderAngle( side, f ); transform.translate( 0.0f, 0.5f, 0.5f ); - transform.multiply( Vec3f.NEGATIVE_X.getDegreesQuaternion( toolAngle ) ); + transform.mulPose( Vector3f.XN.rotationDegrees( toolAngle ) ); transform.translate( 0.0f, -0.5f, -0.5f ); TransformedModel model = upgrade.getModel( turtle.getAccess(), side ); model.push( transform ); renderModel( transform, renderer, lightmapCoord, overlayLight, model.getModel(), null ); - transform.pop(); + transform.popPose(); - transform.pop(); + transform.popPose(); } - private void renderModel( @Nonnull MatrixStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, - ModelIdentifier modelLocation, int[] tints ) + private void renderModel( @Nonnull PoseStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, + ModelResourceLocation modelLocation, int[] tints ) { - BakedModelManager modelManager = MinecraftClient.getInstance() + ModelManager modelManager = Minecraft.getInstance() .getItemRenderer() - .getModels() + .getItemModelShaper() .getModelManager(); renderModel( transform, renderer, lightmapCoord, overlayLight, modelManager.getModel( modelLocation ), tints ); } - private void renderModel( @Nonnull MatrixStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, BakedModel model, - int[] tints ) + private void renderModel( @Nonnull PoseStack transform, @Nonnull VertexConsumer renderer, int lightmapCoord, int overlayLight, BakedModel model, + int[] tints ) { random.setSeed( 0 ); renderQuads( transform, renderer, lightmapCoord, overlayLight, model.getQuads( null, null, random ), tints ); @@ -191,27 +191,27 @@ public class TileEntityTurtleRenderer implements BlockEntityRenderer } } - private static void renderQuads( @Nonnull MatrixStack transform, @Nonnull VertexConsumer buffer, int lightmapCoord, int overlayLight, + private static void renderQuads( @Nonnull PoseStack transform, @Nonnull VertexConsumer buffer, int lightmapCoord, int overlayLight, List quads, int[] tints ) { - MatrixStack.Entry matrix = transform.peek(); + PoseStack.Pose matrix = transform.last(); for( BakedQuad bakedquad : quads ) { int tint = -1; - if( tints != null && bakedquad.hasColor() ) + if( tints != null && bakedquad.isTinted() ) { - int idx = bakedquad.getColorIndex(); + int idx = bakedquad.getTintIndex(); if( idx >= 0 && idx < tints.length ) { - tint = tints[bakedquad.getColorIndex()]; + tint = tints[bakedquad.getTintIndex()]; } } float f = (float) (tint >> 16 & 255) / 255.0F; float f1 = (float) (tint >> 8 & 255) / 255.0F; float f2 = (float) (tint & 255) / 255.0F; - buffer.quad( matrix, + buffer.putBulkData( matrix, bakedquad, new float[] { 1.0F, 1.0F, 1.0F, 1.0F }, f, diff --git a/src/main/java/dan200/computercraft/client/render/TurtleModelLoader.java b/src/main/java/dan200/computercraft/client/render/TurtleModelLoader.java index 1882ac2bd..01a32e812 100644 --- a/src/main/java/dan200/computercraft/client/render/TurtleModelLoader.java +++ b/src/main/java/dan200/computercraft/client/render/TurtleModelLoader.java @@ -10,13 +10,9 @@ import com.mojang.datafixers.util.Pair; import dan200.computercraft.ComputerCraft; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.ModelBakeSettings; -import net.minecraft.client.render.model.ModelLoader; -import net.minecraft.client.render.model.UnbakedModel; -import net.minecraft.client.texture.Sprite; -import net.minecraft.client.util.SpriteIdentifier; -import net.minecraft.util.Identifier; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.*; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; import java.util.Arrays; @@ -29,15 +25,15 @@ import java.util.stream.Collectors; public final class TurtleModelLoader { public static final TurtleModelLoader INSTANCE = new TurtleModelLoader(); - private static final Identifier NORMAL_TURTLE_MODEL = new Identifier( ComputerCraft.MOD_ID, "block/turtle_normal" ); - private static final Identifier ADVANCED_TURTLE_MODEL = new Identifier( ComputerCraft.MOD_ID, "block/turtle_advanced" ); - private static final Identifier COLOUR_TURTLE_MODEL = new Identifier( ComputerCraft.MOD_ID, "block/turtle_colour" ); + private static final ResourceLocation NORMAL_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_normal" ); + private static final ResourceLocation ADVANCED_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_advanced" ); + private static final ResourceLocation COLOUR_TURTLE_MODEL = new ResourceLocation( ComputerCraft.MOD_ID, "block/turtle_colour" ); private TurtleModelLoader() { } - public boolean accepts( @Nonnull Identifier name ) + public boolean accepts( @Nonnull ResourceLocation name ) { return name.getNamespace() .equals( ComputerCraft.MOD_ID ) && (name.getPath() @@ -46,7 +42,7 @@ public final class TurtleModelLoader } @Nonnull - public UnbakedModel loadModel( @Nonnull Identifier name ) + public UnbakedModel loadModel( @Nonnull ResourceLocation name ) { if( name.getNamespace() .equals( ComputerCraft.MOD_ID ) ) @@ -65,39 +61,39 @@ public final class TurtleModelLoader private static final class TurtleModel implements UnbakedModel { - private final Identifier family; + private final ResourceLocation family; - private TurtleModel( Identifier family ) + private TurtleModel( ResourceLocation family ) { this.family = family; } @Override - public Collection getTextureDependencies( Function modelGetter, - Set> missingTextureErrors ) + public Collection getMaterials( Function modelGetter, + Set> missingTextureErrors ) { - return getModelDependencies() + return getDependencies() .stream() .flatMap( x -> modelGetter.apply( x ) - .getTextureDependencies( modelGetter, missingTextureErrors ) + .getMaterials( modelGetter, missingTextureErrors ) .stream() ) .collect( Collectors.toSet() ); } @Nonnull @Override - public Collection getModelDependencies() + public Collection getDependencies() { return Arrays.asList( family, COLOUR_TURTLE_MODEL ); } @Override - public BakedModel bake( @Nonnull ModelLoader loader, @Nonnull Function spriteGetter, @Nonnull ModelBakeSettings state, - Identifier modelId ) + public BakedModel bake( @Nonnull ModelBakery loader, @Nonnull Function spriteGetter, @Nonnull ModelState state, + ResourceLocation modelId ) { - return new TurtleSmartItemModel( loader.getOrLoadModel( family ) + return new TurtleSmartItemModel( loader.getModel( family ) .bake( loader, spriteGetter, state, modelId ), - loader.getOrLoadModel( COLOUR_TURTLE_MODEL ) + loader.getModel( COLOUR_TURTLE_MODEL ) .bake( loader, spriteGetter, state, modelId ) ); } } diff --git a/src/main/java/dan200/computercraft/client/render/TurtleMultiModel.java b/src/main/java/dan200/computercraft/client/render/TurtleMultiModel.java index bc7a6e46b..7f364725e 100644 --- a/src/main/java/dan200/computercraft/client/render/TurtleMultiModel.java +++ b/src/main/java/dan200/computercraft/client/render/TurtleMultiModel.java @@ -6,17 +6,17 @@ package dan200.computercraft.client.render; +import com.mojang.math.Transformation; import dan200.computercraft.api.client.TransformedModel; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.block.BlockState; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.BakedQuad; -import net.minecraft.client.render.model.json.ModelOverrideList; -import net.minecraft.client.render.model.json.ModelTransformation; -import net.minecraft.client.texture.Sprite; -import net.minecraft.util.math.AffineTransformation; -import net.minecraft.util.math.Direction; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.block.model.ItemTransforms; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.core.Direction; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nonnull; import java.util.*; @@ -26,13 +26,13 @@ public class TurtleMultiModel implements BakedModel { private final BakedModel baseModel; private final BakedModel overlayModel; - private final AffineTransformation generalTransform; + private final Transformation generalTransform; private final TransformedModel leftUpgradeModel; private final TransformedModel rightUpgradeModel; private List generalQuads = null; private final Map> faceQuads = new EnumMap<>( Direction.class ); - public TurtleMultiModel( BakedModel baseModel, BakedModel overlayModel, AffineTransformation generalTransform, TransformedModel leftUpgradeModel, + public TurtleMultiModel( BakedModel baseModel, BakedModel overlayModel, Transformation generalTransform, TransformedModel leftUpgradeModel, TransformedModel rightUpgradeModel ) { // Get the models @@ -77,14 +77,14 @@ public class TurtleMultiModel implements BakedModel } if( leftUpgradeModel != null ) { - AffineTransformation upgradeTransform = generalTransform.multiply( leftUpgradeModel.getMatrix() ); + Transformation upgradeTransform = generalTransform.compose( leftUpgradeModel.getMatrix() ); ModelTransformer.transformQuadsTo( quads, leftUpgradeModel.getModel() .getQuads( state, side, rand ), upgradeTransform.getMatrix() ); } if( rightUpgradeModel != null ) { - AffineTransformation upgradeTransform = generalTransform.multiply( rightUpgradeModel.getMatrix() ); + Transformation upgradeTransform = generalTransform.compose( rightUpgradeModel.getMatrix() ); ModelTransformer.transformQuadsTo( quads, rightUpgradeModel.getModel() .getQuads( state, side, rand ), upgradeTransform.getMatrix() ); @@ -100,43 +100,43 @@ public class TurtleMultiModel implements BakedModel } @Override - public boolean hasDepth() + public boolean isGui3d() { - return baseModel.hasDepth(); + return baseModel.isGui3d(); } @Override - public boolean isSideLit() + public boolean usesBlockLight() { - return baseModel.isSideLit(); + return baseModel.usesBlockLight(); } @Override - public boolean isBuiltin() + public boolean isCustomRenderer() { - return baseModel.isBuiltin(); + return baseModel.isCustomRenderer(); } @Nonnull @Override @Deprecated - public Sprite getParticleSprite() + public TextureAtlasSprite getParticleIcon() { - return baseModel.getParticleSprite(); + return baseModel.getParticleIcon(); } @Nonnull @Override @Deprecated - public ModelTransformation getTransformation() + public ItemTransforms getTransforms() { - return baseModel.getTransformation(); + return baseModel.getTransforms(); } @Nonnull @Override - public ModelOverrideList getOverrides() + public ItemOverrides getOverrides() { - return ModelOverrideList.EMPTY; + return ItemOverrides.EMPTY; } } diff --git a/src/main/java/dan200/computercraft/client/render/TurtlePlayerRenderer.java b/src/main/java/dan200/computercraft/client/render/TurtlePlayerRenderer.java index 5b113f97a..047ebd0e1 100644 --- a/src/main/java/dan200/computercraft/client/render/TurtlePlayerRenderer.java +++ b/src/main/java/dan200/computercraft/client/render/TurtlePlayerRenderer.java @@ -5,31 +5,31 @@ */ package dan200.computercraft.client.render; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.shared.turtle.core.TurtlePlayer; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.EntityRenderer; -import net.minecraft.client.render.entity.EntityRendererFactory; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.util.Identifier; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.EntityRenderer; +import net.minecraft.client.renderer.entity.EntityRendererProvider; +import net.minecraft.resources.ResourceLocation; import javax.annotation.Nonnull; public class TurtlePlayerRenderer extends EntityRenderer { //FIXME Make sure this isn't an issue. Context was EntityRenderDispatcher. - public TurtlePlayerRenderer( EntityRendererFactory.Context context ) + public TurtlePlayerRenderer( EntityRendererProvider.Context context ) { super( context ); } @Override - public void render( @Nonnull TurtlePlayer entityIn, float entityYaw, float partialTicks, @Nonnull MatrixStack transform, - @Nonnull VertexConsumerProvider buffer, int packedLightIn ) + public void render( @Nonnull TurtlePlayer entityIn, float entityYaw, float partialTicks, @Nonnull PoseStack transform, + @Nonnull MultiBufferSource buffer, int packedLightIn ) { } @Nonnull @Override - public Identifier getTexture( @Nonnull TurtlePlayer entity ) + public ResourceLocation getTextureLocation( @Nonnull TurtlePlayer entity ) { return ComputerBorderRenderer.BACKGROUND_NORMAL; } diff --git a/src/main/java/dan200/computercraft/client/render/TurtleSmartItemModel.java b/src/main/java/dan200/computercraft/client/render/TurtleSmartItemModel.java index 077e78ad7..1b575234f 100644 --- a/src/main/java/dan200/computercraft/client/render/TurtleSmartItemModel.java +++ b/src/main/java/dan200/computercraft/client/render/TurtleSmartItemModel.java @@ -6,6 +6,8 @@ package dan200.computercraft.client.render; import com.google.common.base.Objects; +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; @@ -14,22 +16,20 @@ import dan200.computercraft.shared.util.Holiday; import dan200.computercraft.shared.util.HolidayUtil; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.block.BlockState; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.BakedModelManager; -import net.minecraft.client.render.model.BakedQuad; -import net.minecraft.client.render.model.json.ModelOverrideList; -import net.minecraft.client.render.model.json.ModelTransformation; -import net.minecraft.client.texture.Sprite; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.AffineTransformation; -import net.minecraft.util.math.Direction; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.block.model.ItemTransforms; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.ModelManager; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -41,17 +41,17 @@ import java.util.Random; @Environment( EnvType.CLIENT ) public class TurtleSmartItemModel implements BakedModel { - private static final AffineTransformation identity, flip; + private static final Transformation identity, flip; static { - MatrixStack stack = new MatrixStack(); + PoseStack stack = new PoseStack(); stack.scale( 0, -1, 0 ); stack.translate( 0, 0, 1 ); - identity = AffineTransformation.identity(); - flip = new AffineTransformation( stack.peek() - .getModel() ); + identity = Transformation.identity(); + flip = new Transformation( stack.last() + .pose() ); } private static class TurtleModelCombination @@ -59,11 +59,11 @@ public class TurtleSmartItemModel implements BakedModel final boolean colour; final ITurtleUpgrade leftUpgrade; final ITurtleUpgrade rightUpgrade; - final Identifier overlay; + final ResourceLocation overlay; final boolean christmas; final boolean flip; - TurtleModelCombination( boolean colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, Identifier overlay, boolean christmas, + TurtleModelCombination( boolean colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, ResourceLocation overlay, boolean christmas, boolean flip ) { this.colour = colour; @@ -109,7 +109,7 @@ public class TurtleSmartItemModel implements BakedModel private final BakedModel colourModel; private final HashMap cachedModels = new HashMap<>(); - private final ModelOverrideList overrides; + private final ItemOverrides overrides; public TurtleSmartItemModel( BakedModel familyModel, BakedModel colourModel ) { @@ -117,17 +117,17 @@ public class TurtleSmartItemModel implements BakedModel this.colourModel = colourModel; // this actually works I think, trust me - overrides = new ModelOverrideList( null, null, null, Collections.emptyList() ) + overrides = new ItemOverrides( null, null, null, Collections.emptyList() ) { @Nonnull @Override - public BakedModel apply( BakedModel originalModel, ItemStack stack, @Nullable ClientWorld world, @Nullable LivingEntity entity, int seed ) + public BakedModel resolve( BakedModel originalModel, ItemStack stack, @Nullable ClientLevel world, @Nullable LivingEntity entity, int seed ) { ItemTurtle turtle = (ItemTurtle) stack.getItem(); int colour = turtle.getColour( stack ); ITurtleUpgrade leftUpgrade = turtle.getUpgrade( stack, TurtleSide.LEFT ); ITurtleUpgrade rightUpgrade = turtle.getUpgrade( stack, TurtleSide.RIGHT ); - Identifier overlay = turtle.getOverlay( stack ); + ResourceLocation overlay = turtle.getOverlay( stack ); boolean christmas = HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS; String label = turtle.getLabel( stack ); boolean flip = label != null && (label.equals( "Dinnerbone" ) || label.equals( "Grumm" )); @@ -145,15 +145,15 @@ public class TurtleSmartItemModel implements BakedModel private BakedModel buildModel( TurtleModelCombination combo ) { - MinecraftClient mc = MinecraftClient.getInstance(); - BakedModelManager modelManager = mc.getItemRenderer() - .getModels() + Minecraft mc = Minecraft.getInstance(); + ModelManager modelManager = mc.getItemRenderer() + .getItemModelShaper() .getModelManager(); - ModelIdentifier overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.overlay, combo.christmas ); + ModelResourceLocation overlayModelLocation = TileEntityTurtleRenderer.getTurtleOverlayModel( combo.overlay, combo.christmas ); BakedModel baseModel = combo.colour ? colourModel : familyModel; BakedModel overlayModel = overlayModelLocation != null ? modelManager.getModel( overlayModelLocation ) : null; - AffineTransformation transform = combo.flip ? flip : identity; + Transformation transform = combo.flip ? flip : identity; TransformedModel leftModel = combo.leftUpgrade != null ? combo.leftUpgrade.getModel( null, TurtleSide.LEFT ) : null; TransformedModel rightModel = combo.rightUpgrade != null ? combo.rightUpgrade.getModel( null, TurtleSide.RIGHT ) : null; return new TurtleMultiModel( baseModel, overlayModel, transform, leftModel, rightModel ); @@ -174,33 +174,33 @@ public class TurtleSmartItemModel implements BakedModel } @Override - public boolean hasDepth() + public boolean isGui3d() { - return familyModel.hasDepth(); + return familyModel.isGui3d(); } @Override - public boolean isSideLit() + public boolean usesBlockLight() { - return familyModel.isSideLit(); + return familyModel.usesBlockLight(); } @Override - public boolean isBuiltin() + public boolean isCustomRenderer() { - return familyModel.isBuiltin(); + return familyModel.isCustomRenderer(); } @Override @Deprecated - public Sprite getParticleSprite() + public TextureAtlasSprite getParticleIcon() { - return familyModel.getParticleSprite(); + return familyModel.getParticleIcon(); } @Nonnull @Override - public ModelOverrideList getOverrides() + public ItemOverrides getOverrides() { return overrides; } @@ -208,9 +208,9 @@ public class TurtleSmartItemModel implements BakedModel @Nonnull @Override @Deprecated - public ModelTransformation getTransformation() + public ItemTransforms getTransforms() { - return familyModel.getTransformation(); + return familyModel.getTransforms(); } } diff --git a/src/main/java/dan200/computercraft/core/apis/ComputerAccess.java b/src/main/java/dan200/computercraft/core/apis/ComputerAccess.java index 77203c656..fdf68c141 100644 --- a/src/main/java/dan200/computercraft/core/apis/ComputerAccess.java +++ b/src/main/java/dan200/computercraft/core/apis/ComputerAccess.java @@ -35,6 +35,7 @@ public abstract class ComputerAccess implements IComputerAccess { ComputerCraft.log.warn( "Peripheral or API called mount but did not call unmount for {}", mounts ); } + for( String mount : mounts ) { fileSystem.unmount( mount ); diff --git a/src/main/java/dan200/computercraft/core/apis/FSAPI.java b/src/main/java/dan200/computercraft/core/apis/FSAPI.java index 6d1e5f2f6..9e1059545 100644 --- a/src/main/java/dan200/computercraft/core/apis/FSAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/FSAPI.java @@ -68,6 +68,13 @@ public class FSAPI implements ILuaAPI * @param path The path to list. * @return A table with a list of files in the directory. * @throws LuaException If the path doesn't exist. + * @cc.usage List all files under {@code /rom/} + *
    {@code
    +     * local files = fs.list("/rom/")
    +     * for i = 1, #files do
    +     *   print(files[i])
    +     * end
    +     * }
    */ @LuaFunction public final String[] list( String path ) throws LuaException @@ -92,6 +99,12 @@ public class FSAPI implements ILuaAPI * @throws LuaException On argument errors. * @cc.tparam string path The first part of the path. For example, a parent directory path. * @cc.tparam string ... Additional parts of the path to combine. + * @cc.changed 1.95.0 Now supports multiple arguments. + * @cc.usage Combine several file paths together + *
    {@code
    +     * fs.combine("/rom/programs", "../apis", "parallel.lua")
    +     * -- => rom/apis/parallel.lua
    +     * }
    */ @LuaFunction public final String combine( IArguments arguments ) throws LuaException @@ -114,6 +127,12 @@ public class FSAPI implements ILuaAPI * * @param path The path to get the name from. * @return The final part of the path (the file name). + * @cc.since 1.2 + * @cc.usage Get the file name of {@code rom/startup.lua} + *
    {@code
    +     * fs.getName("rom/startup.lua")
    +     * -- => startup.lua
    +     * }
    */ @LuaFunction public final String getName( String path ) @@ -126,6 +145,12 @@ public class FSAPI implements ILuaAPI * * @param path The path to get the directory from. * @return The path with the final part removed (the parent directory). + * @cc.since 1.63 + * @cc.usage Get the directory name of {@code rom/startup.lua} + *
    {@code
    +     * fs.getDir("rom/startup.lua")
    +     * -- => rom
    +     * }
    */ @LuaFunction public final String getDir( String path ) @@ -139,6 +164,7 @@ public class FSAPI implements ILuaAPI * @param path The file to get the file size of. * @return The size of the file, in bytes. * @throws LuaException If the path doesn't exist. + * @cc.since 1.3 */ @LuaFunction public final long getSize( String path ) throws LuaException @@ -304,10 +330,15 @@ public class FSAPI implements ILuaAPI /** * Opens a file for reading or writing at a path. * - * The mode parameter can be {@code r} to read, {@code w} to write (deleting - * all contents), or {@code a} to append (keeping contents). If {@code b} is - * added to the end, the file will be opened in binary mode; otherwise, it's - * opened in text mode. + * The {@code mode} string can be any of the following: + *
      + *
    • "r": Read mode
    • + *
    • "w": Write mode
    • + *
    • "a": Append mode
    • + *
    + * + * The mode may also have a "b" at the end, which opens the file in "binary + * mode". This allows you to read binary files, as well as seek within a file. * * @param path The path to the file to open. * @param mode The mode to open the file with. @@ -316,6 +347,37 @@ public class FSAPI implements ILuaAPI * @cc.treturn [1] table A file handle object for the file. * @cc.treturn [2] nil If the file does not exist, or cannot be opened. * @cc.treturn string|nil A message explaining why the file cannot be opened. + * @cc.usage Read the contents of a file. + *
    {@code
    +     * local file = fs.open("/rom/help/intro.txt", "r")
    +     * local contents = file.readAll()
    +     * file.close()
    +     *
    +     * print(contents)
    +     * }
    + * @cc.usage Open a file and read all lines into a table. @{io.lines} offers an alternative way to do this. + *
    {@code
    +     * local file = fs.open("/rom/motd.txt", "r")
    +     * local lines = {}
    +     * while true do
    +     *   local line = file.readLine()
    +     *
    +     *   -- If line is nil then we've reached the end of the file and should stop
    +     *   if not line then break end
    +     *
    +     *   lines[#lines + 1] = line
    +     * end
    +     *
    +     * file.close()
    +     *
    +     * print(lines[math.random(#lines)]) -- Pick a random line and print it.
    +     * }
    + * @cc.usage Open a file and write some text to it. You can run {@code edit out.txt} to see the written text. + *
    {@code
    +     * local file = fs.open("out.txt", "w")
    +     * file.write("Just testing some code")
    +     * file.close() -- Remember to call close, otherwise changes may not be written!
    +     * }
    */ @LuaFunction public final Object[] open( String path, String mode ) throws LuaException @@ -344,9 +406,11 @@ public class FSAPI implements ILuaAPI return new Object[] { new EncodedWritableHandle( writer.get(), writer ) }; } case "rb": + { // Open the file for binary reading, then create a wrapper around the reader FileSystemWrapper reader = fileSystem.openForRead( path, Function.identity() ); return new Object[] { BinaryReadableHandle.of( reader.get(), reader ) }; + } case "wb": { // Open the file for binary writing, then create a wrapper around the writer @@ -354,9 +418,11 @@ public class FSAPI implements ILuaAPI return new Object[] { BinaryWritableHandle.of( writer.get(), writer ) }; } case "ab": + { // Open the file for binary appending, then create a wrapper around the reader FileSystemWrapper writer = fileSystem.openForWrite( path, true, Function.identity() ); return new Object[] { BinaryWritableHandle.of( writer.get(), writer ) }; + } default: throw new LuaException( "Unsupported mode" ); } @@ -396,6 +462,8 @@ public class FSAPI implements ILuaAPI * @return The amount of free space available, in bytes. * @throws LuaException If the path doesn't exist. * @cc.treturn number|"unlimited" The amount of free space available, in bytes, or "unlimited". + * @cc.since 1.4 + * @see #getCapacity To get the capacity of this drive. */ @LuaFunction public final Object getFreeSpace( String path ) throws LuaException @@ -422,6 +490,7 @@ public class FSAPI implements ILuaAPI * @param path The wildcard-qualified path to search for. * @return A list of paths that match the search string. * @throws LuaException If the path doesn't exist. + * @cc.since 1.6 */ @LuaFunction public final String[] find( String path ) throws LuaException @@ -438,17 +507,15 @@ public class FSAPI implements ILuaAPI } /** - * Returns true if a path is mounted to the parent filesystem. - * - * The root filesystem "/" is considered a mount, along with disk folders and the rom folder. Other programs - * (such as network shares) can extend this to make other mount types by correctly assigning their return value for - * getDrive. + * Returns the capacity of the drive the path is located on. * * @param path The path of the drive to get. * @return The drive's capacity. * @throws LuaException If the capacity cannot be determined. * @cc.treturn number|nil This drive's capacity. This will be nil for "read-only" drives, such as the ROM or * treasure disks. + * @cc.since 1.87.0 + * @see #getFreeSpace To get the free space available on this drive. */ @LuaFunction public final Object getCapacity( String path ) throws LuaException @@ -477,6 +544,9 @@ public class FSAPI implements ILuaAPI * @return The resulting attributes. * @throws LuaException If the path does not exist. * @cc.treturn { size = number, isDir = boolean, isReadOnly = boolean, created = number, modified = number } The resulting attributes. + * @cc.since 1.87.0 + * @cc.changed 1.91.0 Renamed `modification` field to `modified`. + * @cc.changed 1.95.2 Added `isReadOnly` to attributes. * @see #getSize If you only care about the file's size. * @see #isDir If you only care whether a path is a directory or not. */ diff --git a/src/main/java/dan200/computercraft/core/apis/OSAPI.java b/src/main/java/dan200/computercraft/core/apis/OSAPI.java index 0ef4899bc..3140326d7 100644 --- a/src/main/java/dan200/computercraft/core/apis/OSAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/OSAPI.java @@ -204,14 +204,15 @@ public class OSAPI implements ILuaAPI } /** - * Sets an alarm that will fire at the specified world time. When it fires, - * an {@code alarm} event will be added to the event queue with the ID - * returned from this function as the first parameter. + * Sets an alarm that will fire at the specified in-game time. When it + * fires, * an {@code alarm} event will be added to the event queue with the + * ID * returned from this function as the first parameter. * * @param time The time at which to fire the alarm, in the range [0.0, 24.0). * @return The ID of the new alarm. This can be used to filter the * {@code alarm} event, or {@link #cancelAlarm cancel the alarm}. * @throws LuaException If the time is out of range. + * @cc.since 1.2 * @see #cancelAlarm To cancel an alarm. */ @LuaFunction @@ -232,6 +233,7 @@ public class OSAPI implements ILuaAPI * alarm from firing. * * @param token The ID of the alarm to cancel. + * @cc.since 1.2 * @see #setAlarm To set an alarm. */ @LuaFunction @@ -277,6 +279,7 @@ public class OSAPI implements ILuaAPI * * @return The label of the computer. * @cc.treturn string The label of the computer. + * @cc.since 1.3 */ @LuaFunction( { "getComputerLabel", "computerLabel" } ) public final Object[] getComputerLabel() @@ -289,6 +292,7 @@ public class OSAPI implements ILuaAPI * Set the label of this computer. * * @param label The new label. May be {@code nil} in order to clear it. + * @cc.since 1.3 */ @LuaFunction public final void setComputerLabel( Optional label ) @@ -300,6 +304,7 @@ public class OSAPI implements ILuaAPI * Returns the number of seconds that the computer has been running. * * @return The computer's uptime. + * @cc.since 1.2 */ @LuaFunction public final double clock() @@ -311,7 +316,7 @@ public class OSAPI implements ILuaAPI * Returns the current time depending on the string passed in. This will * always be in the range [0.0, 24.0). * - * * If called with {@code ingame}, the current world time will be returned. + * * If called with {@code dan200.computercraft.ingame}, the current world time will be returned. * This is the default if nothing is passed. * * If called with {@code utc}, returns the hour of the day in UTC time. * * If called with {@code local}, returns the hour of the day in the @@ -321,10 +326,19 @@ public class OSAPI implements ILuaAPI * which will convert the date fields into a UNIX timestamp (number of * seconds since 1 January 1970). * - * @param args The locale of the time, or a table filled by {@code os.date("*t")} to decode. Defaults to {@code ingame} locale if not specified. + * @param args The locale of the time, or a table filled by {@code os.date("*t")} to decode. Defaults to {@code dan200.computercraft.ingame} locale if not specified. * @return The hour of the selected locale, or a UNIX timestamp from the table, depending on the argument passed in. * @throws LuaException If an invalid locale is passed. - * @cc.tparam [opt] string|table locale The locale of the time, or a table filled by {@code os.date("*t")} to decode. Defaults to {@code ingame} locale if not specified. + * @cc.tparam [opt] string|table locale The locale of the time, or a table filled by {@code os.date("*t")} to decode. Defaults to {@code dan200.computercraft.ingame} locale if not specified. + * @cc.see textutils.formatTime To convert times into a user-readable string. + * @cc.usage Print the current in-game time. + *
    {@code
    +     * textutils.formatTime(os.time())
    +     * }
    + * @cc.since 1.2 + * @cc.changed 1.80pr1 Add support for getting the local local and UTC time. + * @cc.changed 1.82.0 Arguments are now case insensitive. + * @cc.changed 1.83.0 {@link #time(IArguments)} now accepts table arguments and converts them to UNIX timestamps. * @see #date To get a date table that can be converted with this function. */ @LuaFunction @@ -333,14 +347,14 @@ public class OSAPI implements ILuaAPI Object value = args.get( 0 ); if( value instanceof Map ) return LuaDateTime.fromTable( (Map) value ); - String param = args.optString( 0, "ingame" ); + String param = args.optString( 0, "dan200.computercraft.ingame" ); switch( param.toLowerCase( Locale.ROOT ) ) { case "utc": // Get Hour of day (UTC) return getTimeForCalendar( Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ) ); case "local": // Get Hour of day (local time) return getTimeForCalendar( Calendar.getInstance() ); - case "ingame": // Get in-game hour + case "dan200.computercraft.ingame": // Get in-game hour return time; default: throw new LuaException( "Unsupported operation" ); @@ -350,27 +364,29 @@ public class OSAPI implements ILuaAPI /** * Returns the day depending on the locale specified. * - * * If called with {@code ingame}, returns the number of days since the + * * If called with {@code dan200.computercraft.ingame}, returns the number of days since the * world was created. This is the default. * * If called with {@code utc}, returns the number of days since 1 January * 1970 in the UTC timezone. * * If called with {@code local}, returns the number of days since 1 * January 1970 in the server's local timezone. * - * @param args The locale to get the day for. Defaults to {@code ingame} if not set. + * @param args The locale to get the day for. Defaults to {@code dan200.computercraft.ingame} if not set. * @return The day depending on the selected locale. * @throws LuaException If an invalid locale is passed. + * @cc.since 1.48 + * @cc.changed 1.82.0 Arguments are now case insensitive. */ @LuaFunction public final int day( Optional args ) throws LuaException { - switch( args.orElse( "ingame" ).toLowerCase( Locale.ROOT ) ) + switch( args.orElse( "dan200.computercraft.ingame" ).toLowerCase( Locale.ROOT ) ) { case "utc": // Get numbers of days since 1970-01-01 (utc) return getDayForCalendar( Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ) ); case "local": // Get numbers of days since 1970-01-01 (local time) return getDayForCalendar( Calendar.getInstance() ); - case "ingame":// Get game day + case "dan200.computercraft.ingame":// Get game day return day; default: throw new LuaException( "Unsupported operation" ); @@ -380,21 +396,29 @@ public class OSAPI implements ILuaAPI /** * Returns the number of milliseconds since an epoch depending on the locale. * - * * If called with {@code ingame}, returns the number of milliseconds since the + * * If called with {@code dan200.computercraft.ingame}, returns the number of milliseconds since the * world was created. This is the default. * * If called with {@code utc}, returns the number of milliseconds since 1 * January 1970 in the UTC timezone. * * If called with {@code local}, returns the number of milliseconds since 1 * January 1970 in the server's local timezone. * - * @param args The locale to get the milliseconds for. Defaults to {@code ingame} if not set. + * @param args The locale to get the milliseconds for. Defaults to {@code dan200.computercraft.ingame} if not set. * @return The milliseconds since the epoch depending on the selected locale. * @throws LuaException If an invalid locale is passed. + * @cc.since 1.80pr1 + * @cc.usage Get the current time and use {@link #date} to convert it to a table. + *
    {@code
    +     * -- Dividing by 1000 converts it from milliseconds to seconds.
    +     * local time = os.epoch("local") / 1000
    +     * local time_table = os.date("*t", time)
    +     * print(textutils.serialize(time_table))
    +     * }
    */ @LuaFunction public final long epoch( Optional args ) throws LuaException { - switch( args.orElse( "ingame" ).toLowerCase( Locale.ROOT ) ) + switch( args.orElse( "dan200.computercraft.ingame" ).toLowerCase( Locale.ROOT ) ) { case "utc": { @@ -403,10 +427,12 @@ public class OSAPI implements ILuaAPI return getEpochForCalendar( c ); } case "local": + { // Get local epoch Calendar c = Calendar.getInstance(); return getEpochForCalendar( c ); - case "ingame": + } + case "dan200.computercraft.ingame": // Get in-game epoch synchronized( alarms ) { @@ -436,6 +462,11 @@ public class OSAPI implements ILuaAPI * @param timeA The time to convert to a string. This defaults to the current time. * @return The resulting format string. * @throws LuaException If an invalid format is passed. + * @cc.since 1.83.0 + * @cc.usage Print the current date in a user-friendly string. + *
    {@code
    +     * os.date("%A %d %B %Y") -- See the reference above!
    +     * }
    */ @LuaFunction public final Object date( Optional formatA, Optional timeA ) throws LuaException diff --git a/src/main/java/dan200/computercraft/core/apis/RedstoneAPI.java b/src/main/java/dan200/computercraft/core/apis/RedstoneAPI.java index 186199302..3fc1285d4 100644 --- a/src/main/java/dan200/computercraft/core/apis/RedstoneAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/RedstoneAPI.java @@ -30,15 +30,15 @@ import dan200.computercraft.core.computer.ComputerSide; * * @cc.usage Toggle the redstone signal above the computer every 0.5 seconds. * - *
    + * 
    {@code
      * while true do
      *   redstone.setOutput("top", not redstone.getOutput("top"))
      *   sleep(0.5)
      * end
    - * 
    + * }
    * @cc.usage Mimic a redstone comparator in [subtraction mode][comparator]. * - *
    + * 
    {@code
      * while true do
      *   local rear = rs.getAnalogueInput("back")
      *   local sides = math.max(rs.getAnalogueInput("left"), rs.getAnalogueInput("right"))
    @@ -46,7 +46,7 @@ import dan200.computercraft.core.computer.ComputerSide;
      *
      *   os.pullEvent("redstone") -- Wait for a change to inputs.
      * end
    - * 
    + * }
    * * [comparator]: https://minecraft.gamepedia.com/Redstone_Comparator#Subtract_signal_strength "Redstone Comparator on * the Minecraft wiki." @@ -72,6 +72,7 @@ public class RedstoneAPI implements ILuaAPI * "back". * * @return A table of valid sides. + * @cc.since 1.2 */ @LuaFunction public final String[] getSides() @@ -122,6 +123,7 @@ public class RedstoneAPI implements ILuaAPI * @param side The side to set. * @param value The signal strength between 0 and 15. * @throws LuaException If {@code value} is not betwene 0 and 15. + * @cc.since 1.51 */ @LuaFunction( { "setAnalogOutput", "setAnalogueOutput" } ) public final void setAnalogOutput( ComputerSide side, int value ) throws LuaException @@ -135,6 +137,7 @@ public class RedstoneAPI implements ILuaAPI * * @param side The side to get. * @return The output signal strength, between 0 and 15. + * @cc.since 1.51 * @see #setAnalogOutput */ @LuaFunction( { "getAnalogOutput", "getAnalogueOutput" } ) @@ -148,6 +151,7 @@ public class RedstoneAPI implements ILuaAPI * * @param side The side to get. * @return The input signal strength, between 0 and 15. + * @cc.since 1.51 */ @LuaFunction( { "getAnalogInput", "getAnalogueInput" } ) public final int getAnalogInput( ComputerSide side ) @@ -201,9 +205,9 @@ public class RedstoneAPI implements ILuaAPI * @param mask The mask to test. * @return If the colours are on. * @cc.usage Check if @{colors.white} and @{colors.black} are on above the computer. - *
    +     * 
    {@code
          * print(redstone.testBundledInput("top", colors.combine(colors.white, colors.black)))
    -     * 
    + * }
    * @see #getBundledInput */ @LuaFunction diff --git a/src/main/java/dan200/computercraft/core/apis/TermAPI.java b/src/main/java/dan200/computercraft/core/apis/TermAPI.java index 6b1816096..d0fa42ff1 100644 --- a/src/main/java/dan200/computercraft/core/apis/TermAPI.java +++ b/src/main/java/dan200/computercraft/core/apis/TermAPI.java @@ -46,6 +46,7 @@ public class TermAPI extends TermMethods implements ILuaAPI * @cc.treturn number The red channel, will be between 0 and 1. * @cc.treturn number The green channel, will be between 0 and 1. * @cc.treturn number The blue channel, will be between 0 and 1. + * @cc.since 1.81.0 * @see TermMethods#setPaletteColour(IArguments) To change the palette colour. */ @LuaFunction( { "nativePaletteColour", "nativePaletteColor" } ) diff --git a/src/main/java/dan200/computercraft/core/apis/TermMethods.java b/src/main/java/dan200/computercraft/core/apis/TermMethods.java index ce5545124..420c8fc95 100644 --- a/src/main/java/dan200/computercraft/core/apis/TermMethods.java +++ b/src/main/java/dan200/computercraft/core/apis/TermMethods.java @@ -112,6 +112,7 @@ public abstract class TermMethods * * @return If the cursor is blinking. * @throws LuaException (hidden) If the terminal cannot be found. + * @cc.since 1.80pr1.9 */ @LuaFunction public final boolean getCursorBlink() throws LuaException @@ -179,6 +180,7 @@ public abstract class TermMethods * @return The current text colour. * @throws LuaException (hidden) If the terminal cannot be found. * @cc.see colors For a list of colour constants, returned by this function. + * @cc.since 1.74 */ @LuaFunction( { "getTextColour", "getTextColor" } ) public final int getTextColour() throws LuaException @@ -192,6 +194,8 @@ public abstract class TermMethods * @param colourArg The new text colour. * @throws LuaException (hidden) If the terminal cannot be found. * @cc.see colors For a list of colour constants. + * @cc.since 1.45 + * @cc.changed 1.80pr1 Standard computers can now use all 16 colors, being changed to grayscale on screen. */ @LuaFunction( { "setTextColour", "setTextColor" } ) public final void setTextColour( int colourArg ) throws LuaException @@ -211,6 +215,7 @@ public abstract class TermMethods * @return The current background colour. * @throws LuaException (hidden) If the terminal cannot be found. * @cc.see colors For a list of colour constants, returned by this function. + * @cc.since 1.74 */ @LuaFunction( { "getBackgroundColour", "getBackgroundColor" } ) public final int getBackgroundColour() throws LuaException @@ -225,6 +230,8 @@ public abstract class TermMethods * @param colourArg The new background colour. * @throws LuaException (hidden) If the terminal cannot be found. * @cc.see colors For a list of colour constants. + * @cc.since 1.45 + * @cc.changed 1.80pr1 Standard computers can now use all 16 colors, being changed to grayscale on screen. */ @LuaFunction( { "setBackgroundColour", "setBackgroundColor" } ) public final void setBackgroundColour( int colourArg ) throws LuaException @@ -245,6 +252,7 @@ public abstract class TermMethods * * @return Whether this terminal supports colour. * @throws LuaException (hidden) If the terminal cannot be found. + * @cc.since 1.45 */ @LuaFunction( { "isColour", "isColor" } ) public final boolean getIsColour() throws LuaException @@ -267,6 +275,8 @@ public abstract class TermMethods * @param backgroundColour The corresponding background colours. * @throws LuaException If the three inputs are not the same length. * @cc.see colors For a list of colour constants, and their hexadecimal values. + * @cc.since 1.74 + * @cc.changed 1.80pr1 Standard computers can now use all 16 colors, being changed to grayscale on screen. * @cc.usage Prints "Hello, world!" in rainbow text. *
    {@code
          * term.blit("Hello, world!","01234456789ab","0000000000000")
    @@ -319,6 +329,7 @@ public abstract class TermMethods
          * }
    * @cc.see colors.unpackRGB To convert from the 24-bit format to three separate channels. * @cc.see colors.packRGB To convert from three separate channels to the 24-bit format. + * @cc.since 1.80pr1 */ @LuaFunction( { "setPaletteColour", "setPaletteColor" } ) public final void setPaletteColour( IArguments args ) throws LuaException @@ -348,6 +359,7 @@ public abstract class TermMethods * @cc.treturn number The red channel, will be between 0 and 1. * @cc.treturn number The green channel, will be between 0 and 1. * @cc.treturn number The blue channel, will be between 0 and 1. + * @cc.since 1.80pr1 */ @LuaFunction( { "getPaletteColour", "getPaletteColor" } ) public final Object[] getPaletteColour( int colourArg ) throws LuaException diff --git a/src/main/java/dan200/computercraft/core/apis/handles/BinaryReadableHandle.java b/src/main/java/dan200/computercraft/core/apis/handles/BinaryReadableHandle.java index 4477dde92..b026aa750 100644 --- a/src/main/java/dan200/computercraft/core/apis/handles/BinaryReadableHandle.java +++ b/src/main/java/dan200/computercraft/core/apis/handles/BinaryReadableHandle.java @@ -61,6 +61,7 @@ public class BinaryReadableHandle extends HandleGeneric * @cc.treturn [1] nil If we are at the end of the file. * @cc.treturn [2] number The value of the byte read. This is returned when the {@code count} is absent. * @cc.treturn [3] string The bytes read as a string. This is returned when the {@code count} is given. + * @cc.changed 1.80pr1 Now accepts an integer argument to read multiple bytes, returning a string instead of a number. */ @LuaFunction public final Object[] read( Optional countArg ) throws LuaException @@ -145,6 +146,7 @@ public class BinaryReadableHandle extends HandleGeneric * @return The file, or {@code null} if at the end of it. * @throws LuaException If the file has been closed. * @cc.treturn string|nil The remaining contents of the file, or {@code nil} if we are at the end. + * @cc.since 1.80pr1 */ @LuaFunction public final Object[] readAll() throws LuaException @@ -182,6 +184,8 @@ public class BinaryReadableHandle extends HandleGeneric * @return The read string. * @throws LuaException If the file has been closed. * @cc.treturn string|nil The read line or {@code nil} if at the end of the file. + * @cc.since 1.80pr1.9 + * @cc.changed 1.81.0 `\r` is now stripped. */ @LuaFunction public final Object[] readLine( Optional withTrailingArg ) throws LuaException @@ -259,6 +263,7 @@ public class BinaryReadableHandle extends HandleGeneric * @cc.treturn [1] number The new position. * @cc.treturn [2] nil If seeking failed. * @cc.treturn string The reason seeking failed. + * @cc.since 1.80pr1.9 */ @LuaFunction public final Object[] seek( Optional whence, Optional offset ) throws LuaException diff --git a/src/main/java/dan200/computercraft/core/apis/handles/BinaryWritableHandle.java b/src/main/java/dan200/computercraft/core/apis/handles/BinaryWritableHandle.java index 796582855..39e234648 100644 --- a/src/main/java/dan200/computercraft/core/apis/handles/BinaryWritableHandle.java +++ b/src/main/java/dan200/computercraft/core/apis/handles/BinaryWritableHandle.java @@ -55,6 +55,7 @@ public class BinaryWritableHandle extends HandleGeneric * @throws LuaException If the file has been closed. * @cc.tparam [1] number The byte to write. * @cc.tparam [2] string The string to write. + * @cc.changed 1.80pr1 Now accepts a string to write multiple bytes. */ @LuaFunction public final void write( IArguments arguments ) throws LuaException @@ -130,6 +131,7 @@ public class BinaryWritableHandle extends HandleGeneric * @cc.treturn [1] number The new position. * @cc.treturn [2] nil If seeking failed. * @cc.treturn string The reason seeking failed. + * @cc.since 1.80pr1.9 */ @LuaFunction public final Object[] seek( Optional whence, Optional offset ) throws LuaException diff --git a/src/main/java/dan200/computercraft/core/apis/handles/EncodedReadableHandle.java b/src/main/java/dan200/computercraft/core/apis/handles/EncodedReadableHandle.java index 28576f70d..27e1b7083 100644 --- a/src/main/java/dan200/computercraft/core/apis/handles/EncodedReadableHandle.java +++ b/src/main/java/dan200/computercraft/core/apis/handles/EncodedReadableHandle.java @@ -50,6 +50,7 @@ public class EncodedReadableHandle extends HandleGeneric * @return The read string. * @throws LuaException If the file has been closed. * @cc.treturn string|nil The read line or {@code nil} if at the end of the file. + * @cc.changed 1.81.0 Added option to return trailing newline. */ @LuaFunction public final Object[] readLine( Optional withTrailingArg ) throws LuaException @@ -116,6 +117,7 @@ public class EncodedReadableHandle extends HandleGeneric * @throws LuaException When trying to read a negative number of characters. * @throws LuaException If the file has been closed. * @cc.treturn string|nil The read characters, or {@code nil} if at the of the file. + * @cc.since 1.80pr1.4 */ @LuaFunction public final Object[] read( Optional countA ) throws LuaException diff --git a/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java b/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java index ffd895b0b..d5b1b18f2 100644 --- a/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java +++ b/src/main/java/dan200/computercraft/core/apis/http/NetworkUtils.java @@ -201,7 +201,7 @@ public final class NetworkUtils { return "Timed out"; } - else if( cause instanceof SSLHandshakeException || cause instanceof DecoderException && cause.getCause() instanceof SSLHandshakeException ) + else if( cause instanceof SSLHandshakeException || (cause instanceof DecoderException && cause.getCause() instanceof SSLHandshakeException) ) { return "Could not create a secure connection"; } diff --git a/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java b/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java index 13365b453..955e89d4d 100644 --- a/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java +++ b/src/main/java/dan200/computercraft/core/apis/http/options/AddressRule.java @@ -75,7 +75,7 @@ public final class AddressRule if( this.port != null && this.port != port ) return false; return predicate.matches( domain ) || predicate.matches( address ) - || ipv4Address != null && predicate.matches( ipv4Address ); + || (ipv4Address != null && predicate.matches( ipv4Address )); } public static Options apply( Iterable rules, String domain, InetSocketAddress socketAddress ) diff --git a/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java b/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java index c5d72134b..4dcd82c9b 100644 --- a/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java +++ b/src/main/java/dan200/computercraft/core/apis/http/request/HttpResponseHandle.java @@ -46,6 +46,7 @@ public class HttpResponseHandle implements ObjectSource * @return The response code and message. * @cc.treturn number The response code (i.e. 200) * @cc.treturn string The response message (i.e. "OK") + * @cc.changed 1.80pr1.13 Added response message return value. */ @LuaFunction public final Object[] getResponseCode() diff --git a/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandle.java b/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandle.java index 0c74c0c9f..0901cc25e 100644 --- a/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandle.java +++ b/src/main/java/dan200/computercraft/core/apis/http/websocket/WebsocketHandle.java @@ -55,6 +55,8 @@ public class WebsocketHandle implements Closeable * @cc.treturn [1] string The received message. * @cc.treturn boolean If this was a binary message. * @cc.treturn [2] nil If the websocket was closed while waiting, or if we timed out. + * @cc.changed 1.80pr1.13 Added return value indicating whether the message was binary. + * @cc.changed 1.87.0 Added timeout argument. */ @LuaFunction public final MethodResult receive( Optional timeout ) throws LuaException @@ -74,6 +76,7 @@ public class WebsocketHandle implements Closeable * @param binary Whether this message should be treated as a * @throws LuaException If the message is too large. * @throws LuaException If the websocket has been closed. + * @cc.changed 1.81.0 Added argument for binary mode. */ @LuaFunction public final void send( Object message, Optional binary ) throws LuaException diff --git a/src/main/java/dan200/computercraft/core/asm/Generator.java b/src/main/java/dan200/computercraft/core/asm/Generator.java index e68732f95..4cd2d66cf 100644 --- a/src/main/java/dan200/computercraft/core/asm/Generator.java +++ b/src/main/java/dan200/computercraft/core/asm/Generator.java @@ -15,6 +15,7 @@ import dan200.computercraft.api.lua.IArguments; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.lua.MethodResult; +import dan200.computercraft.api.peripheral.PeripheralType; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; @@ -108,7 +109,7 @@ public final class Generator if( instance == null ) continue; if( methods == null ) methods = new ArrayList<>(); - addMethod( methods, method, annotation, instance ); + addMethod( methods, method, annotation, null, instance ); } for( GenericMethod method : GenericMethod.all() ) @@ -119,7 +120,7 @@ public final class Generator if( instance == null ) continue; if( methods == null ) methods = new ArrayList<>(); - addMethod( methods, method.method, method.annotation, instance ); + addMethod( methods, method.method, method.annotation, method.peripheralType, instance ); } if( methods == null ) return Collections.emptyList(); @@ -127,7 +128,7 @@ public final class Generator return Collections.unmodifiableList( methods ); } - private void addMethod( List> methods, Method method, LuaFunction annotation, T instance ) + private void addMethod( List> methods, Method method, LuaFunction annotation, PeripheralType genericType, T instance ) { if( annotation.mainThread() ) instance = wrap.apply( instance ); @@ -135,13 +136,13 @@ public final class Generator boolean isSimple = method.getReturnType() != MethodResult.class && !annotation.mainThread(); if( names.length == 0 ) { - methods.add( new NamedMethod<>( method.getName(), instance, isSimple ) ); + methods.add( new NamedMethod<>( method.getName(), instance, isSimple, genericType ) ); } else { for( String name : names ) { - methods.add( new NamedMethod<>( name, instance, isSimple ) ); + methods.add( new NamedMethod<>( name, instance, isSimple, genericType ) ); } } } diff --git a/src/main/java/dan200/computercraft/core/asm/GenericMethod.java b/src/main/java/dan200/computercraft/core/asm/GenericMethod.java index e0c916c2e..691d9b742 100644 --- a/src/main/java/dan200/computercraft/core/asm/GenericMethod.java +++ b/src/main/java/dan200/computercraft/core/asm/GenericMethod.java @@ -8,6 +8,8 @@ package dan200.computercraft.core.asm; import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.lua.GenericSource; import dan200.computercraft.api.lua.LuaFunction; +import dan200.computercraft.api.peripheral.GenericPeripheral; +import dan200.computercraft.api.peripheral.PeripheralType; import javax.annotation.Nonnull; import java.lang.reflect.Method; @@ -18,6 +20,7 @@ import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; +import java.util.stream.Stream; /** * A generic method is a method belonging to a {@link GenericSource} with a known target. @@ -27,15 +30,17 @@ public class GenericMethod final Method method; final LuaFunction annotation; final Class target; + final PeripheralType peripheralType; private static final List sources = new ArrayList<>(); private static List cache; - GenericMethod( Method method, LuaFunction annotation, Class target ) + GenericMethod( Method method, LuaFunction annotation, Class target, PeripheralType peripheralType ) { this.method = method; this.annotation = annotation; this.target = target; + this.peripheralType = peripheralType; } /** @@ -46,10 +51,28 @@ public class GenericMethod static List all() { if( cache != null ) return cache; - return cache = sources.stream() - .flatMap( x -> Arrays.stream( x.getClass().getDeclaredMethods() ) ) - .map( method -> - { + return cache = sources.stream().flatMap( GenericMethod::getMethods ).collect( Collectors.toList() ); + } + + public static synchronized void register( @Nonnull GenericSource source ) + { + Objects.requireNonNull( source, "Source cannot be null" ); + + if( cache != null ) + { + ComputerCraft.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 ) + { + Class klass = source.getClass(); + PeripheralType type = source instanceof GenericPeripheral ? ((GenericPeripheral) source).getType() : null; + + return Arrays.stream( klass.getDeclaredMethods() ) + .map( method -> { LuaFunction annotation = method.getAnnotation( LuaFunction.class ); if( annotation == null ) return null; @@ -69,22 +92,8 @@ public class GenericMethod Class target = Reflect.getRawType( method, types[0], false ); if( target == null ) return null; - return new GenericMethod( method, annotation, target ); + return new GenericMethod( method, annotation, target, type ); } ) - .filter( Objects::nonNull ) - .collect( Collectors.toList() ); - } - - - public static synchronized void register( @Nonnull GenericSource source ) - { - Objects.requireNonNull( source, "Source cannot be null" ); - - if( cache != null ) - { - ComputerCraft.log.warn( "Registering a generic source {} after cache has been built. This source will be ignored.", cache ); - } - - sources.add( source ); + .filter( Objects::nonNull ); } } diff --git a/src/main/java/dan200/computercraft/core/asm/LuaMethod.java b/src/main/java/dan200/computercraft/core/asm/LuaMethod.java index b0562835c..281ab9c56 100644 --- a/src/main/java/dan200/computercraft/core/asm/LuaMethod.java +++ b/src/main/java/dan200/computercraft/core/asm/LuaMethod.java @@ -13,7 +13,7 @@ import java.util.Collections; public interface LuaMethod { Generator GENERATOR = new Generator<>( LuaMethod.class, Collections.singletonList( ILuaContext.class ), - m -> ( target, context, args ) -> TaskCallback.make( context, () -> TaskCallback.checkUnwrap( m.apply( target, context, args ) ) ) + m -> ( target, context, args ) -> context.executeMainThreadTask( () -> ResultHelpers.checkNormalResult( m.apply( target, context, args ) ) ) ); IntCache DYNAMIC = new IntCache<>( diff --git a/src/main/java/dan200/computercraft/core/asm/NamedMethod.java b/src/main/java/dan200/computercraft/core/asm/NamedMethod.java index ea72bb7a4..35d9c0a77 100644 --- a/src/main/java/dan200/computercraft/core/asm/NamedMethod.java +++ b/src/main/java/dan200/computercraft/core/asm/NamedMethod.java @@ -5,7 +5,10 @@ */ package dan200.computercraft.core.asm; +import dan200.computercraft.api.peripheral.PeripheralType; + import javax.annotation.Nonnull; +import javax.annotation.Nullable; public final class NamedMethod { @@ -13,11 +16,14 @@ public final class NamedMethod private final T method; private final boolean nonYielding; - NamedMethod( String name, T method, boolean nonYielding ) + private final PeripheralType genericType; + + NamedMethod( String name, T method, boolean nonYielding, PeripheralType genericType ) { this.name = name; this.method = method; this.nonYielding = nonYielding; + this.genericType = genericType; } @Nonnull @@ -36,4 +42,10 @@ public final class NamedMethod { return nonYielding; } + + @Nullable + public PeripheralType getGenericType() + { + return genericType; + } } diff --git a/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java b/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java index 38618442f..146896b04 100644 --- a/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java +++ b/src/main/java/dan200/computercraft/core/asm/PeripheralMethod.java @@ -18,7 +18,7 @@ import java.util.Arrays; public interface PeripheralMethod { Generator GENERATOR = new Generator<>( PeripheralMethod.class, Arrays.asList( ILuaContext.class, IComputerAccess.class ), - m -> ( target, context, computer, args ) -> TaskCallback.make( context, () -> TaskCallback.checkUnwrap( m.apply( target, context, computer, args ) ) ) + m -> ( target, context, computer, args ) -> context.executeMainThreadTask( () -> ResultHelpers.checkNormalResult( m.apply( target, context, computer, args ) ) ) ); IntCache DYNAMIC = new IntCache<>( diff --git a/src/main/java/dan200/computercraft/core/asm/ResultHelpers.java b/src/main/java/dan200/computercraft/core/asm/ResultHelpers.java new file mode 100644 index 000000000..7b9b464b2 --- /dev/null +++ b/src/main/java/dan200/computercraft/core/asm/ResultHelpers.java @@ -0,0 +1,27 @@ +/* + * This file is part of ComputerCraft - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. + * Send enquiries to dratcliffe@gmail.com + */ +package dan200.computercraft.core.asm; + +import dan200.computercraft.api.lua.MethodResult; + +final class ResultHelpers +{ + private ResultHelpers() + { + } + + static Object[] checkNormalResult( MethodResult result ) + { + if( result.getCallback() != null ) + { + // Due to how tasks are implemented, we can't currently return a MethodResult. This is an + // entirely artificial limitation - we can remove it if it ever becomes an issue. + throw new IllegalStateException( "Must return MethodResult.of from mainThread function." ); + } + + return result.getResult(); + } +} diff --git a/src/main/java/dan200/computercraft/core/computer/ComputerSide.java b/src/main/java/dan200/computercraft/core/computer/ComputerSide.java index dd925b324..484b361f7 100644 --- a/src/main/java/dan200/computercraft/core/computer/ComputerSide.java +++ b/src/main/java/dan200/computercraft/core/computer/ComputerSide.java @@ -5,7 +5,7 @@ */ package dan200.computercraft.core.computer; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/src/main/java/dan200/computercraft/core/computer/Environment.java b/src/main/java/dan200/computercraft/core/computer/Environment.java index ecc8aea80..3931629f1 100644 --- a/src/main/java/dan200/computercraft/core/computer/Environment.java +++ b/src/main/java/dan200/computercraft/core/computer/Environment.java @@ -309,9 +309,9 @@ public final class Environment implements IAPIEnvironment { int index = side.ordinal(); IPeripheral existing = peripherals[index]; - if( existing == null && peripheral != null || - existing != null && peripheral == null || - existing != null && !existing.equals( peripheral ) ) + if( (existing == null && peripheral != null) || + (existing != null && peripheral == null) || + (existing != null && !existing.equals( peripheral )) ) { peripherals[index] = peripheral; if( peripheralListener != null ) peripheralListener.onPeripheralChanged( side, peripheral ); diff --git a/src/main/java/dan200/computercraft/core/computer/MainThread.java b/src/main/java/dan200/computercraft/core/computer/MainThread.java index 8f53541e2..1c77e3692 100644 --- a/src/main/java/dan200/computercraft/core/computer/MainThread.java +++ b/src/main/java/dan200/computercraft/core/computer/MainThread.java @@ -93,7 +93,7 @@ public final class MainThread executor.updateTime(); // We're not currently on the queue, so update its current execution time to - // ensure its at least as high as the minimum. + // ensure it's at least as high as the minimum. long newRuntime = minimumTime; // Slow down new computers a little bit. diff --git a/src/main/java/dan200/computercraft/core/computer/MainThreadExecutor.java b/src/main/java/dan200/computercraft/core/computer/MainThreadExecutor.java index 07737c4c2..301a9a606 100644 --- a/src/main/java/dan200/computercraft/core/computer/MainThreadExecutor.java +++ b/src/main/java/dan200/computercraft/core/computer/MainThreadExecutor.java @@ -9,7 +9,7 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.peripheral.IWorkMonitor; import dan200.computercraft.core.tracking.Tracking; import dan200.computercraft.shared.turtle.core.TurtleBrain; -import net.minecraft.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntity; import javax.annotation.Nonnull; import java.util.ArrayDeque; diff --git a/src/main/java/dan200/computercraft/core/filesystem/ResourceMount.java b/src/main/java/dan200/computercraft/core/filesystem/ResourceMount.java index b46fc0dcd..d31757cda 100644 --- a/src/main/java/dan200/computercraft/core/filesystem/ResourceMount.java +++ b/src/main/java/dan200/computercraft/core/filesystem/ResourceMount.java @@ -7,18 +7,18 @@ package dan200.computercraft.core.filesystem; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; -import com.google.common.collect.MapMaker; import com.google.common.io.ByteStreams; import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.filesystem.IMount; import dan200.computercraft.core.apis.handles.ArrayByteChannel; import dan200.computercraft.shared.util.IoUtil; -import net.minecraft.resource.ReloadableResourceManager; -import net.minecraft.resource.Resource; -import net.minecraft.resource.ResourceManager; -import net.minecraft.resource.SynchronousResourceReloader; -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; +import net.minecraft.ResourceLocationException; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.SimplePreparableReloadListener; +import net.minecraft.util.profiling.ProfilerFiller; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -27,7 +27,9 @@ import java.io.IOException; import java.io.InputStream; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.TimeUnit; public final class ResourceMount implements IMount @@ -56,56 +58,43 @@ public final class ResourceMount implements IMount .weigher( ( k, v ) -> v.length ) .build(); - private static final MapMaker CACHE_TEMPLATE = new MapMaker().weakValues().concurrencyLevel( 1 ); - /** * Maintain a cache of currently loaded resource mounts. This cache is invalidated when currentManager changes. */ - private static final Map> MOUNT_CACHE = new WeakHashMap<>( 2 ); + private static final Map MOUNT_CACHE = new HashMap<>( 2 ); private final String namespace; private final String subPath; - private final ReloadableResourceManager manager; + private ResourceManager manager; @Nullable private FileEntry root; - public static ResourceMount get( String namespace, String subPath, ReloadableResourceManager manager ) + public static ResourceMount get( String namespace, String subPath, ResourceManager manager ) { - Map cache; - + ResourceLocation path = new ResourceLocation( namespace, subPath ); synchronized( MOUNT_CACHE ) { - cache = MOUNT_CACHE.get( manager ); - if( cache == null ) MOUNT_CACHE.put( manager, cache = CACHE_TEMPLATE.makeMap() ); - } - - Identifier path = new Identifier( namespace, subPath ); - synchronized( cache ) - { - ResourceMount mount = cache.get( path ); - if( mount == null ) cache.put( path, mount = new ResourceMount( namespace, subPath, manager ) ); + ResourceMount mount = MOUNT_CACHE.get( path ); + if( mount == null ) MOUNT_CACHE.put( path, mount = new ResourceMount( namespace, subPath, manager ) ); return mount; } } - private ResourceMount( String namespace, String subPath, ReloadableResourceManager manager ) + private ResourceMount( String namespace, String subPath, ResourceManager manager ) { this.namespace = namespace; this.subPath = subPath; - this.manager = manager; - - Listener.INSTANCE.add( manager, this ); - if( root == null ) load(); + load( manager ); } - private void load() + private void load( ResourceManager manager ) { boolean hasAny = false; String existingNamespace = null; - FileEntry newRoot = new FileEntry( new Identifier( namespace, subPath ) ); - for( Identifier file : manager.findResources( subPath, s -> true ) ) + FileEntry newRoot = new FileEntry( new ResourceLocation( namespace, subPath ) ); + for( ResourceLocation file : manager.listResources( subPath, s -> true ) ) { existingNamespace = file.getNamespace(); @@ -117,6 +106,7 @@ public final class ResourceMount implements IMount hasAny = true; } + this.manager = manager; root = hasAny ? newRoot : null; if( !hasAny ) @@ -160,12 +150,12 @@ public final class ResourceMount implements IMount FileEntry nextEntry = lastEntry.children.get( part ); if( nextEntry == null ) { - Identifier childPath; + ResourceLocation childPath; try { - childPath = new Identifier( namespace, subPath + "/" + path ); + childPath = new ResourceLocation( namespace, subPath + "/" + path ); } - catch( InvalidIdentifierException e ) + catch( ResourceLocationException e ) { ComputerCraft.log.warn( "Cannot create resource location for {} ({})", part, e.getMessage() ); return; @@ -271,11 +261,11 @@ public final class ResourceMount implements IMount private static class FileEntry { - final Identifier identifier; + final ResourceLocation identifier; Map children; long size = -1; - FileEntry( Identifier identifier ) + FileEntry( ResourceLocation identifier ) { this.identifier = identifier; } @@ -292,28 +282,30 @@ public final class ResourceMount implements IMount } /** - * A {@link ResourceReloader} which reloads any associated mounts. - * - * While people should really be keeping a permanent reference to this, some people construct it every - * method call, so let's make this as small as possible. + * A {@link PreparableReloadListener} which reloads any associated mounts and correctly updates the resource manager + * they point to. */ - static class Listener implements SynchronousResourceReloader + public static final SimplePreparableReloadListener RELOAD_LISTENER = new SimplePreparableReloadListener<>() { - private static final Listener INSTANCE = new Listener(); - - private final Set mounts = Collections.newSetFromMap( new WeakHashMap<>() ); - private final Set managers = Collections.newSetFromMap( new WeakHashMap<>() ); + @Nonnull + @Override + protected Void prepare( @Nonnull ResourceManager manager, @Nonnull ProfilerFiller profiler ) + { + profiler.push( "Reloading ComputerCraft mounts" ); + try + { + for( ResourceMount mount : MOUNT_CACHE.values() ) mount.load( manager ); + } + finally + { + profiler.pop(); + } + return null; + } @Override - public void reload( @Nonnull ResourceManager manager ) + protected void apply( @Nonnull Void result, @Nonnull ResourceManager manager, @Nonnull ProfilerFiller profiler ) { - for( ResourceMount mount : mounts ) mount.load(); } - - synchronized void add( ReloadableResourceManager manager, ResourceMount mount ) - { - if( managers.add( manager ) ) manager.registerReloader( this ); - mounts.add( mount ); - } - } + }; } diff --git a/src/main/java/dan200/computercraft/core/lua/LuaContext.java b/src/main/java/dan200/computercraft/core/lua/LuaContext.java index 0e5c792c8..626d15fad 100644 --- a/src/main/java/dan200/computercraft/core/lua/LuaContext.java +++ b/src/main/java/dan200/computercraft/core/lua/LuaContext.java @@ -9,8 +9,6 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaTask; import dan200.computercraft.api.lua.LuaException; -import dan200.computercraft.api.lua.MethodResult; -import dan200.computercraft.core.asm.TaskCallback; import dan200.computercraft.core.computer.Computer; import dan200.computercraft.core.computer.MainThread; @@ -68,11 +66,4 @@ class LuaContext implements ILuaContext throw new LuaException( "Task limit exceeded" ); } } - - @Nonnull - @Override - public MethodResult executeMainThreadTask( @Nonnull ILuaTask task ) throws LuaException - { - return TaskCallback.make( this, task ); - } } diff --git a/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java b/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java index 495d1a2d1..b2cbb021c 100644 --- a/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java +++ b/src/main/java/dan200/computercraft/core/lua/ResultInterpreterFunction.java @@ -24,7 +24,7 @@ class ResultInterpreterFunction extends ResumableVarArgFunction SKIP = new HashSet<>( Arrays.asList( + TrackingField.TASKS, TrackingField.TOTAL_TIME, TrackingField.AVERAGE_TIME, TrackingField.MAX_TIME, + TrackingField.SERVER_COUNT, TrackingField.SERVER_TIME + ) ); + + private static ComputerMBean instance; + + private final Map attributes = new HashMap<>(); + private final Map values = new HashMap<>(); + private final MBeanInfo info; + + private ComputerMBean() + { + List attributes = new ArrayList<>(); + for( Map.Entry field : TrackingField.fields().entrySet() ) + { + if( SKIP.contains( field.getValue() ) ) continue; + + String name = CaseFormat.LOWER_UNDERSCORE.to( CaseFormat.LOWER_CAMEL, field.getKey() ); + add( name, field.getValue(), attributes, null ); + } + + add( "task", TrackingField.TOTAL_TIME, attributes, TrackingField.TASKS ); + add( "serverTask", TrackingField.SERVER_TIME, attributes, TrackingField.SERVER_COUNT ); + + info = new MBeanInfo( + ComputerMBean.class.getSimpleName(), + "metrics about all computers on the server", + attributes.toArray( new MBeanAttributeInfo[0] ), null, null, null + ); + } + + public static void register() + { + try + { + ManagementFactory.getPlatformMBeanServer().registerMBean( instance = new ComputerMBean(), new ObjectName( "dan200.computercraft:type=Computers" ) ); + } + catch( InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | MalformedObjectNameException e ) + { + ComputerCraft.log.warn( "Failed to register JMX bean", e ); + } + } + + public static void registerTracker() + { + if( instance != null ) Tracking.add( instance ); + } + + @Override + public Object getAttribute( String attribute ) throws AttributeNotFoundException + { + LongSupplier value = attributes.get( attribute ); + if( value == null ) throw new AttributeNotFoundException(); + return value.getAsLong(); + } + + @Override + public void setAttribute( Attribute attribute ) throws InvalidAttributeValueException + { + throw new InvalidAttributeValueException( "Cannot set attribute" ); + } + + @Override + public AttributeList getAttributes( String[] attributes ) + { + return null; + } + + @Override + public AttributeList setAttributes( AttributeList attributes ) + { + return new AttributeList(); + } + + @Override + public Object invoke( String actionName, Object[] params, String[] signature ) + { + return null; + } + + @Override + @Nonnull + public MBeanInfo getMBeanInfo() + { + return info; + } + + @Override + public void addTaskTiming( Computer computer, long time ) + { + addValue( computer, TrackingField.TOTAL_TIME, time ); + } + + @Override + public void addServerTiming( Computer computer, long time ) + { + addValue( computer, TrackingField.SERVER_TIME, time ); + } + + @Override + public void addValue( Computer computer, TrackingField field, long change ) + { + Counter counter = values.get( field ); + counter.value.addAndGet( change ); + counter.count.incrementAndGet(); + } + + private MBeanAttributeInfo addAttribute( String name, String description, LongSupplier value ) + { + attributes.put( name, value ); + return new MBeanAttributeInfo( name, "long", description, true, false, false ); + } + + private void add( String name, TrackingField field, List attributes, TrackingField count ) + { + Counter counter = new Counter(); + values.put( field, counter ); + + String prettyName = Language.getInstance().getOrDefault( field.translationKey() ); + attributes.add( addAttribute( name, prettyName, counter.value::longValue ) ); + if( count != null ) + { + String countName = Language.getInstance().getOrDefault( count.translationKey() ); + attributes.add( addAttribute( name + "Count", countName, counter.count::longValue ) ); + } + } + + private static class Counter + { + final AtomicLong value = new AtomicLong(); + final AtomicLong count = new AtomicLong(); + } +} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/ChatHudAccess.java b/src/main/java/dan200/computercraft/fabric/mixin/ChatComponentAccess.java similarity index 57% rename from src/main/java/dan200/computercraft/fabric/mixin/ChatHudAccess.java rename to src/main/java/dan200/computercraft/fabric/mixin/ChatComponentAccess.java index 9d86ea657..dbb945ea4 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/ChatHudAccess.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/ChatComponentAccess.java @@ -5,17 +5,17 @@ */ package dan200.computercraft.fabric.mixin; -import net.minecraft.client.gui.hud.ChatHud; -import net.minecraft.text.Text; +import net.minecraft.client.gui.components.ChatComponent; +import net.minecraft.network.chat.Component; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; -@Mixin( ChatHud.class ) -public interface ChatHudAccess +@Mixin( ChatComponent.class ) +public interface ChatComponentAccess { @Invoker - void callAddMessage( Text text, int messageId ); + void callAddMessage( Component text, int messageId ); @Invoker - void callRemoveMessage( int messageId ); + void callRemoveById( int messageId ); } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/HeldItemRendererAccess.java b/src/main/java/dan200/computercraft/fabric/mixin/HeldItemRendererAccess.java deleted file mode 100644 index a799fdf3a..000000000 --- a/src/main/java/dan200/computercraft/fabric/mixin/HeldItemRendererAccess.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * This file is part of ComputerCraft - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. - * Send enquiries to dratcliffe@gmail.com - */ -package dan200.computercraft.fabric.mixin; - -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.item.HeldItemRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.util.Arm; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - -@Mixin( HeldItemRenderer.class ) -public interface HeldItemRendererAccess -{ - @Invoker - float callGetMapAngle( float tickDelta ); - - @Invoker - void callRenderArm( MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, Arm arm ); - - @Invoker - void callRenderArmHoldingItem( MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, float equipProgress, float swingProgress, Arm arm ); -} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/ItemInHandRendererAccess.java b/src/main/java/dan200/computercraft/fabric/mixin/ItemInHandRendererAccess.java new file mode 100644 index 000000000..d86132958 --- /dev/null +++ b/src/main/java/dan200/computercraft/fabric/mixin/ItemInHandRendererAccess.java @@ -0,0 +1,26 @@ +/* + * This file is part of ComputerCraft - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. + * Send enquiries to dratcliffe@gmail.com + */ +package dan200.computercraft.fabric.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.world.entity.HumanoidArm; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin( ItemInHandRenderer.class ) +public interface ItemInHandRendererAccess +{ + @Invoker + float callCalculateMapTilt( float tickDelta ); + + @Invoker + void callRenderMapHand( PoseStack matrices, MultiBufferSource vertexConsumers, int light, HumanoidArm arm ); + + @Invoker + void callRenderPlayerArm( PoseStack matrices, MultiBufferSource vertexConsumers, int light, float equipProgress, float swingProgress, HumanoidArm arm ); +} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/WorldSavePathAccess.java b/src/main/java/dan200/computercraft/fabric/mixin/LevelResourceAccess.java similarity index 70% rename from src/main/java/dan200/computercraft/fabric/mixin/WorldSavePathAccess.java rename to src/main/java/dan200/computercraft/fabric/mixin/LevelResourceAccess.java index fcaff65cf..cd777c710 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/WorldSavePathAccess.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/LevelResourceAccess.java @@ -5,15 +5,15 @@ */ package dan200.computercraft.fabric.mixin; -import net.minecraft.util.WorldSavePath; +import net.minecraft.world.level.storage.LevelResource; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; -@Mixin( WorldSavePath.class ) -public interface WorldSavePathAccess +@Mixin( LevelResource.class ) +public interface LevelResourceAccess { @Invoker( "" ) - static WorldSavePath createWorldSavePath( String relativePath ) + static LevelResource create( String relativePath ) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MinecraftServerAccess.java b/src/main/java/dan200/computercraft/fabric/mixin/MinecraftServerAccess.java index 8ce40b911..5e6efce13 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MinecraftServerAccess.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MinecraftServerAccess.java @@ -5,14 +5,14 @@ */ package dan200.computercraft.fabric.mixin; -import net.minecraft.resource.ServerResourceManager; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.packs.resources.ResourceManager; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin( MinecraftServer.class ) public interface MinecraftServerAccess { - @Accessor - ServerResourceManager getServerResourceManager(); + @Invoker + ResourceManager callGetResourceManager(); } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinBlock.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinBlock.java index 559c8faf7..01defc0f9 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinBlock.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinBlock.java @@ -6,38 +6,37 @@ package dan200.computercraft.fabric.mixin; import dan200.computercraft.shared.util.DropConsumer; -import net.minecraft.block.Block; -import net.minecraft.entity.ItemEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import java.util.function.Supplier; - +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; +import java.util.function.Supplier; + /** * Captures block drops. * - * @see Block#dropStack(World, BlockPos, ItemStack) + * @see Block#popResource(Level, Supplier, ItemStack) */ @Mixin( Block.class ) public class MixinBlock { - @Inject( method = "dropStack(Lnet/minecraft/world/World;Ljava/util/function/Supplier;Lnet/minecraft/item/ItemStack;)V", + @Inject( + method = "popResource(Lnet/minecraft/world/level/Level;Ljava/util/function/Supplier;Lnet/minecraft/world/item/ItemStack;)V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/ItemEntity;setToDefaultPickupDelay()V" + target = "Lnet/minecraft/world/entity/item/ItemEntity;setDefaultPickUpDelay()V" ), locals = LocalCapture.CAPTURE_FAILSOFT, cancellable = true ) - private static void dropStack( World world, Supplier itemEntitySupplier, ItemStack stack, CallbackInfo callbackInfo, ItemEntity itemEntity ) + private static void dropStack( Level world, Supplier itemEntitySupplier, ItemStack stack, CallbackInfo callbackInfo, ItemEntity itemEntity ) { - if( DropConsumer.onHarvestDrops( world, itemEntity.getBlockPos(), stack ) ) + if( DropConsumer.onHarvestDrops( world, itemEntity.blockPosition(), stack ) ) { callbackInfo.cancel(); } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinEntity.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinEntity.java index 5bb1671b9..d2e63f1ef 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinEntity.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinEntity.java @@ -6,9 +6,9 @@ package dan200.computercraft.fabric.mixin; import dan200.computercraft.shared.util.DropConsumer; -import net.minecraft.entity.Entity; -import net.minecraft.entity.ItemEntity; -import net.minecraft.item.ItemStack; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -17,15 +17,15 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /** * Captures entities. * - * @see Entity#dropStack(ItemStack, float) + * @see Entity#spawnAtLocation(ItemStack, float) */ @Mixin( Entity.class ) public class MixinEntity { - @Inject( method = "dropStack(Lnet/minecraft/item/ItemStack;F)Lnet/minecraft/entity/ItemEntity;", - at = @At( value = "INVOKE", target = "Lnet/minecraft/world/World;spawnEntity(Lnet/minecraft/entity/Entity;)Z" ), + @Inject( method = "spawnAtLocation(Lnet/minecraft/world/item/ItemStack;F)Lnet/minecraft/world/entity/item/ItemEntity;", + at = @At( value = "INVOKE", target = "Lnet/minecraft/world/level/Level;addFreshEntity(Lnet/minecraft/world/entity/Entity;)Z" ), cancellable = true ) - public void dropStack( ItemStack stack, float height, CallbackInfoReturnable callbackInfo ) + public void spawnAtLocation( ItemStack stack, float height, CallbackInfoReturnable callbackInfo ) { if( DropConsumer.onLivingDrops( (Entity) (Object) this, stack ) ) { diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinGameRenderer.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinGameRenderer.java index 7bb875fc3..11db72756 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinGameRenderer.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinGameRenderer.java @@ -6,13 +6,13 @@ package dan200.computercraft.fabric.mixin; +import com.mojang.blaze3d.shaders.Program; import com.mojang.datafixers.util.Pair; import dan200.computercraft.client.render.MonitorTextureBufferShader; import dan200.computercraft.client.render.RenderTypes; -import net.minecraft.client.gl.Program; -import net.minecraft.client.render.GameRenderer; -import net.minecraft.client.render.Shader; -import net.minecraft.resource.ResourceManager; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.server.packs.resources.ResourceManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -26,18 +26,18 @@ import java.util.function.Consumer; @Mixin( GameRenderer.class ) public class MixinGameRenderer { - @Inject( method = "loadShaders", at = @At( value = "INVOKE_ASSIGN", target = "Ljava/util/List;add(Ljava/lang/Object;)Z", ordinal = 53 ), locals = LocalCapture.CAPTURE_FAILSOFT ) - private void loadShaders( ResourceManager manager, CallbackInfo info, List list, List>> list2 ) throws IOException + @Inject( method = "reloadShaders", at = @At( value = "INVOKE_ASSIGN", target = "Ljava/util/List;add(Ljava/lang/Object;)Z", ordinal = 53 ), locals = LocalCapture.CAPTURE_FAILSOFT ) + private void reloadShaders( ResourceManager manager, CallbackInfo info, List list, List>> list2 ) throws IOException { - list2.add( Pair.of( new Shader( + list2.add( Pair.of( new ShaderInstance( manager, "terminal", - RenderTypes.TERMINAL_WITHOUT_DEPTH.getVertexFormat() + RenderTypes.TERMINAL_WITHOUT_DEPTH.format() ), shader -> RenderTypes.terminalShader = shader ) ); list2.add( Pair.of( new MonitorTextureBufferShader( manager, "monitor_tbo", - RenderTypes.MONITOR_TBO.getVertexFormat() + RenderTypes.MONITOR_TBO.format() ), shader -> RenderTypes.monitorTboShader = (MonitorTextureBufferShader) shader ) ); } } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinHandledScreen.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinHandledScreen.java deleted file mode 100644 index 34eca48ca..000000000 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinHandledScreen.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of ComputerCraft - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. - * Send enquiries to dratcliffe@gmail.com - */ -package dan200.computercraft.fabric.mixin; - -import dan200.computercraft.client.gui.widgets.WidgetTerminal; -import net.minecraft.client.gui.Element; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.text.Text; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin( HandledScreen.class ) -public class MixinHandledScreen extends Screen -{ - protected MixinHandledScreen( Text title ) - { - super( title ); - } - - @Inject( method = "mouseReleased", at = @At ( "HEAD" ) ) - public void mouseReleased( double mouseX, double mouseY, int button, CallbackInfoReturnable cir ) - { - for ( Element child : this.children() ) - { - if ( child instanceof WidgetTerminal ) - { - child.mouseReleased( mouseX, mouseY, button ); - } - } - } -} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinItemFrameEntityRenderer.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinItemFrameRenderer.java similarity index 63% rename from src/main/java/dan200/computercraft/fabric/mixin/MixinItemFrameEntityRenderer.java rename to src/main/java/dan200/computercraft/fabric/mixin/MixinItemFrameRenderer.java index 92ba04c51..f70265a5f 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinItemFrameEntityRenderer.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinItemFrameRenderer.java @@ -5,46 +5,46 @@ */ package dan200.computercraft.fabric.mixin; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.client.render.ItemPrintoutRenderer; import dan200.computercraft.shared.media.items.ItemPrintout; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.ItemFrameEntityRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.decoration.ItemFrameEntity; -import net.minecraft.item.ItemStack; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.ItemFrameRenderer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.decoration.ItemFrame; +import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin( ItemFrameEntityRenderer.class ) +@Mixin( ItemFrameRenderer.class ) @Environment( EnvType.CLIENT ) -public class MixinItemFrameEntityRenderer +public class MixinItemFrameRenderer { @Inject( method = "render", at = @At( value = "INVOKE", - target = "Lnet/minecraft/client/util/math/MatrixStack;multiply(Lnet/minecraft/util/math/Quaternion;)V", + target = "Lcom/mojang/blaze3d/vertex/PoseStack;mulPose(Lcom/mojang/math/Quaternion;)V", ordinal = 2, shift = At.Shift.AFTER ), cancellable = true ) private void renderItem( - ItemFrameEntity itemFrameEntity, float f, float g, MatrixStack matrixStack, - VertexConsumerProvider vertexConsumerProvider, int itemFrameEntityLight, CallbackInfo info + ItemFrame itemFrameEntity, float f, float g, PoseStack matrixStack, + MultiBufferSource vertexConsumerProvider, int itemFrameEntityLight, CallbackInfo info ) { - ItemStack stack = itemFrameEntity.getHeldItemStack(); + ItemStack stack = itemFrameEntity.getItem(); if( stack.getItem() instanceof ItemPrintout ) { int light = itemFrameEntity.getType() == EntityType.GLOW_ITEM_FRAME ? 0xf000d2 : itemFrameEntityLight; // See getLightVal. ItemPrintoutRenderer.INSTANCE.renderInFrame( matrixStack, vertexConsumerProvider, stack, light ); // TODO: need to find how to make if statement instead return, like it doing Forge - matrixStack.pop(); + matrixStack.popPose(); info.cancel(); } } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinHeldItemRenderer.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinItemInHandRenderer.java similarity index 50% rename from src/main/java/dan200/computercraft/fabric/mixin/MixinHeldItemRenderer.java rename to src/main/java/dan200/computercraft/fabric/mixin/MixinItemInHandRenderer.java index 4573b1bd2..1b5b821b5 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinHeldItemRenderer.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinItemInHandRenderer.java @@ -5,49 +5,31 @@ */ package dan200.computercraft.fabric.mixin; +import com.mojang.blaze3d.vertex.PoseStack; import dan200.computercraft.client.render.ItemPocketRenderer; import dan200.computercraft.client.render.ItemPrintoutRenderer; import dan200.computercraft.shared.media.items.ItemPrintout; import dan200.computercraft.shared.pocket.items.ItemPocketComputer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.network.AbstractClientPlayerEntity; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.item.HeldItemRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Arm; -import net.minecraft.util.Hand; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin( HeldItemRenderer.class ) +@Mixin( ItemInHandRenderer.class ) @Environment( EnvType.CLIENT ) -public class MixinHeldItemRenderer +public class MixinItemInHandRenderer { - @Shadow - private void renderArmHoldingItem( MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, float equipProgress, float swingProgress, - Arm arm ) - { - } - - @Shadow - private float getMapAngle( float pitch ) - { - return 0; - } - - @Inject( method = "Lnet/minecraft/client/render/item/HeldItemRenderer;renderFirstPersonItem(Lnet/minecraft/client/network/AbstractClientPlayerEntity;" + - "FFLnet/minecraft/util/Hand;FLnet/minecraft/item/ItemStack;FLnet/minecraft/client/util/math/MatrixStack;" + - "Lnet/minecraft/client/render/VertexConsumerProvider;I)V", - at = @At( "HEAD" ), - cancellable = true ) + @Inject( method = "renderArmWithItem", at = @At( "HEAD" ), cancellable = true ) public void renderFirstPersonItem( - AbstractClientPlayerEntity player, float var2, float pitch, Hand hand, float swingProgress, - ItemStack stack, float equipProgress, MatrixStack matrixStack, VertexConsumerProvider provider, int light, + AbstractClientPlayer player, float var2, float pitch, InteractionHand hand, float swingProgress, + ItemStack stack, float equipProgress, PoseStack matrixStack, MultiBufferSource provider, int light, CallbackInfo callback ) { diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinLanguage.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinLanguage.java index cd053439c..60fdb1a89 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinLanguage.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinLanguage.java @@ -10,7 +10,7 @@ import com.google.common.collect.ImmutableMap; import com.google.gson.JsonParseException; import dan200.computercraft.shared.peripheral.generic.data.ItemData; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.util.Language; +import net.minecraft.locale.Language; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,7 +22,6 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; -import java.util.Map; import java.util.function.BiConsumer; /** @@ -38,7 +37,7 @@ public class MixinLanguage private static Logger LOGGER; @Shadow - public static void load( InputStream inputStream, BiConsumer entryConsumer ) + public static void loadFromJson( InputStream inputStream, BiConsumer entryConsumer ) { } @@ -46,21 +45,20 @@ public class MixinLanguage { String path = "/assets/" + modId + "/lang/en_us.json"; - try ( InputStream inputStream = Language.class.getResourceAsStream( path ) ) + try( InputStream inputStream = Language.class.getResourceAsStream( path ) ) { - if ( inputStream == null ) return; - load( inputStream, biConsumer ); + if( inputStream == null ) return; + loadFromJson( inputStream, biConsumer ); } - catch ( JsonParseException | IOException e ) + catch( JsonParseException | IOException e ) { LOGGER.error( "Couldn't read strings from " + path, e ); } } - @Inject( method = "create", locals = LocalCapture.CAPTURE_FAILSOFT, at = @At( value = "INVOKE", remap = false, target = "Lcom/google/common/collect/ImmutableMap$Builder;build()Lcom/google/common/collect/ImmutableMap;" ) ) - private static void create( CallbackInfoReturnable cir, ImmutableMap.Builder builder ) + @Inject( method = "loadDefault", locals = LocalCapture.CAPTURE_FAILSOFT, at = @At( value = "INVOKE", remap = false, target = "Lcom/google/common/collect/ImmutableMap$Builder;build()Lcom/google/common/collect/ImmutableMap;" ) ) + private static void loadDefault( CallbackInfoReturnable cir, ImmutableMap.Builder builder ) { - final Map originalTranslation = builder.build(); /* We must ensure that the keys are de-duplicated because we can't catch the error that might otherwise * occur when the injected function calls build() on the ImmutableMap builder. So we use our own hash map and * exclude "minecraft", as the injected function has already loaded those keys at this point. @@ -72,9 +70,6 @@ public class MixinLanguage loadModLangFile( id, translations::put ); } ); - // This is needed to remove keys that exist in vanilla Minecraft (Consistency+ does this) - translations.keySet().removeIf( originalTranslation::containsKey ); - builder.putAll( translations ); } } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinWorld.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinLevel.java similarity index 65% rename from src/main/java/dan200/computercraft/fabric/mixin/MixinWorld.java rename to src/main/java/dan200/computercraft/fabric/mixin/MixinLevel.java index be1e1a8ba..f9132b54e 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinWorld.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinLevel.java @@ -6,9 +6,8 @@ package dan200.computercraft.fabric.mixin; import dan200.computercraft.shared.common.TileGeneric; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -23,22 +22,16 @@ import java.util.Collection; * * Forge does this, this is just a bodge to get Fabric in line with that behaviour. */ -@Mixin( World.class ) -public class MixinWorld +@Mixin( Level.class ) +public class MixinLevel { @Shadow - private boolean iteratingTickingBlockEntities; + protected boolean tickingBlockEntities; - @Shadow - public boolean isInBuildLimit( BlockPos pos ) + @Inject( method = "setBlockEntity", at = @At( "HEAD" ) ) + public void setBlockEntity( @Nullable BlockEntity entity, CallbackInfo info ) { - return false; - } - - @Inject( method = "addBlockEntity", at = @At( "HEAD" ) ) - public void addBlockEntity( @Nullable BlockEntity entity, CallbackInfo info ) - { - if( entity != null && !entity.isRemoved() && this.isInBuildLimit( entity.getPos() ) && iteratingTickingBlockEntities ) + if( entity != null && !entity.isRemoved() && entity.getLevel().isInWorldBounds( entity.getBlockPos() ) && tickingBlockEntities ) { setWorld( entity, this ); } @@ -46,16 +39,16 @@ public class MixinWorld private static void setWorld( BlockEntity entity, Object world ) { - if( entity.getWorld() != world && entity instanceof TileGeneric ) + if( entity.getLevel() != world && entity instanceof TileGeneric ) { - entity.setWorld( (World) world ); + entity.setLevel( (Level) world ); //TODO why? } } // @Inject( method = "addBlockEntities", at = @At( "HEAD" ) ) public void addBlockEntities( Collection entities, CallbackInfo info ) { - if( iteratingTickingBlockEntities ) + if( tickingBlockEntities ) { for( BlockEntity entity : entities ) { diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinLevelRenderer.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinLevelRenderer.java new file mode 100644 index 000000000..351799c13 --- /dev/null +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinLevelRenderer.java @@ -0,0 +1,37 @@ +/* + * This file is part of ComputerCraft - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. + * Send enquiries to dratcliffe@gmail.com + */ +package dan200.computercraft.fabric.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import dan200.computercraft.client.render.CableHighlightRenderer; +import dan200.computercraft.client.render.MonitorHighlightRenderer; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin( LevelRenderer.class ) +@Environment( EnvType.CLIENT ) +public class MixinLevelRenderer +{ + @Inject( method = "renderHitOutline", cancellable = true, at = @At( "HEAD" ) ) + public void renderHitOutline( PoseStack matrixStack, VertexConsumer vertexConsumer, Entity entity, double d, double e, double f, BlockPos blockPos, + BlockState blockState, CallbackInfo info ) + { + if( CableHighlightRenderer.drawHighlight( matrixStack, vertexConsumer, entity, d, e, f, blockPos, blockState ) + || MonitorHighlightRenderer.drawHighlight( matrixStack, vertexConsumer, entity, d, e, f, blockPos, blockState ) ) + { + info.cancel(); + } + } +} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinMatrix4f.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinMatrix4f.java index 247151863..35d427ff9 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinMatrix4f.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinMatrix4f.java @@ -5,48 +5,65 @@ */ package dan200.computercraft.fabric.mixin; +import com.mojang.math.Matrix4f; import dan200.computercraft.fabric.mixininterface.IMatrix4f; -import net.minecraft.util.math.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin( Matrix4f.class ) public class MixinMatrix4f implements IMatrix4f { - @Shadow protected float a00; - @Shadow protected float a01; - @Shadow protected float a02; - @Shadow protected float a03; - @Shadow protected float a10; - @Shadow protected float a11; - @Shadow protected float a12; - @Shadow protected float a13; - @Shadow protected float a20; - @Shadow protected float a21; - @Shadow protected float a22; - @Shadow protected float a23; - @Shadow protected float a30; - @Shadow protected float a31; - @Shadow protected float a32; - @Shadow protected float a33; + @Shadow + protected float m00; + @Shadow + protected float m01; + @Shadow + protected float m02; + @Shadow + protected float m03; + @Shadow + protected float m10; + @Shadow + protected float m11; + @Shadow + protected float m12; + @Shadow + protected float m13; + @Shadow + protected float m20; + @Shadow + protected float m21; + @Shadow + protected float m22; + @Shadow + protected float m23; + @Shadow + protected float m30; + @Shadow + protected float m31; + @Shadow + protected float m32; + @Shadow + protected float m33; + @Override public void setFloatArray( float[] values ) { - a00 = values[0]; - a01 = values[1]; - a02 = values[2]; - a03 = values[3]; - a10 = values[4]; - a11 = values[5]; - a12 = values[6]; - a13 = values[7]; - a20 = values[8]; - a21 = values[9]; - a22 = values[10]; - a23 = values[11]; - a30 = values[12]; - a31 = values[13]; - a32 = values[14]; - a33 = values[15]; + m00 = values[0]; + m01 = values[1]; + m02 = values[2]; + m03 = values[3]; + m10 = values[4]; + m11 = values[5]; + m12 = values[6]; + m13 = values[7]; + m20 = values[8]; + m21 = values[9]; + m22 = values[10]; + m23 = values[11]; + m30 = values[12]; + m31 = values[13]; + m32 = values[14]; + m33 = values[15]; } } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinMinecraftClient.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinMinecraft.java similarity index 64% rename from src/main/java/dan200/computercraft/fabric/mixin/MixinMinecraftClient.java rename to src/main/java/dan200/computercraft/fabric/mixin/MixinMinecraft.java index 8539fc6b9..dd2e82c0d 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinMinecraftClient.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinMinecraft.java @@ -7,31 +7,31 @@ package dan200.computercraft.fabric.mixin; import dan200.computercraft.client.FrameInfo; import dan200.computercraft.fabric.events.ClientUnloadWorldEvent; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.world.ClientWorld; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.multiplayer.ClientLevel; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin( MinecraftClient.class ) -public abstract class MixinMinecraftClient +@Mixin( Minecraft.class ) +public abstract class MixinMinecraft { - @Inject( method = "render", at = @At( "HEAD" ) ) + @Inject( method = "runTick", at = @At( "HEAD" ) ) private void onRender( CallbackInfo info ) { FrameInfo.onRenderFrame(); } - @Inject( method = "disconnect(Lnet/minecraft/client/gui/screen/Screen;)V", at = @At( "RETURN" ) ) + @Inject( method = "clearLevel(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At( "RETURN" ) ) private void disconnectAfter( Screen screen, CallbackInfo info ) { ClientUnloadWorldEvent.EVENT.invoker().onClientUnloadWorld(); } - @Inject( method = "joinWorld", at = @At( "RETURN" ) ) - private void joinWorldAfter( ClientWorld world, CallbackInfo info ) + @Inject( method = "setLevel", at = @At( "RETURN" ) ) + private void setLevel( ClientLevel world, CallbackInfo info ) { ClientUnloadWorldEvent.EVENT.invoker().onClientUnloadWorld(); } diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinScreen.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinScreen.java index d53ba9939..d06ce67dd 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinScreen.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinScreen.java @@ -8,7 +8,7 @@ package dan200.computercraft.fabric.mixin; import dan200.computercraft.shared.command.ClientCommands; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screens.Screen; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinServerWorld.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinServerLevel.java similarity index 66% rename from src/main/java/dan200/computercraft/fabric/mixin/MixinServerWorld.java rename to src/main/java/dan200/computercraft/fabric/mixin/MixinServerLevel.java index 8d1d79e37..4154327c6 100644 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinServerWorld.java +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinServerLevel.java @@ -6,8 +6,8 @@ package dan200.computercraft.fabric.mixin; import dan200.computercraft.shared.util.DropConsumer; -import net.minecraft.entity.Entity; -import net.minecraft.server.world.ServerWorld; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -16,13 +16,13 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /** * Captures item stacks spawned into the world. * - * @see ServerWorld#spawnEntity(Entity) + * @see ServerLevel#addFreshEntity(Entity) */ -@Mixin( ServerWorld.class ) -public class MixinServerWorld +@Mixin( ServerLevel.class ) +public class MixinServerLevel { - @Inject( method = "spawnEntity", at = @At( "HEAD" ), cancellable = true ) - public void spawnEntity( Entity entity, CallbackInfoReturnable callbackInfo ) + @Inject( method = "addEntity", at = @At( "HEAD" ), cancellable = true ) + public void addEntity( Entity entity, CallbackInfoReturnable callbackInfo ) { if( DropConsumer.onEntitySpawn( entity ) ) { diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinServerPlayerGameMode.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinServerPlayerGameMode.java new file mode 100644 index 000000000..3a15aedda --- /dev/null +++ b/src/main/java/dan200/computercraft/fabric/mixin/MixinServerPlayerGameMode.java @@ -0,0 +1,46 @@ +/* + * This file is part of ComputerCraft - http://www.computercraft.info + * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. + * Send enquiries to dratcliffe@gmail.com + */ +package dan200.computercraft.fabric.mixin; + +import dan200.computercraft.shared.ComputerCraftRegistry; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin( ServerPlayerGameMode.class ) +public class MixinServerPlayerGameMode +{ + @Inject( + at = @At( value = "INVOKE", target = "Lnet/minecraft/world/item/ItemStack;copy()Lnet/minecraft/world/item/ItemStack;", ordinal = 0 ), + method = "useItemOn(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/world/level/Level;Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;", + cancellable = true + ) + private void useItemOn( ServerPlayer player, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hitResult, CallbackInfoReturnable cir ) + { + BlockPos pos = hitResult.getBlockPos(); + BlockState state = world.getBlockState( pos ); + if( player.getMainHandItem().getItem() == ComputerCraftRegistry.ModItems.DISK && state.getBlock() == ComputerCraftRegistry.ModBlocks.DISK_DRIVE ) + { + InteractionResult actionResult = state.use( world, player, hand, hitResult ); + if( actionResult.consumesAction() ) + { + CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger( player, pos, stack ); + cir.setReturnValue( actionResult ); + } + } + } +} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinServerPlayerInteractionManager.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinServerPlayerInteractionManager.java deleted file mode 100644 index c714c2346..000000000 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinServerPlayerInteractionManager.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of ComputerCraft - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. - * Send enquiries to dratcliffe@gmail.com - */ -package dan200.computercraft.fabric.mixin; - -import dan200.computercraft.shared.ComputerCraftRegistry; -import net.minecraft.advancement.criterion.Criteria; -import net.minecraft.block.BlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.network.ServerPlayerInteractionManager; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin( ServerPlayerInteractionManager.class ) -public class MixinServerPlayerInteractionManager -{ - @Inject( at = @At( value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;copy()Lnet/minecraft/item/ItemStack;", ordinal = 0 ), method = "interactBlock(Lnet/minecraft/server/network/ServerPlayerEntity;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/Hand;Lnet/minecraft/util/hit/BlockHitResult;)Lnet/minecraft/util/ActionResult;", cancellable = true ) - private void interact( ServerPlayerEntity player, World world, ItemStack stack, Hand hand, BlockHitResult hitResult, CallbackInfoReturnable cir ) - { - BlockPos pos = hitResult.getBlockPos(); - BlockState state = world.getBlockState( pos ); - if( player.getMainHandStack().getItem() == ComputerCraftRegistry.ModItems.DISK && state.getBlock() == ComputerCraftRegistry.ModBlocks.DISK_DRIVE ) - { - ActionResult actionResult = state.onUse( world, player, hand, hitResult ); - if( actionResult.isAccepted() ) - { - Criteria.ITEM_USED_ON_BLOCK.trigger( player, pos, stack ); - cir.setReturnValue( actionResult ); - } - } - } -} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/MixinWorldRenderer.java b/src/main/java/dan200/computercraft/fabric/mixin/MixinWorldRenderer.java deleted file mode 100644 index fc16eb218..000000000 --- a/src/main/java/dan200/computercraft/fabric/mixin/MixinWorldRenderer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file is part of ComputerCraft - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. - * Send enquiries to dratcliffe@gmail.com - */ -package dan200.computercraft.fabric.mixin; - -import dan200.computercraft.client.render.CableHighlightRenderer; -import dan200.computercraft.client.render.MonitorHighlightRenderer; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.block.BlockState; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.render.WorldRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.BlockPos; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin( WorldRenderer.class ) -@Environment( EnvType.CLIENT ) -public class MixinWorldRenderer -{ - @Inject( method = "drawBlockOutline", cancellable = true, at = @At( "HEAD" ) ) - public void drawBlockOutline( MatrixStack matrixStack, VertexConsumer vertexConsumer, Entity entity, double d, double e, double f, BlockPos blockPos, - BlockState blockState, CallbackInfo info ) - { - if( CableHighlightRenderer.drawHighlight( matrixStack, - vertexConsumer, - entity, - d, - e, - f, - blockPos, - blockState ) || MonitorHighlightRenderer.drawHighlight( matrixStack, - vertexConsumer, - entity, - d, - e, - f, - blockPos, - blockState ) ) - { - info.cancel(); - } - } -} diff --git a/src/main/java/dan200/computercraft/fabric/mixin/SignBlockEntityAccess.java b/src/main/java/dan200/computercraft/fabric/mixin/SignBlockEntityAccess.java deleted file mode 100644 index 10e381803..000000000 --- a/src/main/java/dan200/computercraft/fabric/mixin/SignBlockEntityAccess.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * This file is part of ComputerCraft - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. - * Send enquiries to dratcliffe@gmail.com - */ -package dan200.computercraft.fabric.mixin; - -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.text.Text; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin( SignBlockEntity.class ) -public interface SignBlockEntityAccess -{ - @Accessor - Text[] getTexts(); -} diff --git a/src/main/java/dan200/computercraft/shared/BundledRedstone.java b/src/main/java/dan200/computercraft/shared/BundledRedstone.java index 656ffafab..d99e13f9d 100644 --- a/src/main/java/dan200/computercraft/shared/BundledRedstone.java +++ b/src/main/java/dan200/computercraft/shared/BundledRedstone.java @@ -9,9 +9,9 @@ package dan200.computercraft.shared; import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.redstone.IBundledRedstoneProvider; import dan200.computercraft.shared.common.DefaultBundledRedstoneProvider; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import java.util.ArrayList; @@ -29,20 +29,20 @@ public final class BundledRedstone if( !providers.contains( provider ) ) providers.add( provider ); } - public static int getDefaultOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public static int getDefaultOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) { - return world.isInBuildLimit( pos ) ? DefaultBundledRedstoneProvider.getDefaultBundledRedstoneOutput( world, pos, side ) : -1; + return world.isInWorldBounds( pos ) ? DefaultBundledRedstoneProvider.getDefaultBundledRedstoneOutput( world, pos, side ) : -1; } - public static int getOutput( World world, BlockPos pos, Direction side ) + public static int getOutput( Level world, BlockPos pos, Direction side ) { int signal = getUnmaskedOutput( world, pos, side ); return signal >= 0 ? signal : 0; } - private static int getUnmaskedOutput( World world, BlockPos pos, Direction side ) + private static int getUnmaskedOutput( Level world, BlockPos pos, Direction side ) { - if( !world.isInBuildLimit( pos ) ) + if( !world.isInWorldBounds( pos ) ) { return -1; } diff --git a/src/main/java/dan200/computercraft/shared/ComputerCraftRegistry.java b/src/main/java/dan200/computercraft/shared/ComputerCraftRegistry.java index f1cda3e78..ffc9e7b87 100644 --- a/src/main/java/dan200/computercraft/shared/ComputerCraftRegistry.java +++ b/src/main/java/dan200/computercraft/shared/ComputerCraftRegistry.java @@ -50,25 +50,29 @@ import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder; import net.fabricmc.fabric.api.screenhandler.v1.ScreenHandlerRegistry; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; -import net.minecraft.block.*; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.SpawnGroup; -import net.minecraft.item.BlockItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.Items; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerType; -import net.minecraft.sound.BlockSoundGroup; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.registry.Registry; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; import java.util.function.BiFunction; -import static net.minecraft.util.registry.Registry.BLOCK_ENTITY_TYPE; +import static net.minecraft.core.Registry.BLOCK_ENTITY_TYPE; public final class ComputerCraftRegistry { @@ -118,23 +122,23 @@ public final class ComputerCraftRegistry new BlockWiredModemFull( modemProperties(), ComputerCraftRegistry.ModTiles.WIRED_MODEM_FULL ) ); public static final BlockCable CABLE = register( "cable", new BlockCable( modemProperties() ) ); - private static Block.Settings properties() + private static BlockBehaviour.Properties properties() { //return FabricBlockSettings.copyOf(Blocks.GLASS) // .strength(2); - return AbstractBlock.Settings.of( Material.GLASS ) + return BlockBehaviour.Properties.of( Material.GLASS ) .strength( 2F ) - .sounds( BlockSoundGroup.STONE ) - .nonOpaque(); + .sound( SoundType.STONE ) + .noOcclusion(); } - private static Block.Settings turtleProperties() + private static BlockBehaviour.Properties turtleProperties() { return FabricBlockSettings.copyOf( Blocks.STONE ) .strength( 2.5f ); } - private static Block.Settings modemProperties() + private static BlockBehaviour.Properties modemProperties() { return FabricBlockSettings.copyOf( Blocks.STONE ) .breakByHand( true ) @@ -144,7 +148,7 @@ public final class ComputerCraftRegistry public static T register( String id, T value ) { - return Registry.register( Registry.BLOCK, new Identifier( MOD_ID, id ), value ); + return Registry.register( Registry.BLOCK, new ResourceLocation( MOD_ID, id ), value ); } } @@ -194,7 +198,7 @@ public final class ComputerCraftRegistry { BlockEntityType blockEntityType = FabricBlockEntityTypeBuilder.create( factory::apply, block ).build(); return Registry.register( BLOCK_ENTITY_TYPE, - new Identifier( MOD_ID, id ), + new ResourceLocation( MOD_ID, id ), blockEntityType ); } @@ -202,22 +206,22 @@ public final class ComputerCraftRegistry public static final class ModItems { - private static final ItemGroup mainItemGroup = ComputerCraft.MAIN_GROUP; + private static final CreativeModeTab mainItemGroup = ComputerCraft.MAIN_GROUP; public static final ItemComputer COMPUTER_NORMAL = ofBlock( ModBlocks.COMPUTER_NORMAL, ItemComputer::new ); public static final ItemComputer COMPUTER_ADVANCED = ofBlock( ModBlocks.COMPUTER_ADVANCED, ItemComputer::new ); public static final ItemComputer COMPUTER_COMMAND = ofBlock( ModBlocks.COMPUTER_COMMAND, ItemComputer::new ); public static final ItemPocketComputer POCKET_COMPUTER_NORMAL = register( "pocket_computer_normal", - new ItemPocketComputer( properties().maxCount( 1 ), ComputerFamily.NORMAL ) ); + new ItemPocketComputer( properties().stacksTo( 1 ), ComputerFamily.NORMAL ) ); public static final ItemPocketComputer POCKET_COMPUTER_ADVANCED = register( "pocket_computer_advanced", - new ItemPocketComputer( properties().maxCount( 1 ), + new ItemPocketComputer( properties().stacksTo( 1 ), ComputerFamily.ADVANCED ) ); public static final ItemTurtle TURTLE_NORMAL = ofBlock( ModBlocks.TURTLE_NORMAL, ItemTurtle::new ); public static final ItemTurtle TURTLE_ADVANCED = ofBlock( ModBlocks.TURTLE_ADVANCED, ItemTurtle::new ); - public static final ItemDisk DISK = register( "disk", new ItemDisk( properties().maxCount( 1 ) ) ); - public static final ItemTreasureDisk TREASURE_DISK = register( "treasure_disk", new ItemTreasureDisk( properties().maxCount( 1 ) ) ); - public static final ItemPrintout PRINTED_PAGE = register( "printed_page", new ItemPrintout( properties().maxCount( 1 ), ItemPrintout.Type.PAGE ) ); - public static final ItemPrintout PRINTED_PAGES = register( "printed_pages", new ItemPrintout( properties().maxCount( 1 ), ItemPrintout.Type.PAGES ) ); - public static final ItemPrintout PRINTED_BOOK = register( "printed_book", new ItemPrintout( properties().maxCount( 1 ), ItemPrintout.Type.BOOK ) ); + public static final ItemDisk DISK = register( "disk", new ItemDisk( properties().stacksTo( 1 ) ) ); + public static final ItemTreasureDisk TREASURE_DISK = register( "treasure_disk", new ItemTreasureDisk( properties().stacksTo( 1 ) ) ); + public static final ItemPrintout PRINTED_PAGE = register( "printed_page", new ItemPrintout( properties().stacksTo( 1 ), ItemPrintout.Type.PAGE ) ); + public static final ItemPrintout PRINTED_PAGES = register( "printed_pages", new ItemPrintout( properties().stacksTo( 1 ), ItemPrintout.Type.PAGES ) ); + public static final ItemPrintout PRINTED_BOOK = register( "printed_book", new ItemPrintout( properties().stacksTo( 1 ), ItemPrintout.Type.BOOK ) ); public static final BlockItem SPEAKER = ofBlock( ModBlocks.SPEAKER, BlockItem::new ); public static final BlockItem DISK_DRIVE = ofBlock( ModBlocks.DISK_DRIVE, BlockItem::new ); public static final BlockItem PRINTER = ofBlock( ModBlocks.PRINTER, BlockItem::new ); @@ -229,29 +233,29 @@ public final class ComputerCraftRegistry public static final ItemBlockCable.Cable CABLE = register( "cable", new ItemBlockCable.Cable( ModBlocks.CABLE, properties() ) ); public static final ItemBlockCable.WiredModem WIRED_MODEM = register( "wired_modem", new ItemBlockCable.WiredModem( ModBlocks.CABLE, properties() ) ); - private static I ofBlock( B parent, BiFunction supplier ) + private static I ofBlock( B parent, BiFunction supplier ) { - return Registry.register( Registry.ITEM, Registry.BLOCK.getId( parent ), supplier.apply( parent, properties() ) ); + return Registry.register( Registry.ITEM, Registry.BLOCK.getKey( parent ), supplier.apply( parent, properties() ) ); } - private static Item.Settings properties() + private static Item.Properties properties() { - return new Item.Settings().group( mainItemGroup ); + return new Item.Properties().tab( mainItemGroup ); } private static T register( String id, T item ) { - return Registry.register( Registry.ITEM, new Identifier( MOD_ID, id ), item ); + return Registry.register( Registry.ITEM, new ResourceLocation( MOD_ID, id ), item ); } } public static class ModEntities { public static final EntityType TURTLE_PLAYER = Registry.register( Registry.ENTITY_TYPE, - new Identifier( MOD_ID, "turtle_player" ), - EntityType.Builder.create( SpawnGroup.MISC ).disableSaving() - .disableSummon() - .setDimensions( + new ResourceLocation( MOD_ID, "turtle_player" ), + EntityType.Builder.createNothing( MobCategory.MISC ).noSave() + .noSummon() + .sized( 0, 0 ) .build( @@ -260,36 +264,36 @@ public final class ComputerCraftRegistry public static class ModContainers { - public static final ScreenHandlerType COMPUTER = ContainerData.toType( new Identifier( MOD_ID, "computer" ), ModContainers.COMPUTER, ComputerContainerData::new, ComputerMenuWithoutInventory::new ); - public static final ScreenHandlerType POCKET_COMPUTER = ContainerData.toType( new Identifier( MOD_ID, "pocket_computer" ), ModContainers.POCKET_COMPUTER, ComputerContainerData::new, ComputerMenuWithoutInventory::new ); - public static final ScreenHandlerType POCKET_COMPUTER_NO_TERM = ContainerData.toType( new Identifier( MOD_ID, "pocket_computer_no_term" ), ModContainers.POCKET_COMPUTER_NO_TERM, ComputerContainerData::new, ComputerMenuWithoutInventory::new ); - public static final ScreenHandlerType TURTLE = ContainerData.toType( new Identifier( MOD_ID, "turtle" ), ComputerContainerData::new, ContainerTurtle::new ); - public static final ScreenHandlerType DISK_DRIVE = registerSimple( "disk_drive", ContainerDiskDrive::new ); - public static final ScreenHandlerType PRINTER = registerSimple( "printer", ContainerPrinter::new ); - public static final ScreenHandlerType PRINTOUT = ContainerData.toType( new Identifier( MOD_ID, "printout" ), HeldItemContainerData::new, ContainerHeldItem::createPrintout ); - public static final ScreenHandlerType VIEW_COMPUTER = ContainerData.toType( new Identifier( MOD_ID, "view_computer" ), ViewComputerContainerData::new, ContainerViewComputer::new ); + public static final MenuType COMPUTER = ContainerData.toType( new ResourceLocation( MOD_ID, "computer" ), ModContainers.COMPUTER, ComputerContainerData::new, ComputerMenuWithoutInventory::new ); + public static final MenuType POCKET_COMPUTER = ContainerData.toType( new ResourceLocation( MOD_ID, "pocket_computer" ), ModContainers.POCKET_COMPUTER, ComputerContainerData::new, ComputerMenuWithoutInventory::new ); + public static final MenuType POCKET_COMPUTER_NO_TERM = ContainerData.toType( new ResourceLocation( MOD_ID, "pocket_computer_no_term" ), ModContainers.POCKET_COMPUTER_NO_TERM, ComputerContainerData::new, ComputerMenuWithoutInventory::new ); + public static final MenuType TURTLE = ContainerData.toType( new ResourceLocation( MOD_ID, "turtle" ), ComputerContainerData::new, ContainerTurtle::new ); + public static final MenuType DISK_DRIVE = registerSimple( "disk_drive", ContainerDiskDrive::new ); + public static final MenuType PRINTER = registerSimple( "printer", ContainerPrinter::new ); + public static final MenuType PRINTOUT = ContainerData.toType( new ResourceLocation( MOD_ID, "printout" ), HeldItemContainerData::new, ContainerHeldItem::createPrintout ); + public static final MenuType VIEW_COMPUTER = ContainerData.toType( new ResourceLocation( MOD_ID, "view_computer" ), ViewComputerContainerData::new, ContainerViewComputer::new ); - private static ScreenHandlerType registerSimple( String id, - ScreenHandlerRegistry.SimpleClientHandlerFactory function ) + private static MenuType registerSimple( String id, + ScreenHandlerRegistry.SimpleClientHandlerFactory function ) { - return ScreenHandlerRegistry.registerSimple( new Identifier( MOD_ID, id ), function ); + return ScreenHandlerRegistry.registerSimple( new ResourceLocation( MOD_ID, id ), function ); } } public static final class TurtleUpgrades { - public static TurtleModem wirelessModemNormal = new TurtleModem( false, new Identifier( ComputerCraft.MOD_ID, "wireless_modem_normal" ) ); - public static TurtleModem wirelessModemAdvanced = new TurtleModem( true, new Identifier( ComputerCraft.MOD_ID, "wireless_modem_advanced" ) ); - public static TurtleSpeaker speaker = new TurtleSpeaker( new Identifier( ComputerCraft.MOD_ID, "speaker" ) ); + public static TurtleModem wirelessModemNormal = new TurtleModem( false, new ResourceLocation( ComputerCraft.MOD_ID, "wireless_modem_normal" ) ); + public static TurtleModem wirelessModemAdvanced = new TurtleModem( true, new ResourceLocation( ComputerCraft.MOD_ID, "wireless_modem_advanced" ) ); + public static TurtleSpeaker speaker = new TurtleSpeaker( new ResourceLocation( ComputerCraft.MOD_ID, "speaker" ) ); - public static TurtleCraftingTable craftingTable = new TurtleCraftingTable( new Identifier( "minecraft", "crafting_table" ) ); - public static TurtleSword diamondSword = new TurtleSword( new Identifier( "minecraft", "diamond_sword" ), Items.DIAMOND_SWORD ); - public static TurtleShovel diamondShovel = new TurtleShovel( new Identifier( "minecraft", "diamond_shovel" ), Items.DIAMOND_SHOVEL ); - public static TurtleTool diamondPickaxe = new TurtleTool( new Identifier( "minecraft", "diamond_pickaxe" ), Items.DIAMOND_PICKAXE ); - public static TurtleAxe diamondAxe = new TurtleAxe( new Identifier( "minecraft", "diamond_axe" ), Items.DIAMOND_AXE ); - public static TurtleHoe diamondHoe = new TurtleHoe( new Identifier( "minecraft", "diamond_hoe" ), Items.DIAMOND_HOE ); + public static TurtleCraftingTable craftingTable = new TurtleCraftingTable( new ResourceLocation( "minecraft", "crafting_table" ) ); + public static TurtleSword diamondSword = new TurtleSword( new ResourceLocation( "minecraft", "diamond_sword" ), Items.DIAMOND_SWORD ); + public static TurtleShovel diamondShovel = new TurtleShovel( new ResourceLocation( "minecraft", "diamond_shovel" ), Items.DIAMOND_SHOVEL ); + public static TurtleTool diamondPickaxe = new TurtleTool( new ResourceLocation( "minecraft", "diamond_pickaxe" ), Items.DIAMOND_PICKAXE ); + public static TurtleAxe diamondAxe = new TurtleAxe( new ResourceLocation( "minecraft", "diamond_axe" ), Items.DIAMOND_AXE ); + public static TurtleHoe diamondHoe = new TurtleHoe( new ResourceLocation( "minecraft", "diamond_hoe" ), Items.DIAMOND_HOE ); - public static TurtleTool netheritePickaxe = new TurtleTool( new Identifier( "minecraft", "netherite_pickaxe" ), Items.NETHERITE_PICKAXE ); + public static TurtleTool netheritePickaxe = new TurtleTool( new ResourceLocation( "minecraft", "netherite_pickaxe" ), Items.NETHERITE_PICKAXE ); public static void registerTurtleUpgrades() { diff --git a/src/main/java/dan200/computercraft/shared/MediaProviders.java b/src/main/java/dan200/computercraft/shared/MediaProviders.java index a76eef0be..f934ea453 100644 --- a/src/main/java/dan200/computercraft/shared/MediaProviders.java +++ b/src/main/java/dan200/computercraft/shared/MediaProviders.java @@ -9,7 +9,7 @@ package dan200.computercraft.shared; import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.media.IMedia; import dan200.computercraft.api.media.IMediaProvider; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import java.util.LinkedHashSet; diff --git a/src/main/java/dan200/computercraft/shared/Peripherals.java b/src/main/java/dan200/computercraft/shared/Peripherals.java index 4cab4a12a..6f3329c4b 100644 --- a/src/main/java/dan200/computercraft/shared/Peripherals.java +++ b/src/main/java/dan200/computercraft/shared/Peripherals.java @@ -10,9 +10,9 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.IPeripheralProvider; import dan200.computercraft.shared.peripheral.generic.GenericPeripheralProvider; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,13 +33,13 @@ public final class Peripherals } @Nullable - public static IPeripheral getPeripheral( World world, BlockPos pos, Direction side ) + public static IPeripheral getPeripheral( Level world, BlockPos pos, Direction side ) { - return world.isInBuildLimit( pos ) && !world.isClient ? getPeripheralAt( world, pos, side ) : null; + return world.isInWorldBounds( pos ) && !world.isClientSide ? getPeripheralAt( world, pos, side ) : null; } @Nullable - private static IPeripheral getPeripheralAt( World world, BlockPos pos, Direction side ) + private static IPeripheral getPeripheralAt( Level world, BlockPos pos, Direction side ) { // Try the handlers in order: for( IPeripheralProvider peripheralProvider : providers ) diff --git a/src/main/java/dan200/computercraft/shared/PocketUpgrades.java b/src/main/java/dan200/computercraft/shared/PocketUpgrades.java index 0c5820bea..4c9cafa3c 100644 --- a/src/main/java/dan200/computercraft/shared/PocketUpgrades.java +++ b/src/main/java/dan200/computercraft/shared/PocketUpgrades.java @@ -9,8 +9,8 @@ import dan200.computercraft.api.pocket.IPocketUpgrade; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenCustomHashMap; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Util; +import net.minecraft.Util; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -19,7 +19,7 @@ import java.util.*; public final class PocketUpgrades { private static final Map upgrades = new HashMap<>(); - private static final Map upgradeOwners = new Object2ObjectLinkedOpenCustomHashMap<>( Util.identityHashStrategy() ); + private static final Map upgradeOwners = new Object2ObjectLinkedOpenCustomHashMap<>( Util.identityStrategy() ); private PocketUpgrades() {} diff --git a/src/main/java/dan200/computercraft/shared/TurtlePermissions.java b/src/main/java/dan200/computercraft/shared/TurtlePermissions.java index 19d336d06..98e4cd135 100644 --- a/src/main/java/dan200/computercraft/shared/TurtlePermissions.java +++ b/src/main/java/dan200/computercraft/shared/TurtlePermissions.java @@ -5,21 +5,21 @@ */ package dan200.computercraft.shared; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.core.BlockPos; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; public final class TurtlePermissions { - public static boolean isBlockEnterable( World world, BlockPos pos, PlayerEntity player ) + public static boolean isBlockEnterable( Level world, BlockPos pos, Player player ) { MinecraftServer server = world.getServer(); - return server == null || world.isClient || world instanceof ServerWorld && !server.isSpawnProtected( (ServerWorld) world, pos, player ); + return server == null || world.isClientSide || (world instanceof ServerLevel && !server.isUnderSpawnProtection( (ServerLevel) world, pos, player )); } - public static boolean isBlockEditable( World world, BlockPos pos, PlayerEntity player ) + public static boolean isBlockEditable( Level world, BlockPos pos, Player player ) { return isBlockEnterable( world, pos, player ); } diff --git a/src/main/java/dan200/computercraft/shared/TurtleUpgrades.java b/src/main/java/dan200/computercraft/shared/TurtleUpgrades.java index f59b40577..514c56a59 100644 --- a/src/main/java/dan200/computercraft/shared/TurtleUpgrades.java +++ b/src/main/java/dan200/computercraft/shared/TurtleUpgrades.java @@ -8,7 +8,7 @@ package dan200.computercraft.shared; import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/src/main/java/dan200/computercraft/shared/command/ClientCommands.java b/src/main/java/dan200/computercraft/shared/command/ClientCommands.java index 6845f2815..f67453827 100644 --- a/src/main/java/dan200/computercraft/shared/command/ClientCommands.java +++ b/src/main/java/dan200/computercraft/shared/command/ClientCommands.java @@ -6,7 +6,7 @@ package dan200.computercraft.shared.command; import dan200.computercraft.shared.util.IDAssigner; -import net.minecraft.util.Util; +import net.minecraft.Util; import java.io.File; @@ -42,7 +42,7 @@ public final class ClientCommands File file = new File( IDAssigner.getDir(), "computer/" + id ); if( !file.isDirectory() ) return true; - Util.getOperatingSystem().open( file ); + Util.getPlatform().openFile( file ); return true; } return false; diff --git a/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java b/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java index c225b7c59..b1586a1ac 100644 --- a/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java +++ b/src/main/java/dan200/computercraft/shared/command/CommandComputerCraft.java @@ -23,20 +23,20 @@ import dan200.computercraft.shared.computer.inventory.ContainerViewComputer; import dan200.computercraft.shared.network.container.ViewComputerContainerData; import dan200.computercraft.shared.util.IDAssigner; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.packet.s2c.play.PlayerPositionLookS2CPacket; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.text.LiteralText; -import net.minecraft.text.MutableText; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import java.io.File; @@ -52,7 +52,7 @@ import static dan200.computercraft.shared.command.builder.CommandBuilder.args; import static dan200.computercraft.shared.command.builder.CommandBuilder.command; import static dan200.computercraft.shared.command.builder.HelpingArgumentBuilder.choice; import static dan200.computercraft.shared.command.text.ChatHelpers.*; -import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.commands.Commands.literal; public final class CommandComputerCraft { @@ -66,7 +66,7 @@ public final class CommandComputerCraft { } - public static void register( CommandDispatcher dispatcher, Boolean dedicated ) + public static void register( CommandDispatcher dispatcher, Boolean dedicated ) { dispatcher.register( choice( "computercraft" ) .then( literal( "dump" ) @@ -74,17 +74,17 @@ public final class CommandComputerCraft .executes( context -> { TableBuilder table = new TableBuilder( DUMP_LIST_ID, "Computer", "On", "Position" ); - ServerCommandSource source = context.getSource(); + CommandSourceStack source = context.getSource(); List computers = new ArrayList<>( ComputerCraft.serverComputerRegistry.getComputers() ); // Unless we're on a server, limit the number of rows we can send. - World world = source.getWorld(); + Level world = source.getLevel(); BlockPos pos = new BlockPos( source.getPosition() ); computers.sort( ( a, b ) -> { if( a.getWorld() == b.getWorld() && a.getWorld() == world ) { - return Double.compare( a.getPosition().getSquaredDistance( pos ), b.getPosition().getSquaredDistance( pos ) ); + return Double.compare( a.getPosition().distSqr( pos ), b.getPosition().distSqr( pos ) ); } else if( a.getWorld() == world ) { @@ -148,7 +148,7 @@ public final class CommandComputerCraft if( computer.isOn() ) shutdown++; computer.shutdown(); } - context.getSource().sendFeedback( translate( "commands.computercraft.shutdown.done", shutdown, computers.size() ), false ); + context.getSource().sendSuccess( translate( "commands.computercraft.shutdown.done", shutdown, computers.size() ), false ); return shutdown; } ) ) @@ -162,7 +162,7 @@ public final class CommandComputerCraft if( !computer.isOn() ) on++; computer.turnOn(); } - context.getSource().sendFeedback( translate( "commands.computercraft.turn_on.done", on, computers.size() ), false ); + context.getSource().sendSuccess( translate( "commands.computercraft.turn_on.done", on, computers.size() ), false ); return on; } ) ) @@ -171,25 +171,25 @@ public final class CommandComputerCraft .arg( "computer", oneComputer() ) .executes( context -> { ServerComputer computer = getComputerArgument( context, "computer" ); - World world = computer.getWorld(); + Level world = computer.getWorld(); BlockPos pos = computer.getPosition(); if( world == null || pos == null ) throw TP_NOT_THERE.create(); - Entity entity = context.getSource().getEntityOrThrow(); - if( !(entity instanceof ServerPlayerEntity) ) throw TP_NOT_PLAYER.create(); + Entity entity = context.getSource().getEntityOrException(); + if( !(entity instanceof ServerPlayer) ) throw TP_NOT_PLAYER.create(); - ServerPlayerEntity player = (ServerPlayerEntity) entity; - if( player.getEntityWorld() == world ) + ServerPlayer player = (ServerPlayer) entity; + if( player.getCommandSenderWorld() == world ) { - player.networkHandler.requestTeleport( + player.connection.teleport( pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, 0, 0, - EnumSet.noneOf( PlayerPositionLookS2CPacket.Flag.class ) + EnumSet.noneOf( ClientboundPlayerPositionPacket.RelativeArgument.class ) ); } else { - player.teleport( (ServerWorld) world, + player.teleportTo( (ServerLevel) world, pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, 0, 0 ); } @@ -222,28 +222,28 @@ public final class CommandComputerCraft .requires( UserLevel.OP ) .arg( "computer", oneComputer() ) .executes( context -> { - ServerPlayerEntity player = context.getSource().getPlayer(); + ServerPlayer player = context.getSource().getPlayerOrException(); ServerComputer computer = getComputerArgument( context, "computer" ); computer.sendTerminalState( player ); ViewComputerContainerData container = new ViewComputerContainerData( computer ); container.open( player, new ExtendedScreenHandlerFactory() { @Override - public void writeScreenOpeningData( ServerPlayerEntity player, PacketByteBuf buf ) + public void writeScreenOpeningData( ServerPlayer player, FriendlyByteBuf buf ) { container.toBytes( buf ); } @Nonnull @Override - public MutableText getDisplayName() + public MutableComponent getDisplayName() { - return new TranslatableText( "gui.computercraft.view_computer" ); + return new TranslatableComponent( "gui.computercraft.view_computer" ); } @Nonnull @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory player, @Nonnull PlayerEntity entity ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory player, @Nonnull Player entity ) { return new ContainerViewComputer( id, player, computer ); } @@ -258,7 +258,7 @@ public final class CommandComputerCraft getTimingContext( context.getSource() ).start(); String stopCommand = "/computercraft track stop"; - context.getSource().sendFeedback( translate( "commands.computercraft.track.start.stop", + context.getSource().sendSuccess( translate( "commands.computercraft.track.start.stop", link( text( stopCommand ), stopCommand, translate( "commands.computercraft.track.stop.action" ) ) ), false ); return 1; } ) ) @@ -292,9 +292,9 @@ public final class CommandComputerCraft ); } - private static MutableText linkComputer( ServerCommandSource source, ServerComputer serverComputer, int computerId ) + private static MutableComponent linkComputer( CommandSourceStack source, ServerComputer serverComputer, int computerId ) { - MutableText out = new LiteralText( "" ); + MutableComponent out = new TextComponent( "" ); // Append the computer instance if( serverComputer == null ) @@ -333,14 +333,14 @@ public final class CommandComputerCraft if( UserLevel.OWNER.test( source ) && isPlayer( source ) ) { - MutableText linkPath = linkStorage( computerId ); + MutableComponent linkPath = linkStorage( computerId ); if( linkPath != null ) out.append( " " ).append( linkPath ); } return out; } - private static MutableText linkPosition( ServerCommandSource context, ServerComputer computer ) + private static MutableComponent linkPosition( CommandSourceStack context, ServerComputer computer ) { if( UserLevel.OP.test( context ) ) { @@ -356,7 +356,7 @@ public final class CommandComputerCraft } } - private static MutableText linkStorage( int id ) + private static MutableComponent linkStorage( int id ) { File file = new File( IDAssigner.getDir(), "computer/" + id ); if( !file.isDirectory() ) return null; @@ -369,20 +369,20 @@ public final class CommandComputerCraft } @Nonnull - private static TrackingContext getTimingContext( ServerCommandSource source ) + private static TrackingContext getTimingContext( CommandSourceStack source ) { Entity entity = source.getEntity(); - return entity instanceof PlayerEntity ? Tracking.getContext( entity.getUuid() ) : Tracking.getContext( SYSTEM_UUID ); + return entity instanceof Player ? Tracking.getContext( entity.getUUID() ) : Tracking.getContext( SYSTEM_UUID ); } private static final List DEFAULT_FIELDS = Arrays.asList( TrackingField.TASKS, TrackingField.TOTAL_TIME, TrackingField.AVERAGE_TIME, TrackingField.MAX_TIME ); - private static int displayTimings( ServerCommandSource source, TrackingField sortField, List fields ) throws CommandSyntaxException + private static int displayTimings( CommandSourceStack source, TrackingField sortField, List fields ) throws CommandSyntaxException { return displayTimings( source, getTimingContext( source ).getTimings(), sortField, fields ); } - private static int displayTimings( ServerCommandSource source, @Nonnull List timings, @Nonnull TrackingField sortField, @Nonnull List fields ) throws CommandSyntaxException + private static int displayTimings( CommandSourceStack source, @Nonnull List timings, @Nonnull TrackingField sortField, @Nonnull List fields ) throws CommandSyntaxException { if( timings.isEmpty() ) throw NO_TIMINGS_EXCEPTION.create(); @@ -398,7 +398,7 @@ public final class CommandComputerCraft timings.sort( Comparator.comparing( x -> x.get( sortField ) ).reversed() ); - MutableText[] headers = new MutableText[1 + fields.size()]; + MutableComponent[] headers = new MutableComponent[1 + fields.size()]; headers[0] = translate( "commands.computercraft.track.dump.computer" ); for( int i = 0; i < fields.size(); i++ ) headers[i + 1] = translate( fields.get( i ).translationKey() ); TableBuilder table = new TableBuilder( TRACK_ID, headers ); @@ -408,9 +408,9 @@ public final class CommandComputerCraft Computer computer = entry.getComputer(); ServerComputer serverComputer = computer == null ? null : lookup.get( computer ); - MutableText computerComponent = linkComputer( source, serverComputer, entry.getComputerId() ); + MutableComponent computerComponent = linkComputer( source, serverComputer, entry.getComputerId() ); - MutableText[] row = new MutableText[1 + fields.size()]; + MutableComponent[] row = new MutableComponent[1 + fields.size()]; row[0] = computerComponent; for( int i = 0; i < fields.size(); i++ ) row[i + 1] = text( entry.getFormatted( fields.get( i ) ) ); table.row( row ); diff --git a/src/main/java/dan200/computercraft/shared/command/CommandUtils.java b/src/main/java/dan200/computercraft/shared/command/CommandUtils.java index d64a7935d..df4cd9f2d 100644 --- a/src/main/java/dan200/computercraft/shared/command/CommandUtils.java +++ b/src/main/java/dan200/computercraft/shared/command/CommandUtils.java @@ -10,10 +10,10 @@ import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import dan200.computercraft.api.turtle.FakePlayer; -import net.minecraft.command.CommandSource; -import net.minecraft.entity.Entity; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.SharedSuggestionProvider; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; import java.util.Arrays; import java.util.Locale; @@ -24,28 +24,28 @@ public final class CommandUtils { private CommandUtils() {} - public static boolean isPlayer( ServerCommandSource output ) + public static boolean isPlayer( CommandSourceStack output ) { Entity sender = output.getEntity(); - return sender instanceof ServerPlayerEntity && !(sender instanceof FakePlayer) && ((ServerPlayerEntity) sender).networkHandler != null; + return sender instanceof ServerPlayer && !(sender instanceof FakePlayer) && ((ServerPlayer) sender).connection != null; } @SuppressWarnings( "unchecked" ) public static CompletableFuture suggestOnServer( CommandContext context, SuggestionsBuilder builder, - Function, CompletableFuture> supplier ) + Function, CompletableFuture> supplier ) { Object source = context.getSource(); - if( !(source instanceof CommandSource) ) + if( !(source instanceof SharedSuggestionProvider) ) { return Suggestions.empty(); } - else if( source instanceof ServerCommandSource ) + else if( source instanceof CommandSourceStack ) { - return supplier.apply( (CommandContext) context ); + return supplier.apply( (CommandContext) context ); } else { - return ((CommandSource) source).getCompletions( (CommandContext) context, builder ); + return ((SharedSuggestionProvider) source).customSuggestion( (CommandContext) context, builder ); } } diff --git a/src/main/java/dan200/computercraft/shared/command/Exceptions.java b/src/main/java/dan200/computercraft/shared/command/Exceptions.java index 88f173093..bf077b239 100644 --- a/src/main/java/dan200/computercraft/shared/command/Exceptions.java +++ b/src/main/java/dan200/computercraft/shared/command/Exceptions.java @@ -9,7 +9,7 @@ package dan200.computercraft.shared.command; import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import net.minecraft.text.TranslatableText; +import net.minecraft.network.chat.TranslatableComponent; public final class Exceptions { @@ -25,16 +25,16 @@ public final class Exceptions private static SimpleCommandExceptionType translated( String key ) { - return new SimpleCommandExceptionType( new TranslatableText( key ) ); + return new SimpleCommandExceptionType( new TranslatableComponent( key ) ); } private static DynamicCommandExceptionType translated1( String key ) { - return new DynamicCommandExceptionType( x -> new TranslatableText( key, x ) ); + return new DynamicCommandExceptionType( x -> new TranslatableComponent( key, x ) ); } private static Dynamic2CommandExceptionType translated2( String key ) { - return new Dynamic2CommandExceptionType( ( x, y ) -> new TranslatableText( key, x, y ) ); + return new Dynamic2CommandExceptionType( ( x, y ) -> new TranslatableComponent( key, x, y ) ); } } diff --git a/src/main/java/dan200/computercraft/shared/command/UserLevel.java b/src/main/java/dan200/computercraft/shared/command/UserLevel.java index 1f24c7a82..8f5715edb 100644 --- a/src/main/java/dan200/computercraft/shared/command/UserLevel.java +++ b/src/main/java/dan200/computercraft/shared/command/UserLevel.java @@ -5,17 +5,17 @@ */ package dan200.computercraft.shared.command; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.commands.CommandSourceStack; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; import java.util.function.Predicate; /** * The level a user must be at in order to execute a command. */ -public enum UserLevel implements Predicate +public enum UserLevel implements Predicate { /** * Only can be used by the owner of the server: namely the server console or the player in SSP. @@ -53,20 +53,20 @@ public enum UserLevel implements Predicate } @Override - public boolean test( ServerCommandSource source ) + public boolean test( CommandSourceStack source ) { if( this == ANYONE ) return true; if( this == OWNER ) return isOwner( source ); if( this == OWNER_OP && isOwner( source ) ) return true; - return source.hasPermissionLevel( toLevel() ); + return source.hasPermission( toLevel() ); } - private static boolean isOwner( ServerCommandSource source ) + private static boolean isOwner( CommandSourceStack source ) { MinecraftServer server = source.getServer(); Entity sender = source.getEntity(); - return server.isDedicated() - ? source.getEntity() == null && source.hasPermissionLevel( 4 ) && source.getName().equals( "Server" ) - : sender instanceof PlayerEntity && ((PlayerEntity) sender).getGameProfile().getName().equalsIgnoreCase( server.getServerModName() ); + return server.isDedicatedServer() + ? source.getEntity() == null && source.hasPermission( 4 ) && source.getTextName().equals( "Server" ) + : sender instanceof Player && ((Player) sender).getGameProfile().getName().equalsIgnoreCase( server.getServerModName() ); } } diff --git a/src/main/java/dan200/computercraft/shared/command/arguments/ArgumentSerializers.java b/src/main/java/dan200/computercraft/shared/command/arguments/ArgumentSerializers.java index a8520734d..afacc524e 100644 --- a/src/main/java/dan200/computercraft/shared/command/arguments/ArgumentSerializers.java +++ b/src/main/java/dan200/computercraft/shared/command/arguments/ArgumentSerializers.java @@ -8,33 +8,33 @@ package dan200.computercraft.shared.command.arguments; import com.mojang.brigadier.arguments.ArgumentType; import dan200.computercraft.ComputerCraft; -import net.minecraft.command.argument.ArgumentTypes; -import net.minecraft.command.argument.serialize.ArgumentSerializer; -import net.minecraft.command.argument.serialize.ConstantArgumentSerializer; -import net.minecraft.util.Identifier; +import net.minecraft.commands.synchronization.ArgumentSerializer; +import net.minecraft.commands.synchronization.ArgumentTypes; +import net.minecraft.commands.synchronization.EmptyArgumentSerializer; +import net.minecraft.resources.ResourceLocation; public final class ArgumentSerializers { public static void register() { - register( new Identifier( ComputerCraft.MOD_ID, "tracking_field" ), TrackingFieldArgumentType.trackingField() ); - register( new Identifier( ComputerCraft.MOD_ID, "computer" ), ComputerArgumentType.oneComputer() ); - register( new Identifier( ComputerCraft.MOD_ID, "computers" ), ComputersArgumentType.class, new ComputersArgumentType.Serializer() ); - registerUnsafe( new Identifier( ComputerCraft.MOD_ID, "repeat" ), RepeatArgumentType.class, new RepeatArgumentType.Serializer() ); + register( new ResourceLocation( ComputerCraft.MOD_ID, "tracking_field" ), TrackingFieldArgumentType.trackingField() ); + register( new ResourceLocation( ComputerCraft.MOD_ID, "computer" ), ComputerArgumentType.oneComputer() ); + register( new ResourceLocation( ComputerCraft.MOD_ID, "computers" ), ComputersArgumentType.class, new ComputersArgumentType.Serializer() ); + registerUnsafe( new ResourceLocation( ComputerCraft.MOD_ID, "repeat" ), RepeatArgumentType.class, new RepeatArgumentType.Serializer() ); } - private static > void register( Identifier id, T instance ) + private static > void register( ResourceLocation id, T instance ) { - registerUnsafe( id, instance.getClass(), new ConstantArgumentSerializer<>( () -> instance ) ); + registerUnsafe( id, instance.getClass(), new EmptyArgumentSerializer<>( () -> instance ) ); } - private static > void register( Identifier id, Class type, ArgumentSerializer serializer ) + private static > void register( ResourceLocation id, Class type, ArgumentSerializer serializer ) { ArgumentTypes.register( id.toString(), type, serializer ); } @SuppressWarnings( "unchecked" ) - private static > void registerUnsafe( Identifier id, Class type, ArgumentSerializer serializer ) + private static > void registerUnsafe( ResourceLocation id, Class type, ArgumentSerializer serializer ) { ArgumentTypes.register( id.toString(), type, (ArgumentSerializer) serializer ); } diff --git a/src/main/java/dan200/computercraft/shared/command/arguments/ComputerArgumentType.java b/src/main/java/dan200/computercraft/shared/command/arguments/ComputerArgumentType.java index 06840b154..2d6e0e77e 100644 --- a/src/main/java/dan200/computercraft/shared/command/arguments/ComputerArgumentType.java +++ b/src/main/java/dan200/computercraft/shared/command/arguments/ComputerArgumentType.java @@ -14,7 +14,7 @@ import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import dan200.computercraft.shared.command.arguments.ComputersArgumentType.ComputersSupplier; import dan200.computercraft.shared.computer.core.ServerComputer; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; import java.util.Collection; import java.util.concurrent.CompletableFuture; @@ -34,7 +34,7 @@ public final class ComputerArgumentType implements ArgumentType context, String name ) throws CommandSyntaxException + public static ServerComputer getComputerArgument( CommandContext context, String name ) throws CommandSyntaxException { return context.getArgument( name, ComputerSupplier.class ) .unwrap( context.getSource() ); @@ -98,6 +98,6 @@ public final class ComputerArgumentType implements ArgumentType getComputersArgument( CommandContext context, String name ) throws CommandSyntaxException + public static Collection getComputersArgument( CommandContext context, String name ) throws CommandSyntaxException { return context.getArgument( name, ComputersSupplier.class ) .unwrap( context.getSource() ); } - public static Set unwrap( ServerCommandSource source, Collection suppliers ) throws CommandSyntaxException + public static Set unwrap( CommandSourceStack source, Collection suppliers ) throws CommandSyntaxException { Set computers = new HashSet<>(); for( ComputersSupplier supplier : suppliers ) @@ -188,27 +188,27 @@ public final class ComputersArgumentType implements ArgumentType unwrap( ServerCommandSource source ) throws CommandSyntaxException; + Collection unwrap( CommandSourceStack source ) throws CommandSyntaxException; } public static class Serializer implements ArgumentSerializer { @Override - public void toPacket( @Nonnull ComputersArgumentType arg, @Nonnull PacketByteBuf buf ) + public void serializeToNetwork( @Nonnull ComputersArgumentType arg, @Nonnull FriendlyByteBuf buf ) { buf.writeBoolean( arg.requireSome ); } @Nonnull @Override - public ComputersArgumentType fromPacket( @Nonnull PacketByteBuf buf ) + public ComputersArgumentType deserializeFromNetwork( @Nonnull FriendlyByteBuf buf ) { return buf.readBoolean() ? SOME : MANY; } @Override - public void toJson( @Nonnull ComputersArgumentType arg, @Nonnull JsonObject json ) + public void serializeToJson( @Nonnull ComputersArgumentType arg, @Nonnull JsonObject json ) { json.addProperty( "requireSome", arg.requireSome ); } diff --git a/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java b/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java index d38c6b51c..41076124d 100644 --- a/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java +++ b/src/main/java/dan200/computercraft/shared/command/arguments/RepeatArgumentType.java @@ -15,11 +15,11 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import net.minecraft.command.argument.ArgumentTypes; -import net.minecraft.command.argument.serialize.ArgumentSerializer; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; +import net.minecraft.commands.synchronization.ArgumentSerializer; +import net.minecraft.commands.synchronization.ArgumentTypes; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; import javax.annotation.Nonnull; import java.util.ArrayList; @@ -138,11 +138,11 @@ public final class RepeatArgumentType implements ArgumentType> public static class Serializer implements ArgumentSerializer> { @Override - public void toPacket( @Nonnull RepeatArgumentType arg, @Nonnull PacketByteBuf buf ) + public void serializeToNetwork( @Nonnull RepeatArgumentType arg, @Nonnull FriendlyByteBuf buf ) { buf.writeBoolean( arg.flatten ); - ArgumentTypes.toPacket( buf, arg.child ); - buf.writeText( getMessage( arg ) ); + ArgumentTypes.serialize( buf, arg.child ); + buf.writeComponent( getMessage( arg ) ); } @Nonnull @@ -151,32 +151,32 @@ public final class RepeatArgumentType implements ArgumentType> "unchecked", "rawtypes" } ) - public RepeatArgumentType fromPacket( @Nonnull PacketByteBuf buf ) + public RepeatArgumentType deserializeFromNetwork( @Nonnull FriendlyByteBuf buf ) { boolean isList = buf.readBoolean(); - ArgumentType child = ArgumentTypes.fromPacket( buf ); - Text message = buf.readText(); + ArgumentType child = ArgumentTypes.deserialize( buf ); + Component message = buf.readComponent(); BiConsumer, ?> appender = isList ? ( list, x ) -> list.addAll( (Collection) x ) : List::add; return new RepeatArgumentType( child, appender, isList, new SimpleCommandExceptionType( message ) ); } @Override - public void toJson( @Nonnull RepeatArgumentType arg, @Nonnull JsonObject json ) + public void serializeToJson( @Nonnull RepeatArgumentType arg, @Nonnull JsonObject json ) { json.addProperty( "flatten", arg.flatten ); json.addProperty( "child", "<>" ); // TODO: Potentially serialize this using reflection. - json.addProperty( "error", Text.Serializer.toJson( getMessage( arg ) ) ); + json.addProperty( "error", Component.Serializer.toJson( getMessage( arg ) ) ); } - private static Text getMessage( RepeatArgumentType arg ) + private static Component getMessage( RepeatArgumentType arg ) { Message message = arg.some.create() .getRawMessage(); - if( message instanceof Text ) + if( message instanceof Component ) { - return (Text) message; + return (Component) message; } - return new LiteralText( message.getString() ); + return new TextComponent( message.getString() ); } } } diff --git a/src/main/java/dan200/computercraft/shared/command/builder/ArgCommand.java b/src/main/java/dan200/computercraft/shared/command/builder/ArgCommand.java index ea834c4c8..c478b67b5 100644 --- a/src/main/java/dan200/computercraft/shared/command/builder/ArgCommand.java +++ b/src/main/java/dan200/computercraft/shared/command/builder/ArgCommand.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.command.builder; import com.mojang.brigadier.Command; diff --git a/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java b/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java index 72233bd69..07c5d9ee6 100644 --- a/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java +++ b/src/main/java/dan200/computercraft/shared/command/builder/CommandBuilder.java @@ -13,7 +13,7 @@ import com.mojang.brigadier.builder.RequiredArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.tree.CommandNode; import dan200.computercraft.shared.command.arguments.RepeatArgumentType; -import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.commands.CommandSourceStack; import java.util.ArrayList; import java.util.Collections; @@ -34,14 +34,14 @@ public class CommandBuilder implements CommandNodeBuilder> private List> args = new ArrayList<>(); private Predicate requires; - public static CommandBuilder args() + public static CommandBuilder args() { return new CommandBuilder<>(); } - public static CommandBuilder command( String literal ) + public static CommandBuilder command( String literal ) { - CommandBuilder builder = new CommandBuilder<>(); + CommandBuilder builder = new CommandBuilder<>(); builder.args.add( literal( literal ) ); return builder; } diff --git a/src/main/java/dan200/computercraft/shared/command/builder/CommandNodeBuilder.java b/src/main/java/dan200/computercraft/shared/command/builder/CommandNodeBuilder.java index dc10a5eea..f2e108727 100644 --- a/src/main/java/dan200/computercraft/shared/command/builder/CommandNodeBuilder.java +++ b/src/main/java/dan200/computercraft/shared/command/builder/CommandNodeBuilder.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.command.builder; import com.mojang.brigadier.tree.CommandNode; diff --git a/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java b/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java index c7bd1248e..286b25986 100644 --- a/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java +++ b/src/main/java/dan200/computercraft/shared/command/builder/HelpingArgumentBuilder.java @@ -13,12 +13,12 @@ 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 net.minecraft.server.command.ServerCommandSource; -import net.minecraft.text.ClickEvent; -import net.minecraft.text.LiteralText; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.ClickEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.TextComponent; import javax.annotation.Nonnull; import java.util.ArrayList; @@ -31,11 +31,11 @@ import static dan200.computercraft.shared.command.text.ChatHelpers.translate; * An alternative to {@link LiteralArgumentBuilder} which also provides a {@code /... help} command, and defaults to that command when no arguments are * given. */ -public final class HelpingArgumentBuilder extends LiteralArgumentBuilder +public final class HelpingArgumentBuilder extends LiteralArgumentBuilder { - private static final Formatting HEADER = Formatting.LIGHT_PURPLE; - private static final Formatting SYNOPSIS = Formatting.AQUA; - private static final Formatting NAME = Formatting.GREEN; + private static final ChatFormatting HEADER = ChatFormatting.LIGHT_PURPLE; + private static final ChatFormatting SYNOPSIS = ChatFormatting.AQUA; + private static final ChatFormatting NAME = ChatFormatting.GREEN; private final Collection children = new ArrayList<>(); private HelpingArgumentBuilder( String literal ) @@ -48,11 +48,11 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder helpForChild( CommandNode node, String id, String command ) + private static Command helpForChild( CommandNode node, String id, String command ) { return context -> { context.getSource() - .sendFeedback( getHelp( context, + .sendSuccess( getHelp( context, node, id + "." + node.getName() .replace( '-', '_' ), @@ -61,28 +61,28 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder context, CommandNode node, String id, String command ) + private static Component getHelp( CommandContext context, CommandNode node, String id, String command ) { // An ugly hack to extract usage information from the dispatcher. We generate a temporary node, generate // the shorthand usage, and emit that. - CommandDispatcher dispatcher = context.getSource() + CommandDispatcher dispatcher = context.getSource() .getServer() - .getCommandManager() + .getCommands() .getDispatcher(); - CommandNode temp = new LiteralCommandNode<>( "_", null, x -> true, null, null, false ); + CommandNode temp = new LiteralCommandNode<>( "_", null, x -> true, null, null, false ); temp.addChild( node ); String usage = dispatcher.getSmartUsage( temp, context.getSource() ) .get( node ) .substring( node.getName() .length() ); - MutableText output = new LiteralText( "" ).append( coloured( "/" + command + usage, HEADER ) ) + MutableComponent output = new TextComponent( "" ).append( coloured( "/" + command + usage, HEADER ) ) .append( " " ) .append( coloured( translate( "commands." + id + ".synopsis" ), SYNOPSIS ) ) .append( "\n" ) .append( translate( "commands." + id + ".desc" ) ); - for( CommandNode child : node.getChildren() ) + for( CommandNode child : node.getChildren() ) { if( !child.getRequirement() .test( context.getSource() ) || !(child instanceof LiteralCommandNode) ) @@ -92,7 +92,7 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder then( final ArgumentBuilder argument ) + public LiteralArgumentBuilder then( final ArgumentBuilder argument ) { if( getRedirect() != null ) { @@ -129,7 +129,7 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder then( CommandNode argument ) + public LiteralArgumentBuilder then( CommandNode argument ) { if( !(argument instanceof LiteralCommandNode) ) { @@ -139,45 +139,45 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder executes( final Command command ) + public LiteralArgumentBuilder executes( final Command command ) { throw new IllegalStateException( "Cannot use executes on a HelpingArgumentBuilder" ); } @Override - public LiteralCommandNode build() + public LiteralCommandNode build() { return buildImpl( getLiteral().replace( '-', '_' ), getLiteral() ); } - private LiteralCommandNode build( @Nonnull String id, @Nonnull String command ) + private LiteralCommandNode build( @Nonnull String id, @Nonnull String command ) { return buildImpl( id + "." + getLiteral().replace( '-', '_' ), command + " " + getLiteral() ); } - private LiteralCommandNode buildImpl( String id, String command ) + private LiteralCommandNode buildImpl( String id, String command ) { HelpCommand helpCommand = new HelpCommand( id, command ); - LiteralCommandNode node = new LiteralCommandNode<>( getLiteral(), + LiteralCommandNode node = new LiteralCommandNode<>( getLiteral(), helpCommand, getRequirement(), getRedirect(), getRedirectModifier(), isFork() ); helpCommand.node = node; // Set up a /... help command - LiteralArgumentBuilder helpNode = - LiteralArgumentBuilder.literal( "help" ).requires( x -> getArguments().stream() - .anyMatch( - y -> y.getRequirement() - .test( - x ) ) ) + LiteralArgumentBuilder helpNode = + LiteralArgumentBuilder.literal( "help" ).requires( x -> getArguments().stream() + .anyMatch( + y -> y.getRequirement() + .test( + x ) ) ) .executes( helpCommand ); // Add all normal command children to this and the help node - for( CommandNode child : getArguments() ) + for( CommandNode child : getArguments() ) { node.addChild( child ); - helpNode.then( LiteralArgumentBuilder.literal( child.getName() ).requires( child.getRequirement() ) + helpNode.then( LiteralArgumentBuilder.literal( child.getName() ).requires( child.getRequirement() ) .executes( helpForChild( child, id, command ) ) .build() ); } @@ -185,9 +185,9 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder child = childBuilder.build( id, command ); + LiteralCommandNode child = childBuilder.build( id, command ); node.addChild( child ); - helpNode.then( LiteralArgumentBuilder.literal( child.getName() ).requires( child.getRequirement() ) + helpNode.then( LiteralArgumentBuilder.literal( child.getName() ).requires( child.getRequirement() ) .executes( helpForChild( child, id, command ) ) .redirect( child.getChild( "help" ) ) .build() ); @@ -198,11 +198,11 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder + private static final class HelpCommand implements Command { private final String id; private final String command; - LiteralCommandNode node; + LiteralCommandNode node; private HelpCommand( String id, String command ) { @@ -211,10 +211,10 @@ public final class HelpingArgumentBuilder extends LiteralArgumentBuilder context ) + public int run( CommandContext context ) { context.getSource() - .sendFeedback( getHelp( context, node, id, command ), false ); + .sendSuccess( getHelp( context, node, id, command ), false ); return 0; } } diff --git a/src/main/java/dan200/computercraft/shared/command/text/ChatHelpers.java b/src/main/java/dan200/computercraft/shared/command/text/ChatHelpers.java index 03a8deae0..6bce38c25 100644 --- a/src/main/java/dan200/computercraft/shared/command/text/ChatHelpers.java +++ b/src/main/java/dan200/computercraft/shared/command/text/ChatHelpers.java @@ -5,80 +5,80 @@ */ package dan200.computercraft.shared.command.text; -import net.minecraft.text.*; -import net.minecraft.util.Formatting; -import net.minecraft.util.math.BlockPos; +import net.minecraft.ChatFormatting; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.*; /** * Various helpers for building chat messages. */ public final class ChatHelpers { - private static final Formatting HEADER = Formatting.LIGHT_PURPLE; + private static final ChatFormatting HEADER = ChatFormatting.LIGHT_PURPLE; private ChatHelpers() {} - public static MutableText coloured( String text, Formatting colour ) + public static MutableComponent coloured( String text, ChatFormatting colour ) { - MutableText component = new LiteralText( text == null ? "" : text ); + MutableComponent component = new TextComponent( text == null ? "" : text ); component.setStyle( component.getStyle().withColor( colour ) ); return component; } - public static T coloured( T component, Formatting colour ) + public static T coloured( T component, ChatFormatting colour ) { component.setStyle( component.getStyle().withColor( colour ) ); return component; } - public static MutableText text( String text ) + public static MutableComponent text( String text ) { - return new LiteralText( text == null ? "" : text ); + return new TextComponent( text == null ? "" : text ); } - public static MutableText translate( String text ) + public static MutableComponent translate( String text ) { - return new TranslatableText( text == null ? "" : text ); + return new TranslatableComponent( text == null ? "" : text ); } - public static MutableText translate( String text, Object... args ) + public static MutableComponent translate( String text, Object... args ) { - return new TranslatableText( text == null ? "" : text, args ); + return new TranslatableComponent( text == null ? "" : text, args ); } - public static MutableText list( MutableText... children ) + public static MutableComponent list( MutableComponent... children ) { - MutableText component = new LiteralText( "" ); - for( MutableText child : children ) + MutableComponent component = new TextComponent( "" ); + for( MutableComponent child : children ) { component.append( child ); } return component; } - public static MutableText position( BlockPos pos ) + public static MutableComponent position( BlockPos pos ) { if( pos == null ) return translate( "commands.computercraft.generic.no_position" ); return translate( "commands.computercraft.generic.position", pos.getX(), pos.getY(), pos.getZ() ); } - public static MutableText bool( boolean value ) + public static MutableComponent bool( boolean value ) { return value - ? coloured( translate( "commands.computercraft.generic.yes" ), Formatting.GREEN ) - : coloured( translate( "commands.computercraft.generic.no" ), Formatting.RED ); + ? coloured( translate( "commands.computercraft.generic.yes" ), ChatFormatting.GREEN ) + : coloured( translate( "commands.computercraft.generic.no" ), ChatFormatting.RED ); } - public static MutableText link( MutableText component, String command, MutableText toolTip ) + public static MutableComponent link( MutableComponent component, String command, MutableComponent toolTip ) { return link( component, new ClickEvent( ClickEvent.Action.RUN_COMMAND, command ), toolTip ); } - public static MutableText link( MutableText component, ClickEvent click, MutableText toolTip ) + public static MutableComponent link( MutableComponent component, ClickEvent click, MutableComponent toolTip ) { Style style = component.getStyle(); - if( style.getColor() == null ) style = style.withColor( Formatting.YELLOW ); + if( style.getColor() == null ) style = style.withColor( ChatFormatting.YELLOW ); style = style.withClickEvent( click ); style = style.withHoverEvent( new HoverEvent( HoverEvent.Action.SHOW_TEXT, toolTip ) ); @@ -87,17 +87,17 @@ public final class ChatHelpers return component; } - public static MutableText header( String text ) + public static MutableComponent header( String text ) { return coloured( text, HEADER ); } - public static MutableText copy( String text ) + public static MutableComponent copy( String text ) { - LiteralText name = new LiteralText( text ); + TextComponent name = new TextComponent( text ); name.setStyle( name.getStyle() .withClickEvent( new ClickEvent( ClickEvent.Action.COPY_TO_CLIPBOARD, text ) ) - .withHoverEvent( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new TranslatableText( "gui.computercraft.tooltip.copy" ) ) ) ); + .withHoverEvent( new HoverEvent( HoverEvent.Action.SHOW_TEXT, new TranslatableComponent( "gui.computercraft.tooltip.copy" ) ) ) ); return name; } } diff --git a/src/main/java/dan200/computercraft/shared/command/text/ServerTableFormatter.java b/src/main/java/dan200/computercraft/shared/command/text/ServerTableFormatter.java index fe8ee5b7c..2076f77f0 100644 --- a/src/main/java/dan200/computercraft/shared/command/text/ServerTableFormatter.java +++ b/src/main/java/dan200/computercraft/shared/command/text/ServerTableFormatter.java @@ -6,32 +6,32 @@ package dan200.computercraft.shared.command.text; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; public class ServerTableFormatter implements TableFormatter { - private final ServerCommandSource source; + private final CommandSourceStack source; - public ServerTableFormatter( ServerCommandSource source ) + public ServerTableFormatter( CommandSourceStack source ) { this.source = source; } @Override @Nullable - public Text getPadding( Text component, int width ) + public Component getPadding( Component component, int width ) { int extraWidth = width - getWidth( component ); if( extraWidth <= 0 ) { return null; } - return new LiteralText( StringUtils.repeat( ' ', extraWidth ) ); + return new TextComponent( StringUtils.repeat( ' ', extraWidth ) ); } @Override @@ -41,15 +41,15 @@ public class ServerTableFormatter implements TableFormatter } @Override - public int getWidth( Text component ) + public int getWidth( Component component ) { return component.getString() .length(); } @Override - public void writeLine( int id, Text component ) + public void writeLine( int id, Component component ) { - source.sendFeedback( component, false ); + source.sendSuccess( component, false ); } } diff --git a/src/main/java/dan200/computercraft/shared/command/text/TableBuilder.java b/src/main/java/dan200/computercraft/shared/command/text/TableBuilder.java index c65c58294..8bdc6495a 100644 --- a/src/main/java/dan200/computercraft/shared/command/text/TableBuilder.java +++ b/src/main/java/dan200/computercraft/shared/command/text/TableBuilder.java @@ -9,9 +9,9 @@ package dan200.computercraft.shared.command.text; import dan200.computercraft.shared.command.CommandUtils; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.network.client.ChatTableClientMessage; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -21,12 +21,12 @@ import java.util.List; public class TableBuilder { private final int id; - private final Text[] headers; - private final ArrayList rows = new ArrayList<>(); + private final Component[] headers; + private final ArrayList rows = new ArrayList<>(); private int columns = -1; private int additional; - public TableBuilder( int id, @Nonnull Text... headers ) + public TableBuilder( int id, @Nonnull Component... headers ) { if( id < 0 ) { @@ -54,7 +54,7 @@ public class TableBuilder throw new IllegalArgumentException( "ID must be positive" ); } this.id = id; - this.headers = new Text[headers.length]; + this.headers = new Component[headers.length]; columns = headers.length; for( int i = 0; i < headers.length; i++ ) @@ -63,7 +63,7 @@ public class TableBuilder } } - public void row( @Nonnull Text... row ) + public void row( @Nonnull Component... row ) { if( columns == -1 ) { @@ -101,13 +101,13 @@ public class TableBuilder } @Nullable - public Text[] getHeaders() + public Component[] getHeaders() { return headers; } @Nonnull - public List getRows() + public List getRows() { return rows; } @@ -122,12 +122,12 @@ public class TableBuilder this.additional = additional; } - public void display( ServerCommandSource source ) + public void display( CommandSourceStack source ) { if( CommandUtils.isPlayer( source ) ) { trim( 18 ); - NetworkHandler.sendToPlayer( (ServerPlayerEntity) source.getEntity(), new ChatTableClientMessage( this ) ); + NetworkHandler.sendToPlayer( (ServerPlayer) source.getEntity(), new ChatTableClientMessage( this ) ); } else { diff --git a/src/main/java/dan200/computercraft/shared/command/text/TableFormatter.java b/src/main/java/dan200/computercraft/shared/command/text/TableFormatter.java index 3c942e2d8..a3db10584 100644 --- a/src/main/java/dan200/computercraft/shared/command/text/TableFormatter.java +++ b/src/main/java/dan200/computercraft/shared/command/text/TableFormatter.java @@ -6,9 +6,9 @@ package dan200.computercraft.shared.command.text; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; @@ -18,8 +18,8 @@ import static dan200.computercraft.shared.command.text.ChatHelpers.translate; public interface TableFormatter { - Text SEPARATOR = coloured( "| ", Formatting.GRAY ); - Text HEADER = coloured( "=", Formatting.GRAY ); + Component SEPARATOR = coloured( "| ", ChatFormatting.GRAY ); + Component HEADER = coloured( "=", ChatFormatting.GRAY ); default int display( TableBuilder table ) { @@ -32,7 +32,7 @@ public interface TableFormatter int columns = table.getColumns(); int[] maxWidths = new int[columns]; - Text[] headers = table.getHeaders(); + Component[] headers = table.getHeaders(); if( headers != null ) { for( int i = 0; i < columns; i++ ) @@ -41,7 +41,7 @@ public interface TableFormatter } } - for( Text[] row : table.getRows() ) + for( Component[] row : table.getRows() ) { for( int i = 0; i < row.length; i++ ) { @@ -71,11 +71,11 @@ public interface TableFormatter if( headers != null ) { - LiteralText line = new LiteralText( "" ); + TextComponent line = new TextComponent( "" ); for( int i = 0; i < columns - 1; i++ ) { line.append( headers[i] ); - Text padding = getPadding( headers[i], maxWidths[i] ); + Component padding = getPadding( headers[i], maxWidths[i] ); if( padding != null ) { line.append( padding ); @@ -90,16 +90,16 @@ public interface TableFormatter // it a tad prettier. int rowCharWidth = getWidth( HEADER ); int rowWidth = totalWidth / rowCharWidth + (totalWidth % rowCharWidth == 0 ? 0 : 1); - writeLine( rowId++, coloured( StringUtils.repeat( HEADER.getString(), rowWidth ), Formatting.GRAY ) ); + writeLine( rowId++, coloured( StringUtils.repeat( HEADER.getString(), rowWidth ), ChatFormatting.GRAY ) ); } - for( Text[] row : table.getRows() ) + for( Component[] row : table.getRows() ) { - LiteralText line = new LiteralText( "" ); + TextComponent line = new TextComponent( "" ); for( int i = 0; i < columns - 1; i++ ) { line.append( row[i] ); - Text padding = getPadding( row[i], maxWidths[i] ); + Component padding = getPadding( row[i], maxWidths[i] ); if( padding != null ) { line.append( padding ); @@ -112,13 +112,13 @@ public interface TableFormatter if( table.getAdditional() > 0 ) { - writeLine( rowId++, coloured( translate( "commands.computercraft.generic.additional_rows", table.getAdditional() ), Formatting.AQUA ) ); + writeLine( rowId++, coloured( translate( "commands.computercraft.generic.additional_rows", table.getAdditional() ), ChatFormatting.AQUA ) ); } return rowId - table.getId(); } - int getWidth( Text component ); + int getWidth( Component component ); /** * Get the minimum padding between each column. @@ -135,7 +135,7 @@ public interface TableFormatter * @return The padding for this component, or {@code null} if none is needed. */ @Nullable - Text getPadding( Text component, int width ); + Component getPadding( Component component, int width ); - void writeLine( int id, Text component ); + void writeLine( int id, Component component ); } diff --git a/src/main/java/dan200/computercraft/shared/common/BlockGeneric.java b/src/main/java/dan200/computercraft/shared/common/BlockGeneric.java index 8150b6ec2..3ed0c90c7 100644 --- a/src/main/java/dan200/computercraft/shared/common/BlockGeneric.java +++ b/src/main/java/dan200/computercraft/shared/common/BlockGeneric.java @@ -6,29 +6,29 @@ package dan200.computercraft.shared.common; -import net.minecraft.block.Block; -import net.minecraft.block.BlockRenderType; -import net.minecraft.block.BlockState; -import net.minecraft.block.BlockWithEntity; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseEntityBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Random; -public abstract class BlockGeneric extends BlockWithEntity +public abstract class BlockGeneric extends BaseEntityBlock { private final BlockEntityType type; - public BlockGeneric( Settings settings, BlockEntityType type ) + public BlockGeneric( Properties settings, BlockEntityType type ) { super( settings ); this.type = type; @@ -40,15 +40,15 @@ public abstract class BlockGeneric extends BlockWithEntity } @Override - public BlockRenderType getRenderType( BlockState state ) + public RenderShape getRenderShape( BlockState state ) { - return BlockRenderType.MODEL; + return RenderShape.MODEL; } @Override @Deprecated - public final void neighborUpdate( @Nonnull BlockState state, World world, @Nonnull BlockPos pos, @Nonnull Block neighbourBlock, - @Nonnull BlockPos neighbourPos, boolean isMoving ) + public final void neighborChanged( @Nonnull BlockState state, Level world, @Nonnull BlockPos pos, @Nonnull Block neighbourBlock, + @Nonnull BlockPos neighbourPos, boolean isMoving ) { BlockEntity tile = world.getBlockEntity( pos ); if( tile instanceof TileGeneric ) @@ -59,7 +59,7 @@ public abstract class BlockGeneric extends BlockWithEntity @Override @Deprecated - public final void onStateReplaced( @Nonnull BlockState block, @Nonnull World world, @Nonnull BlockPos pos, BlockState replace, boolean bool ) + public final void onRemove( @Nonnull BlockState block, @Nonnull Level world, @Nonnull BlockPos pos, BlockState replace, boolean bool ) { if( block.getBlock() == replace.getBlock() ) { @@ -67,7 +67,7 @@ public abstract class BlockGeneric extends BlockWithEntity } BlockEntity tile = world.getBlockEntity( pos ); - super.onStateReplaced( block, world, pos, replace, bool ); + super.onRemove( block, world, pos, replace, bool ); world.removeBlockEntity( pos ); if( tile instanceof TileGeneric ) { @@ -78,16 +78,16 @@ public abstract class BlockGeneric extends BlockWithEntity @Nonnull @Override @Deprecated - public final ActionResult onUse( @Nonnull BlockState state, World world, @Nonnull BlockPos pos, @Nonnull PlayerEntity player, @Nonnull Hand hand, - @Nonnull BlockHitResult hit ) + public final InteractionResult use( @Nonnull BlockState state, Level world, @Nonnull BlockPos pos, @Nonnull Player player, @Nonnull InteractionHand hand, + @Nonnull BlockHitResult hit ) { BlockEntity tile = world.getBlockEntity( pos ); - return tile instanceof TileGeneric ? ((TileGeneric) tile).onActivate( player, hand, hit ) : ActionResult.PASS; + return tile instanceof TileGeneric ? ((TileGeneric) tile).onActivate( player, hand, hit ) : InteractionResult.PASS; } @Override @Deprecated - public void scheduledTick( @Nonnull BlockState state, ServerWorld world, @Nonnull BlockPos pos, @Nonnull Random rand ) + public void tick( @Nonnull BlockState state, ServerLevel world, @Nonnull BlockPos pos, @Nonnull Random rand ) { BlockEntity te = world.getBlockEntity( pos ); if( te instanceof TileGeneric ) @@ -98,11 +98,11 @@ public abstract class BlockGeneric extends BlockWithEntity @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { - if ( this.type != null ) + if( this.type != null ) { - return type.instantiate( pos, state ); + return type.create( pos, state ); } return null; } diff --git a/src/main/java/dan200/computercraft/shared/common/ClientTerminal.java b/src/main/java/dan200/computercraft/shared/common/ClientTerminal.java index 45601a8bc..be189e35e 100644 --- a/src/main/java/dan200/computercraft/shared/common/ClientTerminal.java +++ b/src/main/java/dan200/computercraft/shared/common/ClientTerminal.java @@ -8,7 +8,7 @@ package dan200.computercraft.shared.common; import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.shared.network.client.TerminalState; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; public class ClientTerminal implements ITerminal { @@ -80,12 +80,12 @@ public class ClientTerminal implements ITerminal } } - public void readDescription( NbtCompound nbt ) + public void readDescription( CompoundTag nbt ) { colour = nbt.getBoolean( "colour" ); if( nbt.contains( "terminal" ) ) { - NbtCompound terminal = nbt.getCompound( "terminal" ); + CompoundTag terminal = nbt.getCompound( "terminal" ); resizeTerminal( terminal.getInt( "term_width" ), terminal.getInt( "term_height" ) ); this.terminal.readFromNBT( terminal ); } diff --git a/src/main/java/dan200/computercraft/shared/common/ColourableRecipe.java b/src/main/java/dan200/computercraft/shared/common/ColourableRecipe.java index 251bb104b..21c0282ad 100644 --- a/src/main/java/dan200/computercraft/shared/common/ColourableRecipe.java +++ b/src/main/java/dan200/computercraft/shared/common/ColourableRecipe.java @@ -8,34 +8,34 @@ package dan200.computercraft.shared.common; import dan200.computercraft.shared.util.ColourTracker; import dan200.computercraft.shared.util.ColourUtils; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.SpecialCraftingRecipe; -import net.minecraft.recipe.SpecialRecipeSerializer; -import net.minecraft.util.DyeColor; -import net.minecraft.util.Identifier; -import net.minecraft.world.World; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; -public final class ColourableRecipe extends SpecialCraftingRecipe +public final class ColourableRecipe extends CustomRecipe { - public static final RecipeSerializer SERIALIZER = new SpecialRecipeSerializer<>( ColourableRecipe::new ); + public static final RecipeSerializer SERIALIZER = new SimpleRecipeSerializer<>( ColourableRecipe::new ); - private ColourableRecipe( Identifier id ) + private ColourableRecipe( ResourceLocation id ) { super( id ); } @Override - public boolean matches( @Nonnull CraftingInventory inv, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inv, @Nonnull Level world ) { boolean hasColourable = false; boolean hasDye = false; - for( int i = 0; i < inv.size(); i++ ) + for( int i = 0; i < inv.getContainerSize(); i++ ) { - ItemStack stack = inv.getStack( i ); + ItemStack stack = inv.getItem( i ); if( stack.isEmpty() ) { continue; @@ -64,15 +64,15 @@ public final class ColourableRecipe extends SpecialCraftingRecipe @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inv ) + public ItemStack assemble( @Nonnull CraftingContainer inv ) { ItemStack colourable = ItemStack.EMPTY; ColourTracker tracker = new ColourTracker(); - for( int i = 0; i < inv.size(); i++ ) + for( int i = 0; i < inv.getContainerSize(); i++ ) { - ItemStack stack = inv.getStack( i ); + ItemStack stack = inv.getItem( i ); if( stack.isEmpty() ) { @@ -93,7 +93,7 @@ public final class ColourableRecipe extends SpecialCraftingRecipe } @Override - public boolean fits( int x, int y ) + public boolean canCraftInDimensions( int x, int y ) { return x >= 2 && y >= 2; } diff --git a/src/main/java/dan200/computercraft/shared/common/ContainerHeldItem.java b/src/main/java/dan200/computercraft/shared/common/ContainerHeldItem.java index e3150f8e8..e3492864e 100644 --- a/src/main/java/dan200/computercraft/shared/common/ContainerHeldItem.java +++ b/src/main/java/dan200/computercraft/shared/common/ContainerHeldItem.java @@ -9,34 +9,34 @@ package dan200.computercraft.shared.common; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.network.container.HeldItemContainerData; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerType; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; -import net.minecraft.util.Hand; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class ContainerHeldItem extends ScreenHandler +public class ContainerHeldItem extends AbstractContainerMenu { private final ItemStack stack; - private final Hand hand; + private final InteractionHand hand; - public ContainerHeldItem( ScreenHandlerType type, int id, PlayerEntity player, Hand hand ) + public ContainerHeldItem( MenuType type, int id, Player player, InteractionHand hand ) { super( type, id ); this.hand = hand; - stack = player.getStackInHand( hand ) + stack = player.getItemInHand( hand ) .copy(); } - public static ContainerHeldItem createPrintout( int id, PlayerInventory inventory, HeldItemContainerData data ) + public static ContainerHeldItem createPrintout( int id, Inventory inventory, HeldItemContainerData data ) { return new ContainerHeldItem( ComputerCraftRegistry.ModContainers.PRINTOUT, id, inventory.player, data.getHand() ); } @@ -48,48 +48,48 @@ public class ContainerHeldItem extends ScreenHandler } @Override - public boolean canUse( @Nonnull PlayerEntity player ) + public boolean stillValid( @Nonnull Player player ) { if( !player.isAlive() ) { return false; } - ItemStack stack = player.getStackInHand( hand ); + ItemStack stack = player.getItemInHand( hand ); return stack == this.stack || !stack.isEmpty() && !this.stack.isEmpty() && stack.getItem() == this.stack.getItem(); } public static class Factory implements ExtendedScreenHandlerFactory { - private final ScreenHandlerType type; - private final Text name; - private final Hand hand; + private final MenuType type; + private final Component name; + private final InteractionHand hand; - public Factory( ScreenHandlerType type, ItemStack stack, Hand hand ) + public Factory( MenuType type, ItemStack stack, InteractionHand hand ) { this.type = type; - name = stack.getName(); + name = stack.getHoverName(); this.hand = hand; } @Nonnull @Override - public Text getDisplayName() + public Component getDisplayName() { return name; } @Nullable @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory inventory, @Nonnull PlayerEntity player ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory inventory, @Nonnull Player player ) { return new ContainerHeldItem( type, id, player, hand ); } @Override - public void writeScreenOpeningData( ServerPlayerEntity serverPlayerEntity, PacketByteBuf packetByteBuf ) + public void writeScreenOpeningData( ServerPlayer serverPlayerEntity, FriendlyByteBuf packetByteBuf ) { - packetByteBuf.writeEnumConstant( hand ); + packetByteBuf.writeEnum( hand ); } } } diff --git a/src/main/java/dan200/computercraft/shared/common/DefaultBundledRedstoneProvider.java b/src/main/java/dan200/computercraft/shared/common/DefaultBundledRedstoneProvider.java index b1642f413..09800368b 100644 --- a/src/main/java/dan200/computercraft/shared/common/DefaultBundledRedstoneProvider.java +++ b/src/main/java/dan200/computercraft/shared/common/DefaultBundledRedstoneProvider.java @@ -7,22 +7,22 @@ package dan200.computercraft.shared.common; import dan200.computercraft.api.redstone.IBundledRedstoneProvider; -import net.minecraft.block.Block; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import javax.annotation.Nonnull; public class DefaultBundledRedstoneProvider implements IBundledRedstoneProvider { @Override - public int getBundledRedstoneOutput( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public int getBundledRedstoneOutput( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) { return getDefaultBundledRedstoneOutput( world, pos, side ); } - public static int getDefaultBundledRedstoneOutput( World world, BlockPos pos, Direction side ) + public static int getDefaultBundledRedstoneOutput( Level world, BlockPos pos, Direction side ) { Block block = world.getBlockState( pos ) .getBlock(); diff --git a/src/main/java/dan200/computercraft/shared/common/IBundledRedstoneBlock.java b/src/main/java/dan200/computercraft/shared/common/IBundledRedstoneBlock.java index 0be19a1ff..90478f3bb 100644 --- a/src/main/java/dan200/computercraft/shared/common/IBundledRedstoneBlock.java +++ b/src/main/java/dan200/computercraft/shared/common/IBundledRedstoneBlock.java @@ -3,16 +3,15 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.common; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; public interface IBundledRedstoneBlock { - boolean getBundledRedstoneConnectivity( World world, BlockPos pos, Direction side ); + boolean getBundledRedstoneConnectivity( Level world, BlockPos pos, Direction side ); - int getBundledRedstoneOutput( World world, BlockPos pos, Direction side ); + int getBundledRedstoneOutput( Level world, BlockPos pos, Direction side ); } diff --git a/src/main/java/dan200/computercraft/shared/common/IColouredItem.java b/src/main/java/dan200/computercraft/shared/common/IColouredItem.java index d3e5041ec..50597e449 100644 --- a/src/main/java/dan200/computercraft/shared/common/IColouredItem.java +++ b/src/main/java/dan200/computercraft/shared/common/IColouredItem.java @@ -6,8 +6,8 @@ package dan200.computercraft.shared.common; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; public interface IColouredItem { @@ -20,7 +20,7 @@ public interface IColouredItem static int getColourBasic( ItemStack stack ) { - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); return tag != null && tag.contains( NBT_COLOUR ) ? tag.getInt( NBT_COLOUR ) : -1; } @@ -35,7 +35,7 @@ public interface IColouredItem { if( colour == -1 ) { - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); if( tag != null ) { tag.remove( NBT_COLOUR ); @@ -43,7 +43,7 @@ public interface IColouredItem } else { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_COLOUR, colour ); } } diff --git a/src/main/java/dan200/computercraft/shared/common/ITerminal.java b/src/main/java/dan200/computercraft/shared/common/ITerminal.java index 2a6a9a9e0..48577e5da 100644 --- a/src/main/java/dan200/computercraft/shared/common/ITerminal.java +++ b/src/main/java/dan200/computercraft/shared/common/ITerminal.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.common; import dan200.computercraft.core.terminal.Terminal; diff --git a/src/main/java/dan200/computercraft/shared/common/ServerTerminal.java b/src/main/java/dan200/computercraft/shared/common/ServerTerminal.java index 1adb7207e..6a95c9e5b 100644 --- a/src/main/java/dan200/computercraft/shared/common/ServerTerminal.java +++ b/src/main/java/dan200/computercraft/shared/common/ServerTerminal.java @@ -8,7 +8,7 @@ package dan200.computercraft.shared.common; import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.shared.network.client.TerminalState; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; import java.util.concurrent.atomic.AtomicBoolean; @@ -85,12 +85,12 @@ public class ServerTerminal implements ITerminal return new TerminalState( colour, terminal ); } - public void writeDescription( NbtCompound nbt ) + public void writeDescription( CompoundTag nbt ) { nbt.putBoolean( "colour", colour ); if( terminal != null ) { - NbtCompound terminal = new NbtCompound(); + CompoundTag terminal = new CompoundTag(); terminal.putInt( "term_width", this.terminal.getWidth() ); terminal.putInt( "term_height", this.terminal.getHeight() ); this.terminal.writeToNBT( terminal ); diff --git a/src/main/java/dan200/computercraft/shared/common/TileGeneric.java b/src/main/java/dan200/computercraft/shared/common/TileGeneric.java index 787a18442..7363d0b4b 100644 --- a/src/main/java/dan200/computercraft/shared/common/TileGeneric.java +++ b/src/main/java/dan200/computercraft/shared/common/TileGeneric.java @@ -7,15 +7,15 @@ package dan200.computercraft.shared.common; import net.fabricmc.fabric.api.block.entity.BlockEntityClientSerializable; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nonnull; @@ -36,16 +36,16 @@ public abstract class TileGeneric extends BlockEntity implements BlockEntityClie public final void updateBlock() { - markDirty(); - BlockPos pos = getPos(); - BlockState state = getCachedState(); - getWorld().updateListeners( pos, state, state, 3 ); + setChanged(); + BlockPos pos = getBlockPos(); + BlockState state = getBlockState(); + getLevel().sendBlockUpdated( pos, state, state, 3 ); } @Nonnull - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - return ActionResult.PASS; + return InteractionResult.PASS; } public void onNeighbourChange( @Nonnull BlockPos neighbour ) @@ -60,9 +60,9 @@ public abstract class TileGeneric extends BlockEntity implements BlockEntityClie { } - public boolean isUsable( PlayerEntity player, boolean ignoreRange ) + public boolean isUsable( Player player, boolean ignoreRange ) { - if( player == null || !player.isAlive() || getWorld().getBlockEntity( getPos() ) != this ) + if( player == null || !player.isAlive() || getLevel().getBlockEntity( getBlockPos() ) != this ) { return false; } @@ -72,33 +72,33 @@ public abstract class TileGeneric extends BlockEntity implements BlockEntityClie } double range = getInteractRange( player ); - BlockPos pos = getPos(); - return player.getEntityWorld() == getWorld() && player.squaredDistanceTo( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ) <= range * range; + BlockPos pos = getBlockPos(); + return player.getCommandSenderWorld() == getLevel() && player.distanceToSqr( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ) <= range * range; } - protected double getInteractRange( PlayerEntity player ) + protected double getInteractRange( Player player ) { return 8.0; } @Override - public void fromClientTag( NbtCompound compoundTag ) + public void fromClientTag( CompoundTag compoundTag ) { readDescription( compoundTag ); } - protected void readDescription( @Nonnull NbtCompound nbt ) + protected void readDescription( @Nonnull CompoundTag nbt ) { } @Override - public NbtCompound toClientTag( NbtCompound compoundTag ) + public CompoundTag toClientTag( CompoundTag compoundTag ) { writeDescription( compoundTag ); return compoundTag; } - protected void writeDescription( @Nonnull NbtCompound nbt ) + protected void writeDescription( @Nonnull CompoundTag nbt ) { } } diff --git a/src/main/java/dan200/computercraft/shared/computer/apis/CommandAPI.java b/src/main/java/dan200/computercraft/shared/computer/apis/CommandAPI.java index a739044e2..25cce42ed 100644 --- a/src/main/java/dan200/computercraft/shared/computer/apis/CommandAPI.java +++ b/src/main/java/dan200/computercraft/shared/computer/apis/CommandAPI.java @@ -13,17 +13,17 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.lua.*; import dan200.computercraft.shared.computer.blocks.TileCommandComputer; import dan200.computercraft.shared.util.NBTUtil; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.CommandManager; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.state.property.Property; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; import java.util.*; @@ -66,19 +66,19 @@ public class CommandAPI implements ILuaAPI private Object[] doCommand( String command ) { - MinecraftServer server = computer.getWorld() + MinecraftServer server = computer.getLevel() .getServer(); - if( server == null || !server.areCommandBlocksEnabled() ) + if( server == null || !server.isCommandBlockEnabled() ) { return new Object[] { false, createOutput( "Command blocks disabled by server" ) }; } - CommandManager commandManager = server.getCommandManager(); + Commands commandManager = server.getCommands(); TileCommandComputer.CommandReceiver receiver = computer.getReceiver(); try { receiver.clearOutput(); - int result = commandManager.execute( computer.getSource(), command ); + int result = commandManager.performCommand( computer.getSource(), command ); return new Object[] { result > 0, receiver.copyOutput(), result }; } catch( Throwable t ) @@ -132,14 +132,14 @@ public class CommandAPI implements ILuaAPI @LuaFunction( mainThread = true ) public final List list( IArguments args ) throws LuaException { - MinecraftServer server = computer.getWorld() + MinecraftServer server = computer.getLevel() .getServer(); if( server == null ) { return Collections.emptyList(); } - CommandNode node = server.getCommandManager() + CommandNode node = server.getCommands() .getDispatcher() .getRoot(); for( int j = 0; j < args.count(); j++ ) @@ -176,7 +176,7 @@ public class CommandAPI implements ILuaAPI public final Object[] getBlockPosition() { // This is probably safe to do on the Lua thread. Probably. - BlockPos pos = computer.getPos(); + BlockPos pos = computer.getBlockPos(); return new Object[] { pos.getX(), pos.getY(), pos.getZ() }; } @@ -201,10 +201,10 @@ public class CommandAPI implements ILuaAPI public final List> getBlockInfos( int minX, int minY, int minZ, int maxX, int maxY, int maxZ ) throws LuaException { // Get the details of the block - World world = computer.getWorld(); + Level world = computer.getLevel(); BlockPos min = new BlockPos( Math.min( minX, maxX ), Math.min( minY, maxY ), Math.min( minZ, maxZ ) ); BlockPos max = new BlockPos( Math.max( minX, maxX ), Math.max( minY, maxY ), Math.max( minZ, maxZ ) ); - if( !world.isInBuildLimit( min ) || !world.isInBuildLimit( max ) ) + if( !world.isInWorldBounds( min ) || !world.isInWorldBounds( max ) ) { throw new LuaException( "Co-ordinates out of range" ); } @@ -231,18 +231,18 @@ public class CommandAPI implements ILuaAPI return results; } - private static Map getBlockInfo( World world, BlockPos pos ) + private static Map getBlockInfo( Level world, BlockPos pos ) { // Get the details of the block BlockState state = world.getBlockState( pos ); Block block = state.getBlock(); Map table = new HashMap<>(); - table.put( "name", Registry.BLOCK.getId( block ).toString() ); - table.put( "world", world.getRegistryKey() ); + table.put( "name", Registry.BLOCK.getKey( block ).toString() ); + table.put( "world", world.dimension() ); Map stateTable = new HashMap<>(); - for( ImmutableMap.Entry, Comparable> entry : state.getEntries().entrySet() ) + for( ImmutableMap.Entry, Comparable> entry : state.getValues().entrySet() ) { Property property = entry.getKey(); stateTable.put( property.getName(), getPropertyValue( property, entry.getValue() ) ); @@ -252,7 +252,7 @@ public class CommandAPI implements ILuaAPI BlockEntity tile = world.getBlockEntity( pos ); if( tile != null ) { - table.put( "nbt", NBTUtil.toLua( tile.writeNbt( new NbtCompound() ) ) ); + table.put( "nbt", NBTUtil.toLua( tile.save( new CompoundTag() ) ) ); } return table; @@ -268,7 +268,7 @@ public class CommandAPI implements ILuaAPI { return value; } - return property.name( value ); + return property.getName( value ); } /** @@ -287,9 +287,9 @@ public class CommandAPI implements ILuaAPI public final Map getBlockInfo( int x, int y, int z ) throws LuaException { // Get the details of the block - World world = computer.getWorld(); + Level world = computer.getLevel(); BlockPos position = new BlockPos( x, y, z ); - if( world.isInBuildLimit( position ) ) + if( world.isInWorldBounds( position ) ) { return getBlockInfo( world, position ); } diff --git a/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputer.java b/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputer.java index 39b725791..5e5f2ceda 100644 --- a/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputer.java @@ -10,45 +10,45 @@ import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerState; import dan200.computercraft.shared.computer.items.ComputerItemFactory; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.EnumProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.DirectionProperty; +import net.minecraft.world.level.block.state.properties.EnumProperty; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class BlockComputer extends BlockComputerBase { - public static final EnumProperty STATE = EnumProperty.of( "state", ComputerState.class ); - public static final DirectionProperty FACING = Properties.HORIZONTAL_FACING; + public static final EnumProperty STATE = EnumProperty.create( "state", ComputerState.class ); + public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; - public BlockComputer( Settings settings, ComputerFamily family, BlockEntityType type ) + public BlockComputer( Properties settings, ComputerFamily family, BlockEntityType type ) { super( settings, family, type ); - setDefaultState( getDefaultState().with( FACING, Direction.NORTH ) - .with( STATE, ComputerState.OFF ) ); + registerDefaultState( defaultBlockState().setValue( FACING, Direction.NORTH ) + .setValue( STATE, ComputerState.OFF ) ); } @Nullable @Override - public BlockState getPlacementState( ItemPlacementContext placement ) + public BlockState getStateForPlacement( BlockPlaceContext placement ) { - return getDefaultState().with( FACING, - placement.getPlayerFacing() + return defaultBlockState().setValue( FACING, + placement.getHorizontalDirection() .getOpposite() ); } @Override - protected void appendProperties( StateManager.Builder builder ) + protected void createBlockStateDefinition( StateDefinition.Builder builder ) { builder.add( FACING, STATE ); } @@ -62,7 +62,7 @@ public class BlockComputer extends BlockComputerBase public BlockEntityType getTypeByFamily( ComputerFamily family ) { - return switch ( family ) + return switch( family ) { case COMMAND -> ComputerCraftRegistry.ModTiles.COMPUTER_COMMAND; case ADVANCED -> ComputerCraftRegistry.ModTiles.COMPUTER_ADVANCED; @@ -72,7 +72,7 @@ public class BlockComputer extends BlockComputerBase @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileComputer( getFamily(), getTypeByFamily( getFamily() ), pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputerBase.java b/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputerBase.java index 7a366c74a..00dd5a4ea 100644 --- a/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputerBase.java +++ b/src/main/java/dan200/computercraft/shared/computer/blocks/BlockComputerBase.java @@ -13,34 +13,34 @@ import dan200.computercraft.shared.common.IBundledRedstoneBlock; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.computer.items.IComputerItem; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityTicker; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.loot.context.LootContext; -import net.minecraft.loot.context.LootContextParameters; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.stat.Stats; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.stats.Stats; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; public abstract class BlockComputerBase extends BlockGeneric implements IBundledRedstoneBlock { - private static final Identifier DROP = new Identifier( ComputerCraft.MOD_ID, "computer" ); + private static final ResourceLocation DROP = new ResourceLocation( ComputerCraft.MOD_ID, "computer" ); private final ComputerFamily family; - protected BlockComputerBase( Settings settings, ComputerFamily family, BlockEntityType type ) + protected BlockComputerBase( Properties settings, ComputerFamily family, BlockEntityType type ) { super( settings, type ); this.family = family; @@ -48,9 +48,9 @@ public abstract class BlockComputerBase extends Bloc @Override @Deprecated - public void onBlockAdded( @Nonnull BlockState state, @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState oldState, boolean isMoving ) + public void onPlace( @Nonnull BlockState state, @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState oldState, boolean isMoving ) { - super.onBlockAdded( state, world, pos, oldState, isMoving ); + super.onPlace( state, world, pos, oldState, isMoving ); BlockEntity tile = world.getBlockEntity( pos ); if( tile instanceof TileComputerBase ) @@ -61,21 +61,21 @@ public abstract class BlockComputerBase extends Bloc @Override @Deprecated - public boolean emitsRedstonePower( @Nonnull BlockState state ) + public boolean isSignalSource( @Nonnull BlockState state ) { return true; } @Override @Deprecated - public int getWeakRedstonePower( @Nonnull BlockState state, @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull Direction incomingSide ) + public int getSignal( @Nonnull BlockState state, @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction incomingSide ) { - return getStrongRedstonePower( state, world, pos, incomingSide ); + return getDirectSignal( state, world, pos, incomingSide ); } @Override @Deprecated - public int getStrongRedstonePower( @Nonnull BlockState state, BlockView world, @Nonnull BlockPos pos, @Nonnull Direction incomingSide ) + public int getDirectSignal( @Nonnull BlockState state, BlockGetter world, @Nonnull BlockPos pos, @Nonnull Direction incomingSide ) { BlockEntity entity = world.getBlockEntity( pos ); if( !(entity instanceof TileComputerBase) ) @@ -100,13 +100,13 @@ public abstract class BlockComputerBase extends Bloc } @Override - public boolean getBundledRedstoneConnectivity( World world, BlockPos pos, Direction side ) + public boolean getBundledRedstoneConnectivity( Level world, BlockPos pos, Direction side ) { return true; } @Override - public int getBundledRedstoneOutput( World world, BlockPos pos, Direction side ) + public int getBundledRedstoneOutput( Level world, BlockPos pos, Direction side ) { BlockEntity entity = world.getBlockEntity( pos ); if( !(entity instanceof TileComputerBase) ) @@ -126,21 +126,21 @@ public abstract class BlockComputerBase extends Bloc } @Override - public void afterBreak( @Nonnull World world, PlayerEntity player, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable BlockEntity tile, - @Nonnull ItemStack tool ) + public void playerDestroy( @Nonnull Level world, Player player, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable BlockEntity tile, + @Nonnull ItemStack tool ) { // Don't drop blocks here - see onBlockHarvested. - player.incrementStat( Stats.MINED.getOrCreateStat( this ) ); - player.addExhaustion( 0.005F ); + player.awardStat( Stats.BLOCK_MINED.get( this ) ); + player.causeFoodExhaustion( 0.005F ); } @Override - public void onPlaced( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, @Nonnull ItemStack stack ) + public void setPlacedBy( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, @Nonnull ItemStack stack ) { - super.onPlaced( world, pos, state, placer, stack ); + super.setPlacedBy( world, pos, state, placer, stack ); BlockEntity tile = world.getBlockEntity( pos ); - if( !world.isClient && tile instanceof IComputerTile && stack.getItem() instanceof IComputerItem ) + if( !world.isClientSide && tile instanceof IComputerTile && stack.getItem() instanceof IComputerItem ) { IComputerTile computer = (IComputerTile) tile; IComputerItem item = (IComputerItem) stack.getItem(); @@ -161,7 +161,7 @@ public abstract class BlockComputerBase extends Bloc @Nonnull @Override - public ItemStack getPickStack( BlockView world, BlockPos pos, BlockState state ) + public ItemStack getCloneItemStack( BlockGetter world, BlockPos pos, BlockState state ) { BlockEntity tile = world.getBlockEntity( pos ); if( tile instanceof TileComputerBase ) @@ -173,23 +173,23 @@ public abstract class BlockComputerBase extends Bloc } } - return super.getPickStack( world, pos, state ); + return super.getCloneItemStack( world, pos, state ); } @Nonnull protected abstract ItemStack getItem( TileComputerBase tile ); @Override - public void onBreak( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nonnull PlayerEntity player ) + public void playerWillDestroy( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nonnull Player player ) { // Call super as it is what provides sound and block break particles. Does not do anything else. - super.onBreak( world, pos, state, player ); + super.playerWillDestroy( world, pos, state, player ); - if( !(world instanceof ServerWorld) ) + if( !(world instanceof ServerLevel) ) { return; } - ServerWorld serverWorld = (ServerWorld) world; + ServerLevel serverWorld = (ServerLevel) world; // We drop the item here instead of doing it in the harvest method, as we should // drop computers for creative players too. @@ -198,27 +198,27 @@ public abstract class BlockComputerBase extends Bloc if( tile instanceof TileComputerBase ) { TileComputerBase computer = (TileComputerBase) tile; - LootContext.Builder context = new LootContext.Builder( serverWorld ).random( world.random ) - .parameter( LootContextParameters.ORIGIN, Vec3d.ofCenter( pos ) ) - .parameter( LootContextParameters.TOOL, player.getMainHandStack() ) - .parameter( LootContextParameters.THIS_ENTITY, player ) - .parameter( LootContextParameters.BLOCK_ENTITY, tile ) - .putDrop( DROP, ( ctx, out ) -> out.accept( getItem( computer ) ) ); - for( ItemStack item : state.getDroppedStacks( context ) ) + LootContext.Builder context = new LootContext.Builder( serverWorld ).withRandom( world.random ) + .withParameter( LootContextParams.ORIGIN, Vec3.atCenterOf( pos ) ) + .withParameter( LootContextParams.TOOL, player.getMainHandItem() ) + .withParameter( LootContextParams.THIS_ENTITY, player ) + .withParameter( LootContextParams.BLOCK_ENTITY, tile ) + .withDynamicDrop( DROP, ( ctx, out ) -> out.accept( getItem( computer ) ) ); + for( ItemStack item : state.getDrops( context ) ) { - dropStack( world, pos, item ); + popResource( world, pos, item ); } - state.onStacksDropped( serverWorld, pos, player.getMainHandStack() ); + state.spawnAfterBreak( serverWorld, pos, player.getMainHandItem() ); } } @Nullable @Override - public BlockEntityTicker getTicker( World world, BlockState state, BlockEntityType type ) + public BlockEntityTicker getTicker( Level world, BlockState state, BlockEntityType type ) { - return world.isClient ? null : ( world1, pos, state1, tile ) -> { - if ( tile instanceof TileComputerBase computer ) + return world.isClientSide ? null : ( world1, pos, state1, tile ) -> { + if( tile instanceof TileComputerBase computer ) { computer.serverTick(); } diff --git a/src/main/java/dan200/computercraft/shared/computer/blocks/IComputerTile.java b/src/main/java/dan200/computercraft/shared/computer/blocks/IComputerTile.java index ba3e4fc0d..40e0dca90 100644 --- a/src/main/java/dan200/computercraft/shared/computer/blocks/IComputerTile.java +++ b/src/main/java/dan200/computercraft/shared/computer/blocks/IComputerTile.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.computer.blocks; import dan200.computercraft.shared.computer.core.ComputerFamily; diff --git a/src/main/java/dan200/computercraft/shared/computer/blocks/TileCommandComputer.java b/src/main/java/dan200/computercraft/shared/computer/blocks/TileCommandComputer.java index c9cc998e1..75dffb0b9 100644 --- a/src/main/java/dan200/computercraft/shared/computer/blocks/TileCommandComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/blocks/TileCommandComputer.java @@ -10,20 +10,20 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.shared.computer.apis.CommandAPI; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ServerComputer; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.commands.CommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.CommandOutput; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec2f; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.GameRules; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.HashMap; @@ -45,7 +45,7 @@ public class TileCommandComputer extends TileComputer return receiver; } - public ServerCommandSource getSource() + public CommandSourceStack getSource() { ServerComputer computer = getServerComputer(); String name = "@"; @@ -58,14 +58,14 @@ public class TileCommandComputer extends TileComputer } } - return new ServerCommandSource( receiver, - new Vec3d( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ), - Vec2f.ZERO, - (ServerWorld) getWorld(), + return new CommandSourceStack( receiver, + new Vec3( worldPosition.getX() + 0.5, worldPosition.getY() + 0.5, worldPosition.getZ() + 0.5 ), + Vec2.ZERO, + (ServerLevel) getLevel(), 2, name, - new LiteralText( name ), - getWorld().getServer(), + new TextComponent( name ), + getLevel().getServer(), null ); } @@ -78,30 +78,30 @@ public class TileCommandComputer extends TileComputer } @Override - public boolean isUsable( PlayerEntity player, boolean ignoreRange ) + public boolean isUsable( Player player, boolean ignoreRange ) { return isUsable( player ) && super.isUsable( player, ignoreRange ); } - public static boolean isUsable( PlayerEntity player ) + public static boolean isUsable( Player player ) { MinecraftServer server = player.getServer(); - if( server == null || !server.areCommandBlocksEnabled() ) + if( server == null || !server.isCommandBlockEnabled() ) { - player.sendMessage( new TranslatableText( "advMode.notEnabled" ), true ); + player.displayClientMessage( new TranslatableComponent( "advMode.notEnabled" ), true ); return false; } - else if( ComputerCraft.commandRequireCreative ? !player.isCreativeLevelTwoOp() : !server.getPlayerManager() - .isOperator( player.getGameProfile() ) ) + else if( ComputerCraft.commandRequireCreative ? !player.canUseGameMasterBlocks() : !server.getPlayerList() + .isOp( player.getGameProfile() ) ) { - player.sendMessage( new TranslatableText( "advMode.notAllowed" ), true ); + player.displayClientMessage( new TranslatableComponent( "advMode.notAllowed" ), true ); return false; } return true; } - public class CommandReceiver implements CommandOutput + public class CommandReceiver implements CommandSource { private final Map output = new HashMap<>(); @@ -121,29 +121,29 @@ public class TileCommandComputer extends TileComputer } @Override - public void sendSystemMessage( @Nonnull Text textComponent, @Nonnull UUID id ) + public void sendMessage( @Nonnull Component textComponent, @Nonnull UUID id ) { output.put( output.size() + 1, textComponent.getString() ); } @Override - public boolean shouldReceiveFeedback() + public boolean acceptsSuccess() { - return getWorld().getGameRules() - .getBoolean( GameRules.SEND_COMMAND_FEEDBACK ); + return getLevel().getGameRules() + .getBoolean( GameRules.RULE_SENDCOMMANDFEEDBACK ); } @Override - public boolean shouldTrackOutput() + public boolean acceptsFailure() { return true; } @Override - public boolean shouldBroadcastConsoleToOps() + public boolean shouldInformAdmins() { - return getWorld().getGameRules() - .getBoolean( GameRules.COMMAND_BLOCK_OUTPUT ); + return getLevel().getGameRules() + .getBoolean( GameRules.RULE_COMMANDBLOCKOUTPUT ); } } } diff --git a/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputer.java b/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputer.java index 280f4c4d5..82fbdeac4 100644 --- a/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputer.java @@ -13,13 +13,13 @@ import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ComputerState; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.computer.inventory.ComputerMenuWithoutInventory; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,7 +33,7 @@ public class TileComputer extends TileComputerBase super( type, family, pos, state ); } - public boolean isUsableByPlayer( PlayerEntity player ) + public boolean isUsableByPlayer( Player player ) { return isUsable( player, false ); } @@ -41,17 +41,17 @@ public class TileComputer extends TileComputerBase @Override protected void updateBlockState( ComputerState newState ) { - BlockState existing = getCachedState(); - if( existing.get( BlockComputer.STATE ) != newState ) + BlockState existing = getBlockState(); + if( existing.getValue( BlockComputer.STATE ) != newState ) { - getWorld().setBlockState( getPos(), existing.with( BlockComputer.STATE, newState ), 3 ); + getLevel().setBlock( getBlockPos(), existing.setValue( BlockComputer.STATE, newState ), 3 ); } } @Override public Direction getDirection() { - return getCachedState().get( BlockComputer.FACING ); + return getBlockState().getValue( BlockComputer.FACING ); } @Override @@ -74,13 +74,13 @@ public class TileComputer extends TileComputerBase protected ServerComputer createComputer( int instanceID, int id ) { ComputerFamily family = getFamily(); - ServerComputer computer = new ServerComputer( getWorld(), + ServerComputer computer = new ServerComputer( getLevel(), id, label, instanceID, family, ComputerCraft.computerTermWidth, ComputerCraft.computerTermHeight ); - computer.setPosition( getPos() ); + computer.setPosition( getBlockPos() ); return computer; } @@ -103,7 +103,7 @@ public class TileComputer extends TileComputerBase @Nullable @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory inventory, @Nonnull PlayerEntity player ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory inventory, @Nonnull Player player ) { return new ComputerMenuWithoutInventory( ComputerCraftRegistry.ModContainers.COMPUTER, id, inventory, this::isUsableByPlayer, createServerComputer(), getFamily() ); } diff --git a/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputerBase.java b/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputerBase.java index 0e6955f9c..4cd86d5ef 100644 --- a/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputerBase.java +++ b/src/main/java/dan200/computercraft/shared/computer/blocks/TileComputerBase.java @@ -21,26 +21,26 @@ import dan200.computercraft.shared.util.DirectionUtil; import dan200.computercraft.shared.util.RedstoneUtil; import joptsimple.internal.Strings; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.RedstoneWireBlock; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.Nameable; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.Nameable; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.RedStoneWireBlock; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -72,7 +72,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT unload(); for( Direction dir : DirectionUtil.FACINGS ) { - RedstoneUtil.propagateRedstoneOutput( getWorld(), getPos(), dir ); + RedstoneUtil.propagateRedstoneOutput( getLevel(), getBlockPos(), dir ); } } @@ -86,7 +86,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT { if( instanceID >= 0 ) { - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { ComputerCraft.serverComputerRegistry.remove( instanceID ); } @@ -96,42 +96,42 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - ItemStack currentItem = player.getStackInHand( hand ); - if( !currentItem.isEmpty() && currentItem.getItem() == Items.NAME_TAG && canNameWithTag( player ) && currentItem.hasCustomName() ) + ItemStack currentItem = player.getItemInHand( hand ); + if( !currentItem.isEmpty() && currentItem.getItem() == Items.NAME_TAG && canNameWithTag( player ) && currentItem.hasCustomHoverName() ) { // Label to rename computer - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { - setLabel( currentItem.getName() + setLabel( currentItem.getHoverName() .getString() ); - currentItem.decrement( 1 ); + currentItem.shrink( 1 ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } - else if( !player.isInSneakingPose() ) + else if( !player.isCrouching() ) { // Regular right click to activate computer - if( !getWorld().isClient && isUsable( player, false ) ) + if( !getLevel().isClientSide && isUsable( player, false ) ) { createServerComputer().turnOn(); createServerComputer().sendTerminalState( player ); new ComputerContainerData( createServerComputer() ).open( player, this ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } - return ActionResult.PASS; + return InteractionResult.PASS; } - protected boolean canNameWithTag( PlayerEntity player ) + protected boolean canNameWithTag( Player player ) { return false; } public ServerComputer createServerComputer() { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { return null; } @@ -159,14 +159,14 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT public ServerComputer getServerComputer() { - return getWorld().isClient ? null : ComputerCraft.serverComputerRegistry.get( instanceID ); + return getLevel().isClientSide ? null : ComputerCraft.serverComputerRegistry.get( instanceID ); } protected abstract ServerComputer createComputer( int instanceID, int id ); public void updateInput() { - if( getWorld() == null || getWorld().isClient ) + if( getLevel() == null || getLevel().isClientSide ) { return; } @@ -181,7 +181,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT BlockPos pos = computer.getPosition(); for( Direction dir : DirectionUtil.FACINGS ) { - updateSideInput( computer, dir, pos.offset( dir ) ); + updateSideInput( computer, dir, pos.relative( dir ) ); } } @@ -190,11 +190,11 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT Direction offsetSide = dir.getOpposite(); ComputerSide localDir = remapToLocalSide( dir ); - computer.setRedstoneInput( localDir, getRedstoneInput( world, offset, dir ) ); - computer.setBundledRedstoneInput( localDir, BundledRedstone.getOutput( getWorld(), offset, offsetSide ) ); + computer.setRedstoneInput( localDir, getRedstoneInput( level, offset, dir ) ); + computer.setBundledRedstoneInput( localDir, BundledRedstone.getOutput( getLevel(), offset, offsetSide ) ); if( !isPeripheralBlockedOnSide( localDir ) ) { - IPeripheral peripheral = Peripherals.getPeripheral( getWorld(), offset, offsetSide ); + IPeripheral peripheral = Peripherals.getPeripheral( getLevel(), offset, offsetSide ); computer.setPeripheral( localDir, peripheral ); } } @@ -212,16 +212,16 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT * @param side The side we are reading from * @return The effective redstone power */ - protected static int getRedstoneInput( World world, BlockPos pos, Direction side ) + protected static int getRedstoneInput( Level world, BlockPos pos, Direction side ) { - int power = world.getEmittedRedstonePower( pos, side ); + int power = world.getSignal( pos, side ); if( power >= 15 ) { return power; } BlockState neighbour = world.getBlockState( pos ); - return neighbour.getBlock() == Blocks.REDSTONE_WIRE ? Math.max( power, neighbour.get( RedstoneWireBlock.POWER ) ) : power; + return neighbour.getBlock() == Blocks.REDSTONE_WIRE ? Math.max( power, neighbour.getValue( RedStoneWireBlock.POWER ) ) : power; } protected boolean isPeripheralBlockedOnSide( ComputerSide localSide ) @@ -249,7 +249,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT } @Override - protected void readDescription( @Nonnull NbtCompound nbt ) + protected void readDescription( @Nonnull CompoundTag nbt ) { super.readDescription( nbt ); label = nbt.contains( NBT_LABEL ) ? nbt.getString( NBT_LABEL ) : null; @@ -257,7 +257,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT } @Override - protected void writeDescription( @Nonnull NbtCompound nbt ) + protected void writeDescription( @Nonnull CompoundTag nbt ) { super.writeDescription( nbt ); if( label != null ) @@ -313,16 +313,16 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT updateBlock(); for( Direction dir : DirectionUtil.FACINGS ) { - RedstoneUtil.propagateRedstoneOutput( getWorld(), getPos(), dir ); + RedstoneUtil.propagateRedstoneOutput( getLevel(), getBlockPos(), dir ); } } protected abstract void updateBlockState( ComputerState newState ); @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); + super.load( nbt ); // Load ID, label and power state computerID = nbt.contains( NBT_ID ) ? nbt.getInt( NBT_ID ) : -1; @@ -332,7 +332,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT @Nonnull @Override - public NbtCompound writeNbt( @Nonnull NbtCompound nbt ) + public CompoundTag save( @Nonnull CompoundTag nbt ) { // Save ID, label and power state if( computerID >= 0 ) @@ -344,19 +344,19 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT nbt.putString( NBT_LABEL, label ); } nbt.putBoolean( NBT_ON, on ); - return super.writeNbt( nbt ); + return super.save( nbt ); } @Override - public void markRemoved() + public void setRemoved() { unload(); - super.markRemoved(); + super.setRemoved(); } private void updateInput( BlockPos neighbour ) { - if( getWorld() == null || this.world.isClient ) + if( getLevel() == null || this.level.isClientSide ) { return; } @@ -369,7 +369,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT for( Direction dir : DirectionUtil.FACINGS ) { - BlockPos offset = pos.offset( dir ); + BlockPos offset = worldPosition.relative( dir ); if( offset.equals( neighbour ) ) { updateSideInput( computer, dir, offset ); @@ -383,7 +383,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT private void updateInput( Direction dir ) { - if( getWorld() == null || this.world.isClient ) + if( getLevel() == null || this.level.isClientSide ) { return; } @@ -394,7 +394,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT return; } - updateSideInput( computer, dir, pos.offset( dir ) ); + updateSideInput( computer, dir, worldPosition.relative( dir ) ); } @Override @@ -406,7 +406,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT @Override public final void setComputerID( int id ) { - if( this.world.isClient || computerID == id ) + if( this.level.isClientSide || computerID == id ) { return; } @@ -417,7 +417,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT { computer.setID( computerID ); } - markDirty(); + setChanged(); } @Override @@ -431,7 +431,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT @Override public final void setLabel( String label ) { - if( this.world.isClient || Objects.equals( this.label, label ) ) + if( this.level.isClientSide || Objects.equals( this.label, label ) ) { return; } @@ -442,7 +442,7 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT { computer.setLabel( label ); } - markDirty(); + setChanged(); } @Override @@ -477,10 +477,10 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT @Nonnull @Override - public Text getName() + public Component getName() { - return hasCustomName() ? new LiteralText( label ) : new TranslatableText( getCachedState().getBlock() - .getTranslationKey() ); + return hasCustomName() ? new TextComponent( label ) : new TranslatableComponent( getBlockState().getBlock() + .getDescriptionId() ); } @Override @@ -491,22 +491,22 @@ public abstract class TileComputerBase extends TileGeneric implements IComputerT @Nonnull @Override - public Text getDisplayName() + public Component getDisplayName() { return Nameable.super.getDisplayName(); } @Nullable @Override - public Text getCustomName() + public Component getCustomName() { - return hasCustomName() ? new LiteralText( label ) : null; + return hasCustomName() ? new TextComponent( label ) : null; } @Override - public void writeScreenOpeningData( ServerPlayerEntity serverPlayerEntity, PacketByteBuf packetByteBuf ) + public void writeScreenOpeningData( ServerPlayer serverPlayerEntity, FriendlyByteBuf packetByteBuf ) { packetByteBuf.writeInt( getServerComputer().getInstanceID() ); - packetByteBuf.writeEnumConstant( getServerComputer().getFamily() ); + packetByteBuf.writeEnum( getServerComputer().getFamily() ); } } diff --git a/src/main/java/dan200/computercraft/shared/computer/core/ClientComputer.java b/src/main/java/dan200/computercraft/shared/computer/core/ClientComputer.java index 615b65eef..df0a18625 100644 --- a/src/main/java/dan200/computercraft/shared/computer/core/ClientComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/core/ClientComputer.java @@ -9,7 +9,7 @@ package dan200.computercraft.shared.computer.core; import dan200.computercraft.shared.common.ClientTerminal; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.network.server.*; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; public class ClientComputer extends ClientTerminal implements IComputer { @@ -17,7 +17,7 @@ public class ClientComputer extends ClientTerminal implements IComputer private boolean on = false; private boolean blinking = false; - private NbtCompound userData = null; + private CompoundTag userData = null; public ClientComputer( int instanceID ) @@ -26,7 +26,7 @@ public class ClientComputer extends ClientTerminal implements IComputer this.instanceID = instanceID; } - public NbtCompound getUserData() + public CompoundTag getUserData() { return userData; } @@ -123,7 +123,7 @@ public class ClientComputer extends ClientTerminal implements IComputer NetworkHandler.sendToServer( new MouseEventServerMessage( instanceID, MouseEventServerMessage.TYPE_SCROLL, direction, x, y ) ); } - public void setState( ComputerState state, NbtCompound userData ) + public void setState( ComputerState state, CompoundTag userData ) { on = state != ComputerState.OFF; blinking = state == ComputerState.BLINKING; diff --git a/src/main/java/dan200/computercraft/shared/computer/core/ClientComputerRegistry.java b/src/main/java/dan200/computercraft/shared/computer/core/ClientComputerRegistry.java index 725a8c7a5..fa87eb642 100644 --- a/src/main/java/dan200/computercraft/shared/computer/core/ClientComputerRegistry.java +++ b/src/main/java/dan200/computercraft/shared/computer/core/ClientComputerRegistry.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.computer.core; public class ClientComputerRegistry extends ComputerRegistry diff --git a/src/main/java/dan200/computercraft/shared/computer/core/ComputerState.java b/src/main/java/dan200/computercraft/shared/computer/core/ComputerState.java index 29e427049..35f815cde 100644 --- a/src/main/java/dan200/computercraft/shared/computer/core/ComputerState.java +++ b/src/main/java/dan200/computercraft/shared/computer/core/ComputerState.java @@ -6,11 +6,11 @@ package dan200.computercraft.shared.computer.core; -import net.minecraft.util.StringIdentifiable; +import net.minecraft.util.StringRepresentable; import javax.annotation.Nonnull; -public enum ComputerState implements StringIdentifiable +public enum ComputerState implements StringRepresentable { OFF( "off", "" ), ON( "on", "_on" ), BLINKING( "blinking", "_blink" ); @@ -25,7 +25,7 @@ public enum ComputerState implements StringIdentifiable @Nonnull @Override - public String asString() + public String getSerializedName() { return name; } diff --git a/src/main/java/dan200/computercraft/shared/computer/core/IContainerComputer.java b/src/main/java/dan200/computercraft/shared/computer/core/IContainerComputer.java index d3ff52edf..f33461ab6 100644 --- a/src/main/java/dan200/computercraft/shared/computer/core/IContainerComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/core/IContainerComputer.java @@ -8,7 +8,7 @@ package dan200.computercraft.shared.computer.core; import dan200.computercraft.shared.computer.upload.FileSlice; import dan200.computercraft.shared.computer.upload.FileUpload; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.level.ServerPlayer; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -61,7 +61,7 @@ public interface IContainerComputer * @param uploader The player uploading files. * @param uploadId The unique ID of this upload. */ - void finishUpload( @Nonnull ServerPlayerEntity uploader, @Nonnull UUID uploadId ); + void finishUpload( @Nonnull ServerPlayer uploader, @Nonnull UUID uploadId ); /** * Continue an upload. @@ -69,5 +69,5 @@ public interface IContainerComputer * @param uploader The player uploading files. * @param overwrite Whether the files should be overwritten or not. */ - void confirmUpload( @Nonnull ServerPlayerEntity uploader, boolean overwrite ); + void confirmUpload( @Nonnull ServerPlayer uploader, boolean overwrite ); } diff --git a/src/main/java/dan200/computercraft/shared/computer/core/ServerComputer.java b/src/main/java/dan200/computercraft/shared/computer/core/ServerComputer.java index 8204424c9..cdc9fdcad 100644 --- a/src/main/java/dan200/computercraft/shared/computer/core/ServerComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/core/ServerComputer.java @@ -24,12 +24,12 @@ import dan200.computercraft.shared.network.client.ComputerDataClientMessage; import dan200.computercraft.shared.network.client.ComputerDeletedClientMessage; import dan200.computercraft.shared.network.client.ComputerTerminalClientMessage; import me.shedaniel.cloth.api.utils.v1.GameInstanceUtils; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.screen.ScreenHandler; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -40,15 +40,15 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput private final int instanceID; private final ComputerFamily family; private final Computer computer; - private World world; + private Level world; private BlockPos position; - private NbtCompound userData; + private CompoundTag userData; private boolean changed; private boolean changedLastFrame; private int ticksSincePing; - public ServerComputer( World world, int computerID, String label, int instanceID, ComputerFamily family, int terminalWidth, int terminalHeight ) + public ServerComputer( Level world, int computerID, String label, int instanceID, ComputerFamily family, int terminalWidth, int terminalHeight ) { super( family != ComputerFamily.NORMAL, terminalWidth, terminalHeight ); this.instanceID = instanceID; @@ -71,12 +71,12 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput return family; } - public World getWorld() + public Level getWorld() { return world; } - public void setWorld( World world ) + public void setWorld( Level world ) { this.world = world; } @@ -128,11 +128,11 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput computer.unload(); } - public NbtCompound getUserData() + public CompoundTag getUserData() { if( userData == null ) { - userData = new NbtCompound(); + userData = new CompoundTag(); } return userData; } @@ -162,8 +162,8 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput // Send terminal state to clients who are currently interacting with the computer. NetworkMessage packet = null; - for( PlayerEntity player : server.getPlayerManager() - .getPlayerList() ) + for( Player player : server.getPlayerList() + .getPlayers() ) { if( isInteracting( player ) ) { @@ -188,7 +188,7 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput return new ComputerDataClientMessage( this ); } - protected boolean isInteracting( PlayerEntity player ) + protected boolean isInteracting( Player player ) { return getContainer( player ) != null; } @@ -199,14 +199,14 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput } @Nullable - public IContainerComputer getContainer( PlayerEntity player ) + public IContainerComputer getContainer( Player player ) { if( player == null ) { return null; } - ScreenHandler container = player.currentScreenHandler; + AbstractContainerMenu container = player.containerMenu; if( !(container instanceof IContainerComputer) ) { return null; @@ -264,13 +264,13 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput return computer.isOn() && computer.isBlinking(); } - public void sendComputerState( PlayerEntity player ) + public void sendComputerState( Player player ) { // Send state to client NetworkHandler.sendToPlayer( player, createComputerPacket() ); } - public void sendTerminalState( PlayerEntity player ) + public void sendTerminalState( Player player ) { // Send terminal state to client NetworkHandler.sendToPlayer( player, createTerminalPacket() ); @@ -352,13 +352,13 @@ public class ServerComputer extends ServerTerminal implements IComputer, IComput @Override public int getDay() { - return (int) ((world.getTimeOfDay() + 6000) / 24000) + 1; + return (int) ((world.getDayTime() + 6000) / 24000) + 1; } @Override public double getTimeOfDay() { - return (world.getTimeOfDay() + 6000) % 24000 / 1000.0; + return (world.getDayTime() + 6000) % 24000 / 1000.0; } @Override diff --git a/src/main/java/dan200/computercraft/shared/computer/inventory/ComputerMenuWithoutInventory.java b/src/main/java/dan200/computercraft/shared/computer/inventory/ComputerMenuWithoutInventory.java index f3384de72..8b7971397 100644 --- a/src/main/java/dan200/computercraft/shared/computer/inventory/ComputerMenuWithoutInventory.java +++ b/src/main/java/dan200/computercraft/shared/computer/inventory/ComputerMenuWithoutInventory.java @@ -9,9 +9,9 @@ import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.IComputer; import dan200.computercraft.shared.network.container.ComputerContainerData; import dan200.computercraft.shared.util.InvisibleSlot; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.screen.ScreenHandlerType; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.MenuType; import java.util.function.Predicate; @@ -22,19 +22,19 @@ import java.util.function.Predicate; */ public class ComputerMenuWithoutInventory extends ContainerComputerBase { - public ComputerMenuWithoutInventory( ScreenHandlerType type, int id, PlayerInventory player, Predicate canUse, IComputer computer, ComputerFamily family ) + public ComputerMenuWithoutInventory( MenuType type, int id, Inventory player, Predicate canUse, IComputer computer, ComputerFamily family ) { super( type, id, canUse, computer, family ); addSlots( player ); } - public ComputerMenuWithoutInventory( ScreenHandlerType type, int id, PlayerInventory player, ComputerContainerData data ) + public ComputerMenuWithoutInventory( MenuType type, int id, Inventory player, ComputerContainerData data ) { super( type, id, player, data ); addSlots( player ); } - private void addSlots( PlayerInventory player ) + private void addSlots( Inventory player ) { for( int i = 0; i < 9; i++ ) addSlot( new InvisibleSlot( player, i ) ); } diff --git a/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerComputerBase.java b/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerComputerBase.java index 8ea9bbc7e..3579669e6 100644 --- a/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerComputerBase.java +++ b/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerComputerBase.java @@ -17,12 +17,12 @@ import dan200.computercraft.shared.computer.upload.UploadResult; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.network.client.UploadResultMessage; import dan200.computercraft.shared.network.container.ComputerContainerData; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerType; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.TranslatableText; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -32,11 +32,11 @@ import java.util.*; import java.util.function.Function; import java.util.function.Predicate; -public abstract class ContainerComputerBase extends ScreenHandler implements IContainerComputer +public abstract class ContainerComputerBase extends AbstractContainerMenu implements IContainerComputer { private static final String LIST_PREFIX = "\n \u2022 "; - private final Predicate canUse; + private final Predicate canUse; private final IComputer computer; private final ComputerFamily family; private final InputState input = new InputState( this ); @@ -44,7 +44,7 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo private UUID toUploadId; private List toUpload; - public ContainerComputerBase( ScreenHandlerType type, int id, PlayerInventory player, ComputerContainerData data ) + public ContainerComputerBase( MenuType type, int id, Inventory player, ComputerContainerData data ) { this( type, id, @@ -53,8 +53,8 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo data.getFamily() ); } - public ContainerComputerBase( ScreenHandlerType type, int id, Predicate canUse, IComputer computer, - ComputerFamily family ) + public ContainerComputerBase( MenuType type, int id, Predicate canUse, IComputer computer, + ComputerFamily family ) { super( type, id ); this.canUse = canUse; @@ -62,10 +62,10 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo this.family = family; } - protected static IComputer getComputer( PlayerInventory player, ComputerContainerData data ) + protected static IComputer getComputer( Inventory player, ComputerContainerData data ) { int id = data.getInstanceId(); - if( !player.player.world.isClient ) + if( !player.player.level.isClientSide ) { return ComputerCraft.serverComputerRegistry.get( id ); } @@ -99,14 +99,14 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo } @Override - public void close( @Nonnull PlayerEntity player ) + public void removed( @Nonnull Player player ) { - super.close( player ); + super.removed( player ); input.close(); } @Override - public boolean canUse( @Nonnull PlayerEntity player ) + public boolean stillValid( @Nonnull Player player ) { return canUse.test( player ); } @@ -131,7 +131,7 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo } @Override - public void finishUpload( @Nonnull ServerPlayerEntity uploader, @Nonnull UUID uploadId ) + public void finishUpload( @Nonnull ServerPlayer uploader, @Nonnull UUID uploadId ) { if( toUploadId == null || toUpload == null || toUpload.isEmpty() || !toUploadId.equals( uploadId ) ) { @@ -144,7 +144,7 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo } @Override - public void confirmUpload( @Nonnull ServerPlayerEntity uploader, boolean overwrite ) + public void confirmUpload( @Nonnull ServerPlayer uploader, boolean overwrite ) { if( toUploadId == null || toUpload == null || toUpload.isEmpty() ) { @@ -170,7 +170,7 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo if( !upload.checksumMatches() ) { ComputerCraft.log.warn( "Checksum failed to match for {}.", upload.getName() ); - return new UploadResultMessage( UploadResult.ERROR, new TranslatableText( "gui.computercraft.upload.failed.corrupted" ) ); + return new UploadResultMessage( UploadResult.ERROR, new TranslatableComponent( "gui.computercraft.upload.failed.corrupted" ) ); } } @@ -186,7 +186,7 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo { return new UploadResultMessage( UploadResult.ERROR, - new TranslatableText( "gui.computercraft.upload.failed.overwrite_dir", upload.getName() ) + new TranslatableComponent( "gui.computercraft.upload.failed.overwrite_dir", upload.getName() ) ); } @@ -200,7 +200,7 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo toUpload = files; return new UploadResultMessage( UploadResult.CONFIRM_OVERWRITE, - new TranslatableText( "gui.computercraft.upload.overwrite.detail", joiner.toString() ) + new TranslatableComponent( "gui.computercraft.upload.overwrite.detail", joiner.toString() ) ); } @@ -219,13 +219,13 @@ public abstract class ContainerComputerBase extends ScreenHandler implements ICo } return new UploadResultMessage( - UploadResult.SUCCESS, new TranslatableText( "gui.computercraft.upload.success.msg", files.size() ) + UploadResult.SUCCESS, new TranslatableComponent( "gui.computercraft.upload.success.msg", files.size() ) ); } catch( FileSystemException | IOException e ) { ComputerCraft.log.error( "Error uploading files", e ); - return new UploadResultMessage( UploadResult.ERROR, new TranslatableText( "gui.computercraft.upload.failed.generic", e.getMessage() ) ); + return new UploadResultMessage( UploadResult.ERROR, new TranslatableComponent( "gui.computercraft.upload.failed.generic", e.getMessage() ) ); } } } diff --git a/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerViewComputer.java b/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerViewComputer.java index 341908650..3f7013dd2 100644 --- a/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerViewComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/inventory/ContainerViewComputer.java @@ -12,8 +12,8 @@ import dan200.computercraft.shared.computer.blocks.TileCommandComputer; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.network.container.ViewComputerContainerData; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; import javax.annotation.Nonnull; @@ -22,20 +22,20 @@ public class ContainerViewComputer extends ComputerMenuWithoutInventory private final int width; private final int height; - public ContainerViewComputer( int id, PlayerInventory player, ServerComputer computer ) + public ContainerViewComputer( int id, Inventory player, ServerComputer computer ) { super( ComputerCraftRegistry.ModContainers.VIEW_COMPUTER, id, player, p -> canInteractWith( computer, p ), computer, computer.getFamily() ); width = height = 0; } - public ContainerViewComputer( int id, PlayerInventory player, ViewComputerContainerData data ) + public ContainerViewComputer( int id, Inventory player, ViewComputerContainerData data ) { super( ComputerCraftRegistry.ModContainers.VIEW_COMPUTER, id, player, data ); width = data.getWidth(); height = data.getHeight(); } - private static boolean canInteractWith( @Nonnull ServerComputer computer, @Nonnull PlayerEntity player ) + private static boolean canInteractWith( @Nonnull ServerComputer computer, @Nonnull Player player ) { // If this computer no longer exists then discard it. if( ComputerCraft.serverComputerRegistry.get( computer.getInstanceID() ) != computer ) diff --git a/src/main/java/dan200/computercraft/shared/computer/items/ComputerItemFactory.java b/src/main/java/dan200/computercraft/shared/computer/items/ComputerItemFactory.java index b267240c5..30dd6286d 100644 --- a/src/main/java/dan200/computercraft/shared/computer/items/ComputerItemFactory.java +++ b/src/main/java/dan200/computercraft/shared/computer/items/ComputerItemFactory.java @@ -9,7 +9,7 @@ package dan200.computercraft.shared.computer.items; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.computer.blocks.TileComputer; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; diff --git a/src/main/java/dan200/computercraft/shared/computer/items/IComputerItem.java b/src/main/java/dan200/computercraft/shared/computer/items/IComputerItem.java index e887dbb6b..06a0e46ae 100644 --- a/src/main/java/dan200/computercraft/shared/computer/items/IComputerItem.java +++ b/src/main/java/dan200/computercraft/shared/computer/items/IComputerItem.java @@ -7,8 +7,8 @@ package dan200.computercraft.shared.computer.items; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -18,13 +18,13 @@ public interface IComputerItem default int getComputerID( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_ID ) ? nbt.getInt( NBT_ID ) : -1; } default String getLabel( @Nonnull ItemStack stack ) { - return stack.hasCustomName() ? stack.getName() + return stack.hasCustomHoverName() ? stack.getHoverName() .getString() : null; } diff --git a/src/main/java/dan200/computercraft/shared/computer/items/ItemComputer.java b/src/main/java/dan200/computercraft/shared/computer/items/ItemComputer.java index 3fc0370e8..26b6c26f9 100644 --- a/src/main/java/dan200/computercraft/shared/computer/items/ItemComputer.java +++ b/src/main/java/dan200/computercraft/shared/computer/items/ItemComputer.java @@ -8,14 +8,14 @@ package dan200.computercraft.shared.computer.items; import dan200.computercraft.shared.computer.blocks.BlockComputer; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.item.ItemStack; -import net.minecraft.text.LiteralText; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; public class ItemComputer extends ItemComputerBase { - public ItemComputer( BlockComputer block, Settings settings ) + public ItemComputer( BlockComputer block, Properties settings ) { super( block, settings ); } @@ -25,12 +25,12 @@ public class ItemComputer extends ItemComputerBase ItemStack result = new ItemStack( this ); if( id >= 0 ) { - result.getOrCreateNbt() + result.getOrCreateTag() .putInt( NBT_ID, id ); } if( label != null ) { - result.setCustomName( new LiteralText( label ) ); + result.setHoverName( new TextComponent( label ) ); } return result; } @@ -39,9 +39,9 @@ public class ItemComputer extends ItemComputerBase public ItemStack withFamily( @Nonnull ItemStack stack, @Nonnull ComputerFamily family ) { ItemStack result = ComputerItemFactory.create( getComputerID( stack ), null, family ); - if( stack.hasCustomName() ) + if( stack.hasCustomHoverName() ) { - result.setCustomName( stack.getName() ); + result.setHoverName( stack.getHoverName() ); } return result; } diff --git a/src/main/java/dan200/computercraft/shared/computer/items/ItemComputerBase.java b/src/main/java/dan200/computercraft/shared/computer/items/ItemComputerBase.java index 482e2916b..93bd3bc03 100644 --- a/src/main/java/dan200/computercraft/shared/computer/items/ItemComputerBase.java +++ b/src/main/java/dan200/computercraft/shared/computer/items/ItemComputerBase.java @@ -12,14 +12,14 @@ import dan200.computercraft.api.filesystem.IMount; import dan200.computercraft.api.media.IMedia; import dan200.computercraft.shared.computer.blocks.BlockComputerBase; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemStack; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.Formatting; -import net.minecraft.world.World; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -29,21 +29,21 @@ public abstract class ItemComputerBase extends BlockItem implements IComputerIte { private final ComputerFamily family; - public ItemComputerBase( BlockComputerBase block, Settings settings ) + public ItemComputerBase( BlockComputerBase block, Properties settings ) { super( block, settings ); family = block.getFamily(); } @Override - public void appendTooltip( @Nonnull ItemStack stack, @Nullable World world, @Nonnull List list, @Nonnull TooltipContext options ) + public void appendHoverText( @Nonnull ItemStack stack, @Nullable Level world, @Nonnull List list, @Nonnull TooltipFlag options ) { if( options.isAdvanced() || getLabel( stack ) == null ) { int id = getComputerID( stack ); if( id >= 0 ) { - list.add( new TranslatableText( "gui.computercraft.tooltip.computer_id", id ).formatted( Formatting.GRAY ) ); + list.add( new TranslatableComponent( "gui.computercraft.tooltip.computer_id", id ).withStyle( ChatFormatting.GRAY ) ); } } } @@ -67,17 +67,17 @@ public abstract class ItemComputerBase extends BlockItem implements IComputerIte { if( label != null ) { - stack.setCustomName( new LiteralText( label ) ); + stack.setHoverName( new TextComponent( label ) ); } else { - stack.removeCustomName(); + stack.resetHoverName(); } return true; } @Override - public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world ) + public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world ) { ComputerFamily family = getFamily(); if( family != ComputerFamily.COMMAND ) diff --git a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerConvertRecipe.java b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerConvertRecipe.java index 8b4cfaa58..1ac0f93e1 100644 --- a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerConvertRecipe.java +++ b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerConvertRecipe.java @@ -7,13 +7,13 @@ package dan200.computercraft.shared.computer.recipe; import dan200.computercraft.shared.computer.items.IComputerItem; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.ShapedRecipe; -import net.minecraft.util.Identifier; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.core.NonNullList; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.ShapedRecipe; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; @@ -24,7 +24,7 @@ public abstract class ComputerConvertRecipe extends ShapedRecipe { private final String group; - public ComputerConvertRecipe( Identifier identifier, String group, int width, int height, DefaultedList ingredients, ItemStack result ) + public ComputerConvertRecipe( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result ) { super( identifier, group, width, height, ingredients, result ); this.group = group; @@ -38,16 +38,16 @@ public abstract class ComputerConvertRecipe extends ShapedRecipe } @Override - public boolean matches( @Nonnull CraftingInventory inventory, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inventory, @Nonnull Level world ) { if( !super.matches( inventory, world ) ) { return false; } - for( int i = 0; i < inventory.size(); i++ ) + for( int i = 0; i < inventory.getContainerSize(); i++ ) { - if( inventory.getStack( i ) + if( inventory.getItem( i ) .getItem() instanceof IComputerItem ) { return true; @@ -59,12 +59,12 @@ public abstract class ComputerConvertRecipe extends ShapedRecipe @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inventory ) + public ItemStack assemble( @Nonnull CraftingContainer inventory ) { // Find our computer item and convert it. - for( int i = 0; i < inventory.size(); i++ ) + for( int i = 0; i < inventory.getContainerSize(); i++ ) { - ItemStack stack = inventory.getStack( i ); + ItemStack stack = inventory.getItem( i ); if( stack.getItem() instanceof IComputerItem ) { return convert( (IComputerItem) stack.getItem(), stack ); diff --git a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java index d882505f9..148d5967a 100644 --- a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java +++ b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerFamilyRecipe.java @@ -9,13 +9,13 @@ package dan200.computercraft.shared.computer.recipe; import com.google.gson.JsonObject; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.util.RecipeUtil; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.util.Identifier; -import net.minecraft.util.JsonHelper; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.core.NonNullList; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.GsonHelper; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; import javax.annotation.Nonnull; @@ -23,7 +23,7 @@ public abstract class ComputerFamilyRecipe extends ComputerConvertRecipe { private final ComputerFamily family; - public ComputerFamilyRecipe( Identifier identifier, String group, int width, int height, DefaultedList ingredients, ItemStack result, + public ComputerFamilyRecipe( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result, ComputerFamily family ) { super( identifier, group, width, height, ingredients, result ); @@ -39,51 +39,51 @@ public abstract class ComputerFamilyRecipe extends ComputerConvertRecipe { @Nonnull @Override - public T read( @Nonnull Identifier identifier, @Nonnull JsonObject json ) + public T fromJson( @Nonnull ResourceLocation identifier, @Nonnull JsonObject json ) { - String group = JsonHelper.getString( json, "group", "" ); + String group = GsonHelper.getAsString( json, "group", "" ); ComputerFamily family = RecipeUtil.getFamily( json, "family" ); RecipeUtil.ShapedTemplate template = RecipeUtil.getTemplate( json ); - ItemStack result = outputFromJson( JsonHelper.getObject( json, "result" ) ); + ItemStack result = itemStackFromJson( GsonHelper.getAsJsonObject( json, "result" ) ); return create( identifier, group, template.width, template.height, template.ingredients, result, family ); } - protected abstract T create( Identifier identifier, String group, int width, int height, DefaultedList ingredients, ItemStack result, + protected abstract T create( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result, ComputerFamily family ); @Nonnull @Override - public T read( @Nonnull Identifier identifier, @Nonnull PacketByteBuf buf ) + public T fromNetwork( @Nonnull ResourceLocation identifier, @Nonnull FriendlyByteBuf buf ) { int width = buf.readVarInt(); int height = buf.readVarInt(); - String group = buf.readString( Short.MAX_VALUE ); + String group = buf.readUtf( Short.MAX_VALUE ); - DefaultedList ingredients = DefaultedList.ofSize( width * height, Ingredient.EMPTY ); + NonNullList ingredients = NonNullList.withSize( width * height, Ingredient.EMPTY ); for( int i = 0; i < ingredients.size(); i++ ) { - ingredients.set( i, Ingredient.fromPacket( buf ) ); + ingredients.set( i, Ingredient.fromNetwork( buf ) ); } - ItemStack result = buf.readItemStack(); - ComputerFamily family = buf.readEnumConstant( ComputerFamily.class ); + ItemStack result = buf.readItem(); + ComputerFamily family = buf.readEnum( ComputerFamily.class ); return create( identifier, group, width, height, ingredients, result, family ); } @Override - public void write( @Nonnull PacketByteBuf buf, @Nonnull T recipe ) + public void toNetwork( @Nonnull FriendlyByteBuf buf, @Nonnull T recipe ) { buf.writeVarInt( recipe.getWidth() ); buf.writeVarInt( recipe.getHeight() ); - buf.writeString( recipe.getGroup() ); + buf.writeUtf( recipe.getGroup() ); for( Ingredient ingredient : recipe.getIngredients() ) { - ingredient.write( buf ); + ingredient.toNetwork( buf ); } - buf.writeItemStack( recipe.getOutput() ); - buf.writeEnumConstant( recipe.getFamily() ); + buf.writeItem( recipe.getResultItem() ); + buf.writeEnum( recipe.getFamily() ); } } } diff --git a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerUpgradeRecipe.java b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerUpgradeRecipe.java index b22c10b14..7f10134eb 100644 --- a/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerUpgradeRecipe.java +++ b/src/main/java/dan200/computercraft/shared/computer/recipe/ComputerUpgradeRecipe.java @@ -8,11 +8,11 @@ package dan200.computercraft.shared.computer.recipe; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.items.IComputerItem; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.util.Identifier; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.core.NonNullList; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; import javax.annotation.Nonnull; @@ -22,14 +22,14 @@ public class ComputerUpgradeRecipe extends ComputerFamilyRecipe new ComputerFamilyRecipe.Serializer() { @Override - protected ComputerUpgradeRecipe create( Identifier identifier, String group, int width, int height, DefaultedList ingredients, + protected ComputerUpgradeRecipe create( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result, ComputerFamily family ) { return new ComputerUpgradeRecipe( identifier, group, width, height, ingredients, result, family ); } }; - public ComputerUpgradeRecipe( Identifier identifier, String group, int width, int height, DefaultedList ingredients, ItemStack result, + public ComputerUpgradeRecipe( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result, ComputerFamily family ) { super( identifier, group, width, height, ingredients, result, family ); diff --git a/src/main/java/dan200/computercraft/shared/computer/upload/UploadResult.java b/src/main/java/dan200/computercraft/shared/computer/upload/UploadResult.java index 2c332c0ef..11398b04c 100644 --- a/src/main/java/dan200/computercraft/shared/computer/upload/UploadResult.java +++ b/src/main/java/dan200/computercraft/shared/computer/upload/UploadResult.java @@ -5,8 +5,8 @@ */ package dan200.computercraft.shared.computer.upload; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; public enum UploadResult { @@ -14,12 +14,12 @@ public enum UploadResult ERROR, CONFIRM_OVERWRITE; - public static final Text SUCCESS_TITLE = new TranslatableText( "gui.computercraft.upload.success" ); + public static final Component SUCCESS_TITLE = new TranslatableComponent( "gui.computercraft.upload.success" ); - public static final Text FAILED_TITLE = new TranslatableText( "gui.computercraft.upload.failed" ); - public static final Text COMPUTER_OFF_MSG = new TranslatableText( "gui.computercraft.upload.failed.computer_off" ); - public static final Text OUT_OF_SPACE_MSG = new TranslatableText( "gui.computercraft.upload.failed.out_of_space" ); - public static final Text TOO_MUCH_MSG = new TranslatableText( "gui.computercraft.upload.failed.too_much" ); + public static final Component FAILED_TITLE = new TranslatableComponent( "gui.computercraft.upload.failed" ); + public static final Component COMPUTER_OFF_MSG = new TranslatableComponent( "gui.computercraft.upload.failed.computer_off" ); + public static final Component OUT_OF_SPACE_MSG = new TranslatableComponent( "gui.computercraft.upload.failed.out_of_space" ); + public static final Component TOO_MUCH_MSG = new TranslatableComponent( "gui.computercraft.upload.failed.too_much" ); - public static final Text UPLOAD_OVERWRITE = new TranslatableText( "gui.computercraft.upload.overwrite" ); + public static final Component UPLOAD_OVERWRITE = new TranslatableComponent( "gui.computercraft.upload.overwrite" ); } diff --git a/src/main/java/dan200/computercraft/shared/data/BlockNamedEntityLootCondition.java b/src/main/java/dan200/computercraft/shared/data/BlockNamedEntityLootCondition.java index ee98295f1..e25f4f891 100644 --- a/src/main/java/dan200/computercraft/shared/data/BlockNamedEntityLootCondition.java +++ b/src/main/java/dan200/computercraft/shared/data/BlockNamedEntityLootCondition.java @@ -3,16 +3,15 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.data; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.loot.condition.LootCondition; -import net.minecraft.loot.condition.LootConditionType; -import net.minecraft.loot.context.LootContext; -import net.minecraft.loot.context.LootContextParameter; -import net.minecraft.loot.context.LootContextParameters; -import net.minecraft.util.Nameable; +import net.minecraft.world.Nameable; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParam; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; import javax.annotation.Nonnull; import java.util.Collections; @@ -21,10 +20,10 @@ import java.util.Set; /** * A loot condition which checks if the tile entity has a name. */ -public final class BlockNamedEntityLootCondition implements LootCondition +public final class BlockNamedEntityLootCondition implements LootItemCondition { public static final BlockNamedEntityLootCondition INSTANCE = new BlockNamedEntityLootCondition(); - public static final LootConditionType TYPE = ConstantLootConditionSerializer.type( INSTANCE ); + public static final LootItemConditionType TYPE = ConstantLootConditionSerializer.type( INSTANCE ); public static final Builder BUILDER = () -> INSTANCE; private BlockNamedEntityLootCondition() @@ -34,20 +33,20 @@ public final class BlockNamedEntityLootCondition implements LootCondition @Override public boolean test( LootContext lootContext ) { - BlockEntity tile = lootContext.get( LootContextParameters.BLOCK_ENTITY ); + BlockEntity tile = lootContext.getParamOrNull( LootContextParams.BLOCK_ENTITY ); return tile instanceof Nameable && ((Nameable) tile).hasCustomName(); } @Nonnull @Override - public Set> getRequiredParameters() + public Set> getReferencedContextParams() { - return Collections.singleton( LootContextParameters.BLOCK_ENTITY ); + return Collections.singleton( LootContextParams.BLOCK_ENTITY ); } @Override @Nonnull - public LootConditionType getType() + public LootItemConditionType getType() { return TYPE; } diff --git a/src/main/java/dan200/computercraft/shared/data/ConstantLootConditionSerializer.java b/src/main/java/dan200/computercraft/shared/data/ConstantLootConditionSerializer.java index 8a45e575b..ea3ab1333 100644 --- a/src/main/java/dan200/computercraft/shared/data/ConstantLootConditionSerializer.java +++ b/src/main/java/dan200/computercraft/shared/data/ConstantLootConditionSerializer.java @@ -3,19 +3,18 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.data; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; -import net.minecraft.loot.condition.LootCondition; -import net.minecraft.loot.condition.LootConditionType; -import net.minecraft.util.JsonSerializer; +import net.minecraft.world.level.storage.loot.Serializer; +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; import javax.annotation.Nonnull; -public final class ConstantLootConditionSerializer implements JsonSerializer +public final class ConstantLootConditionSerializer implements Serializer { private final T instance; @@ -24,19 +23,19 @@ public final class ConstantLootConditionSerializer impl this.instance = instance; } - public static LootConditionType type( T condition ) + public static LootItemConditionType type( T condition ) { - return new LootConditionType( new ConstantLootConditionSerializer<>( condition ) ); + return new LootItemConditionType( new ConstantLootConditionSerializer<>( condition ) ); } @Override - public void toJson( @Nonnull JsonObject json, @Nonnull T object, @Nonnull JsonSerializationContext context ) + public void serialize( @Nonnull JsonObject json, @Nonnull T object, @Nonnull JsonSerializationContext context ) { } @Nonnull @Override - public T fromJson( @Nonnull JsonObject json, @Nonnull JsonDeserializationContext context ) + public T deserialize( @Nonnull JsonObject json, @Nonnull JsonDeserializationContext context ) { return instance; } diff --git a/src/main/java/dan200/computercraft/shared/data/HasComputerIdLootCondition.java b/src/main/java/dan200/computercraft/shared/data/HasComputerIdLootCondition.java index 7b2717d29..4127ec6ef 100644 --- a/src/main/java/dan200/computercraft/shared/data/HasComputerIdLootCondition.java +++ b/src/main/java/dan200/computercraft/shared/data/HasComputerIdLootCondition.java @@ -3,16 +3,15 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.data; import dan200.computercraft.shared.computer.blocks.IComputerTile; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.loot.condition.LootCondition; -import net.minecraft.loot.condition.LootConditionType; -import net.minecraft.loot.context.LootContext; -import net.minecraft.loot.context.LootContextParameter; -import net.minecraft.loot.context.LootContextParameters; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParam; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; import javax.annotation.Nonnull; import java.util.Collections; @@ -21,10 +20,10 @@ import java.util.Set; /** * A loot condition which checks if the tile entity has has a non-0 ID. */ -public final class HasComputerIdLootCondition implements LootCondition +public final class HasComputerIdLootCondition implements LootItemCondition { public static final HasComputerIdLootCondition INSTANCE = new HasComputerIdLootCondition(); - public static final LootConditionType TYPE = ConstantLootConditionSerializer.type( INSTANCE ); + public static final LootItemConditionType TYPE = ConstantLootConditionSerializer.type( INSTANCE ); public static final Builder BUILDER = () -> INSTANCE; private HasComputerIdLootCondition() @@ -34,20 +33,20 @@ public final class HasComputerIdLootCondition implements LootCondition @Override public boolean test( LootContext lootContext ) { - BlockEntity tile = lootContext.get( LootContextParameters.BLOCK_ENTITY ); + BlockEntity tile = lootContext.getParamOrNull( LootContextParams.BLOCK_ENTITY ); return tile instanceof IComputerTile && ((IComputerTile) tile).getComputerID() >= 0; } @Nonnull @Override - public Set> getRequiredParameters() + public Set> getReferencedContextParams() { - return Collections.singleton( LootContextParameters.BLOCK_ENTITY ); + return Collections.singleton( LootContextParams.BLOCK_ENTITY ); } @Override @Nonnull - public LootConditionType getType() + public LootItemConditionType getType() { return TYPE; } diff --git a/src/main/java/dan200/computercraft/shared/data/PlayerCreativeLootCondition.java b/src/main/java/dan200/computercraft/shared/data/PlayerCreativeLootCondition.java index debdffb46..3666ffbb6 100644 --- a/src/main/java/dan200/computercraft/shared/data/PlayerCreativeLootCondition.java +++ b/src/main/java/dan200/computercraft/shared/data/PlayerCreativeLootCondition.java @@ -3,16 +3,15 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.data; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.loot.condition.LootCondition; -import net.minecraft.loot.condition.LootConditionType; -import net.minecraft.loot.context.LootContext; -import net.minecraft.loot.context.LootContextParameter; -import net.minecraft.loot.context.LootContextParameters; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParam; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; import javax.annotation.Nonnull; import java.util.Collections; @@ -21,10 +20,10 @@ import java.util.Set; /** * A loot condition which checks if the entity is in creative mode. */ -public final class PlayerCreativeLootCondition implements LootCondition +public final class PlayerCreativeLootCondition implements LootItemCondition { public static final PlayerCreativeLootCondition INSTANCE = new PlayerCreativeLootCondition(); - public static final LootConditionType TYPE = ConstantLootConditionSerializer.type( INSTANCE ); + public static final LootItemConditionType TYPE = ConstantLootConditionSerializer.type( INSTANCE ); public static final Builder BUILDER = () -> INSTANCE; private PlayerCreativeLootCondition() @@ -34,20 +33,20 @@ public final class PlayerCreativeLootCondition implements LootCondition @Override public boolean test( LootContext lootContext ) { - Entity entity = lootContext.get( LootContextParameters.THIS_ENTITY ); - return entity instanceof PlayerEntity && ((PlayerEntity) entity).getAbilities().creativeMode; + Entity entity = lootContext.getParamOrNull( LootContextParams.THIS_ENTITY ); + return entity instanceof Player && ((Player) entity).getAbilities().instabuild; } @Nonnull @Override - public Set> getRequiredParameters() + public Set> getReferencedContextParams() { - return Collections.singleton( LootContextParameters.THIS_ENTITY ); + return Collections.singleton( LootContextParams.THIS_ENTITY ); } @Override @Nonnull - public LootConditionType getType() + public LootItemConditionType getType() { return TYPE; } diff --git a/src/main/java/dan200/computercraft/shared/integration/ModMenuIntegration.java b/src/main/java/dan200/computercraft/shared/integration/ModMenuIntegration.java index f973cf5a5..081f43de4 100644 --- a/src/main/java/dan200/computercraft/shared/integration/ModMenuIntegration.java +++ b/src/main/java/dan200/computercraft/shared/integration/ModMenuIntegration.java @@ -15,8 +15,8 @@ import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; // A poor mod menu integration just for testing the monitor rendering changes we've been making :) @@ -28,7 +28,7 @@ public class ModMenuIntegration implements ModMenuApi { return parent -> { ConfigBuilder builder = ConfigBuilder.create().setParentScreen( parent ) - .setTitle( new LiteralText( "Computer Craft" ) ) + .setTitle( new TextComponent( "Computer Craft" ) ) .setSavingRunnable( () -> { Config.clientSpec.correct( Config.clientConfig ); Config.sync(); @@ -36,14 +36,14 @@ public class ModMenuIntegration implements ModMenuApi ComputerCraft.log.info( "Monitor renderer: {}", ComputerCraft.monitorRenderer ); } ); - ConfigCategory client = builder.getOrCreateCategory( new LiteralText( "Client" ) ); + ConfigCategory client = builder.getOrCreateCategory( new TextComponent( "Client" ) ); ConfigEntryBuilder entryBuilder = builder.entryBuilder(); - client.addEntry( entryBuilder.startEnumSelector( new LiteralText( "Monitor Renderer" ), MonitorRenderer.class, ComputerCraft.monitorRenderer ) + client.addEntry( entryBuilder.startEnumSelector( new TextComponent( "Monitor Renderer" ), MonitorRenderer.class, ComputerCraft.monitorRenderer ) .setDefaultValue( MonitorRenderer.BEST ) - .setSaveConsumer( renderer -> { Config.clientConfig.set( "monitor_renderer", renderer ); } ) - .setTooltip( Text.of( Config.clientConfig.getComment( "monitor_renderer" ) ) ) + .setSaveConsumer( renderer -> Config.clientConfig.set( "monitor_renderer", renderer ) ) + .setTooltip( Component.nullToEmpty( Config.clientConfig.getComment( "monitor_renderer" ) ) ) .build() ); return builder.build(); diff --git a/src/main/java/dan200/computercraft/shared/media/items/ItemDisk.java b/src/main/java/dan200/computercraft/shared/media/items/ItemDisk.java index 3d656c87a..f7b5731b9 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/ItemDisk.java +++ b/src/main/java/dan200/computercraft/shared/media/items/ItemDisk.java @@ -13,17 +13,17 @@ import dan200.computercraft.api.media.IMedia; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.IColouredItem; import dan200.computercraft.shared.util.Colour; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.item.Item; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.Formatting; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.ChatFormatting; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,28 +33,28 @@ public class ItemDisk extends Item implements IMedia, IColouredItem { private static final String NBT_ID = "DiskId"; - public ItemDisk( Settings settings ) + public ItemDisk( Properties settings ) { super( settings ); } @Override - public void appendTooltip( @Nonnull ItemStack stack, @Nullable World world, @Nonnull List list, TooltipContext options ) + public void appendHoverText( @Nonnull ItemStack stack, @Nullable Level world, @Nonnull List list, TooltipFlag options ) { if( options.isAdvanced() ) { int id = getDiskID( stack ); if( id >= 0 ) { - list.add( new TranslatableText( "gui.computercraft.tooltip.disk_id", id ).formatted( Formatting.GRAY ) ); + list.add( new TranslatableComponent( "gui.computercraft.tooltip.disk_id", id ).withStyle( ChatFormatting.GRAY ) ); } } } @Override - public void appendStacks( @Nonnull ItemGroup tabs, @Nonnull DefaultedList list ) + public void fillItemCategory( @Nonnull CreativeModeTab tabs, @Nonnull NonNullList list ) { - if( !isIn( tabs ) ) + if( !allowdedIn( tabs ) ) { return; } @@ -78,21 +78,21 @@ public class ItemDisk extends Item implements IMedia, IColouredItem { if( id >= 0 ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_ID, id ); } } public static int getDiskID( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_ID ) ? nbt.getInt( NBT_ID ) : -1; } @Override public String getLabel( @Nonnull ItemStack stack ) { - return stack.hasCustomName() ? stack.getName() + return stack.hasCustomHoverName() ? stack.getHoverName() .getString() : null; } @@ -101,17 +101,17 @@ public class ItemDisk extends Item implements IMedia, IColouredItem { if( label != null ) { - stack.setCustomName( new LiteralText( label ) ); + stack.setHoverName( new TextComponent( label ) ); } else { - stack.removeCustomName(); + stack.resetHoverName(); } return true; } @Override - public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world ) + public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world ) { int diskID = getDiskID( stack ); if( diskID < 0 ) diff --git a/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java b/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java index 07ecffb99..b27525b76 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java +++ b/src/main/java/dan200/computercraft/shared/media/items/ItemPrintout.java @@ -9,17 +9,17 @@ package dan200.computercraft.shared.media.items; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.ContainerHeldItem; import dan200.computercraft.shared.network.container.HeldItemContainerData; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.TypedActionResult; -import net.minecraft.world.World; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import java.util.List; @@ -35,7 +35,7 @@ public class ItemPrintout extends Item private static final String NBT_LINE_COLOUR = "Color"; private final Type type; - public ItemPrintout( Settings settings, Type type ) + public ItemPrintout( Properties settings, Type type ) { super( settings ); this.type = type; @@ -55,12 +55,12 @@ public class ItemPrintout extends Item // Build NBT if( title != null ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putString( NBT_TITLE, title ); } if( text != null ) { - NbtCompound tag = stack.getOrCreateNbt(); + CompoundTag tag = stack.getOrCreateTag(); tag.putInt( NBT_PAGES, text.length / LINES_PER_PAGE ); for( int i = 0; i < text.length; i++ ) { @@ -72,7 +72,7 @@ public class ItemPrintout extends Item } if( colours != null ) { - NbtCompound tag = stack.getOrCreateNbt(); + CompoundTag tag = stack.getOrCreateTag(); for( int i = 0; i < colours.length; i++ ) { if( colours[i] != null ) @@ -105,7 +105,7 @@ public class ItemPrintout extends Item private static String[] getLines( @Nonnull ItemStack stack, String prefix ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); int numLines = getPageCount( stack ) * LINES_PER_PAGE; String[] lines = new String[numLines]; for( int i = 0; i < lines.length; i++ ) @@ -117,7 +117,7 @@ public class ItemPrintout extends Item public static int getPageCount( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_PAGES ) ? nbt.getInt( NBT_PAGES ) : 1; } @@ -128,31 +128,31 @@ public class ItemPrintout extends Item @Nonnull @Override - public TypedActionResult use( World world, @Nonnull PlayerEntity player, @Nonnull Hand hand ) + public InteractionResultHolder use( Level world, @Nonnull Player player, @Nonnull InteractionHand hand ) { - if( !world.isClient ) + if( !world.isClientSide ) { new HeldItemContainerData( hand ).open( player, new ContainerHeldItem.Factory( ComputerCraftRegistry.ModContainers.PRINTOUT, - player.getStackInHand( hand ), + player.getItemInHand( hand ), hand ) ); } - return new TypedActionResult<>( ActionResult.SUCCESS, player.getStackInHand( hand ) ); + return new InteractionResultHolder<>( InteractionResult.SUCCESS, player.getItemInHand( hand ) ); } @Override - public void appendTooltip( @Nonnull ItemStack stack, World world, @Nonnull List list, @Nonnull TooltipContext options ) + public void appendHoverText( @Nonnull ItemStack stack, Level world, @Nonnull List list, @Nonnull TooltipFlag options ) { String title = getTitle( stack ); if( title != null && !title.isEmpty() ) { - list.add( new LiteralText( title ) ); + list.add( new TextComponent( title ) ); } } public static String getTitle( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_TITLE ) ? nbt.getString( NBT_TITLE ) : null; } diff --git a/src/main/java/dan200/computercraft/shared/media/items/ItemTreasureDisk.java b/src/main/java/dan200/computercraft/shared/media/items/ItemTreasureDisk.java index ae4e6e990..5c0fbfceb 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/ItemTreasureDisk.java +++ b/src/main/java/dan200/computercraft/shared/media/items/ItemTreasureDisk.java @@ -12,15 +12,15 @@ import dan200.computercraft.api.media.IMedia; import dan200.computercraft.core.filesystem.SubMount; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.util.Colour; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.item.Item; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,7 +33,7 @@ public class ItemTreasureDisk extends Item implements IMedia private static final String NBT_COLOUR = "Colour"; private static final String NBT_SUB_PATH = "SubPath"; - public ItemTreasureDisk( Settings settings ) + public ItemTreasureDisk( Properties settings ) { super( settings ); } @@ -41,7 +41,7 @@ public class ItemTreasureDisk extends Item implements IMedia public static ItemStack create( String subPath, int colourIndex ) { ItemStack result = new ItemStack( ComputerCraftRegistry.ModItems.TREASURE_DISK ); - NbtCompound nbt = result.getOrCreateNbt(); + CompoundTag nbt = result.getOrCreateTag(); nbt.putString( NBT_SUB_PATH, subPath ); int slash = subPath.indexOf( '/' ); @@ -62,29 +62,29 @@ public class ItemTreasureDisk extends Item implements IMedia public static int getColour( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_COLOUR ) ? nbt.getInt( NBT_COLOUR ) : Colour.BLUE.getHex(); } @Override - public void appendTooltip( @Nonnull ItemStack stack, @Nullable World world, @Nonnull List list, @Nonnull TooltipContext tooltipOptions ) + public void appendHoverText( @Nonnull ItemStack stack, @Nullable Level world, @Nonnull List list, @Nonnull TooltipFlag tooltipOptions ) { String label = getTitle( stack ); if( !label.isEmpty() ) { - list.add( new LiteralText( label ) ); + list.add( new TextComponent( label ) ); } } @Override - public void appendStacks( @Nonnull ItemGroup group, @Nonnull DefaultedList stacks ) + public void fillItemCategory( @Nonnull CreativeModeTab group, @Nonnull NonNullList stacks ) { } @Nonnull private static String getTitle( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_TITLE ) ? nbt.getString( NBT_TITLE ) : "'alongtimeago' by dan200"; } @@ -95,7 +95,7 @@ public class ItemTreasureDisk extends Item implements IMedia } @Override - public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world ) + public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world ) { IMount rootTreasure = getTreasureMount(); String subPath = getSubPath( stack ); @@ -128,7 +128,7 @@ public class ItemTreasureDisk extends Item implements IMedia @Nonnull private static String getSubPath( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_SUB_PATH ) ? nbt.getString( NBT_SUB_PATH ) : "dan200/alongtimeago"; } } diff --git a/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java b/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java index 6a4a7f8d2..ff63c44a1 100644 --- a/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java +++ b/src/main/java/dan200/computercraft/shared/media/items/RecordMedia.java @@ -6,11 +6,11 @@ package dan200.computercraft.shared.media.items; import dan200.computercraft.api.media.IMedia; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.MusicDiscItem; -import net.minecraft.sound.SoundEvent; -import net.minecraft.text.TranslatableText; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.RecordItem; import javax.annotation.Nonnull; @@ -35,22 +35,22 @@ public final class RecordMedia implements IMedia public String getAudioTitle( @Nonnull ItemStack stack ) { Item item = stack.getItem(); - if( !(item instanceof MusicDiscItem) ) + if( !(item instanceof RecordItem) ) { return null; } - return new TranslatableText( item.getTranslationKey() + ".desc" ).getString(); + return new TranslatableComponent( item.getDescriptionId() + ".desc" ).getString(); } @Override public SoundEvent getAudio( @Nonnull ItemStack stack ) { Item item = stack.getItem(); - if( !(item instanceof MusicDiscItem) ) + if( !(item instanceof RecordItem) ) { return null; } - return ((MusicDiscItem) item).getSound(); + return ((RecordItem) item).getSound(); } } diff --git a/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java b/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java index 748e61f91..d2f479581 100644 --- a/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java +++ b/src/main/java/dan200/computercraft/shared/media/recipes/DiskRecipe.java @@ -10,40 +10,40 @@ import dan200.computercraft.shared.media.items.ItemDisk; import dan200.computercraft.shared.util.Colour; import dan200.computercraft.shared.util.ColourTracker; import dan200.computercraft.shared.util.ColourUtils; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.SpecialCraftingRecipe; -import net.minecraft.recipe.SpecialRecipeSerializer; -import net.minecraft.util.DyeColor; -import net.minecraft.util.Identifier; -import net.minecraft.world.World; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; -public class DiskRecipe extends SpecialCraftingRecipe +public class DiskRecipe extends CustomRecipe { - public static final RecipeSerializer SERIALIZER = new SpecialRecipeSerializer<>( DiskRecipe::new ); - private final Ingredient paper = Ingredient.ofItems( Items.PAPER ); + public static final RecipeSerializer SERIALIZER = new SimpleRecipeSerializer<>( DiskRecipe::new ); + private final Ingredient paper = Ingredient.of( Items.PAPER ); // TODO: Ingredient.fromTag( Tags.Items.DUSTS_REDSTONE ); - private final Ingredient redstone = Ingredient.ofItems( Items.REDSTONE ); + private final Ingredient redstone = Ingredient.of( Items.REDSTONE ); - public DiskRecipe( Identifier id ) + public DiskRecipe( ResourceLocation id ) { super( id ); } @Override - public boolean matches( @Nonnull CraftingInventory inv, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inv, @Nonnull Level world ) { boolean paperFound = false; boolean redstoneFound = false; - for( int i = 0; i < inv.size(); i++ ) + for( int i = 0; i < inv.getContainerSize(); i++ ) { - ItemStack stack = inv.getStack( i ); + ItemStack stack = inv.getItem( i ); if( !stack.isEmpty() ) { @@ -75,13 +75,13 @@ public class DiskRecipe extends SpecialCraftingRecipe @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inv ) + public ItemStack assemble( @Nonnull CraftingContainer inv ) { ColourTracker tracker = new ColourTracker(); - for( int i = 0; i < inv.size(); i++ ) + for( int i = 0; i < inv.getContainerSize(); i++ ) { - ItemStack stack = inv.getStack( i ); + ItemStack stack = inv.getItem( i ); if( stack.isEmpty() ) { @@ -99,7 +99,7 @@ public class DiskRecipe extends SpecialCraftingRecipe } @Override - public boolean fits( int x, int y ) + public boolean canCraftInDimensions( int x, int y ) { return x >= 2 && y >= 2; } @@ -113,7 +113,7 @@ public class DiskRecipe extends SpecialCraftingRecipe @Nonnull @Override - public ItemStack getOutput() + public ItemStack getResultItem() { return ItemDisk.createFromIDAndColour( -1, null, Colour.BLUE.getHex() ); } diff --git a/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java b/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java index 421af7edf..5c9b48cde 100644 --- a/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java +++ b/src/main/java/dan200/computercraft/shared/media/recipes/PrintoutRecipe.java @@ -7,46 +7,46 @@ package dan200.computercraft.shared.media.recipes; import dan200.computercraft.shared.media.items.ItemPrintout; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.SpecialCraftingRecipe; -import net.minecraft.recipe.SpecialRecipeSerializer; -import net.minecraft.util.Identifier; -import net.minecraft.world.World; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; -public final class PrintoutRecipe extends SpecialCraftingRecipe +public final class PrintoutRecipe extends CustomRecipe { - public static final RecipeSerializer SERIALIZER = new SpecialRecipeSerializer<>( PrintoutRecipe::new ); - private final Ingredient paper = Ingredient.ofItems( Items.PAPER ); - private final Ingredient leather = Ingredient.ofItems( Items.LEATHER ); - private final Ingredient string = Ingredient.ofItems( Items.STRING ); + public static final RecipeSerializer SERIALIZER = new SimpleRecipeSerializer<>( PrintoutRecipe::new ); + private final Ingredient paper = Ingredient.of( Items.PAPER ); + private final Ingredient leather = Ingredient.of( Items.LEATHER ); + private final Ingredient string = Ingredient.of( Items.STRING ); - private PrintoutRecipe( Identifier id ) + private PrintoutRecipe( ResourceLocation id ) { super( id ); } @Nonnull @Override - public ItemStack getOutput() + public ItemStack getResultItem() { return ItemPrintout.createMultipleFromTitleAndText( null, null, null ); } @Override - public boolean matches( @Nonnull CraftingInventory inventory, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inventory, @Nonnull Level world ) { - return !craft( inventory ).isEmpty(); + return !assemble( inventory ).isEmpty(); } @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inventory ) + public ItemStack assemble( @Nonnull CraftingContainer inventory ) { // See if we match the recipe, and extract the input disk ID and dye colour int numPages = 0; @@ -59,7 +59,7 @@ public final class PrintoutRecipe extends SpecialCraftingRecipe { for( int x = 0; x < inventory.getWidth(); x++ ) { - ItemStack stack = inventory.getStack( x + y * inventory.getWidth() ); + ItemStack stack = inventory.getItem( x + y * inventory.getWidth() ); if( !stack.isEmpty() ) { if( stack.getItem() instanceof ItemPrintout && ((ItemPrintout) stack.getItem()).getType() != ItemPrintout.Type.BOOK ) @@ -153,7 +153,7 @@ public final class PrintoutRecipe extends SpecialCraftingRecipe } @Override - public boolean fits( int x, int y ) + public boolean canCraftInDimensions( int x, int y ) { return x >= 3 && y >= 3; } diff --git a/src/main/java/dan200/computercraft/shared/network/NetworkHandler.java b/src/main/java/dan200/computercraft/shared/network/NetworkHandler.java index e37f4411e..7d82ef22d 100644 --- a/src/main/java/dan200/computercraft/shared/network/NetworkHandler.java +++ b/src/main/java/dan200/computercraft/shared/network/NetworkHandler.java @@ -21,17 +21,17 @@ import net.fabricmc.fabric.api.network.ClientSidePacketRegistry; import net.fabricmc.fabric.api.network.PacketContext; import net.fabricmc.fabric.api.network.ServerSidePacketRegistry; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.MinecraftClient; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.network.packet.c2s.play.CustomPayloadC2SPacket; -import net.minecraft.network.packet.s2c.play.CustomPayloadS2CPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.chunk.WorldChunk; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.phys.Vec3; import java.util.function.BiConsumer; import java.util.function.Function; @@ -39,10 +39,10 @@ import java.util.function.Supplier; public final class NetworkHandler { - private static final Int2ObjectMap> packetReaders = new Int2ObjectOpenHashMap<>(); + private static final Int2ObjectMap> packetReaders = new Int2ObjectOpenHashMap<>(); private static final Object2IntMap> packetIds = new Object2IntOpenHashMap<>(); - private static final Identifier ID = new Identifier( ComputerCraft.MOD_ID, "main" ); + private static final ResourceLocation ID = new ResourceLocation( ComputerCraft.MOD_ID, "main" ); private NetworkHandler() { @@ -79,7 +79,7 @@ public final class NetworkHandler registerMainThread( 19, UploadResultMessage.class, UploadResultMessage::new ); } - private static void receive( PacketContext context, PacketByteBuf buffer ) + private static void receive( PacketContext context, FriendlyByteBuf buffer ) { int type = buffer.readByte(); packetReaders.get( type ) @@ -94,7 +94,7 @@ public final class NetworkHandler * @param id The identifier for this packet type * @param decoder The factory for this type of packet. */ - private static void registerMainThread( int id, Class type, Function decoder ) + private static void registerMainThread( int id, Class type, Function decoder ) { packetIds.put( type, id ); packetReaders.put( id, ( context, buf ) -> { @@ -111,52 +111,52 @@ public final class NetworkHandler .getClass(); } - private static PacketByteBuf encode( NetworkMessage message ) + private static FriendlyByteBuf encode( NetworkMessage message ) { - PacketByteBuf buf = new PacketByteBuf( Unpooled.buffer() ); + FriendlyByteBuf buf = new FriendlyByteBuf( Unpooled.buffer() ); buf.writeByte( packetIds.getInt( message.getClass() ) ); message.toBytes( buf ); return buf; } - public static void sendToPlayer( PlayerEntity player, NetworkMessage packet ) + public static void sendToPlayer( Player player, NetworkMessage packet ) { - ((ServerPlayerEntity) player).networkHandler.sendPacket( new CustomPayloadS2CPacket( ID, encode( packet ) ) ); + ((ServerPlayer) player).connection.send( new ClientboundCustomPayloadPacket( ID, encode( packet ) ) ); } public static void sendToAllPlayers( NetworkMessage packet ) { MinecraftServer server = GameInstanceUtils.getServer(); - server.getPlayerManager() - .sendToAll( new CustomPayloadS2CPacket( ID, encode( packet ) ) ); + server.getPlayerList() + .broadcastAll( new ClientboundCustomPayloadPacket( ID, encode( packet ) ) ); } public static void sendToAllPlayers( MinecraftServer server, NetworkMessage packet ) { - server.getPlayerManager() - .sendToAll( new CustomPayloadS2CPacket( ID, encode( packet ) ) ); + server.getPlayerList() + .broadcastAll( new ClientboundCustomPayloadPacket( ID, encode( packet ) ) ); } @Environment( EnvType.CLIENT ) public static void sendToServer( NetworkMessage packet ) { - MinecraftClient.getInstance().player.networkHandler.sendPacket( new CustomPayloadC2SPacket( ID, encode( packet ) ) ); + Minecraft.getInstance().player.connection.send( new ServerboundCustomPayloadPacket( ID, encode( packet ) ) ); } - public static void sendToAllAround( NetworkMessage packet, World world, Vec3d pos, double range ) + public static void sendToAllAround( NetworkMessage packet, Level world, Vec3 pos, double range ) { world.getServer() - .getPlayerManager() - .sendToAround( null, pos.x, pos.y, pos.z, range, world.getRegistryKey(), new CustomPayloadS2CPacket( ID, encode( packet ) ) ); + .getPlayerList() + .broadcast( null, pos.x, pos.y, pos.z, range, world.dimension(), new ClientboundCustomPayloadPacket( ID, encode( packet ) ) ); } - public static void sendToAllTracking( NetworkMessage packet, WorldChunk chunk ) + public static void sendToAllTracking( NetworkMessage packet, LevelChunk chunk ) { - for( PlayerEntity player : chunk.getWorld().getPlayers() ) + for( Player player : chunk.getLevel().players() ) { - if ( chunk.getWorld().getRegistryKey().getValue() == player.getEntityWorld().getRegistryKey().getValue() && player.getChunkPos().equals( chunk.getPos() ) ) + if( chunk.getLevel().dimension().location() == player.getCommandSenderWorld().dimension().location() && player.chunkPosition().equals( chunk.getPos() ) ) { - ((ServerPlayerEntity) player).networkHandler.sendPacket( new CustomPayloadS2CPacket( ID, encode( packet ) ) ); + ((ServerPlayer) player).connection.send( new ClientboundCustomPayloadPacket( ID, encode( packet ) ) ); } } } diff --git a/src/main/java/dan200/computercraft/shared/network/NetworkMessage.java b/src/main/java/dan200/computercraft/shared/network/NetworkMessage.java index b1ab12c69..bcffe6950 100644 --- a/src/main/java/dan200/computercraft/shared/network/NetworkMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/NetworkMessage.java @@ -7,7 +7,7 @@ package dan200.computercraft.shared.network; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -23,7 +23,7 @@ public interface NetworkMessage * * @param buf The buffer to write data to. */ - void toBytes( @Nonnull PacketByteBuf buf ); + void toBytes( @Nonnull FriendlyByteBuf buf ); /** * Handle this {@link NetworkMessage}. diff --git a/src/main/java/dan200/computercraft/shared/network/client/ChatTableClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/ChatTableClientMessage.java index c21f60edf..b3f93804c 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/ChatTableClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/ChatTableClientMessage.java @@ -12,8 +12,8 @@ import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.text.Text; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; import javax.annotation.Nonnull; @@ -30,17 +30,17 @@ public class ChatTableClientMessage implements NetworkMessage this.table = table; } - public ChatTableClientMessage( @Nonnull PacketByteBuf buf ) + public ChatTableClientMessage( @Nonnull FriendlyByteBuf buf ) { int id = buf.readVarInt(); int columns = buf.readVarInt(); TableBuilder table; if( buf.readBoolean() ) { - Text[] headers = new Text[columns]; + Component[] headers = new Component[columns]; for( int i = 0; i < columns; i++ ) { - headers[i] = buf.readText(); + headers[i] = buf.readComponent(); } table = new TableBuilder( id, headers ); } @@ -52,10 +52,10 @@ public class ChatTableClientMessage implements NetworkMessage int rows = buf.readVarInt(); for( int i = 0; i < rows; i++ ) { - Text[] row = new Text[columns]; + Component[] row = new Component[columns]; for( int j = 0; j < columns; j++ ) { - row[j] = buf.readText(); + row[j] = buf.readComponent(); } table.row( row ); } @@ -65,26 +65,26 @@ public class ChatTableClientMessage implements NetworkMessage } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { buf.writeVarInt( table.getId() ); buf.writeVarInt( table.getColumns() ); buf.writeBoolean( table.getHeaders() != null ); if( table.getHeaders() != null ) { - for( Text header : table.getHeaders() ) + for( Component header : table.getHeaders() ) { - buf.writeText( header ); + buf.writeComponent( header ); } } buf.writeVarInt( table.getRows() .size() ); - for( Text[] row : table.getRows() ) + for( Component[] row : table.getRows() ) { - for( Text column : row ) + for( Component column : row ) { - buf.writeText( column ); + buf.writeComponent( column ); } } diff --git a/src/main/java/dan200/computercraft/shared/network/client/ComputerClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/ComputerClientMessage.java index ad04ce2aa..d3349cdfc 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/ComputerClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/ComputerClientMessage.java @@ -3,13 +3,12 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.network.client; import dan200.computercraft.ComputerCraft; import dan200.computercraft.shared.computer.core.ClientComputer; import dan200.computercraft.shared.network.NetworkMessage; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -25,7 +24,7 @@ public abstract class ComputerClientMessage implements NetworkMessage this.instanceId = instanceId; } - public ComputerClientMessage( @Nonnull PacketByteBuf buf ) + public ComputerClientMessage( @Nonnull FriendlyByteBuf buf ) { instanceId = buf.readVarInt(); } @@ -36,7 +35,7 @@ public abstract class ComputerClientMessage implements NetworkMessage } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { buf.writeVarInt( instanceId ); } diff --git a/src/main/java/dan200/computercraft/shared/network/client/ComputerDataClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/ComputerDataClientMessage.java index 405d7e29e..8092fb5c5 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/ComputerDataClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/ComputerDataClientMessage.java @@ -9,8 +9,8 @@ package dan200.computercraft.shared.network.client; import dan200.computercraft.shared.computer.core.ComputerState; import dan200.computercraft.shared.computer.core.ServerComputer; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -20,7 +20,7 @@ import javax.annotation.Nonnull; public class ComputerDataClientMessage extends ComputerClientMessage { private final ComputerState state; - private final NbtCompound userData; + private final CompoundTag userData; public ComputerDataClientMessage( ServerComputer computer ) { @@ -29,18 +29,18 @@ public class ComputerDataClientMessage extends ComputerClientMessage userData = computer.getUserData(); } - public ComputerDataClientMessage( @Nonnull PacketByteBuf buf ) + public ComputerDataClientMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); - state = buf.readEnumConstant( ComputerState.class ); + state = buf.readEnum( ComputerState.class ); userData = buf.readNbt(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); - buf.writeEnumConstant( state ); + buf.writeEnum( state ); buf.writeNbt( userData ); } diff --git a/src/main/java/dan200/computercraft/shared/network/client/ComputerDeletedClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/ComputerDeletedClientMessage.java index 7ae774055..322c11cc4 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/ComputerDeletedClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/ComputerDeletedClientMessage.java @@ -8,7 +8,7 @@ package dan200.computercraft.shared.network.client; import dan200.computercraft.ComputerCraft; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; public class ComputerDeletedClientMessage extends ComputerClientMessage { @@ -17,7 +17,7 @@ public class ComputerDeletedClientMessage extends ComputerClientMessage super( instanceId ); } - public ComputerDeletedClientMessage( PacketByteBuf buffer ) + public ComputerDeletedClientMessage( FriendlyByteBuf buffer ) { super( buffer ); } diff --git a/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java index a6a7b745c..447ab42a6 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/ComputerTerminalClientMessage.java @@ -7,7 +7,7 @@ package dan200.computercraft.shared.network.client; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -21,14 +21,14 @@ public class ComputerTerminalClientMessage extends ComputerClientMessage this.state = state; } - public ComputerTerminalClientMessage( @Nonnull PacketByteBuf buf ) + public ComputerTerminalClientMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); state = new TerminalState( buf ); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); state.write( buf ); diff --git a/src/main/java/dan200/computercraft/shared/network/client/MonitorClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/MonitorClientMessage.java index 740171dab..00289ce75 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/MonitorClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/MonitorClientMessage.java @@ -8,11 +8,11 @@ package dan200.computercraft.shared.network.client; import dan200.computercraft.shared.network.NetworkMessage; import dan200.computercraft.shared.peripheral.monitor.TileMonitor; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.math.BlockPos; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.level.block.entity.BlockEntity; import javax.annotation.Nonnull; @@ -27,14 +27,14 @@ public class MonitorClientMessage implements NetworkMessage this.state = state; } - public MonitorClientMessage( @Nonnull PacketByteBuf buf ) + public MonitorClientMessage( @Nonnull FriendlyByteBuf buf ) { pos = buf.readBlockPos(); state = new TerminalState( buf ); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { buf.writeBlockPos( pos ); state.write( buf ); @@ -43,13 +43,13 @@ public class MonitorClientMessage implements NetworkMessage @Override public void handle( PacketContext context ) { - ClientPlayerEntity player = MinecraftClient.getInstance().player; - if( player == null || player.world == null ) + LocalPlayer player = Minecraft.getInstance().player; + if( player == null || player.level == null ) { return; } - BlockEntity te = player.world.getBlockEntity( pos ); + BlockEntity te = player.level.getBlockEntity( pos ); if( !(te instanceof TileMonitor) ) { return; diff --git a/src/main/java/dan200/computercraft/shared/network/client/PlayRecordClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/PlayRecordClientMessage.java index 35587fdcf..4ee745101 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/PlayRecordClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/PlayRecordClientMessage.java @@ -10,12 +10,12 @@ import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.client.MinecraftClient; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.sound.SoundEvent; -import net.minecraft.text.LiteralText; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.registry.Registry; +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.sounds.SoundEvent; import javax.annotation.Nonnull; @@ -46,13 +46,13 @@ public class PlayRecordClientMessage implements NetworkMessage soundEvent = null; } - public PlayRecordClientMessage( PacketByteBuf buf ) + public PlayRecordClientMessage( FriendlyByteBuf buf ) { pos = buf.readBlockPos(); if( buf.readBoolean() ) { - name = buf.readString( Short.MAX_VALUE ); - soundEvent = Registry.SOUND_EVENT.get( buf.readIdentifier() ); + name = buf.readUtf( Short.MAX_VALUE ); + soundEvent = Registry.SOUND_EVENT.get( buf.readResourceLocation() ); } else { @@ -62,7 +62,7 @@ public class PlayRecordClientMessage implements NetworkMessage } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { buf.writeBlockPos( pos ); if( soundEvent == null ) @@ -72,8 +72,8 @@ public class PlayRecordClientMessage implements NetworkMessage else { buf.writeBoolean( true ); - buf.writeString( name ); - buf.writeIdentifier( soundEvent.getId() ); + buf.writeUtf( name ); + buf.writeResourceLocation( soundEvent.getLocation() ); } } @@ -81,11 +81,11 @@ public class PlayRecordClientMessage implements NetworkMessage @Environment( EnvType.CLIENT ) public void handle( PacketContext context ) { - MinecraftClient mc = MinecraftClient.getInstance(); - mc.worldRenderer.playSong( soundEvent, pos ); + Minecraft mc = Minecraft.getInstance(); + mc.levelRenderer.playStreamingMusic( soundEvent, pos ); if( name != null ) { - mc.inGameHud.setRecordPlayingOverlay( new LiteralText( name ) ); + mc.gui.setNowPlaying( new TextComponent( name ) ); } } } diff --git a/src/main/java/dan200/computercraft/shared/network/client/SpeakerMoveClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/SpeakerMoveClientMessage.java index 9bfe74a03..f00c35d33 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/SpeakerMoveClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/SpeakerMoveClientMessage.java @@ -10,8 +10,8 @@ import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.math.Vec3d; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.UUID; @@ -26,27 +26,27 @@ import java.util.UUID; public class SpeakerMoveClientMessage implements NetworkMessage { private final UUID source; - private final Vec3d pos; + private final Vec3 pos; - public SpeakerMoveClientMessage( UUID source, Vec3d pos ) + public SpeakerMoveClientMessage( UUID source, Vec3 pos ) { this.source = source; this.pos = pos; } - public SpeakerMoveClientMessage( PacketByteBuf buf ) + public SpeakerMoveClientMessage( FriendlyByteBuf buf ) { - source = buf.readUuid(); - pos = new Vec3d( buf.readDouble(), buf.readDouble(), buf.readDouble() ); + source = buf.readUUID(); + pos = new Vec3( buf.readDouble(), buf.readDouble(), buf.readDouble() ); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { - buf.writeUuid( source ); - buf.writeDouble( pos.getX() ); - buf.writeDouble( pos.getY() ); - buf.writeDouble( pos.getZ() ); + buf.writeUUID( source ); + buf.writeDouble( pos.x() ); + buf.writeDouble( pos.y() ); + buf.writeDouble( pos.z() ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/network/client/SpeakerPlayClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/SpeakerPlayClientMessage.java index a913d1ea9..f0c8f7ecc 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/SpeakerPlayClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/SpeakerPlayClientMessage.java @@ -10,9 +10,9 @@ import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Vec3d; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.UUID; @@ -27,12 +27,12 @@ import java.util.UUID; public class SpeakerPlayClientMessage implements NetworkMessage { private final UUID source; - private final Vec3d pos; - private final Identifier sound; + private final Vec3 pos; + private final ResourceLocation sound; private final float volume; private final float pitch; - public SpeakerPlayClientMessage( UUID source, Vec3d pos, Identifier event, float volume, float pitch ) + public SpeakerPlayClientMessage( UUID source, Vec3 pos, ResourceLocation event, float volume, float pitch ) { this.source = source; this.pos = pos; @@ -41,23 +41,23 @@ public class SpeakerPlayClientMessage implements NetworkMessage this.pitch = pitch; } - public SpeakerPlayClientMessage( PacketByteBuf buf ) + public SpeakerPlayClientMessage( FriendlyByteBuf buf ) { - source = buf.readUuid(); - pos = new Vec3d( buf.readDouble(), buf.readDouble(), buf.readDouble() ); - sound = buf.readIdentifier(); + source = buf.readUUID(); + pos = new Vec3( buf.readDouble(), buf.readDouble(), buf.readDouble() ); + sound = buf.readResourceLocation(); volume = buf.readFloat(); pitch = buf.readFloat(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { - buf.writeUuid( source ); - buf.writeDouble( pos.getX() ); - buf.writeDouble( pos.getY() ); - buf.writeDouble( pos.getZ() ); - buf.writeIdentifier( sound ); + buf.writeUUID( source ); + buf.writeDouble( pos.x() ); + buf.writeDouble( pos.y() ); + buf.writeDouble( pos.z() ); + buf.writeResourceLocation( sound ); buf.writeFloat( volume ); buf.writeFloat( pitch ); } diff --git a/src/main/java/dan200/computercraft/shared/network/client/SpeakerStopClientMessage.java b/src/main/java/dan200/computercraft/shared/network/client/SpeakerStopClientMessage.java index bdc630244..ab7d5c57e 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/SpeakerStopClientMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/SpeakerStopClientMessage.java @@ -10,7 +10,7 @@ import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; import java.util.UUID; @@ -31,15 +31,15 @@ public class SpeakerStopClientMessage implements NetworkMessage this.source = source; } - public SpeakerStopClientMessage( PacketByteBuf buf ) + public SpeakerStopClientMessage( FriendlyByteBuf buf ) { - source = buf.readUuid(); + source = buf.readUUID(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { - buf.writeUuid( source ); + buf.writeUUID( source ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/network/client/TerminalState.java b/src/main/java/dan200/computercraft/shared/network/client/TerminalState.java index 0ecfe413c..1b7bd8504 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/TerminalState.java +++ b/src/main/java/dan200/computercraft/shared/network/client/TerminalState.java @@ -11,7 +11,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.buffer.Unpooled; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nullable; import java.io.IOException; @@ -62,11 +62,11 @@ public class TerminalState height = terminal.getHeight(); ByteBuf buf = buffer = Unpooled.buffer(); - terminal.write( new PacketByteBuf( buf ) ); + terminal.write( new FriendlyByteBuf( buf ) ); } } - public TerminalState( PacketByteBuf buf ) + public TerminalState( FriendlyByteBuf buf ) { colour = buf.readBoolean(); compress = buf.readBoolean(); @@ -124,7 +124,7 @@ public class TerminalState } } - public void write( PacketByteBuf buf ) + public void write( FriendlyByteBuf buf ) { buf.writeBoolean( colour ); buf.writeBoolean( compress ); @@ -191,6 +191,6 @@ public class TerminalState { throw new NullPointerException( "buffer" ); } - terminal.read( new PacketByteBuf( buffer ) ); + terminal.read( new FriendlyByteBuf( buffer ) ); } } diff --git a/src/main/java/dan200/computercraft/shared/network/client/UploadResultMessage.java b/src/main/java/dan200/computercraft/shared/network/client/UploadResultMessage.java index 012908bd4..8d8283665 100644 --- a/src/main/java/dan200/computercraft/shared/network/client/UploadResultMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/client/UploadResultMessage.java @@ -10,10 +10,10 @@ import dan200.computercraft.client.gui.OptionScreen; import dan200.computercraft.shared.computer.upload.UploadResult; import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.text.Text; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; import javax.annotation.Nonnull; @@ -23,33 +23,33 @@ public class UploadResultMessage implements NetworkMessage public static final UploadResultMessage OUT_OF_SPACE = new UploadResultMessage( UploadResult.ERROR, UploadResult.OUT_OF_SPACE_MSG ); private final UploadResult result; - private final Text message; + private final Component message; - public UploadResultMessage( UploadResult result, Text message ) + public UploadResultMessage( UploadResult result, Component message ) { this.result = result; this.message = message; } - public UploadResultMessage( @Nonnull PacketByteBuf buf ) + public UploadResultMessage( @Nonnull FriendlyByteBuf buf ) { - result = buf.readEnumConstant( UploadResult.class ); - message = buf.readText(); + result = buf.readEnum( UploadResult.class ); + message = buf.readComponent(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { - buf.writeEnumConstant( result ); - buf.writeText( message ); + buf.writeEnum( result ); + buf.writeComponent( message ); } @Override public void handle( PacketContext context ) { - MinecraftClient minecraft = MinecraftClient.getInstance(); + Minecraft minecraft = Minecraft.getInstance(); - Screen screen = OptionScreen.unwrap( minecraft.currentScreen ); + Screen screen = OptionScreen.unwrap( minecraft.screen ); if( screen instanceof ComputerScreenBase ) { ((ComputerScreenBase) screen).uploadResult( result, message ); diff --git a/src/main/java/dan200/computercraft/shared/network/container/ComputerContainerData.java b/src/main/java/dan200/computercraft/shared/network/container/ComputerContainerData.java index 7edd25185..f39a12acf 100644 --- a/src/main/java/dan200/computercraft/shared/network/container/ComputerContainerData.java +++ b/src/main/java/dan200/computercraft/shared/network/container/ComputerContainerData.java @@ -8,7 +8,7 @@ package dan200.computercraft.shared.network.container; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ServerComputer; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; public class ComputerContainerData implements ContainerData { @@ -21,17 +21,17 @@ public class ComputerContainerData implements ContainerData family = computer.getFamily(); } - public ComputerContainerData( PacketByteBuf byteBuf ) + public ComputerContainerData( FriendlyByteBuf byteBuf ) { id = byteBuf.readInt(); - family = byteBuf.readEnumConstant( ComputerFamily.class ); + family = byteBuf.readEnum( ComputerFamily.class ); } @Override - public void toBytes( PacketByteBuf buf ) + public void toBytes( FriendlyByteBuf buf ) { buf.writeInt( id ); - buf.writeEnumConstant( family ); + buf.writeEnum( family ); } public int getInstanceId() diff --git a/src/main/java/dan200/computercraft/shared/network/container/ContainerData.java b/src/main/java/dan200/computercraft/shared/network/container/ContainerData.java index c29d774b8..2fd9e0406 100644 --- a/src/main/java/dan200/computercraft/shared/network/container/ContainerData.java +++ b/src/main/java/dan200/computercraft/shared/network/container/ContainerData.java @@ -7,13 +7,13 @@ package dan200.computercraft.shared.network.container; import net.fabricmc.fabric.api.screenhandler.v1.ScreenHandlerRegistry; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.ScreenHandlerType; -import net.minecraft.util.Identifier; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; import javax.annotation.Nonnull; import java.util.function.Function; @@ -23,7 +23,7 @@ import java.util.function.Function; */ public interface ContainerData { - static ScreenHandlerType toType( Identifier identifier, Function reader, + static MenuType toType( ResourceLocation identifier, Function reader, Factory factory ) { return ScreenHandlerRegistry.registerExtended( identifier, @@ -31,7 +31,8 @@ public interface ContainerData playerInventory, reader.apply( packetByteBuf ) ) ); } - static ScreenHandlerType toType( Identifier identifier, ScreenHandlerType type, Function reader, + + static MenuType toType( ResourceLocation identifier, MenuType type, Function reader, FixedFactory factory ) { return ScreenHandlerRegistry.registerExtended( identifier, @@ -40,21 +41,21 @@ public interface ContainerData reader.apply( packetByteBuf ) ) ); } - void toBytes( PacketByteBuf buf ); + void toBytes( FriendlyByteBuf buf ); - default void open( PlayerEntity player, NamedScreenHandlerFactory owner ) + default void open( Player player, MenuProvider owner ) { - if ( player.world.isClient ) return; - player.openHandledScreen( owner ); + if( player.level.isClientSide ) return; + player.openMenu( owner ); } - interface Factory + interface Factory { - C create( int id, @Nonnull PlayerInventory inventory, T data ); + C create( int id, @Nonnull Inventory inventory, T data ); } - interface FixedFactory + interface FixedFactory { - C create( ScreenHandlerType type, int id, @Nonnull PlayerInventory inventory, T data ); + C create( MenuType type, int id, @Nonnull Inventory inventory, T data ); } } diff --git a/src/main/java/dan200/computercraft/shared/network/container/HeldItemContainerData.java b/src/main/java/dan200/computercraft/shared/network/container/HeldItemContainerData.java index a32e35af0..3650b2a52 100644 --- a/src/main/java/dan200/computercraft/shared/network/container/HeldItemContainerData.java +++ b/src/main/java/dan200/computercraft/shared/network/container/HeldItemContainerData.java @@ -3,12 +3,11 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.network.container; import dan200.computercraft.shared.common.ContainerHeldItem; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.util.Hand; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.InteractionHand; import javax.annotation.Nonnull; @@ -20,26 +19,26 @@ import javax.annotation.Nonnull; */ public class HeldItemContainerData implements ContainerData { - private final Hand hand; + private final InteractionHand hand; - public HeldItemContainerData( Hand hand ) + public HeldItemContainerData( InteractionHand hand ) { this.hand = hand; } - public HeldItemContainerData( PacketByteBuf buffer ) + public HeldItemContainerData( FriendlyByteBuf buffer ) { - hand = buffer.readEnumConstant( Hand.class ); + hand = buffer.readEnum( InteractionHand.class ); } @Override - public void toBytes( PacketByteBuf buf ) + public void toBytes( FriendlyByteBuf buf ) { - buf.writeEnumConstant( hand ); + buf.writeEnum( hand ); } @Nonnull - public Hand getHand() + public InteractionHand getHand() { return hand; } diff --git a/src/main/java/dan200/computercraft/shared/network/container/ViewComputerContainerData.java b/src/main/java/dan200/computercraft/shared/network/container/ViewComputerContainerData.java index 7999ca681..dd0c995f5 100644 --- a/src/main/java/dan200/computercraft/shared/network/container/ViewComputerContainerData.java +++ b/src/main/java/dan200/computercraft/shared/network/container/ViewComputerContainerData.java @@ -3,12 +3,11 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.network.container; import dan200.computercraft.core.terminal.Terminal; import dan200.computercraft.shared.computer.core.ServerComputer; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -37,7 +36,7 @@ public class ViewComputerContainerData extends ComputerContainerData } } - public ViewComputerContainerData( PacketByteBuf buffer ) + public ViewComputerContainerData( FriendlyByteBuf buffer ) { super( buffer ); width = buffer.readVarInt(); @@ -45,7 +44,7 @@ public class ViewComputerContainerData extends ComputerContainerData } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); buf.writeVarInt( width ); diff --git a/src/main/java/dan200/computercraft/shared/network/server/ComputerActionServerMessage.java b/src/main/java/dan200/computercraft/shared/network/server/ComputerActionServerMessage.java index 00395bbca..212dd6eae 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/ComputerActionServerMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/ComputerActionServerMessage.java @@ -9,7 +9,7 @@ package dan200.computercraft.shared.network.server; import dan200.computercraft.shared.computer.core.IContainerComputer; import dan200.computercraft.shared.computer.core.ServerComputer; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -23,17 +23,17 @@ public class ComputerActionServerMessage extends ComputerServerMessage this.action = action; } - public ComputerActionServerMessage( @Nonnull PacketByteBuf buf ) + public ComputerActionServerMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); - action = buf.readEnumConstant( Action.class ); + action = buf.readEnum( Action.class ); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); - buf.writeEnumConstant( action ); + buf.writeEnum( action ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/network/server/ComputerServerMessage.java b/src/main/java/dan200/computercraft/shared/network/server/ComputerServerMessage.java index 3acf35e38..867f5dcd4 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/ComputerServerMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/ComputerServerMessage.java @@ -11,7 +11,7 @@ import dan200.computercraft.shared.computer.core.IContainerComputer; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -29,13 +29,13 @@ public abstract class ComputerServerMessage implements NetworkMessage this.instanceId = instanceId; } - public ComputerServerMessage( @Nonnull PacketByteBuf buf ) + public ComputerServerMessage( @Nonnull FriendlyByteBuf buf ) { instanceId = buf.readVarInt(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { buf.writeVarInt( instanceId ); } diff --git a/src/main/java/dan200/computercraft/shared/network/server/ContinueUploadMessage.java b/src/main/java/dan200/computercraft/shared/network/server/ContinueUploadMessage.java index 557433f63..bc1e0847a 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/ContinueUploadMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/ContinueUploadMessage.java @@ -8,8 +8,8 @@ package dan200.computercraft.shared.network.server; import dan200.computercraft.shared.computer.core.IContainerComputer; import dan200.computercraft.shared.computer.core.ServerComputer; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; import javax.annotation.Nonnull; @@ -23,14 +23,14 @@ public class ContinueUploadMessage extends ComputerServerMessage this.overwrite = overwrite; } - public ContinueUploadMessage( @Nonnull PacketByteBuf buf ) + public ContinueUploadMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); overwrite = buf.readBoolean(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); buf.writeBoolean( overwrite ); @@ -39,7 +39,7 @@ public class ContinueUploadMessage extends ComputerServerMessage @Override protected void handle( PacketContext context, @Nonnull ServerComputer computer, @Nonnull IContainerComputer container ) { - ServerPlayerEntity player = (ServerPlayerEntity) context.getPlayer(); + ServerPlayer player = (ServerPlayer) context.getPlayer(); if( player != null ) container.confirmUpload( player, overwrite ); } } diff --git a/src/main/java/dan200/computercraft/shared/network/server/KeyEventServerMessage.java b/src/main/java/dan200/computercraft/shared/network/server/KeyEventServerMessage.java index cf00e23f0..99c514933 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/KeyEventServerMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/KeyEventServerMessage.java @@ -10,7 +10,7 @@ import dan200.computercraft.shared.computer.core.IContainerComputer; import dan200.computercraft.shared.computer.core.InputState; import dan200.computercraft.shared.computer.core.ServerComputer; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -30,7 +30,7 @@ public class KeyEventServerMessage extends ComputerServerMessage this.key = key; } - public KeyEventServerMessage( @Nonnull PacketByteBuf buf ) + public KeyEventServerMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); type = buf.readByte(); @@ -38,7 +38,7 @@ public class KeyEventServerMessage extends ComputerServerMessage } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); buf.writeByte( type ); diff --git a/src/main/java/dan200/computercraft/shared/network/server/MouseEventServerMessage.java b/src/main/java/dan200/computercraft/shared/network/server/MouseEventServerMessage.java index 872f168ed..024ca7547 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/MouseEventServerMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/MouseEventServerMessage.java @@ -10,7 +10,7 @@ import dan200.computercraft.shared.computer.core.IContainerComputer; import dan200.computercraft.shared.computer.core.InputState; import dan200.computercraft.shared.computer.core.ServerComputer; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -35,7 +35,7 @@ public class MouseEventServerMessage extends ComputerServerMessage this.y = y; } - public MouseEventServerMessage( @Nonnull PacketByteBuf buf ) + public MouseEventServerMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); type = buf.readByte(); @@ -45,7 +45,7 @@ public class MouseEventServerMessage extends ComputerServerMessage } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); buf.writeByte( type ); diff --git a/src/main/java/dan200/computercraft/shared/network/server/QueueEventServerMessage.java b/src/main/java/dan200/computercraft/shared/network/server/QueueEventServerMessage.java index 730d7b6f9..04506ad0f 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/QueueEventServerMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/QueueEventServerMessage.java @@ -10,8 +10,8 @@ import dan200.computercraft.shared.computer.core.IContainerComputer; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.util.NBTUtil; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -34,20 +34,20 @@ public class QueueEventServerMessage extends ComputerServerMessage this.args = args; } - public QueueEventServerMessage( @Nonnull PacketByteBuf buf ) + public QueueEventServerMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); - event = buf.readString( Short.MAX_VALUE ); + event = buf.readUtf( Short.MAX_VALUE ); - NbtCompound args = buf.readNbt(); + CompoundTag args = buf.readNbt(); this.args = args == null ? null : NBTUtil.decodeObjects( args ); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); - buf.writeString( event ); + buf.writeUtf( event ); buf.writeNbt( args == null ? null : NBTUtil.encodeObjects( args ) ); } diff --git a/src/main/java/dan200/computercraft/shared/network/server/RequestComputerMessage.java b/src/main/java/dan200/computercraft/shared/network/server/RequestComputerMessage.java index af7f8b29d..81151437a 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/RequestComputerMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/RequestComputerMessage.java @@ -10,7 +10,7 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.network.NetworkMessage; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.network.FriendlyByteBuf; import javax.annotation.Nonnull; @@ -23,13 +23,13 @@ public class RequestComputerMessage implements NetworkMessage this.instance = instance; } - public RequestComputerMessage( @Nonnull PacketByteBuf buf ) + public RequestComputerMessage( @Nonnull FriendlyByteBuf buf ) { instance = buf.readVarInt(); } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { buf.writeVarInt( instance ); } diff --git a/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java b/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java index 136ce08bb..bf2ccc9d8 100644 --- a/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java +++ b/src/main/java/dan200/computercraft/shared/network/server/UploadFileMessage.java @@ -13,8 +13,8 @@ import dan200.computercraft.shared.computer.upload.FileUpload; import dan200.computercraft.shared.network.NetworkHandler; import io.netty.handler.codec.DecoderException; import net.fabricmc.fabric.api.network.PacketContext; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; import javax.annotation.Nonnull; import java.nio.ByteBuffer; @@ -47,10 +47,10 @@ public class UploadFileMessage extends ComputerServerMessage this.slices = slices; } - public UploadFileMessage( @Nonnull PacketByteBuf buf ) + public UploadFileMessage( @Nonnull FriendlyByteBuf buf ) { super( buf ); - uuid = buf.readUuid(); + uuid = buf.readUUID(); int flag = this.flag = buf.readByte(); int totalSize = 0; @@ -62,7 +62,7 @@ public class UploadFileMessage extends ComputerServerMessage List files = this.files = new ArrayList<>( nFiles ); for( int i = 0; i < nFiles; i++ ) { - String name = buf.readString( MAX_FILE_NAME ); + String name = buf.readUtf( MAX_FILE_NAME ); int size = buf.readVarInt(); if( size > MAX_SIZE || (totalSize += size) >= MAX_SIZE ) { @@ -99,10 +99,10 @@ public class UploadFileMessage extends ComputerServerMessage } @Override - public void toBytes( @Nonnull PacketByteBuf buf ) + public void toBytes( @Nonnull FriendlyByteBuf buf ) { super.toBytes( buf ); - buf.writeUuid( uuid ); + buf.writeUUID( uuid ); buf.writeByte( flag ); if( (flag & FLAG_FIRST) != 0 ) @@ -110,7 +110,7 @@ public class UploadFileMessage extends ComputerServerMessage buf.writeVarInt( files.size() ); for( FileUpload file : files ) { - buf.writeString( file.getName(), MAX_FILE_NAME ); + buf.writeUtf( file.getName(), MAX_FILE_NAME ); buf.writeVarInt( file.getLength() ); buf.writeBytes( file.getChecksum() ); } @@ -175,7 +175,7 @@ public class UploadFileMessage extends ComputerServerMessage @Override protected void handle( PacketContext context, @Nonnull ServerComputer computer, @Nonnull IContainerComputer container ) { - ServerPlayerEntity player = (ServerPlayerEntity) context.getPlayer(); + ServerPlayer player = (ServerPlayer) context.getPlayer(); if( player != null ) { if( (flag & FLAG_FIRST) != 0 ) container.startUpload( uuid, files ); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java index c812dd91b..1453aa7c7 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/commandblock/CommandBlockPeripheral.java @@ -10,8 +10,8 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.lua.LuaFunction; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.computer.apis.CommandAPI; -import net.minecraft.block.entity.CommandBlockBlockEntity; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.entity.CommandBlockEntity; import javax.annotation.Nonnull; @@ -26,11 +26,11 @@ import javax.annotation.Nonnull; */ public class CommandBlockPeripheral implements IPeripheral { - private static final Identifier CAP_ID = new Identifier( ComputerCraft.MOD_ID, "command_block" ); + private static final ResourceLocation CAP_ID = new ResourceLocation( ComputerCraft.MOD_ID, "command_block" ); - private final CommandBlockBlockEntity commandBlock; + private final CommandBlockEntity commandBlock; - public CommandBlockPeripheral( CommandBlockBlockEntity commandBlock ) + public CommandBlockPeripheral( CommandBlockEntity commandBlock ) { this.commandBlock = commandBlock; } @@ -63,7 +63,7 @@ public class CommandBlockPeripheral implements IPeripheral @LuaFunction( mainThread = true ) public final String getCommand() { - return commandBlock.getCommandExecutor() + return commandBlock.getCommandBlock() .getCommand(); } @@ -75,10 +75,10 @@ public class CommandBlockPeripheral implements IPeripheral @LuaFunction( mainThread = true ) public final void setCommand( String command ) { - commandBlock.getCommandExecutor() + commandBlock.getCommandBlock() .setCommand( command ); - commandBlock.getCommandExecutor() - .markDirty(); + commandBlock.getCommandBlock() + .onUpdated(); } /** @@ -91,9 +91,9 @@ public class CommandBlockPeripheral implements IPeripheral @LuaFunction( mainThread = true ) public final Object[] runCommand() { - commandBlock.getCommandExecutor() - .execute( commandBlock.getWorld() ); - int result = commandBlock.getCommandExecutor() + commandBlock.getCommandBlock() + .performCommand( commandBlock.getLevel() ); + int result = commandBlock.getCommandBlock() .getSuccessCount(); return result > 0 ? new Object[] { true } : new Object[] { false, "Command failed" }; } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/BlockDiskDrive.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/BlockDiskDrive.java index 295054c01..3839d391c 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/BlockDiskDrive.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/BlockDiskDrive.java @@ -8,99 +8,99 @@ package dan200.computercraft.shared.peripheral.diskdrive; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityTicker; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.stat.Stats; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.EnumProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.Nameable; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.stats.Stats; +import net.minecraft.world.Nameable; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.DirectionProperty; +import net.minecraft.world.level.block.state.properties.EnumProperty; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class BlockDiskDrive extends BlockGeneric { - static final DirectionProperty FACING = Properties.HORIZONTAL_FACING; - static final EnumProperty STATE = EnumProperty.of( "state", DiskDriveState.class ); + static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; + static final EnumProperty STATE = EnumProperty.create( "state", DiskDriveState.class ); - public BlockDiskDrive( Settings settings ) + public BlockDiskDrive( Properties settings ) { super( settings, ComputerCraftRegistry.ModTiles.DISK_DRIVE ); - setDefaultState( getStateManager().getDefaultState() - .with( FACING, Direction.NORTH ) - .with( STATE, DiskDriveState.EMPTY ) ); + registerDefaultState( getStateDefinition().any() + .setValue( FACING, Direction.NORTH ) + .setValue( STATE, DiskDriveState.EMPTY ) ); } @Nullable @Override - public BlockState getPlacementState( ItemPlacementContext placement ) + public BlockState getStateForPlacement( BlockPlaceContext placement ) { - return getDefaultState().with( FACING, - placement.getPlayerFacing() + return defaultBlockState().setValue( FACING, + placement.getHorizontalDirection() .getOpposite() ); } @Nullable @Override - public BlockEntityTicker getTicker( World world, BlockState state, BlockEntityType type ) + public BlockEntityTicker getTicker( Level world, BlockState state, BlockEntityType type ) { - return world.isClient ? null : BlockDiskDrive.checkType( type, ComputerCraftRegistry.ModTiles.DISK_DRIVE, TileDiskDrive::tick ); + return world.isClientSide ? null : BlockDiskDrive.createTickerHelper( type, ComputerCraftRegistry.ModTiles.DISK_DRIVE, TileDiskDrive::tick ); } @Override - public void afterBreak( - @Nonnull World world, @Nonnull PlayerEntity player, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable BlockEntity te, @Nonnull ItemStack stack + public void playerDestroy( + @Nonnull Level world, @Nonnull Player player, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable BlockEntity te, @Nonnull ItemStack stack ) { if( te instanceof Nameable && ((Nameable) te).hasCustomName() ) { - player.incrementStat( Stats.MINED.getOrCreateStat( this ) ); - player.addExhaustion( 0.005F ); + player.awardStat( Stats.BLOCK_MINED.get( this ) ); + player.causeFoodExhaustion( 0.005F ); ItemStack result = new ItemStack( this ); - result.setCustomName( ((Nameable) te).getCustomName() ); - dropStack( world, pos, result ); + result.setHoverName( ((Nameable) te).getCustomName() ); + popResource( world, pos, result ); } else { - super.afterBreak( world, player, pos, state, te, stack ); + super.playerDestroy( world, player, pos, state, te, stack ); } } @Override - public void onPlaced( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, ItemStack stack ) + public void setPlacedBy( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, ItemStack stack ) { - if( stack.hasCustomName() ) + if( stack.hasCustomHoverName() ) { BlockEntity tileentity = world.getBlockEntity( pos ); if( tileentity instanceof TileDiskDrive ) { - ((TileDiskDrive) tileentity).customName = stack.getName(); + ((TileDiskDrive) tileentity).customName = stack.getHoverName(); } } } @Override - protected void appendProperties( StateManager.Builder properties ) + protected void createBlockStateDefinition( StateDefinition.Builder properties ) { properties.add( FACING, STATE ); } @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileDiskDrive( ComputerCraftRegistry.ModTiles.DISK_DRIVE, pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java index 385fe16b1..5053c5f0b 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/ContainerDiskDrive.java @@ -7,26 +7,26 @@ package dan200.computercraft.shared.peripheral.diskdrive; import dan200.computercraft.shared.ComputerCraftRegistry; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.slot.Slot; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; -public class ContainerDiskDrive extends ScreenHandler +public class ContainerDiskDrive extends AbstractContainerMenu { - private final Inventory inventory; + private final Container inventory; - public ContainerDiskDrive( int id, PlayerInventory player ) + public ContainerDiskDrive( int id, Inventory player ) { - this( id, player, new SimpleInventory( 1 ) ); + this( id, player, new SimpleContainer( 1 ) ); } - public ContainerDiskDrive( int id, PlayerInventory player, Inventory inventory ) + public ContainerDiskDrive( int id, Inventory player, Container inventory ) { super( ComputerCraftRegistry.ModContainers.DISK_DRIVE, id ); @@ -50,21 +50,21 @@ public class ContainerDiskDrive extends ScreenHandler @Nonnull @Override - public ItemStack transferSlot( @Nonnull PlayerEntity player, int slotIndex ) + public ItemStack quickMoveStack( @Nonnull Player player, int slotIndex ) { Slot slot = slots.get( slotIndex ); - if( slot == null || !slot.hasStack() ) + if( slot == null || !slot.hasItem() ) { return ItemStack.EMPTY; } - ItemStack existing = slot.getStack() + ItemStack existing = slot.getItem() .copy(); ItemStack result = existing.copy(); if( slotIndex == 0 ) { // Insert into player inventory - if( !insertItem( existing, 1, 37, true ) ) + if( !moveItemStackTo( existing, 1, 37, true ) ) { return ItemStack.EMPTY; } @@ -72,7 +72,7 @@ public class ContainerDiskDrive extends ScreenHandler else { // Insert into drive inventory - if( !insertItem( existing, 0, 1, false ) ) + if( !moveItemStackTo( existing, 0, 1, false ) ) { return ItemStack.EMPTY; } @@ -80,11 +80,11 @@ public class ContainerDiskDrive extends ScreenHandler if( existing.isEmpty() ) { - slot.setStack( ItemStack.EMPTY ); + slot.set( ItemStack.EMPTY ); } else { - slot.markDirty(); + slot.setChanged(); } if( existing.getCount() == result.getCount() ) @@ -92,13 +92,13 @@ public class ContainerDiskDrive extends ScreenHandler return ItemStack.EMPTY; } - slot.onTakeItem( player, existing ); + slot.onTake( player, existing ); return result; } @Override - public boolean canUse( @Nonnull PlayerEntity player ) + public boolean stillValid( @Nonnull Player player ) { - return inventory.canPlayerUse( player ); + return inventory.stillValid( player ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDrivePeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDrivePeripheral.java index 91ee5bc82..1be070474 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDrivePeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDrivePeripheral.java @@ -14,7 +14,7 @@ import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.MediaProviders; import dan200.computercraft.shared.media.items.ItemDisk; import dan200.computercraft.shared.util.StringUtil; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDriveState.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDriveState.java index 1e146c3c7..cbd06d69c 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDriveState.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/DiskDriveState.java @@ -6,11 +6,11 @@ package dan200.computercraft.shared.peripheral.diskdrive; -import net.minecraft.util.StringIdentifiable; +import net.minecraft.util.StringRepresentable; import javax.annotation.Nonnull; -public enum DiskDriveState implements StringIdentifiable +public enum DiskDriveState implements StringRepresentable { EMPTY( "empty" ), FULL( "full" ), INVALID( "invalid" ); @@ -23,7 +23,7 @@ public enum DiskDriveState implements StringIdentifiable @Override @Nonnull - public String asString() + public String getSerializedName() { return name; } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java index 957f209b3..b209601b4 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/diskdrive/TileDiskDrive.java @@ -17,25 +17,25 @@ import dan200.computercraft.shared.common.TileGeneric; import dan200.computercraft.shared.util.DefaultInventory; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.RecordUtil; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.ItemEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.sound.SoundEvent; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.Nameable; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.Nameable; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -43,12 +43,12 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -public final class TileDiskDrive extends TileGeneric implements DefaultInventory, IPeripheralTile, Nameable, NamedScreenHandlerFactory +public final class TileDiskDrive extends TileGeneric implements DefaultInventory, IPeripheralTile, Nameable, MenuProvider { private static final String NBT_NAME = "CustomName"; private static final String NBT_ITEM = "Item"; private final Map computers = new HashMap<>(); - Text customName; + Component customName; @Nonnull private ItemStack diskStack = ItemStack.EMPTY; private IMount diskMount = null; @@ -74,81 +74,81 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - if( player.isInSneakingPose() ) + if( player.isCrouching() ) { // Try to put a disk into the drive - ItemStack disk = player.getStackInHand( hand ); + ItemStack disk = player.getItemInHand( hand ); if( disk.isEmpty() ) { - return ActionResult.PASS; + return InteractionResult.PASS; } - if( !getWorld().isClient && getStack( 0 ).isEmpty() && MediaProviders.get( disk ) != null ) + if( !getLevel().isClientSide && getItem( 0 ).isEmpty() && MediaProviders.get( disk ) != null ) { setDiskStack( disk ); - player.setStackInHand( hand, ItemStack.EMPTY ); + player.setItemInHand( hand, ItemStack.EMPTY ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } else { // Open the GUI - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { - player.openHandledScreen( this ); + player.openMenu( this ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } } public Direction getDirection() { - return getCachedState().get( BlockDiskDrive.FACING ); + return getBlockState().getValue( BlockDiskDrive.FACING ); } @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); - customName = nbt.contains( NBT_NAME ) ? Text.Serializer.fromJson( nbt.getString( NBT_NAME ) ) : null; + super.load( nbt ); + customName = nbt.contains( NBT_NAME ) ? Component.Serializer.fromJson( nbt.getString( NBT_NAME ) ) : null; if( nbt.contains( NBT_ITEM ) ) { - NbtCompound item = nbt.getCompound( NBT_ITEM ); - diskStack = ItemStack.fromNbt( item ); + CompoundTag item = nbt.getCompound( NBT_ITEM ); + diskStack = ItemStack.of( item ); diskMount = null; } } @Nonnull @Override - public NbtCompound writeNbt( @Nonnull NbtCompound nbt ) + public CompoundTag save( @Nonnull CompoundTag nbt ) { if( customName != null ) { - nbt.putString( NBT_NAME, Text.Serializer.toJson( customName ) ); + nbt.putString( NBT_NAME, Component.Serializer.toJson( customName ) ); } if( !diskStack.isEmpty() ) { - NbtCompound item = new NbtCompound(); - diskStack.writeNbt( item ); + CompoundTag item = new CompoundTag(); + diskStack.save( item ); nbt.put( NBT_ITEM, item ); } - return super.writeNbt( nbt ); + return super.save( nbt ); } @Override - public void markDirty() + public void setChanged() { - if( !world.isClient ) + if( !level.isClientSide ) { updateBlockState(); } - super.markDirty(); + super.setChanged(); } - public static void tick( World world, BlockPos pos, BlockState state, TileDiskDrive tileDiskDrive ) + public static void tick( Level world, BlockPos pos, BlockState state, TileDiskDrive tileDiskDrive ) { // Ejection if( tileDiskDrive.ejectQueued ) @@ -160,7 +160,7 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory // Music synchronized( tileDiskDrive ) { - if( !world.isClient && tileDiskDrive.recordPlaying != tileDiskDrive.recordQueued || tileDiskDrive.restartRecord ) + if( !world.isClientSide && tileDiskDrive.recordPlaying != tileDiskDrive.recordQueued || tileDiskDrive.restartRecord ) { tileDiskDrive.restartRecord = false; if( tileDiskDrive.recordQueued ) @@ -189,7 +189,7 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory // IInventory implementation @Override - public int size() + public int getContainerSize() { return 1; } @@ -202,14 +202,14 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory @Nonnull @Override - public ItemStack getStack( int slot ) + public ItemStack getItem( int slot ) { return diskStack; } @Nonnull @Override - public ItemStack removeStack( int slot, int count ) + public ItemStack removeItem( int slot, int count ) { if( diskStack.isEmpty() ) { @@ -219,18 +219,18 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory if( diskStack.getCount() <= count ) { ItemStack disk = diskStack; - setStack( slot, ItemStack.EMPTY ); + setItem( slot, ItemStack.EMPTY ); return disk; } ItemStack part = diskStack.split( count ); - setStack( slot, diskStack.isEmpty() ? ItemStack.EMPTY : diskStack ); + setItem( slot, diskStack.isEmpty() ? ItemStack.EMPTY : diskStack ); return part; } @Nonnull @Override - public ItemStack removeStack( int slot ) + public ItemStack removeItemNoUpdate( int slot ) { ItemStack result = diskStack; diskStack = ItemStack.EMPTY; @@ -240,13 +240,13 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory } @Override - public void setStack( int slot, @Nonnull ItemStack stack ) + public void setItem( int slot, @Nonnull ItemStack stack ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { diskStack = stack; diskMount = null; - markDirty(); + setChanged(); return; } @@ -280,7 +280,7 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory // Swap disk over diskStack = stack; diskMount = null; - markDirty(); + setChanged(); // Mount new disk if( !diskStack.isEmpty() ) @@ -295,15 +295,15 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory } @Override - public boolean canPlayerUse( @Nonnull PlayerEntity player ) + public boolean stillValid( @Nonnull Player player ) { return isUsable( player, false ); } @Override - public void clear() + public void clearContent() { - setStack( 0, ItemStack.EMPTY ); + setItem( 0, ItemStack.EMPTY ); } @Nonnull @@ -341,7 +341,7 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory { if( diskMount == null ) { - diskMount = contents.createDataMount( diskStack, getWorld() ); + diskMount = contents.createDataMount( diskStack, getLevel() ); } if( diskMount != null ) { @@ -383,12 +383,12 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory @Nonnull ItemStack getDiskStack() { - return getStack( 0 ); + return getItem( 0 ); } void setDiskStack( @Nonnull ItemStack stack ) { - setStack( 0, stack ); + setItem( 0, stack ); } void unmount( IComputerAccess computer ) @@ -449,7 +449,7 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory private void updateBlockState() { - if( removed ) + if( remove ) { return; } @@ -467,18 +467,18 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory private void updateBlockState( DiskDriveState state ) { - BlockState blockState = getCachedState(); - if( blockState.get( BlockDiskDrive.STATE ) == state ) + BlockState blockState = getBlockState(); + if( blockState.getValue( BlockDiskDrive.STATE ) == state ) { return; } - getWorld().setBlockState( getPos(), blockState.with( BlockDiskDrive.STATE, state ) ); + getLevel().setBlockAndUpdate( getBlockPos(), blockState.setValue( BlockDiskDrive.STATE, state ) ); } private synchronized void ejectContents( boolean destroyed ) { - if( this.world.isClient || diskStack.isEmpty() ) + if( this.level.isClientSide || diskStack.isEmpty() ) { return; } @@ -493,21 +493,21 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory if( !destroyed ) { Direction dir = getDirection(); - xOff = dir.getOffsetX(); - zOff = dir.getOffsetZ(); + xOff = dir.getStepX(); + zOff = dir.getStepZ(); } - BlockPos pos = getPos(); + BlockPos pos = getBlockPos(); double x = pos.getX() + 0.5 + xOff * 0.5; double y = pos.getY() + 0.75; double z = pos.getZ() + 0.5 + zOff * 0.5; - ItemEntity entityitem = new ItemEntity( getWorld(), x, y, z, disks ); - entityitem.setVelocity( xOff * 0.15, 0, zOff * 0.15 ); + ItemEntity entityitem = new ItemEntity( getLevel(), x, y, z, disks ); + entityitem.setDeltaMovement( xOff * 0.15, 0, zOff * 0.15 ); - getWorld().spawnEntity( entityitem ); + getLevel().addFreshEntity( entityitem ); if( !destroyed ) { - getWorld().syncGlobalEvent( 1000, getPos(), 0 ); + getLevel().globalLevelEvent( 1000, getBlockPos(), 0 ); } } @@ -517,11 +517,11 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory SoundEvent record = contents != null ? contents.getAudio( diskStack ) : null; if( record != null ) { - RecordUtil.playRecord( record, contents.getAudioTitle( diskStack ), getWorld(), getPos() ); + RecordUtil.playRecord( record, contents.getAudioTitle( diskStack ), getLevel(), getBlockPos() ); } else { - RecordUtil.playRecord( null, null, getWorld(), getPos() ); + RecordUtil.playRecord( null, null, getLevel(), getBlockPos() ); } } @@ -529,15 +529,15 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory private void stopRecord() { - RecordUtil.playRecord( null, null, getWorld(), getPos() ); + RecordUtil.playRecord( null, null, getLevel(), getBlockPos() ); } @Nonnull @Override - public Text getName() + public Component getName() { - return customName != null ? customName : new TranslatableText( getCachedState().getBlock() - .getTranslationKey() ); + return customName != null ? customName : new TranslatableComponent( getBlockState().getBlock() + .getDescriptionId() ); } @Override @@ -548,21 +548,21 @@ public final class TileDiskDrive extends TileGeneric implements DefaultInventory @Nonnull @Override - public Text getDisplayName() + public Component getDisplayName() { return Nameable.super.getDisplayName(); } @Nullable @Override - public Text getCustomName() + public Component getCustomName() { return customName; } @Nonnull @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory inventory, @Nonnull PlayerEntity player ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory inventory, @Nonnull Player player ) { return new ContainerDiskDrive( id, inventory, this ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java index c4c59ee4a..6e75ebd32 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheral.java @@ -12,9 +12,9 @@ import dan200.computercraft.api.lua.MethodResult; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IDynamicPeripheral; import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -28,7 +28,7 @@ class GenericPeripheral implements IDynamicPeripheral GenericPeripheral( BlockEntity tile, List methods ) { - Identifier type = BlockEntityType.getId( tile.getType() ); + ResourceLocation type = BlockEntityType.getKey( tile.getType() ); this.tile = tile; this.type = type == null ? "unknown" : type.toString(); this.methods = methods; diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java index d4b3e0b16..d77203984 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/GenericPeripheralProvider.java @@ -8,10 +8,10 @@ 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 net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +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 javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -21,7 +21,7 @@ import java.util.List; public class GenericPeripheralProvider { @Nullable - public static IPeripheral getPeripheral( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side ) + public static IPeripheral getPeripheral( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull Direction side ) { BlockEntity tile = world.getBlockEntity( pos ); if( tile == null ) return null; diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java index eca38e63f..406d62466 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/SaturatedMethod.java @@ -44,9 +44,8 @@ final class SaturatedMethod public boolean equals( Object obj ) { if( obj == this ) return true; - if( !(obj instanceof SaturatedMethod) ) return false; + if( !(obj instanceof SaturatedMethod other) ) return false; - SaturatedMethod other = (SaturatedMethod) obj; return method == other.method && target.equals( other.target ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/BlockData.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/BlockData.java index 4b9a9e0ed..352d37669 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/BlockData.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/BlockData.java @@ -6,8 +6,8 @@ package dan200.computercraft.shared.peripheral.generic.data; import com.google.common.collect.ImmutableMap; -import net.minecraft.block.BlockState; -import net.minecraft.state.property.Property; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; import javax.annotation.Nonnull; import java.util.HashMap; @@ -21,7 +21,7 @@ public class BlockData data.put( "name", DataHelpers.getId( state.getBlock() ) ); Map stateTable = new HashMap<>(); - for( ImmutableMap.Entry, ? extends Comparable> entry : state.getEntries().entrySet() ) + for( ImmutableMap.Entry, ? extends Comparable> entry : state.getValues().entrySet() ) { Property property = entry.getKey(); stateTable.put( property.getName(), getPropertyValue( property, entry.getValue() ) ); @@ -35,6 +35,6 @@ public class BlockData private static Object getPropertyValue( Property property, Comparable value ) { if( value instanceof String || value instanceof Number || value instanceof Boolean ) return value; - return property.name( value ); + return property.getName( value ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/DataHelpers.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/DataHelpers.java index 210aa5b5a..86bcd9d4f 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/DataHelpers.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/DataHelpers.java @@ -5,11 +5,11 @@ */ package dan200.computercraft.shared.peripheral.generic.data; -import net.minecraft.block.Block; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.item.Item; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.block.Block; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -20,34 +20,34 @@ import java.util.Map; public final class DataHelpers { private DataHelpers() - { } + {} @Nonnull - public static Map getTags( @Nonnull Collection tags ) + public static Map getTags( @Nonnull Collection tags ) { Map result = new HashMap<>( tags.size() ); - for( Identifier location : tags ) result.put( location.toString(), true ); + for( ResourceLocation location : tags ) result.put( location.toString(), true ); return result; } @Nullable public static String getId( @Nonnull Block block ) { - Identifier id = Registry.BLOCK.getId( block ); + ResourceLocation id = Registry.BLOCK.getKey( block ); return id == null ? null : id.toString(); } @Nullable public static String getId( @Nonnull Item item ) { - Identifier id = Registry.ITEM.getId( item ); + ResourceLocation id = Registry.ITEM.getKey( item ); return id == null ? null : id.toString(); } @Nullable public static String getId( @Nonnull Enchantment enchantment ) { - Identifier id = Registry.ENCHANTMENT.getId( enchantment ); + ResourceLocation id = Registry.ENCHANTMENT.getKey( enchantment ); return id == null ? null : id.toString(); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java index a5781483a..314a645e0 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/data/ItemData.java @@ -7,18 +7,18 @@ package dan200.computercraft.shared.peripheral.generic.data; import com.google.gson.JsonParseException; import dan200.computercraft.shared.util.NBTUtil; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.item.EnchantedBookItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtList; -import net.minecraft.nbt.NbtElement; -import net.minecraft.tag.ServerTagManagerHolder; -import net.minecraft.tag.TagGroup; -import net.minecraft.text.Text; -import net.minecraft.util.registry.Registry; +import net.minecraft.core.Registry; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.chat.Component; +import net.minecraft.tags.SerializationTags; +import net.minecraft.tags.TagCollection; +import net.minecraft.world.item.EnchantedBookItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.EnchantmentHelper; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -43,7 +43,7 @@ public class ItemData public static > T fillBasic( @Nonnull T data, @Nonnull ItemStack stack ) { fillBasicSafe( data, stack ); - String hash = NBTUtil.getNBTHash( stack.getNbt() ); + String hash = NBTUtil.getNBTHash( stack.getTag() ); if( hash != null ) data.put( "nbt", hash ); return data; @@ -56,39 +56,39 @@ public class ItemData fillBasic( data, stack ); - data.put( "displayName", stack.getName().getString() ); - data.put( "maxCount", stack.getMaxCount() ); + data.put( "displayName", stack.getHoverName().getString() ); + data.put( "maxCount", stack.getMaxStackSize() ); - if( stack.isDamageable() ) + if( stack.isDamageableItem() ) { - data.put( "damage", stack.getDamage() ); + data.put( "damage", stack.getDamageValue() ); data.put( "maxDamage", stack.getMaxDamage() ); } if( stack.isDamaged() ) { - data.put( "durability", (double) stack.getDamage() / stack.getMaxDamage() ); + data.put( "durability", (double) stack.getDamageValue() / stack.getMaxDamage() ); } // requireNonNull is safe because we got the Identifiers out of the TagGroup to start with. Would be nicer // to stream the tags directly but TagGroup isn't a collection :( - TagGroup itemTags = ServerTagManagerHolder.getTagManager().getOrCreateTagGroup( Registry.ITEM_KEY ); - data.put( "tags", DataHelpers.getTags( itemTags.getTagIds().stream() + TagCollection itemTags = SerializationTags.getInstance().getOrEmpty( Registry.ITEM_REGISTRY ); + data.put( "tags", DataHelpers.getTags( itemTags.getAvailableTags().stream() .filter( id -> Objects.requireNonNull( itemTags.getTag( id ) ).contains( stack.getItem() ) ) .collect( Collectors.toList() ) ) ); // chaos x2 - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); if( tag != null && tag.contains( "display", NBTUtil.TAG_COMPOUND ) ) { - NbtCompound displayTag = tag.getCompound( "display" ); + CompoundTag displayTag = tag.getCompound( "display" ); if( displayTag.contains( "Lore", NBTUtil.TAG_LIST ) ) { - NbtList loreTag = displayTag.getList( "Lore", NBTUtil.TAG_STRING ); + ListTag loreTag = displayTag.getList( "Lore", NBTUtil.TAG_STRING ); data.put( "lore", loreTag.stream() .map( ItemData::parseTextComponent ) .filter( Objects::nonNull ) - .map( Text::getString ) + .map( Component::getString ) .collect( Collectors.toList() ) ); } } @@ -113,11 +113,11 @@ public class ItemData @Nullable - private static Text parseTextComponent( @Nonnull NbtElement x ) + private static Component parseTextComponent( @Nonnull Tag x ) { try { - return Text.Serializer.fromJson( x.toString() ); + return Component.Serializer.fromJson( x.toString() ); } catch( JsonParseException e ) { @@ -139,17 +139,17 @@ public class ItemData if( stack.getItem() instanceof EnchantedBookItem && (hideFlags & 32) == 0 ) { - addEnchantments( EnchantedBookItem.getEnchantmentNbt( stack ), enchants ); + addEnchantments( EnchantedBookItem.getEnchantments( stack ), enchants ); } - if( stack.hasEnchantments() && (hideFlags & 1) == 0 ) + if( stack.isEnchanted() && (hideFlags & 1) == 0 ) { /* * Mimic the EnchantmentHelper.getEnchantments(ItemStack stack) behavior without special case for Enchanted book. * I'll do that to have the same data than ones displayed in tooltip. * @see EnchantmentHelper.getEnchantments(ItemStack stack) */ - addEnchantments( stack.getEnchantments(), enchants ); + addEnchantments( stack.getEnchantmentTags(), enchants ); } return enchants; @@ -162,21 +162,21 @@ public class ItemData * @param enchants The enchantment map to add it to. * @see EnchantmentHelper */ - private static void addEnchantments( @Nonnull NbtList rawEnchants, @Nonnull ArrayList> enchants ) + private static void addEnchantments( @Nonnull ListTag rawEnchants, @Nonnull ArrayList> enchants ) { if( rawEnchants.isEmpty() ) return; enchants.ensureCapacity( enchants.size() + rawEnchants.size() ); - for( Map.Entry entry : EnchantmentHelper.fromNbt( rawEnchants ).entrySet() ) + for( Map.Entry entry : EnchantmentHelper.deserializeEnchantments( rawEnchants ).entrySet() ) { Enchantment enchantment = entry.getKey(); Integer level = entry.getValue(); HashMap enchant = new HashMap<>( 3 ); enchant.put( "name", DataHelpers.getId( enchantment ) ); enchant.put( "level", level ); - enchant.put( "displayName", enchantment.getName( level ).getString() ); + enchant.put( "displayName", enchantment.getFullname( level ).getString() ); enchants.add( enchant ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java b/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java index 4b5d76be1..7be7113b5 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/generic/methods/InventoryMethods.java @@ -14,11 +14,11 @@ import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.peripheral.generic.data.ItemData; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.ItemStorage; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.Nameable; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.Container; +import net.minecraft.world.Nameable; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.BlockEntity; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -37,9 +37,9 @@ public class InventoryMethods implements GenericSource { @Nonnull @Override - public Identifier id() + public ResourceLocation id() { - return new Identifier( ComputerCraft.MOD_ID, "inventory" ); + return new ResourceLocation( ComputerCraft.MOD_ID, "inventory" ); } /** @@ -49,7 +49,7 @@ public class InventoryMethods implements GenericSource * @return The number of slots in this inventory. */ @LuaFunction( mainThread = true ) - public static int size( Inventory inventory ) + public static int size( Container inventory ) { return extractHandler( inventory ).size(); } @@ -61,12 +61,12 @@ public class InventoryMethods implements GenericSource * @return The name of this inventory, or {@code nil} if not present. */ @LuaFunction( mainThread = true ) - public static String name( Inventory inventory ) + public static String name( Container inventory ) { if( inventory instanceof Nameable ) { Nameable i = (Nameable) inventory; - return i.hasCustomName() ? i.getName().asString() : null; + return i.hasCustomName() ? i.getName().getContents() : null; } return null; } @@ -95,7 +95,7 @@ public class InventoryMethods implements GenericSource * } */ @LuaFunction( mainThread = true ) - public static Map> list( Inventory inventory ) + public static Map> list( Container inventory ) { ItemStorage itemStorage = extractHandler( inventory ); @@ -142,7 +142,7 @@ public class InventoryMethods implements GenericSource */ @Nullable @LuaFunction( mainThread = true ) - public static Map getItemDetail( Inventory inventory, int slot ) throws LuaException + public static Map getItemDetail( Container inventory, int slot ) throws LuaException { ItemStorage itemStorage = extractHandler( inventory ); @@ -173,10 +173,10 @@ public class InventoryMethods implements GenericSource * } */ @LuaFunction( mainThread = true ) - public static int getItemLimit( Inventory inventory, int slot ) throws LuaException + public static int getItemLimit( Container inventory, int slot ) throws LuaException { - assertBetween( slot, 1, inventory.size(), "Slot out of range (%s)" ); - return inventory.getMaxCountPerStack(); + assertBetween( slot, 1, inventory.getContainerSize(), "Slot out of range (%s)" ); + return inventory.getMaxStackSize(); } /** @@ -206,7 +206,7 @@ public class InventoryMethods implements GenericSource */ @LuaFunction( mainThread = true ) public static int pushItems( - Inventory from, IComputerAccess computer, + Container from, IComputerAccess computer, String toName, int fromSlot, Optional limit, Optional toSlot ) throws LuaException { @@ -255,7 +255,7 @@ public class InventoryMethods implements GenericSource */ @LuaFunction( mainThread = true ) public static int pullItems( - Inventory to, IComputerAccess computer, + Container to, IComputerAccess computer, String fromName, int fromSlot, Optional limit, Optional toSlot ) throws LuaException { @@ -284,15 +284,15 @@ public class InventoryMethods implements GenericSource { if( object instanceof BlockEntity ) { - Inventory inventory = InventoryUtil.getInventory( (BlockEntity) object ); + Container inventory = InventoryUtil.getInventory( (BlockEntity) object ); if( inventory != null ) { return ItemStorage.wrap( inventory ); } } - else if ( object instanceof Inventory ) + else if( object instanceof Container ) { - return ItemStorage.wrap( (Inventory) object ); + return ItemStorage.wrap( (Container) object ); } return null; diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java index 27e02f18f..e312c43ff 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemPeripheral.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.peripheral.modem; import dan200.computercraft.api.lua.LuaException; @@ -14,8 +13,8 @@ import dan200.computercraft.api.network.IPacketSender; import dan200.computercraft.api.network.Packet; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.HashSet; @@ -28,9 +27,9 @@ import java.util.Set; */ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPacketReceiver { + private IPacketNetwork network; private final Set computers = new HashSet<>( 1 ); private final ModemState state; - private IPacketNetwork network; protected ModemPeripheral( ModemState state ) { @@ -42,6 +41,20 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa return state; } + private synchronized void setNetwork( IPacketNetwork network ) + { + if( this.network == network ) return; + + // Leave old network + if( this.network != null ) this.network.removeReceiver( this ); + + // Set new network + this.network = network; + + // Join new network + if( this.network != null ) this.network.addReceiver( this ); + } + public void destroy() { setNetwork( null ); @@ -50,21 +63,14 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa @Override public void receiveSameDimension( @Nonnull Packet packet, double distance ) { - if( packet.getSender() == this || !state.isOpen( packet.getChannel() ) ) - { - return; - } + if( packet.sender() == this || !state.isOpen( packet.channel() ) ) return; synchronized( computers ) { for( IComputerAccess computer : computers ) { computer.queueEvent( "modem_message", - computer.getAttachmentName(), - packet.getChannel(), - packet.getReplyChannel(), - packet.getPayload(), - distance ); + computer.getAttachmentName(), packet.channel(), packet.replyChannel(), packet.payload(), distance ); } } } @@ -72,20 +78,20 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa @Override public void receiveDifferentDimension( @Nonnull Packet packet ) { - if( packet.getSender() == this || !state.isOpen( packet.getChannel() ) ) - { - return; - } + if( packet.sender() == this || !state.isOpen( packet.channel() ) ) return; synchronized( computers ) { for( IComputerAccess computer : computers ) { - computer.queueEvent( "modem_message", computer.getAttachmentName(), packet.getChannel(), packet.getReplyChannel(), packet.getPayload() ); + computer.queueEvent( "modem_message", + computer.getAttachmentName(), packet.channel(), packet.replyChannel(), packet.payload() ); } } } + protected abstract IPacketNetwork getNetwork(); + @Nonnull @Override public String getType() @@ -93,60 +99,15 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa return "modem"; } - @Override - public synchronized void attach( @Nonnull IComputerAccess computer ) + private static int parseChannel( int channel ) throws LuaException { - synchronized( computers ) - { - computers.add( computer ); - } - - setNetwork( getNetwork() ); - } - - protected abstract IPacketNetwork getNetwork(); - - private synchronized void setNetwork( IPacketNetwork network ) - { - if( this.network == network ) - { - return; - } - - // Leave old network - if( this.network != null ) - { - this.network.removeReceiver( this ); - } - - // Set new network - this.network = network; - - // Join new network - if( this.network != null ) - { - this.network.addReceiver( this ); - } - } - - @Override - public synchronized void detach( @Nonnull IComputerAccess computer ) - { - boolean empty; - synchronized( computers ) - { - computers.remove( computer ); - empty = computers.isEmpty(); - } - - if( empty ) - { - setNetwork( null ); - } + if( channel < 0 || channel > 65535 ) throw new LuaException( "Expected number in range 0-65535" ); + return channel; } /** - * Open a channel on a modem. A channel must be open in order to receive messages. Modems can have up to 128 channels open at one time. + * Open a channel on a modem. A channel must be open in order to receive messages. Modems can have up to 128 + * channels open at one time. * * @param channel The channel to open. This must be a number between 0 and 65535. * @throws LuaException If the channel is out of range. @@ -158,15 +119,6 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa state.open( parseChannel( channel ) ); } - private static int parseChannel( int channel ) throws LuaException - { - if( channel < 0 || channel > 65535 ) - { - throw new LuaException( "Expected number in range 0-65535" ); - } - return channel; - } - /** * Check if a channel is open. * @@ -202,13 +154,14 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa } /** - * Sends a modem message on a certain channel. Modems listening on the channel will queue a {@code modem_message} event on adjacent computers. + * Sends a modem message on a certain channel. Modems listening on the channel will queue a {@code modem_message} + * event on adjacent computers. * *
    Note: The channel does not need be open to send a message.
    * * @param channel The channel to send messages on. * @param replyChannel The channel that responses to this message should be sent on. - * @param payload The object to send. This can be a string, number, or table. + * @param payload The object to send. This can be a boolean, string, number, or table. * @throws LuaException If the channel is out of range. */ @LuaFunction @@ -217,14 +170,11 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa parseChannel( channel ); parseChannel( replyChannel ); - World world = getWorld(); - Vec3d position = getPosition(); + Level world = getLevel(); + Vec3 position = getPosition(); IPacketNetwork network = this.network; - if( world == null || position == null || network == null ) - { - return; - } + if( world == null || position == null || network == null ) return; Packet packet = new Packet( channel, replyChannel, payload, this ); if( isInterdimensional() ) @@ -240,7 +190,8 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa /** * Determine if this is a wired or wireless modem. * - * Some methods (namely those dealing with wired networks and remote peripherals) are only available on wired modems. + * Some methods (namely those dealing with wired networks and remote peripherals) are only available on wired + * modems. * * @return {@code true} if this is a wireless modem. */ @@ -251,6 +202,30 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa return network != null && network.isWireless(); } + @Override + public synchronized void attach( @Nonnull IComputerAccess computer ) + { + synchronized( computers ) + { + computers.add( computer ); + } + + setNetwork( getNetwork() ); + } + + @Override + public synchronized void detach( @Nonnull IComputerAccess computer ) + { + boolean empty; + synchronized( computers ) + { + computers.remove( computer ); + empty = computers.isEmpty(); + } + + if( empty ) setNetwork( null ); + } + @Nonnull @Override public String getSenderID() @@ -263,8 +238,7 @@ public abstract class ModemPeripheral implements IPeripheral, IPacketSender, IPa } else { - IComputerAccess computer = computers.iterator() - .next(); + IComputerAccess computer = computers.iterator().next(); return computer.getID() + "_" + computer.getAttachmentName(); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemShapes.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemShapes.java index 1cf37fe63..365abeca4 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemShapes.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/ModemShapes.java @@ -6,26 +6,26 @@ package dan200.computercraft.shared.peripheral.modem; -import net.minecraft.util.math.Direction; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.util.shape.VoxelShapes; +import net.minecraft.core.Direction; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nonnull; public final class ModemShapes { private static final VoxelShape[] BOXES = new VoxelShape[] { - VoxelShapes.cuboid( 0.125, 0.0, 0.125, 0.875, 0.1875, 0.875 ), + Shapes.box( 0.125, 0.0, 0.125, 0.875, 0.1875, 0.875 ), // Down - VoxelShapes.cuboid( 0.125, 0.8125, 0.125, 0.875, 1.0, 0.875 ), + Shapes.box( 0.125, 0.8125, 0.125, 0.875, 1.0, 0.875 ), // Up - VoxelShapes.cuboid( 0.125, 0.125, 0.0, 0.875, 0.875, 0.1875 ), + Shapes.box( 0.125, 0.125, 0.0, 0.875, 0.875, 0.1875 ), // North - VoxelShapes.cuboid( 0.125, 0.125, 0.8125, 0.875, 0.875, 1.0 ), + Shapes.box( 0.125, 0.125, 0.8125, 0.875, 0.875, 1.0 ), // South - VoxelShapes.cuboid( 0.0, 0.125, 0.125, 0.1875, 0.875, 0.875 ), + Shapes.box( 0.0, 0.125, 0.125, 0.1875, 0.875, 0.875 ), // West - VoxelShapes.cuboid( 0.8125, 0.125, 0.125, 1.0, 0.875, 0.875 ), + Shapes.box( 0.8125, 0.125, 0.125, 1.0, 0.875, 0.875 ), // East }; @@ -33,6 +33,6 @@ public final class ModemShapes public static VoxelShape getBounds( Direction facing ) { int direction = facing.ordinal(); - return direction < BOXES.length ? BOXES[direction] : VoxelShapes.fullCube(); + return direction < BOXES.length ? BOXES[direction] : Shapes.block(); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockCable.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockCable.java index 7b90d4ffd..f338e29b4 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockCable.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockCable.java @@ -12,25 +12,25 @@ import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; import dan200.computercraft.shared.util.WorldUtil; import net.fabricmc.fabric.api.block.BlockPickInteractionAware; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.ShapeContext; -import net.minecraft.block.Waterloggable; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.fluid.FluidState; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.BooleanProperty; -import net.minecraft.state.property.EnumProperty; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.SimpleWaterloggedBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.minecraft.world.level.block.state.properties.EnumProperty; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -38,20 +38,20 @@ import java.util.EnumMap; import static dan200.computercraft.shared.util.WaterloggableHelpers.*; -public class BlockCable extends BlockGeneric implements Waterloggable, BlockPickInteractionAware +public class BlockCable extends BlockGeneric implements SimpleWaterloggedBlock, BlockPickInteractionAware { - public static final EnumProperty MODEM = EnumProperty.of( "modem", CableModemVariant.class ); - public static final BooleanProperty CABLE = BooleanProperty.of( "cable" ); + public static final EnumProperty MODEM = EnumProperty.create( "modem", CableModemVariant.class ); + public static final BooleanProperty CABLE = BooleanProperty.create( "cable" ); - private static final BooleanProperty NORTH = BooleanProperty.of( "north" ); - private static final BooleanProperty SOUTH = BooleanProperty.of( "south" ); - private static final BooleanProperty EAST = BooleanProperty.of( "east" ); - private static final BooleanProperty WEST = BooleanProperty.of( "west" ); - private static final BooleanProperty UP = BooleanProperty.of( "up" ); - private static final BooleanProperty DOWN = BooleanProperty.of( "down" ); + private static final BooleanProperty NORTH = BooleanProperty.create( "north" ); + private static final BooleanProperty SOUTH = BooleanProperty.create( "south" ); + private static final BooleanProperty EAST = BooleanProperty.create( "east" ); + private static final BooleanProperty WEST = BooleanProperty.create( "west" ); + private static final BooleanProperty UP = BooleanProperty.create( "up" ); + private static final BooleanProperty DOWN = BooleanProperty.create( "down" ); static final EnumMap CONNECTIONS = new EnumMap<>( new ImmutableMap.Builder().put( Direction.DOWN, - DOWN ) + DOWN ) .put( Direction.UP, UP ) .put( Direction.NORTH, @@ -64,56 +64,56 @@ public class BlockCable extends BlockGeneric implements Waterloggable, BlockPick EAST ) .build() ); - public BlockCable( Settings settings ) + public BlockCable( Properties settings ) { super( settings, ComputerCraftRegistry.ModTiles.CABLE ); - setDefaultState( getStateManager().getDefaultState() - .with( MODEM, CableModemVariant.None ) - .with( CABLE, false ) - .with( NORTH, false ) - .with( SOUTH, false ) - .with( EAST, false ) - .with( WEST, false ) - .with( UP, false ) - .with( DOWN, false ) - .with( WATERLOGGED, false ) ); + registerDefaultState( getStateDefinition().any() + .setValue( MODEM, CableModemVariant.None ) + .setValue( CABLE, false ) + .setValue( NORTH, false ) + .setValue( SOUTH, false ) + .setValue( EAST, false ) + .setValue( WEST, false ) + .setValue( UP, false ) + .setValue( DOWN, false ) + .setValue( WATERLOGGED, false ) ); } public static boolean canConnectIn( BlockState state, Direction direction ) { - return state.get( BlockCable.CABLE ) && state.get( BlockCable.MODEM ) + return state.getValue( BlockCable.CABLE ) && state.getValue( BlockCable.MODEM ) .getFacing() != direction; } @Nonnull @Override @Deprecated - public BlockState getStateForNeighborUpdate( @Nonnull BlockState state, @Nonnull Direction side, @Nonnull BlockState otherState, - @Nonnull WorldAccess world, @Nonnull BlockPos pos, @Nonnull BlockPos otherPos ) + public BlockState updateShape( @Nonnull BlockState state, @Nonnull Direction side, @Nonnull BlockState otherState, + @Nonnull LevelAccessor world, @Nonnull BlockPos pos, @Nonnull BlockPos otherPos ) { updateWaterloggedPostPlacement( state, world, pos ); // Should never happen, but handle the case where we've no modem or cable. - if( !state.get( CABLE ) && state.get( MODEM ) == CableModemVariant.None ) + if( !state.getValue( CABLE ) && state.getValue( MODEM ) == CableModemVariant.None ) { - return getFluidState( state ).getBlockState(); + return getFluidState( state ).createLegacyBlock(); } - return state.with( CONNECTIONS.get( side ), doesConnectVisually( state, world, pos, side ) ); + return state.setValue( CONNECTIONS.get( side ), doesConnectVisually( state, world, pos, side ) ); } - public static boolean doesConnectVisually( BlockState state, BlockView world, BlockPos pos, Direction direction ) + public static boolean doesConnectVisually( BlockState state, BlockGetter world, BlockPos pos, Direction direction ) { - if( !state.get( CABLE ) ) + if( !state.getValue( CABLE ) ) { return false; } - if( state.get( MODEM ) + if( state.getValue( MODEM ) .getFacing() == direction ) { return true; } - return ComputerCraftAPI.getWiredElementAt( world, pos.offset( direction ), direction.getOpposite() ) != null; + return ComputerCraftAPI.getWiredElementAt( world, pos.relative( direction ), direction.getOpposite() ) != null; } @Nonnull @@ -124,41 +124,41 @@ public class BlockCable extends BlockGeneric implements Waterloggable, BlockPick return getWaterloggedFluidState( state ); } - public boolean removedByPlayer( BlockState state, World world, BlockPos pos, PlayerEntity player, boolean willHarvest, FluidState fluid ) + public boolean removedByPlayer( BlockState state, Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid ) { - if( state.get( CABLE ) && state.get( MODEM ).getFacing() != null ) + if( state.getValue( CABLE ) && state.getValue( MODEM ).getFacing() != null ) { - BlockHitResult hit = world.raycast( new RaycastContext( + BlockHitResult hit = world.clip( new ClipContext( WorldUtil.getRayStart( player ), WorldUtil.getRayEnd( player ), - RaycastContext.ShapeType.COLLIDER, RaycastContext.FluidHandling.NONE, player + ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, player ) ); if( hit.getType() == HitResult.Type.BLOCK ) { BlockEntity tile = world.getBlockEntity( pos ); - if( tile instanceof TileCable cable && tile.hasWorld() ) + if( tile instanceof TileCable cable && tile.hasLevel() ) { ItemStack item; BlockState newState; - if( WorldUtil.isVecInside( CableShapes.getModemShape( state ), hit.getPos().subtract( pos.getX(), pos.getY(), pos.getZ() ) ) ) + if( WorldUtil.isVecInside( CableShapes.getModemShape( state ), hit.getLocation().subtract( pos.getX(), pos.getY(), pos.getZ() ) ) ) { - newState = state.with( MODEM, CableModemVariant.None ); + newState = state.setValue( MODEM, CableModemVariant.None ); item = new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ); } else { - newState = state.with( CABLE, false ); + newState = state.setValue( CABLE, false ); item = new ItemStack( ComputerCraftRegistry.ModItems.CABLE ); } - world.setBlockState( pos, correctConnections( world, pos, newState ), 3 ); + world.setBlock( pos, correctConnections( world, pos, newState ), 3 ); cable.modemChanged(); cable.connectionsChanged(); - if( !world.isClient && !player.getAbilities().creativeMode ) + if( !world.isClientSide && !player.getAbilities().instabuild ) { - Block.dropStack( world, pos, item ); + Block.popResource( world, pos, item ); } return false; @@ -170,66 +170,66 @@ public class BlockCable extends BlockGeneric implements Waterloggable, BlockPick } @Override - public ItemStack getPickedStack( BlockState state, BlockView world, BlockPos pos, @Nullable PlayerEntity player, HitResult hit ) + public ItemStack getPickedStack( BlockState state, BlockGetter world, BlockPos pos, @Nullable Player player, HitResult hit ) { - Direction modem = state.get( MODEM ).getFacing(); - boolean cable = state.get( CABLE ); + Direction modem = state.getValue( MODEM ).getFacing(); + boolean cable = state.getValue( CABLE ); // If we've only got one, just use that. if( !cable ) return new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ); if( modem == null ) return new ItemStack( ComputerCraftRegistry.ModItems.CABLE ); // We've a modem and cable, so try to work out which one we're interacting with - return hit != null && WorldUtil.isVecInside( CableShapes.getModemShape( state ), hit.getPos().subtract( pos.getX(), pos.getY(), pos.getZ() ) ) + return hit != null && WorldUtil.isVecInside( CableShapes.getModemShape( state ), hit.getLocation().subtract( pos.getX(), pos.getY(), pos.getZ() ) ) ? new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ) : new ItemStack( ComputerCraftRegistry.ModItems.CABLE ); } @Override @Deprecated - public boolean canPlaceAt( BlockState state, @Nonnull WorldView world, @Nonnull BlockPos pos ) + public boolean canSurvive( BlockState state, @Nonnull LevelReader world, @Nonnull BlockPos pos ) { - Direction facing = state.get( MODEM ) + Direction facing = state.getValue( MODEM ) .getFacing(); if( facing == null ) { return true; } - return sideCoversSmallSquare( world, pos.offset( facing ), facing.getOpposite() ); + return canSupportCenter( world, pos.relative( facing ), facing.getOpposite() ); } @Nonnull @Override @Deprecated - public VoxelShape getOutlineShape( @Nonnull BlockState state, @Nonnull BlockView world, @Nonnull BlockPos pos, @Nonnull ShapeContext context ) + public VoxelShape getShape( @Nonnull BlockState state, @Nonnull BlockGetter world, @Nonnull BlockPos pos, @Nonnull CollisionContext context ) { return CableShapes.getShape( state ); } @Nullable @Override - public BlockState getPlacementState( @Nonnull ItemPlacementContext context ) + public BlockState getStateForPlacement( @Nonnull BlockPlaceContext context ) { - BlockState state = getDefaultState().with( WATERLOGGED, getWaterloggedStateForPlacement( context ) ); + BlockState state = defaultBlockState().setValue( WATERLOGGED, getWaterloggedStateForPlacement( context ) ); - if( context.getStack() + if( context.getItemInHand() .getItem() instanceof ItemBlockCable.Cable ) { - World world = context.getWorld(); - BlockPos pos = context.getBlockPos(); - return correctConnections( world, pos, state.with( CABLE, true ) ); + Level world = context.getLevel(); + BlockPos pos = context.getClickedPos(); + return correctConnections( world, pos, state.setValue( CABLE, true ) ); } else { - return state.with( MODEM, - CableModemVariant.from( context.getSide() + return state.setValue( MODEM, + CableModemVariant.from( context.getClickedFace() .getOpposite() ) ); } } @Override - public void onPlaced( World world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, @Nonnull ItemStack stack ) + public void setPlacedBy( Level world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, @Nonnull ItemStack stack ) { BlockEntity tile = world.getBlockEntity( pos ); if( tile instanceof TileCable cable ) @@ -240,40 +240,40 @@ public class BlockCable extends BlockGeneric implements Waterloggable, BlockPick } } - super.onPlaced( world, pos, state, placer, stack ); + super.setPlacedBy( world, pos, state, placer, stack ); } @Override - protected void appendProperties( StateManager.Builder builder ) + protected void createBlockStateDefinition( StateDefinition.Builder builder ) { builder.add( MODEM, CABLE, NORTH, SOUTH, EAST, WEST, UP, DOWN, WATERLOGGED ); } - public static BlockState correctConnections( World world, BlockPos pos, BlockState state ) + public static BlockState correctConnections( Level world, BlockPos pos, BlockState state ) { - if( state.get( CABLE ) ) + if( state.getValue( CABLE ) ) { - return state.with( NORTH, doesConnectVisually( state, world, pos, Direction.NORTH ) ) - .with( SOUTH, doesConnectVisually( state, world, pos, Direction.SOUTH ) ) - .with( EAST, doesConnectVisually( state, world, pos, Direction.EAST ) ) - .with( WEST, doesConnectVisually( state, world, pos, Direction.WEST ) ) - .with( UP, doesConnectVisually( state, world, pos, Direction.UP ) ) - .with( DOWN, doesConnectVisually( state, world, pos, Direction.DOWN ) ); + return state.setValue( NORTH, doesConnectVisually( state, world, pos, Direction.NORTH ) ) + .setValue( SOUTH, doesConnectVisually( state, world, pos, Direction.SOUTH ) ) + .setValue( EAST, doesConnectVisually( state, world, pos, Direction.EAST ) ) + .setValue( WEST, doesConnectVisually( state, world, pos, Direction.WEST ) ) + .setValue( UP, doesConnectVisually( state, world, pos, Direction.UP ) ) + .setValue( DOWN, doesConnectVisually( state, world, pos, Direction.DOWN ) ); } else { - return state.with( NORTH, false ) - .with( SOUTH, false ) - .with( EAST, false ) - .with( WEST, false ) - .with( UP, false ) - .with( DOWN, false ); + return state.setValue( NORTH, false ) + .setValue( SOUTH, false ) + .setValue( EAST, false ) + .setValue( WEST, false ) + .setValue( UP, false ) + .setValue( DOWN, false ); } } @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileCable( ComputerCraftRegistry.ModTiles.CABLE, pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockWiredModemFull.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockWiredModemFull.java index a14875443..2f14df974 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockWiredModemFull.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/BlockWiredModemFull.java @@ -8,38 +8,38 @@ package dan200.computercraft.shared.peripheral.modem.wired; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.BooleanProperty; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BooleanProperty; import javax.annotation.Nullable; public class BlockWiredModemFull extends BlockGeneric { - public static final BooleanProperty MODEM_ON = BooleanProperty.of( "modem" ); - public static final BooleanProperty PERIPHERAL_ON = BooleanProperty.of( "peripheral" ); + public static final BooleanProperty MODEM_ON = BooleanProperty.create( "modem" ); + public static final BooleanProperty PERIPHERAL_ON = BooleanProperty.create( "peripheral" ); - public BlockWiredModemFull( Settings settings, BlockEntityType type ) + public BlockWiredModemFull( Properties settings, BlockEntityType type ) { super( settings, type ); - setDefaultState( getStateManager().getDefaultState() - .with( MODEM_ON, false ) - .with( PERIPHERAL_ON, false ) ); + registerDefaultState( getStateDefinition().any() + .setValue( MODEM_ON, false ) + .setValue( PERIPHERAL_ON, false ) ); } @Override - protected void appendProperties( StateManager.Builder builder ) + protected void createBlockStateDefinition( StateDefinition.Builder builder ) { builder.add( MODEM_ON, PERIPHERAL_ON ); } @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileWiredModemFull( ComputerCraftRegistry.ModTiles.WIRED_MODEM_FULL, pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableModemVariant.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableModemVariant.java index a45f27db7..3c456ab4b 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableModemVariant.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableModemVariant.java @@ -3,16 +3,15 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.peripheral.modem.wired; -import net.minecraft.util.StringIdentifiable; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; +import net.minecraft.util.StringRepresentable; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public enum CableModemVariant implements StringIdentifiable +public enum CableModemVariant implements StringRepresentable { None( "none", null ), DownOff( "down_off", Direction.DOWN ), @@ -54,19 +53,19 @@ public enum CableModemVariant implements StringIdentifiable @Nonnull public static CableModemVariant from( Direction facing ) { - return facing == null ? None : VALUES[1 + facing.getId()]; + return facing == null ? None : VALUES[1 + facing.get3DDataValue()]; } @Nonnull public static CableModemVariant from( Direction facing, boolean modem, boolean peripheral ) { int state = (modem ? 2 : 0) + (peripheral ? 1 : 0); - return facing == null ? None : VALUES[1 + 6 * state + facing.getId()]; + return facing == null ? None : VALUES[1 + 6 * state + facing.get3DDataValue()]; } @Nonnull @Override - public String asString() + public String getSerializedName() { return name; } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableShapes.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableShapes.java index 12bd696cb..11e401df9 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableShapes.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/CableShapes.java @@ -9,10 +9,10 @@ package dan200.computercraft.shared.peripheral.modem.wired; import com.google.common.collect.ImmutableMap; import dan200.computercraft.shared.peripheral.modem.ModemShapes; import dan200.computercraft.shared.util.DirectionUtil; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.Direction; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.util.shape.VoxelShapes; +import net.minecraft.core.Direction; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; import java.util.EnumMap; @@ -23,18 +23,18 @@ public final class CableShapes private static final double MIN = 0.375; private static final double MAX = 1 - MIN; - private static final VoxelShape SHAPE_CABLE_CORE = VoxelShapes.cuboid( MIN, MIN, MIN, MAX, MAX, MAX ); + private static final VoxelShape SHAPE_CABLE_CORE = Shapes.box( MIN, MIN, MIN, MAX, MAX, MAX ); private static final EnumMap SHAPE_CABLE_ARM = new EnumMap<>( new ImmutableMap.Builder().put( Direction.DOWN, - VoxelShapes.cuboid( - MIN, - 0, - MIN, - MAX, - MIN, - MAX ) ) + Shapes.box( + MIN, + 0, + MIN, + MAX, + MIN, + MAX ) ) .put( Direction.UP, - VoxelShapes.cuboid( + Shapes.box( MIN, MAX, MIN, @@ -42,7 +42,7 @@ public final class CableShapes 1, MAX ) ) .put( Direction.NORTH, - VoxelShapes.cuboid( + Shapes.box( MIN, MIN, 0, @@ -50,7 +50,7 @@ public final class CableShapes MAX, MIN ) ) .put( Direction.SOUTH, - VoxelShapes.cuboid( + Shapes.box( MIN, MIN, MAX, @@ -58,7 +58,7 @@ public final class CableShapes MAX, 1 ) ) .put( Direction.WEST, - VoxelShapes.cuboid( + Shapes.box( 0, MIN, MIN, @@ -66,7 +66,7 @@ public final class CableShapes MAX, MAX ) ) .put( Direction.EAST, - VoxelShapes.cuboid( + Shapes.box( MAX, MIN, MIN, @@ -84,9 +84,9 @@ public final class CableShapes public static VoxelShape getCableShape( BlockState state ) { - if( !state.get( CABLE ) ) + if( !state.getValue( CABLE ) ) { - return VoxelShapes.empty(); + return Shapes.empty(); } return getCableShape( getCableIndex( state ) ); } @@ -104,7 +104,7 @@ public final class CableShapes { if( (index & (1 << facing.ordinal())) != 0 ) { - shape = VoxelShapes.union( shape, SHAPE_CABLE_ARM.get( facing ) ); + shape = Shapes.or( shape, SHAPE_CABLE_ARM.get( facing ) ); } } @@ -116,7 +116,7 @@ public final class CableShapes int index = 0; for( Direction facing : DirectionUtil.FACINGS ) { - if( state.get( CONNECTIONS.get( facing ) ) ) + if( state.getValue( CONNECTIONS.get( facing ) ) ) { index |= 1 << facing.ordinal(); } @@ -127,9 +127,9 @@ public final class CableShapes public static VoxelShape getShape( BlockState state ) { - Direction facing = state.get( MODEM ) + Direction facing = state.getValue( MODEM ) .getFacing(); - if( !state.get( CABLE ) ) + if( !state.getValue( CABLE ) ) { return getModemShape( state ); } @@ -146,15 +146,15 @@ public final class CableShapes shape = getCableShape( cableIndex ); if( facing != null ) { - shape = VoxelShapes.union( shape, ModemShapes.getBounds( facing ) ); + shape = Shapes.or( shape, ModemShapes.getBounds( facing ) ); } return SHAPES[index] = shape; } public static VoxelShape getModemShape( BlockState state ) { - Direction facing = state.get( MODEM ) + Direction facing = state.getValue( MODEM ) .getFacing(); - return facing == null ? VoxelShapes.empty() : ModemShapes.getBounds( facing ); + return facing == null ? Shapes.empty() : ModemShapes.getBounds( facing ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/ItemBlockCable.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/ItemBlockCable.java index eb86b95f5..4eadf5d4a 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/ItemBlockCable.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/ItemBlockCable.java @@ -7,22 +7,22 @@ package dan200.computercraft.shared.peripheral.modem.wired; import dan200.computercraft.shared.ComputerCraftRegistry; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.BlockItem; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.sound.BlockSoundGroup; -import net.minecraft.sound.SoundCategory; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Util; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; +import net.minecraft.Util; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.NonNullList; +import net.minecraft.core.Registry; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nonnull; @@ -32,28 +32,28 @@ public abstract class ItemBlockCable extends BlockItem { private String translationKey; - public ItemBlockCable( BlockCable block, Settings settings ) + public ItemBlockCable( BlockCable block, Properties settings ) { super( block, settings ); } - boolean placeAtCorrected( World world, BlockPos pos, BlockState state ) + boolean placeAtCorrected( Level world, BlockPos pos, BlockState state ) { return placeAt( world, pos, correctConnections( world, pos, state ), null ); } - boolean placeAt( World world, BlockPos pos, BlockState state, PlayerEntity player ) + boolean placeAt( Level world, BlockPos pos, BlockState state, Player player ) { // TODO: Check entity collision. - if( !state.canPlaceAt( world, pos ) ) + if( !state.canSurvive( world, pos ) ) { return false; } - world.setBlockState( pos, state, 3 ); - BlockSoundGroup soundType = state.getBlock() - .getSoundGroup( state ); - world.playSound( null, pos, soundType.getPlaceSound(), SoundCategory.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F ); + world.setBlock( pos, state, 3 ); + SoundType soundType = state.getBlock() + .getSoundType( state ); + world.playSound( null, pos, soundType.getPlaceSound(), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F ); BlockEntity tile = world.getBlockEntity( pos ); if( tile instanceof TileCable cable ) @@ -67,19 +67,19 @@ public abstract class ItemBlockCable extends BlockItem @Nonnull @Override - public String getTranslationKey() + public String getDescriptionId() { if( translationKey == null ) { - translationKey = Util.createTranslationKey( "block", Registry.ITEM.getId( this ) ); + translationKey = Util.makeDescriptionId( "block", Registry.ITEM.getKey( this ) ); } return translationKey; } @Override - public void appendStacks( @Nonnull ItemGroup group, @Nonnull DefaultedList list ) + public void fillItemCategory( @Nonnull CreativeModeTab group, @Nonnull NonNullList list ) { - if( isIn( group ) ) + if( allowdedIn( group ) ) { list.add( new ItemStack( this ) ); } @@ -87,36 +87,36 @@ public abstract class ItemBlockCable extends BlockItem public static class WiredModem extends ItemBlockCable { - public WiredModem( BlockCable block, Settings settings ) + public WiredModem( BlockCable block, Properties settings ) { super( block, settings ); } @Nonnull @Override - public ActionResult place( ItemPlacementContext context ) + public InteractionResult place( BlockPlaceContext context ) { - ItemStack stack = context.getStack(); + ItemStack stack = context.getItemInHand(); if( stack.isEmpty() ) { - return ActionResult.FAIL; + return InteractionResult.FAIL; } - World world = context.getWorld(); - BlockPos pos = context.getBlockPos(); + Level world = context.getLevel(); + BlockPos pos = context.getClickedPos(); BlockState existingState = world.getBlockState( pos ); // Try to add a modem to a cable - if( existingState.getBlock() == ComputerCraftRegistry.ModBlocks.CABLE && existingState.get( MODEM ) == CableModemVariant.None ) + if( existingState.getBlock() == ComputerCraftRegistry.ModBlocks.CABLE && existingState.getValue( MODEM ) == CableModemVariant.None ) { - Direction side = context.getSide() + Direction side = context.getClickedFace() .getOpposite(); - BlockState newState = existingState.with( MODEM, CableModemVariant.from( side ) ) - .with( CONNECTIONS.get( side ), existingState.get( CABLE ) ); + BlockState newState = existingState.setValue( MODEM, CableModemVariant.from( side ) ) + .setValue( CONNECTIONS.get( side ), existingState.getValue( CABLE ) ); if( placeAt( world, pos, newState, context.getPlayer() ) ) { - stack.decrement( 1 ); - return ActionResult.SUCCESS; + stack.shrink( 1 ); + return InteractionResult.SUCCESS; } } @@ -126,48 +126,48 @@ public abstract class ItemBlockCable extends BlockItem public static class Cable extends ItemBlockCable { - public Cable( BlockCable block, Settings settings ) + public Cable( BlockCable block, Properties settings ) { super( block, settings ); } @Nonnull @Override - public ActionResult place( ItemPlacementContext context ) + public InteractionResult place( BlockPlaceContext context ) { - ItemStack stack = context.getStack(); + ItemStack stack = context.getItemInHand(); if( stack.isEmpty() ) { - return ActionResult.FAIL; + return InteractionResult.FAIL; } - World world = context.getWorld(); - BlockPos pos = context.getBlockPos(); + Level world = context.getLevel(); + BlockPos pos = context.getClickedPos(); // Try to add a cable to a modem inside the block we're clicking on. - BlockPos insidePos = pos.offset( context.getSide() + BlockPos insidePos = pos.relative( context.getClickedFace() .getOpposite() ); BlockState insideState = world.getBlockState( insidePos ); - if( insideState.getBlock() == ComputerCraftRegistry.ModBlocks.CABLE && !insideState.get( BlockCable.CABLE ) && placeAtCorrected( world, + if( insideState.getBlock() == ComputerCraftRegistry.ModBlocks.CABLE && !insideState.getValue( BlockCable.CABLE ) && placeAtCorrected( world, insidePos, - insideState.with( + insideState.setValue( BlockCable.CABLE, true ) ) ) { - stack.decrement( 1 ); - return ActionResult.SUCCESS; + stack.shrink( 1 ); + return InteractionResult.SUCCESS; } // Try to add a cable to a modem adjacent to this block BlockState existingState = world.getBlockState( pos ); - if( existingState.getBlock() == ComputerCraftRegistry.ModBlocks.CABLE && !existingState.get( BlockCable.CABLE ) && placeAtCorrected( world, + if( existingState.getBlock() == ComputerCraftRegistry.ModBlocks.CABLE && !existingState.getValue( BlockCable.CABLE ) && placeAtCorrected( world, pos, - existingState.with( + existingState.setValue( BlockCable.CABLE, true ) ) ) { - stack.decrement( 1 ); - return ActionResult.SUCCESS; + stack.shrink( 1 ); + return InteractionResult.SUCCESS; } return super.place( context ); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileCable.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileCable.java index 077486c8e..4c8c7ebb5 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileCable.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileCable.java @@ -18,20 +18,20 @@ import dan200.computercraft.shared.common.TileGeneric; import dan200.computercraft.shared.peripheral.modem.ModemState; import dan200.computercraft.shared.util.DirectionUtil; import dan200.computercraft.shared.util.TickScheduler; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -57,10 +57,10 @@ public class TileCable extends TileGeneric implements IPeripheralTile @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { - BlockPos pos = getPos().offset( getDirection() ); - return new Vec3d( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); + BlockPos pos = getBlockPos().relative( getDirection() ); + return new Vec3( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); } @Nonnull @@ -97,7 +97,7 @@ public class TileCable extends TileGeneric implements IPeripheralTile private void onRemove() { - if( world == null || !world.isClient ) + if( level == null || !level.isClientSide ) { node.remove(); connectionsFormed = false; @@ -106,20 +106,20 @@ public class TileCable extends TileGeneric implements IPeripheralTile @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - if( player.isInSneakingPose() ) + if( player.isCrouching() ) { - return ActionResult.PASS; + return InteractionResult.PASS; } if( !canAttachPeripheral() ) { - return ActionResult.FAIL; + return InteractionResult.FAIL; } - if( this.world.isClient ) + if( this.level.isClientSide ) { - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } String oldName = peripheral.getConnectedName(); @@ -129,39 +129,39 @@ public class TileCable extends TileGeneric implements IPeripheralTile { if( oldName != null ) { - player.sendMessage( new TranslatableText( "chat.computercraft.wired_modem.peripheral_disconnected", + player.displayClientMessage( new TranslatableComponent( "chat.computercraft.wired_modem.peripheral_disconnected", ChatHelpers.copy( oldName ) ), false ); } if( newName != null ) { - player.sendMessage( new TranslatableText( "chat.computercraft.wired_modem.peripheral_connected", + player.displayClientMessage( new TranslatableComponent( "chat.computercraft.wired_modem.peripheral_connected", ChatHelpers.copy( newName ) ), false ); } } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } @Override public void onNeighbourChange( @Nonnull BlockPos neighbour ) { Direction dir = getDirection(); - if( neighbour.equals( getPos().offset( dir ) ) && hasModem() && !getCachedState().canPlaceAt( getWorld(), getPos() ) ) + if( neighbour.equals( getBlockPos().relative( dir ) ) && hasModem() && !getBlockState().canSurvive( getLevel(), getBlockPos() ) ) { if( hasCable() ) { // Drop the modem and convert to cable - Block.dropStack( getWorld(), getPos(), new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ) ); - getWorld().setBlockState( getPos(), - getCachedState().with( BlockCable.MODEM, CableModemVariant.None ) ); + Block.popResource( getLevel(), getBlockPos(), new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ) ); + getLevel().setBlockAndUpdate( getBlockPos(), + getBlockState().setValue( BlockCable.MODEM, CableModemVariant.None ) ); modemChanged(); connectionsChanged(); } else { // Drop everything and remove block - Block.dropStack( getWorld(), getPos(), new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ) ); - getWorld().removeBlock( getPos(), false ); + Block.popResource( getLevel(), getBlockPos(), new ItemStack( ComputerCraftRegistry.ModItems.WIRED_MODEM ) ); + getLevel().removeBlock( getBlockPos(), false ); // This'll call #destroy(), so we don't need to reset the network here. } @@ -180,18 +180,18 @@ public class TileCable extends TileGeneric implements IPeripheralTile public boolean hasModem() { - return getCachedState().get( BlockCable.MODEM ) != CableModemVariant.None; + return getBlockState().getValue( BlockCable.MODEM ) != CableModemVariant.None; } boolean hasCable() { - return getCachedState().get( BlockCable.CABLE ); + return getBlockState().getValue( BlockCable.CABLE ); } void modemChanged() { // Tell anyone who cares that the connection state has changed - if( getWorld().isClient ) + if( getLevel().isClientSide ) { return; } @@ -203,25 +203,25 @@ public class TileCable extends TileGeneric implements IPeripheralTile peripheralAccessAllowed = false; peripheral.detach(); node.updatePeripherals( Collections.emptyMap() ); - markDirty(); + setChanged(); updateBlockState(); } } void connectionsChanged() { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { return; } - BlockState state = getCachedState(); - World world = getWorld(); - BlockPos current = getPos(); + BlockState state = getBlockState(); + Level world = getLevel(); + BlockPos current = getBlockPos(); for( Direction facing : DirectionUtil.FACINGS ) { - BlockPos offset = current.offset( facing ); - if( !world.isChunkLoaded( offset ) ) + BlockPos offset = current.relative( facing ); + if( !world.hasChunkAt( offset ) ) { continue; } @@ -255,20 +255,20 @@ public class TileCable extends TileGeneric implements IPeripheralTile private void updateBlockState() { - BlockState state = getCachedState(); - CableModemVariant oldVariant = state.get( BlockCable.MODEM ); + BlockState state = getBlockState(); + CableModemVariant oldVariant = state.getValue( BlockCable.MODEM ); CableModemVariant newVariant = CableModemVariant.from( oldVariant.getFacing(), modem.getModemState() .isOpen(), peripheralAccessAllowed ); if( oldVariant != newVariant ) { - world.setBlockState( getPos(), state.with( BlockCable.MODEM, newVariant ) ); + level.setBlockAndUpdate( getBlockPos(), state.setValue( BlockCable.MODEM, newVariant ) ); } } private void refreshPeripheral() { - if( world != null && !isRemoved() && peripheral.attach( world, getPos(), getDirection() ) ) + if( level != null && !isRemoved() && peripheral.attach( level, getBlockPos(), getDirection() ) ) { updateConnectedPeripherals(); } @@ -291,10 +291,10 @@ public class TileCable extends TileGeneric implements IPeripheralTile public void onNeighbourTileEntityChange( @Nonnull BlockPos neighbour ) { super.onNeighbourTileEntityChange( neighbour ); - if( !world.isClient && peripheralAccessAllowed ) + if( !level.isClientSide && peripheralAccessAllowed ) { Direction facing = getDirection(); - if( getPos().offset( facing ) + if( getBlockPos().relative( facing ) .equals( neighbour ) ) { refreshPeripheral(); @@ -305,7 +305,7 @@ public class TileCable extends TileGeneric implements IPeripheralTile @Override public void blockTick() { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { return; } @@ -323,7 +323,7 @@ public class TileCable extends TileGeneric implements IPeripheralTile connectionsChanged(); if( peripheralAccessAllowed ) { - peripheral.attach( world, pos, getDirection() ); + peripheral.attach( level, worldPosition, getDirection() ); updateConnectedPeripherals(); } } @@ -333,7 +333,7 @@ public class TileCable extends TileGeneric implements IPeripheralTile { if( !peripheralAccessAllowed ) { - peripheral.attach( world, getPos(), getDirection() ); + peripheral.attach( level, getBlockPos(), getDirection() ); if( !peripheral.hasPeripheral() ) { return; @@ -356,56 +356,56 @@ public class TileCable extends TileGeneric implements IPeripheralTile @Nullable private Direction getMaybeDirection() { - return getCachedState().get( BlockCable.MODEM ).getFacing(); + return getBlockState().getValue( BlockCable.MODEM ).getFacing(); } @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); + super.load( nbt ); peripheralAccessAllowed = nbt.getBoolean( NBT_PERIPHERAL_ENABLED ); peripheral.read( nbt, "" ); } @Nonnull @Override - public NbtCompound writeNbt( NbtCompound nbt ) + public CompoundTag save( CompoundTag nbt ) { nbt.putBoolean( NBT_PERIPHERAL_ENABLED, peripheralAccessAllowed ); peripheral.write( nbt, "" ); - return super.writeNbt( nbt ); + return super.save( nbt ); } @Override - public void markRemoved() + public void setRemoved() { - super.markRemoved(); + super.setRemoved(); onRemove(); } @Override - public void cancelRemoval() + public void clearRemoved() { - super.cancelRemoval(); + super.clearRemoved(); TickScheduler.schedule( this ); } @Override - public void setCachedState( BlockState state ) + public void setBlockState( BlockState state ) { - super.setCachedState( state ); + super.setBlockState( state ); if( state != null ) return; - if( !world.isClient ) + if( !level.isClientSide ) { - world.getBlockTickScheduler() - .schedule( pos, - getCachedState().getBlock(), 0 ); + level.getBlockTicks() + .scheduleTick( worldPosition, + getBlockState().getBlock(), 0 ); } } public IWiredElement getElement( Direction facing ) { - return BlockCable.canConnectIn( getCachedState(), facing ) ? cable : null; + return BlockCable.canConnectIn( getBlockState(), facing ) ? cable : null; } @Nonnull @@ -419,17 +419,17 @@ public class TileCable extends TileGeneric implements IPeripheralTile { @Nonnull @Override - public World getWorld() + public Level getLevel() { - return TileCable.this.getWorld(); + return TileCable.this.getLevel(); } @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { - BlockPos pos = getPos(); - return new Vec3d( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); + BlockPos pos = getBlockPos(); + return new Vec3( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileWiredModemFull.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileWiredModemFull.java index abeebbe38..37de3790b 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileWiredModemFull.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/TileWiredModemFull.java @@ -17,19 +17,19 @@ import dan200.computercraft.shared.common.TileGeneric; import dan200.computercraft.shared.peripheral.modem.ModemState; import dan200.computercraft.shared.util.DirectionUtil; import dan200.computercraft.shared.util.TickScheduler; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.LiteralText; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.*; @@ -54,7 +54,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile super( type, pos, state ); for( int i = 0; i < peripherals.length; i++ ) { - Direction facing = Direction.byId( i ); + Direction facing = Direction.from3DDataValue( i ); peripherals[i] = new WiredModemLocalPeripheral(); } } @@ -79,7 +79,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile private void doRemove() { - if( world == null || !world.isClient ) + if( level == null || !level.isClientSide ) { node.remove(); connectionsFormed = false; @@ -88,11 +88,11 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } // On server, we interacted if a peripheral was found @@ -106,7 +106,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile sendPeripheralChanges( player, "chat.computercraft.wired_modem.peripheral_connected", periphNames ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } @Override @@ -118,11 +118,11 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile @Override public void onNeighbourTileEntityChange( @Nonnull BlockPos neighbour ) { - if( !world.isClient && peripheralAccessAllowed ) + if( !level.isClientSide && peripheralAccessAllowed ) { for( Direction facing : DirectionUtil.FACINGS ) { - if( getPos().offset( facing ) + if( getBlockPos().relative( facing ) .equals( neighbour ) ) { refreshPeripheral( facing ); @@ -134,7 +134,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile @Override public void blockTick() { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { return; } @@ -153,7 +153,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile { for( Direction facing : DirectionUtil.FACINGS ) { - peripherals[facing.ordinal()].attach( world, getPos(), facing ); + peripherals[facing.ordinal()].attach( level, getBlockPos(), facing ); } updateConnectedPeripherals(); } @@ -162,17 +162,17 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile private void connectionsChanged() { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { return; } - World world = getWorld(); - BlockPos current = getPos(); + Level world = getLevel(); + BlockPos current = getBlockPos(); for( Direction facing : DirectionUtil.FACINGS ) { - BlockPos offset = current.offset( facing ); - if( !world.isChunkLoaded( offset ) ) + BlockPos offset = current.relative( facing ); + if( !world.hasChunkAt( offset ) ) { continue; } @@ -190,7 +190,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile private void refreshPeripheral( @Nonnull Direction facing ) { WiredModemLocalPeripheral peripheral = peripherals[facing.ordinal()]; - if( world != null && !isRemoved() && peripheral.attach( world, getPos(), facing ) ) + if( level != null && !isRemoved() && peripheral.attach( level, getBlockPos(), facing ) ) { updateConnectedPeripherals(); } @@ -226,16 +226,16 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile private void updateBlockState() { - BlockState state = getCachedState(); + BlockState state = getBlockState(); boolean modemOn = modemState.isOpen(), peripheralOn = peripheralAccessAllowed; - if( state.get( MODEM_ON ) == modemOn && state.get( PERIPHERAL_ON ) == peripheralOn ) + if( state.getValue( MODEM_ON ) == modemOn && state.getValue( PERIPHERAL_ON ) == peripheralOn ) { return; } - getWorld().setBlockState( getPos(), - state.with( MODEM_ON, modemOn ) - .with( PERIPHERAL_ON, peripheralOn ) ); + getLevel().setBlockAndUpdate( getBlockPos(), + state.setValue( MODEM_ON, modemOn ) + .setValue( PERIPHERAL_ON, peripheralOn ) ); } private Set getConnectedPeripheralNames() @@ -265,7 +265,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile for( Direction facing : DirectionUtil.FACINGS ) { WiredModemLocalPeripheral peripheral = peripherals[facing.ordinal()]; - peripheral.attach( world, getPos(), facing ); + peripheral.attach( level, getBlockPos(), facing ); hasAny |= peripheral.hasPeripheral(); } @@ -291,7 +291,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile updateBlockState(); } - private static void sendPeripheralChanges( PlayerEntity player, String kind, Collection peripherals ) + private static void sendPeripheralChanges( Player player, String kind, Collection peripherals ) { if( peripherals.isEmpty() ) { @@ -301,7 +301,7 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile List names = new ArrayList<>( peripherals ); names.sort( Comparator.naturalOrder() ); - LiteralText base = new LiteralText( "" ); + TextComponent base = new TextComponent( "" ); for( int i = 0; i < names.size(); i++ ) { if( i > 0 ) @@ -311,13 +311,13 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile base.append( ChatHelpers.copy( names.get( i ) ) ); } - player.sendMessage( new TranslatableText( kind, base ), false ); + player.displayClientMessage( new TranslatableComponent( kind, base ), false ); } @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); + super.load( nbt ); peripheralAccessAllowed = nbt.getBoolean( NBT_PERIPHERAL_ENABLED ); for( int i = 0; i < peripherals.length; i++ ) { @@ -327,27 +327,27 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile @Nonnull @Override - public NbtCompound writeNbt( NbtCompound nbt ) + public CompoundTag save( CompoundTag nbt ) { nbt.putBoolean( NBT_PERIPHERAL_ENABLED, peripheralAccessAllowed ); for( int i = 0; i < peripherals.length; i++ ) { peripherals[i].write( nbt, Integer.toString( i ) ); } - return super.writeNbt( nbt ); + return super.save( nbt ); } @Override - public void markRemoved() + public void setRemoved() { - super.markRemoved(); + super.setRemoved(); doRemove(); } @Override - public void cancelRemoval() + public void clearRemoved() { - super.cancelRemoval(); + super.clearRemoved(); TickScheduler.schedule( this ); } @@ -378,10 +378,10 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { - BlockPos pos = getPos().offset( side ); - return new Vec3d( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); + BlockPos pos = getBlockPos().relative( side ); + return new Vec3( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); } @Nonnull @@ -430,17 +430,17 @@ public class TileWiredModemFull extends TileGeneric implements IPeripheralTile @Nonnull @Override - public World getWorld() + public Level getLevel() { - return entity.getWorld(); + return entity.getLevel(); } @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { - BlockPos pos = entity.getPos(); - return new Vec3d( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); + BlockPos pos = entity.getBlockPos(); + return new Vec3( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); } } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemLocalPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemLocalPeripheral.java index de10208a1..7f52306bf 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemLocalPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemLocalPeripheral.java @@ -11,11 +11,11 @@ import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.Peripherals; import dan200.computercraft.shared.util.IDAssigner; import dan200.computercraft.shared.util.NBTUtil; -import net.minecraft.block.Block; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -45,7 +45,7 @@ public final class WiredModemLocalPeripheral * @param direction The direction so search in * @return Whether the peripheral changed. */ - public boolean attach( @Nonnull World world, @Nonnull BlockPos origin, @Nonnull Direction direction ) + public boolean attach( @Nonnull Level world, @Nonnull BlockPos origin, @Nonnull Direction direction ) { IPeripheral oldPeripheral = peripheral; IPeripheral peripheral = this.peripheral = getPeripheralFrom( world, origin, direction ); @@ -75,9 +75,9 @@ public final class WiredModemLocalPeripheral } @Nullable - private IPeripheral getPeripheralFrom( World world, BlockPos pos, Direction direction ) + private IPeripheral getPeripheralFrom( Level world, BlockPos pos, Direction direction ) { - BlockPos offset = pos.offset( direction ); + BlockPos offset = pos.relative( direction ); Block block = world.getBlockState( offset ) .getBlock(); @@ -135,7 +135,7 @@ public final class WiredModemLocalPeripheral return peripheral == null ? Collections.emptyMap() : Collections.singletonMap( type + "_" + id, peripheral ); } - public void write( @Nonnull NbtCompound tag, @Nonnull String suffix ) + public void write( @Nonnull CompoundTag tag, @Nonnull String suffix ) { if( id >= 0 ) { @@ -147,7 +147,7 @@ public final class WiredModemLocalPeripheral } } - public void read( @Nonnull NbtCompound tag, @Nonnull String suffix ) + public void read( @Nonnull CompoundTag tag, @Nonnull String suffix ) { id = tag.contains( NBT_PERIPHERAL_ID + suffix, NBTUtil.TAG_ANY_NUMERIC ) ? tag.getInt( NBT_PERIPHERAL_ID + suffix ) : -1; diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java index 242354538..6cf699655 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wired/WiredModemPeripheral.java @@ -22,7 +22,7 @@ import dan200.computercraft.core.apis.PeripheralAPI; import dan200.computercraft.core.asm.PeripheralMethod; import dan200.computercraft.shared.peripheral.modem.ModemPeripheral; import dan200.computercraft.shared.peripheral.modem.ModemState; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -122,9 +122,9 @@ public abstract class WiredModemPeripheral extends ModemPeripheral implements IW @Nonnull @Override - public World getWorld() + public Level getLevel() { - return modem.getWorld(); + return modem.getLevel(); } /** diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/BlockWirelessModem.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/BlockWirelessModem.java index c6ebe3809..b3a03e8a6 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/BlockWirelessModem.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/BlockWirelessModem.java @@ -10,56 +10,56 @@ import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.peripheral.modem.ModemShapes; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.ShapeContext; -import net.minecraft.block.Waterloggable; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.fluid.FluidState; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.BooleanProperty; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.BlockView; -import net.minecraft.world.WorldAccess; -import net.minecraft.world.WorldView; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.LevelReader; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.SimpleWaterloggedBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.minecraft.world.level.block.state.properties.DirectionProperty; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static dan200.computercraft.shared.util.WaterloggableHelpers.*; -public class BlockWirelessModem extends BlockGeneric implements Waterloggable +public class BlockWirelessModem extends BlockGeneric implements SimpleWaterloggedBlock { - public static final DirectionProperty FACING = Properties.FACING; - public static final BooleanProperty ON = BooleanProperty.of( "on" ); + public static final DirectionProperty FACING = BlockStateProperties.FACING; + public static final BooleanProperty ON = BooleanProperty.create( "on" ); private final ComputerFamily family; - public BlockWirelessModem( Settings settings, BlockEntityType type, ComputerFamily family ) + public BlockWirelessModem( Properties settings, BlockEntityType type, ComputerFamily family ) { super( settings, type ); this.family = family; - setDefaultState( getStateManager().getDefaultState() - .with( FACING, Direction.NORTH ) - .with( ON, false ) - .with( WATERLOGGED, false ) ); + registerDefaultState( getStateDefinition().any() + .setValue( FACING, Direction.NORTH ) + .setValue( ON, false ) + .setValue( WATERLOGGED, false ) ); } @Nonnull @Override @Deprecated - public BlockState getStateForNeighborUpdate( @Nonnull BlockState state, @Nonnull Direction side, @Nonnull BlockState otherState, - @Nonnull WorldAccess world, @Nonnull BlockPos pos, @Nonnull BlockPos otherPos ) + public BlockState updateShape( @Nonnull BlockState state, @Nonnull Direction side, @Nonnull BlockState otherState, + @Nonnull LevelAccessor world, @Nonnull BlockPos pos, @Nonnull BlockPos otherPos ) { updateWaterloggedPostPlacement( state, world, pos ); - return side == state.get( FACING ) && !state.canPlaceAt( world, pos ) ? state.getFluidState() - .getBlockState() : state; + return side == state.getValue( FACING ) && !state.canSurvive( world, pos ) ? state.getFluidState() + .createLegacyBlock() : state; } @Nonnull @@ -72,39 +72,39 @@ public class BlockWirelessModem extends BlockGeneric implements Waterloggable @Override @Deprecated - public boolean canPlaceAt( BlockState state, @Nonnull WorldView world, BlockPos pos ) + public boolean canSurvive( BlockState state, @Nonnull LevelReader world, BlockPos pos ) { - Direction facing = state.get( FACING ); - return sideCoversSmallSquare( world, pos.offset( facing ), facing.getOpposite() ); + Direction facing = state.getValue( FACING ); + return canSupportCenter( world, pos.relative( facing ), facing.getOpposite() ); } @Nonnull @Override @Deprecated - public VoxelShape getOutlineShape( BlockState blockState, @Nonnull BlockView blockView, @Nonnull BlockPos blockPos, @Nonnull ShapeContext context ) + public VoxelShape getShape( BlockState blockState, @Nonnull BlockGetter blockView, @Nonnull BlockPos blockPos, @Nonnull CollisionContext context ) { - return ModemShapes.getBounds( blockState.get( FACING ) ); + return ModemShapes.getBounds( blockState.getValue( FACING ) ); } @Nullable @Override - public BlockState getPlacementState( ItemPlacementContext placement ) + public BlockState getStateForPlacement( BlockPlaceContext placement ) { - return getDefaultState().with( FACING, - placement.getSide() - .getOpposite() ) - .with( WATERLOGGED, getWaterloggedStateForPlacement( placement ) ); + return defaultBlockState().setValue( FACING, + placement.getClickedFace() + .getOpposite() ) + .setValue( WATERLOGGED, getWaterloggedStateForPlacement( placement ) ); } @Override - protected void appendProperties( StateManager.Builder builder ) + protected void createBlockStateDefinition( StateDefinition.Builder builder ) { builder.add( FACING, ON, WATERLOGGED ); } public BlockEntityType getTypeByFamily( ComputerFamily family ) { - return switch ( family ) + return switch( family ) { case ADVANCED -> ComputerCraftRegistry.ModTiles.WIRELESS_MODEM_ADVANCED; default -> ComputerCraftRegistry.ModTiles.WIRELESS_MODEM_NORMAL; @@ -113,7 +113,7 @@ public class BlockWirelessModem extends BlockGeneric implements Waterloggable @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileWirelessModem( getTypeByFamily( family ), family == ComputerFamily.ADVANCED, pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/TileWirelessModem.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/TileWirelessModem.java index 82d584a5b..809fa0761 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/TileWirelessModem.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/TileWirelessModem.java @@ -12,12 +12,12 @@ import dan200.computercraft.shared.common.TileGeneric; import dan200.computercraft.shared.peripheral.modem.ModemPeripheral; import dan200.computercraft.shared.peripheral.modem.ModemState; import dan200.computercraft.shared.util.TickScheduler; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; @@ -37,21 +37,21 @@ public class TileWirelessModem extends TileGeneric implements IPeripheralTile } @Override - public void cancelRemoval() + public void clearRemoved() { - super.cancelRemoval(); + super.clearRemoved(); TickScheduler.schedule( this ); } @Override - public void setCachedState( BlockState state ) + public void setBlockState( BlockState state ) { - super.setCachedState( state ); + super.setBlockState( state ); if( state != null ) return; hasModemDirection = false; - world.getBlockTickScheduler() - .schedule( getPos(), - getCachedState().getBlock(), 0 ); + level.getBlockTicks() + .scheduleTick( getBlockPos(), + getBlockState().getBlock(), 0 ); } @Override @@ -87,17 +87,17 @@ public class TileWirelessModem extends TileGeneric implements IPeripheralTile } hasModemDirection = true; - modemDirection = getCachedState().get( BlockWirelessModem.FACING ); + modemDirection = getBlockState().getValue( BlockWirelessModem.FACING ); } private void updateBlockState() { boolean on = modem.getModemState() .isOpen(); - BlockState state = getCachedState(); - if( state.get( BlockWirelessModem.ON ) != on ) + BlockState state = getBlockState(); + if( state.getValue( BlockWirelessModem.ON ) != on ) { - getWorld().setBlockState( getPos(), state.with( BlockWirelessModem.ON, on ) ); + getLevel().setBlockAndUpdate( getBlockPos(), state.setValue( BlockWirelessModem.ON, on ) ); } } @@ -121,18 +121,18 @@ public class TileWirelessModem extends TileGeneric implements IPeripheralTile @Nonnull @Override - public World getWorld() + public Level getLevel() { - return entity.getWorld(); + return entity.getLevel(); } @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { - BlockPos pos = entity.getPos() - .offset( entity.modemDirection ); - return new Vec3d( pos.getX(), pos.getY(), pos.getZ() ); + BlockPos pos = entity.getBlockPos() + .relative( entity.modemDirection ); + return new Vec3( pos.getX(), pos.getY(), pos.getZ() ); } @Nonnull diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessModemPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessModemPeripheral.java index a628cadf0..07f685542 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessModemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessModemPeripheral.java @@ -10,8 +10,8 @@ import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.network.IPacketNetwork; import dan200.computercraft.shared.peripheral.modem.ModemPeripheral; import dan200.computercraft.shared.peripheral.modem.ModemState; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; public abstract class WirelessModemPeripheral extends ModemPeripheral { @@ -32,10 +32,10 @@ public abstract class WirelessModemPeripheral extends ModemPeripheral } else { - World world = getWorld(); + Level world = getLevel(); if( world != null ) { - Vec3d position = getPosition(); + Vec3 position = getPosition(); double minRange = ComputerCraft.modemRange; double maxRange = ComputerCraft.modemHighAltitudeRange; if( world.isRaining() && world.isThundering() ) diff --git a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessNetwork.java b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessNetwork.java index 14f809156..c1f06c922 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessNetwork.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/modem/wireless/WirelessNetwork.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.peripheral.modem.wireless; import dan200.computercraft.api.network.IPacketNetwork; @@ -20,14 +19,10 @@ import java.util.concurrent.ConcurrentHashMap; public class WirelessNetwork implements IPacketNetwork { private static WirelessNetwork universalNetwork = null; - private final Set receivers = Collections.newSetFromMap( new ConcurrentHashMap<>() ); public static WirelessNetwork getUniversal() { - if( universalNetwork == null ) - { - universalNetwork = new WirelessNetwork(); - } + if( universalNetwork == null ) universalNetwork = new WirelessNetwork(); return universalNetwork; } @@ -36,6 +31,8 @@ public class WirelessNetwork implements IPacketNetwork universalNetwork = null; } + private final Set receivers = Collections.newSetFromMap( new ConcurrentHashMap<>() ); + @Override public void addReceiver( @Nonnull IPacketReceiver receiver ) { @@ -50,40 +47,27 @@ public class WirelessNetwork implements IPacketNetwork receivers.remove( receiver ); } - @Override - public boolean isWireless() - { - return true; - } - @Override public void transmitSameDimension( @Nonnull Packet packet, double range ) { Objects.requireNonNull( packet, "packet cannot be null" ); - for( IPacketReceiver device : receivers ) - { - tryTransmit( device, packet, range, false ); - } + for( IPacketReceiver device : receivers ) tryTransmit( device, packet, range, false ); } @Override public void transmitInterdimensional( @Nonnull Packet packet ) { Objects.requireNonNull( packet, "packet cannot be null" ); - for( IPacketReceiver device : receivers ) - { - tryTransmit( device, packet, 0, true ); - } + for( IPacketReceiver device : receivers ) tryTransmit( device, packet, 0, true ); } private static void tryTransmit( IPacketReceiver receiver, Packet packet, double range, boolean interdimensional ) { - IPacketSender sender = packet.getSender(); - if( receiver.getWorld() == sender.getWorld() ) + IPacketSender sender = packet.sender(); + if( receiver.getLevel() == sender.getLevel() ) { double receiveRange = Math.max( range, receiver.getRange() ); // Ensure range is symmetrical - double distanceSq = receiver.getPosition() - .squaredDistanceTo( sender.getPosition() ); + double distanceSq = receiver.getPosition().distanceToSqr( sender.getPosition() ); if( interdimensional || receiver.isInterdimensional() || distanceSq <= receiveRange * receiveRange ) { receiver.receiveSameDimension( packet, Math.sqrt( distanceSq ) ); @@ -97,4 +81,10 @@ public class WirelessNetwork implements IPacketNetwork } } } + + @Override + public boolean isWireless() + { + return true; + } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/BlockMonitor.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/BlockMonitor.java index 22b3175e1..b760dfce8 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/BlockMonitor.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/BlockMonitor.java @@ -9,50 +9,50 @@ package dan200.computercraft.shared.peripheral.monitor; import dan200.computercraft.api.turtle.FakePlayer; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.EnumProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.DirectionProperty; +import net.minecraft.world.level.block.state.properties.EnumProperty; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class BlockMonitor extends BlockGeneric { - public static final DirectionProperty ORIENTATION = DirectionProperty.of( "orientation", Direction.UP, Direction.DOWN, Direction.NORTH ); + public static final DirectionProperty ORIENTATION = DirectionProperty.create( "orientation", Direction.UP, Direction.DOWN, Direction.NORTH ); - public static final DirectionProperty FACING = Properties.HORIZONTAL_FACING; + public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; - static final EnumProperty STATE = EnumProperty.of( "state", MonitorEdgeState.class ); + static final EnumProperty STATE = EnumProperty.create( "state", MonitorEdgeState.class ); public boolean advanced; - public BlockMonitor( Settings settings, BlockEntityType type, boolean advanced ) + public BlockMonitor( Properties settings, BlockEntityType type, boolean advanced ) { super( settings, type ); this.advanced = advanced; // TODO: Test underwater - do we need isSolid at all? - setDefaultState( getStateManager().getDefaultState() - .with( ORIENTATION, Direction.NORTH ) - .with( FACING, Direction.NORTH ) - .with( STATE, MonitorEdgeState.NONE ) ); + registerDefaultState( getStateDefinition().any() + .setValue( ORIENTATION, Direction.NORTH ) + .setValue( FACING, Direction.NORTH ) + .setValue( STATE, MonitorEdgeState.NONE ) ); } @Override @Nullable - public BlockState getPlacementState( ItemPlacementContext context ) + public BlockState getStateForPlacement( BlockPlaceContext context ) { - float pitch = context.getPlayer() == null ? 0 : context.getPlayer().getPitch(); + float pitch = context.getPlayer() == null ? 0 : context.getPlayer().getXRot(); Direction orientation; if( pitch > 66.5f ) { @@ -69,20 +69,20 @@ public class BlockMonitor extends BlockGeneric orientation = Direction.NORTH; } - return getDefaultState().with( FACING, - context.getPlayerFacing() - .getOpposite() ) - .with( ORIENTATION, orientation ); + return defaultBlockState().setValue( FACING, + context.getHorizontalDirection() + .getOpposite() ) + .setValue( ORIENTATION, orientation ); } @Override - public void onPlaced( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState blockState, @Nullable LivingEntity livingEntity, - @Nonnull ItemStack itemStack ) + public void setPlacedBy( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState blockState, @Nullable LivingEntity livingEntity, + @Nonnull ItemStack itemStack ) { - super.onPlaced( world, pos, blockState, livingEntity, itemStack ); + super.setPlacedBy( world, pos, blockState, livingEntity, itemStack ); BlockEntity entity = world.getBlockEntity( pos ); - if( entity instanceof TileMonitor monitor && !world.isClient ) + if( entity instanceof TileMonitor monitor && !world.isClientSide ) { // Defer the block update if we're being placed by another TE. See #691 if( livingEntity == null || livingEntity instanceof FakePlayer ) @@ -96,14 +96,14 @@ public class BlockMonitor extends BlockGeneric } @Override - protected void appendProperties( StateManager.Builder builder ) + protected void createBlockStateDefinition( StateDefinition.Builder builder ) { builder.add( ORIENTATION, FACING, STATE ); } @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileMonitor( advanced ? ComputerCraftRegistry.ModTiles.MONITOR_ADVANCED : ComputerCraftRegistry.ModTiles.MONITOR_NORMAL, advanced, pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/ClientMonitor.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/ClientMonitor.java index db226210e..12eef839f 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/ClientMonitor.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/ClientMonitor.java @@ -8,11 +8,11 @@ package dan200.computercraft.shared.peripheral.monitor; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.VertexBuffer; import dan200.computercraft.shared.common.ClientTerminal; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.gl.VertexBuffer; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorEdgeState.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorEdgeState.java index 1c4a0a87e..d45a52a4f 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorEdgeState.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/MonitorEdgeState.java @@ -6,13 +6,13 @@ package dan200.computercraft.shared.peripheral.monitor; -import net.minecraft.util.StringIdentifiable; +import net.minecraft.util.StringRepresentable; import javax.annotation.Nonnull; import static dan200.computercraft.shared.peripheral.monitor.MonitorEdgeState.Flags.*; -public enum MonitorEdgeState implements StringIdentifiable +public enum MonitorEdgeState implements StringRepresentable { NONE( "none", 0 ), @@ -60,7 +60,7 @@ public enum MonitorEdgeState implements StringIdentifiable @Nonnull @Override - public String asString() + public String getSerializedName() { return name; } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java index 38fd20cfa..f86791dad 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/TileMonitor.java @@ -15,17 +15,17 @@ import dan200.computercraft.shared.common.ServerTerminal; import dan200.computercraft.shared.common.TileGeneric; import dan200.computercraft.shared.network.client.TerminalState; import dan200.computercraft.shared.util.TickScheduler; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; import javax.annotation.Nonnull; import java.util.HashSet; @@ -74,16 +74,16 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile return; } destroyed = true; - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { contractNeighbours(); } } @Override - public void markRemoved() + public void setRemoved() { - super.markRemoved(); + super.setRemoved(); if( clientMonitor != null && xIndex == 0 && yIndex == 0 ) { clientMonitor.destroy(); @@ -103,23 +103,23 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - if( !player.isInSneakingPose() && getFront() == hit.getSide() ) + if( !player.isCrouching() && getFront() == hit.getDirection() ) { - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { - monitorTouched( (float) (hit.getPos().x - hit.getBlockPos() + monitorTouched( (float) (hit.getLocation().x - hit.getBlockPos() .getX()), - (float) (hit.getPos().y - hit.getBlockPos() + (float) (hit.getLocation().y - hit.getBlockPos() .getY()), - (float) (hit.getPos().z - hit.getBlockPos() + (float) (hit.getLocation().z - hit.getBlockPos() .getZ()) ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } - return ActionResult.PASS; + return InteractionResult.PASS; } @Override @@ -172,7 +172,7 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile } @Override - protected final void readDescription( @Nonnull NbtCompound nbt ) + protected final void readDescription( @Nonnull CompoundTag nbt ) { super.readDescription( nbt ); @@ -215,7 +215,7 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile } @Override - protected void writeDescription( @Nonnull NbtCompound nbt ) + protected void writeDescription( @Nonnull CompoundTag nbt ) { super.writeDescription( nbt ); nbt.putInt( NBT_X, xIndex ); @@ -231,18 +231,18 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile private MonitorState getNeighbour( int x, int y ) { - BlockPos pos = getPos(); + BlockPos pos = getBlockPos(); Direction right = getRight(); Direction down = getDown(); int xOffset = -xIndex + x; int yOffset = -yIndex + y; - return getSimilarMonitorAt( pos.offset( right, xOffset ) - .offset( down, yOffset ) ); + return getSimilarMonitorAt( pos.relative( right, xOffset ) + .relative( down, yOffset ) ); } public Direction getRight() { - return getDirection().rotateYCounterclockwise(); + return getDirection().getCounterClockWise(); } public Direction getDown() @@ -257,13 +257,13 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile private MonitorState getSimilarMonitorAt( BlockPos pos ) { - if( pos.equals( getPos() ) ) + if( pos.equals( getBlockPos() ) ) { return MonitorState.present( this ); } - World world = getWorld(); - if( world == null || !world.isChunkLoaded( pos ) ) + Level world = getLevel(); + if( world == null || !world.hasChunkAt( pos ) ) { return MonitorState.UNLOADED; } @@ -283,19 +283,19 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile { // Ensure we're actually a monitor block. This _should_ always be the case, but sometimes there's // fun problems with the block being missing on the client. - BlockState state = getCachedState(); - return state.contains( BlockMonitor.FACING ) ? state.get( BlockMonitor.FACING ) : Direction.NORTH; + BlockState state = getBlockState(); + return state.hasProperty( BlockMonitor.FACING ) ? state.getValue( BlockMonitor.FACING ) : Direction.NORTH; } public Direction getOrientation() { - return getCachedState().get( BlockMonitor.ORIENTATION ); + return getBlockState().getValue( BlockMonitor.ORIENTATION ); } @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); + super.load( nbt ); xIndex = nbt.getInt( NBT_X ); yIndex = nbt.getInt( NBT_Y ); @@ -307,13 +307,13 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile @Nonnull @Override - public NbtCompound writeNbt( NbtCompound nbt ) + public CompoundTag save( CompoundTag nbt ) { nbt.putInt( NBT_X, xIndex ); nbt.putInt( NBT_Y, yIndex ); nbt.putInt( NBT_WIDTH, width ); nbt.putInt( NBT_HEIGHT, height ); - return super.writeNbt( nbt ); + return super.save( nbt ); } // @Override //TODO: make BlockEntityRenderer work with this, i guess. @@ -325,9 +325,9 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile // Sizing and placement stuff @Override - public void cancelRemoval() + public void clearRemoved() { - super.cancelRemoval(); + super.clearRemoved(); needsValidating = true; TickScheduler.schedule( this ); } @@ -397,9 +397,9 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile { // Otherwise fetch the origin and attempt to get its monitor // Note this may load chunks, but we don't really have a choice here. - BlockPos pos = getPos(); - BlockEntity te = world.getBlockEntity( pos.offset( getRight(), -xIndex ) - .offset( getDown(), -yIndex ) ); + BlockPos pos = getBlockPos(); + BlockEntity te = level.getBlockEntity( pos.relative( getRight(), -xIndex ) + .relative( getDown(), -yIndex ) ); if( !(te instanceof TileMonitor) ) { return null; @@ -416,9 +416,9 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile return clientMonitor; } - BlockPos pos = getPos(); - BlockEntity te = world.getBlockEntity( pos.offset( getRight(), -xIndex ) - .offset( getDown(), -yIndex ) ); + BlockPos pos = getBlockPos(); + BlockEntity te = level.getBlockEntity( pos.relative( getRight(), -xIndex ) + .relative( getDown(), -yIndex ) ); if( !(te instanceof TileMonitor) ) { return null; @@ -431,7 +431,7 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile { if( xIndex != 0 || yIndex != 0 ) { - ComputerCraft.log.warn( "Receiving monitor state for non-origin terminal at {}", getPos() ); + ComputerCraft.log.warn( "Receiving monitor state for non-origin terminal at {}", getBlockPos() ); return; } @@ -444,8 +444,8 @@ public class TileMonitor extends TileGeneric implements IPeripheralTile private void updateBlockState() { - getWorld().setBlockState( getPos(), - getCachedState().with( BlockMonitor.STATE, + getLevel().setBlock( getBlockPos(), + getBlockState().setValue( BlockMonitor.STATE, MonitorEdgeState.fromConnections( yIndex < height - 1, yIndex > 0, xIndex > 0, xIndex < width - 1 ) ), 2 ); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java b/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java index 8aa24a4b3..ec660394e 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/monitor/XYPair.java @@ -6,7 +6,7 @@ package dan200.computercraft.shared.peripheral.monitor; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; public class XYPair { diff --git a/src/main/java/dan200/computercraft/shared/peripheral/printer/BlockPrinter.java b/src/main/java/dan200/computercraft/shared/peripheral/printer/BlockPrinter.java index d906fb391..dffbedde4 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/printer/BlockPrinter.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/printer/BlockPrinter.java @@ -8,90 +8,90 @@ package dan200.computercraft.shared.peripheral.printer; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.stat.Stats; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.BooleanProperty; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.Nameable; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.stats.Stats; +import net.minecraft.world.Nameable; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.minecraft.world.level.block.state.properties.DirectionProperty; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class BlockPrinter extends BlockGeneric { - static final BooleanProperty TOP = BooleanProperty.of( "top" ); - static final BooleanProperty BOTTOM = BooleanProperty.of( "bottom" ); - private static final DirectionProperty FACING = Properties.HORIZONTAL_FACING; + static final BooleanProperty TOP = BooleanProperty.create( "top" ); + static final BooleanProperty BOTTOM = BooleanProperty.create( "bottom" ); + private static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; - public BlockPrinter( Settings settings ) + public BlockPrinter( Properties settings ) { super( settings, ComputerCraftRegistry.ModTiles.PRINTER ); - setDefaultState( getStateManager().getDefaultState() - .with( FACING, Direction.NORTH ) - .with( TOP, false ) - .with( BOTTOM, false ) ); + registerDefaultState( getStateDefinition().any() + .setValue( FACING, Direction.NORTH ) + .setValue( TOP, false ) + .setValue( BOTTOM, false ) ); } @Nullable @Override - public BlockState getPlacementState( ItemPlacementContext placement ) + public BlockState getStateForPlacement( BlockPlaceContext placement ) { - return getDefaultState().with( FACING, - placement.getPlayerFacing() + return defaultBlockState().setValue( FACING, + placement.getHorizontalDirection() .getOpposite() ); } @Override - public void afterBreak( @Nonnull World world, @Nonnull PlayerEntity player, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable BlockEntity te, @Nonnull ItemStack stack ) + public void playerDestroy( @Nonnull Level world, @Nonnull Player player, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable BlockEntity te, @Nonnull ItemStack stack ) { if( te instanceof Nameable && ((Nameable) te).hasCustomName() ) { - player.incrementStat( Stats.MINED.getOrCreateStat( this ) ); - player.addExhaustion( 0.005F ); + player.awardStat( Stats.BLOCK_MINED.get( this ) ); + player.causeFoodExhaustion( 0.005F ); ItemStack result = new ItemStack( this ); - result.setCustomName( ((Nameable) te).getCustomName() ); - dropStack( world, pos, result ); + result.setHoverName( ((Nameable) te).getCustomName() ); + popResource( world, pos, result ); } else { - super.afterBreak( world, player, pos, state, te, stack ); + super.playerDestroy( world, player, pos, state, te, stack ); } } @Override - public void onPlaced( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, ItemStack stack ) + public void setPlacedBy( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState state, LivingEntity placer, ItemStack stack ) { - if( stack.hasCustomName() ) + if( stack.hasCustomHoverName() ) { BlockEntity tileentity = world.getBlockEntity( pos ); if( tileentity instanceof TilePrinter ) { - ((TilePrinter) tileentity).customName = stack.getName(); + ((TilePrinter) tileentity).customName = stack.getHoverName(); } } } @Override - protected void appendProperties( StateManager.Builder properties ) + protected void createBlockStateDefinition( StateDefinition.Builder properties ) { properties.add( FACING, TOP, BOTTOM ); } @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TilePrinter( ComputerCraftRegistry.ModTiles.PRINTER, pos, state ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/printer/ContainerPrinter.java b/src/main/java/dan200/computercraft/shared/peripheral/printer/ContainerPrinter.java index 4b94cb54d..0e0e04e16 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/printer/ContainerPrinter.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/printer/ContainerPrinter.java @@ -8,35 +8,35 @@ package dan200.computercraft.shared.peripheral.printer; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.util.SingleIntArray; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.ArrayPropertyDelegate; -import net.minecraft.screen.PropertyDelegate; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.screen.slot.Slot; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ContainerData; +import net.minecraft.world.inventory.SimpleContainerData; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; -public class ContainerPrinter extends ScreenHandler +public class ContainerPrinter extends AbstractContainerMenu { - private final Inventory inventory; - private final PropertyDelegate properties; + private final Container inventory; + private final ContainerData properties; - public ContainerPrinter( int id, PlayerInventory player ) + public ContainerPrinter( int id, Inventory player ) { - this( id, player, new SimpleInventory( TilePrinter.SLOTS ), new ArrayPropertyDelegate( 1 ) ); + this( id, player, new SimpleContainer( TilePrinter.SLOTS ), new SimpleContainerData( 1 ) ); } - private ContainerPrinter( int id, PlayerInventory player, Inventory inventory, PropertyDelegate properties ) + private ContainerPrinter( int id, Inventory player, Container inventory, ContainerData properties ) { super( ComputerCraftRegistry.ModContainers.PRINTER, id ); this.properties = properties; this.inventory = inventory; - addProperties( properties ); + addDataSlots( properties ); // Ink slot addSlot( new Slot( inventory, 0, 13, 35 ) ); @@ -69,7 +69,7 @@ public class ContainerPrinter extends ScreenHandler } } - public ContainerPrinter( int id, PlayerInventory player, TilePrinter printer ) + public ContainerPrinter( int id, Inventory player, TilePrinter printer ) { this( id, player, printer, (SingleIntArray) () -> printer.isPrinting() ? 1 : 0 ); } @@ -81,19 +81,19 @@ public class ContainerPrinter extends ScreenHandler @Nonnull @Override - public ItemStack transferSlot( @Nonnull PlayerEntity player, int index ) + public ItemStack quickMoveStack( @Nonnull Player player, int index ) { Slot slot = slots.get( index ); - if( slot == null || !slot.hasStack() ) + if( slot == null || !slot.hasItem() ) { return ItemStack.EMPTY; } - ItemStack stack = slot.getStack(); + ItemStack stack = slot.getItem(); ItemStack result = stack.copy(); if( index < 13 ) { // Transfer from printer to inventory - if( !insertItem( stack, 13, 49, true ) ) + if( !moveItemStackTo( stack, 13, 49, true ) ) { return ItemStack.EMPTY; } @@ -103,14 +103,14 @@ public class ContainerPrinter extends ScreenHandler // Transfer from inventory to printer if( TilePrinter.isInk( stack ) ) { - if( !insertItem( stack, 0, 1, false ) ) + if( !moveItemStackTo( stack, 0, 1, false ) ) { return ItemStack.EMPTY; } } else //if is paper { - if( !insertItem( stack, 1, 13, false ) ) + if( !moveItemStackTo( stack, 1, 13, false ) ) { return ItemStack.EMPTY; } @@ -119,11 +119,11 @@ public class ContainerPrinter extends ScreenHandler if( stack.isEmpty() ) { - slot.setStack( ItemStack.EMPTY ); + slot.set( ItemStack.EMPTY ); } else { - slot.markDirty(); + slot.setChanged(); } if( stack.getCount() == result.getCount() ) @@ -131,13 +131,13 @@ public class ContainerPrinter extends ScreenHandler return ItemStack.EMPTY; } - slot.onTakeItem( player, stack ); + slot.onTake( player, stack ); return result; } @Override - public boolean canUse( @Nonnull PlayerEntity player ) + public boolean stillValid( @Nonnull Player player ) { - return inventory.canPlayerUse( player ); + return inventory.stillValid( player ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java b/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java index d38eb04e1..7f8dd4737 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/printer/TilePrinter.java @@ -15,33 +15,29 @@ import dan200.computercraft.shared.util.ColourUtils; import dan200.computercraft.shared.util.DefaultSidedInventory; import dan200.computercraft.shared.util.ItemStorage; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.Inventories; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.DyeColor; -import net.minecraft.util.Hand; -import net.minecraft.util.Nameable; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.*; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public final class TilePrinter extends TileGeneric implements DefaultSidedInventory, IPeripheralTile, Nameable, NamedScreenHandlerFactory +public final class TilePrinter extends TileGeneric implements DefaultSidedInventory, IPeripheralTile, Nameable, MenuProvider { static final int SLOTS = 13; private static final String NBT_NAME = "CustomName"; @@ -64,10 +60,10 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent 6, }; private static final int[] SIDE_SLOTS = new int[] { 0 }; - private final DefaultedList inventory = DefaultedList.ofSize( SLOTS, ItemStack.EMPTY ); + private final NonNullList inventory = NonNullList.withSize( SLOTS, ItemStack.EMPTY ); private final ItemStorage itemHandlerAll = ItemStorage.wrap( this ); private final Terminal page = new Terminal( ItemPrintout.LINE_MAX_LENGTH, ItemPrintout.LINES_PER_PAGE ); - Text customName; + Component customName; private String pageTitle = ""; private boolean printing = false; @@ -84,18 +80,18 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { - if( player.isInSneakingPose() ) + if( player.isCrouching() ) { - return ActionResult.PASS; + return InteractionResult.PASS; } - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { - player.openHandledScreen( this ); + player.openMenu( this ); } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } private void ejectContents() @@ -106,11 +102,11 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent if( !stack.isEmpty() ) { // Remove the stack from the inventory - setStack( i, ItemStack.EMPTY ); + setItem( i, ItemStack.EMPTY ); // Spawn the item in the world - WorldUtil.dropItemStack( stack, getWorld(), - Vec3d.of( getPos() ) + WorldUtil.dropItemStack( stack, getLevel(), + Vec3.atLowerCornerOf( getBlockPos() ) .add( 0.5, 0.75, 0.5 ) ); } } @@ -149,28 +145,28 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent private void updateBlockState( boolean top, boolean bottom ) { - if( removed ) + if( remove ) { return; } - BlockState state = getCachedState(); - if( state.get( BlockPrinter.TOP ) == top & state.get( BlockPrinter.BOTTOM ) == bottom ) + BlockState state = getBlockState(); + if( state.getValue( BlockPrinter.TOP ) == top & state.getValue( BlockPrinter.BOTTOM ) == bottom ) { return; } - getWorld().setBlockState( getPos(), - state.with( BlockPrinter.TOP, top ) - .with( BlockPrinter.BOTTOM, bottom ) ); + getLevel().setBlockAndUpdate( getBlockPos(), + state.setValue( BlockPrinter.TOP, top ) + .setValue( BlockPrinter.BOTTOM, bottom ) ); } @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); + super.load( nbt ); - customName = nbt.contains( NBT_NAME ) ? Text.Serializer.fromJson( nbt.getString( NBT_NAME ) ) : null; + customName = nbt.contains( NBT_NAME ) ? Component.Serializer.fromJson( nbt.getString( NBT_NAME ) ) : null; // Read page synchronized( page ) @@ -181,16 +177,16 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent } // Read inventory - Inventories.readNbt( nbt, inventory ); + ContainerHelper.loadAllItems( nbt, inventory ); } @Nonnull @Override - public NbtCompound writeNbt( @Nonnull NbtCompound nbt ) + public CompoundTag save( @Nonnull CompoundTag nbt ) { if( customName != null ) { - nbt.putString( NBT_NAME, Text.Serializer.toJson( customName ) ); + nbt.putString( NBT_NAME, Component.Serializer.toJson( customName ) ); } // Write page @@ -202,9 +198,9 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent } // Write inventory - Inventories.writeNbt( nbt, inventory ); + ContainerHelper.saveAllItems( nbt, inventory ); - return super.writeNbt( nbt ); + return super.save( nbt ); } boolean isPrinting() @@ -214,7 +210,7 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent // IInventory implementation @Override - public int size() + public int getContainerSize() { return inventory.size(); } @@ -234,14 +230,14 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent @Nonnull @Override - public ItemStack getStack( int slot ) + public ItemStack getItem( int slot ) { return inventory.get( slot ); } @Nonnull @Override - public ItemStack removeStack( int slot, int count ) + public ItemStack removeItem( int slot, int count ) { ItemStack stack = inventory.get( slot ); if( stack.isEmpty() ) @@ -251,7 +247,7 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent if( stack.getCount() <= count ) { - setStack( slot, ItemStack.EMPTY ); + setItem( slot, ItemStack.EMPTY ); return stack; } @@ -262,17 +258,17 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent inventory.set( slot, ItemStack.EMPTY ); updateBlockState(); } - markDirty(); + setChanged(); return part; } @Nonnull @Override - public ItemStack removeStack( int slot ) + public ItemStack removeItemNoUpdate( int slot ) { ItemStack result = inventory.get( slot ); inventory.set( slot, ItemStack.EMPTY ); - markDirty(); + setChanged(); updateBlockState(); return result; } @@ -280,32 +276,32 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent // ISidedInventory implementation @Override - public void setStack( int slot, @Nonnull ItemStack stack ) + public void setItem( int slot, @Nonnull ItemStack stack ) { inventory.set( slot, stack ); - markDirty(); + setChanged(); updateBlockState(); } @Override - public boolean canPlayerUse( @Nonnull PlayerEntity playerEntity ) + public boolean stillValid( @Nonnull Player playerEntity ) { return isUsable( playerEntity, false ); } @Override - public void clear() + public void clearContent() { for( int i = 0; i < inventory.size(); i++ ) { inventory.set( i, ItemStack.EMPTY ); } - markDirty(); + setChanged(); updateBlockState(); } @Override - public boolean isValid( int slot, @Nonnull ItemStack stack ) + public boolean canPlaceItem( int slot, @Nonnull ItemStack stack ) { if( slot == 0 ) { @@ -328,7 +324,7 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent @Nonnull @Override - public int[] getAvailableSlots( @Nonnull Direction side ) + public int[] getSlotsForFace( @Nonnull Direction side ) { switch( side ) { @@ -400,7 +396,7 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent if( inventory.get( slot ) .isEmpty() ) { - setStack( slot, stack ); + setItem( slot, stack ); printing = false; return true; } @@ -480,21 +476,21 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent page.setCursorPos( 0, 0 ); // Decrement ink - inkStack.decrement( 1 ); + inkStack.shrink( 1 ); if( inkStack.isEmpty() ) { inventory.set( 0, ItemStack.EMPTY ); } // Decrement paper - paperStack.decrement( 1 ); + paperStack.shrink( 1 ); if( paperStack.isEmpty() ) { inventory.set( i, ItemStack.EMPTY ); updateBlockState(); } - markDirty(); + setChanged(); printing = true; return true; } @@ -503,10 +499,10 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent @Nonnull @Override - public Text getName() + public Component getName() { - return customName != null ? customName : new TranslatableText( getCachedState().getBlock() - .getTranslationKey() ); + return customName != null ? customName : new TranslatableComponent( getBlockState().getBlock() + .getDescriptionId() ); } @Override @@ -516,21 +512,21 @@ public final class TilePrinter extends TileGeneric implements DefaultSidedInvent } @Override - public Text getDisplayName() + public Component getDisplayName() { return Nameable.super.getDisplayName(); } @Nullable @Override - public Text getCustomName() + public Component getCustomName() { return customName; } @Nonnull @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory inventory, @Nonnull PlayerEntity player ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory inventory, @Nonnull Player player ) { return new ContainerPrinter( id, inventory, this ); } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/speaker/BlockSpeaker.java b/src/main/java/dan200/computercraft/shared/peripheral/speaker/BlockSpeaker.java index 34405b92b..73ac34bfc 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/speaker/BlockSpeaker.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/speaker/BlockSpeaker.java @@ -8,59 +8,59 @@ package dan200.computercraft.shared.peripheral.speaker; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.common.BlockGeneric; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityTicker; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.DirectionProperty; import javax.annotation.Nullable; public class BlockSpeaker extends BlockGeneric { - private static final DirectionProperty FACING = Properties.HORIZONTAL_FACING; + private static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; - public BlockSpeaker( Settings settings ) + public BlockSpeaker( Properties settings ) { super( settings, ComputerCraftRegistry.ModTiles.SPEAKER ); - setDefaultState( getStateManager().getDefaultState() - .with( FACING, Direction.NORTH ) ); + registerDefaultState( getStateDefinition().any() + .setValue( FACING, Direction.NORTH ) ); } @Nullable @Override - public BlockState getPlacementState( ItemPlacementContext placement ) + public BlockState getStateForPlacement( BlockPlaceContext placement ) { - return getDefaultState().with( FACING, - placement.getPlayerFacing() + return defaultBlockState().setValue( FACING, + placement.getHorizontalDirection() .getOpposite() ); } @Override - protected void appendProperties( StateManager.Builder properties ) + protected void createBlockStateDefinition( StateDefinition.Builder properties ) { properties.add( FACING ); } @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileSpeaker( ComputerCraftRegistry.ModTiles.SPEAKER, pos, state ); } @Nullable @Override - public BlockEntityTicker getTicker( World world, BlockState state, BlockEntityType type ) + public BlockEntityTicker getTicker( Level world, BlockState state, BlockEntityType type ) { - return world.isClient ? null : BlockSpeaker.checkType( type, ComputerCraftRegistry.ModTiles.SPEAKER, TileSpeaker::tick ); + return world.isClientSide ? null : BlockSpeaker.createTickerHelper( type, ComputerCraftRegistry.ModTiles.SPEAKER, TileSpeaker::tick ); } } diff --git a/src/main/java/dan200/computercraft/shared/peripheral/speaker/SpeakerPeripheral.java b/src/main/java/dan200/computercraft/shared/peripheral/speaker/SpeakerPeripheral.java index a74ea4849..88c5655d1 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/speaker/SpeakerPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/speaker/SpeakerPeripheral.java @@ -14,16 +14,16 @@ import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.network.client.SpeakerMoveClientMessage; import dan200.computercraft.shared.network.client.SpeakerPlayClientMessage; -import net.minecraft.block.enums.Instrument; -import net.minecraft.network.packet.s2c.play.PlaySoundIdS2CPacket; +import net.minecraft.ResourceLocationException; +import net.minecraft.core.BlockPos; +import net.minecraft.network.protocol.game.ClientboundCustomSoundPacket; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.sound.SoundCategory; -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.properties.NoteBlockInstrument; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.Optional; @@ -46,7 +46,7 @@ public abstract class SpeakerPeripheral implements IPeripheral private long lastPlayTime = 0; private long lastPositionTime; - private Vec3d lastPosition; + private Vec3 lastPosition; public void update() { @@ -58,14 +58,14 @@ public abstract class SpeakerPeripheral implements IPeripheral // in the last second. if( lastPlayTime > 0 && (clock - lastPositionTime) >= 20 ) { - Vec3d position = getPosition(); + Vec3 position = getPosition(); if( lastPosition == null || lastPosition.distanceTo( position ) >= 0.1 ) { lastPosition = position; lastPositionTime = clock; NetworkHandler.sendToAllTracking( new SpeakerMoveClientMessage( getSource(), position ), - getWorld().getWorldChunk( new BlockPos( position ) ) + getWorld().getChunkAt( new BlockPos( position ) ) ); } } @@ -104,12 +104,12 @@ public abstract class SpeakerPeripheral implements IPeripheral float volume = (float) checkFinite( 1, volumeA.orElse( 1.0 ) ); float pitch = (float) checkFinite( 2, pitchA.orElse( 1.0 ) ); - Identifier identifier; + ResourceLocation identifier; try { - identifier = new Identifier( name ); + identifier = new ResourceLocation( name ); } - catch( InvalidIdentifierException e ) + catch( ResourceLocationException e ) { throw new LuaException( "Malformed sound name '" + name + "' " ); } @@ -117,7 +117,7 @@ public abstract class SpeakerPeripheral implements IPeripheral return playSound( context, identifier, volume, pitch, false ); } - private synchronized boolean playSound( ILuaContext context, Identifier name, float volume, float pitch, boolean isNote ) throws LuaException + private synchronized boolean playSound( ILuaContext context, ResourceLocation name, float volume, float pitch, boolean isNote ) throws LuaException { if( clock - lastPlayTime < MIN_TICKS_BETWEEN_SOUNDS ) { @@ -127,10 +127,10 @@ public abstract class SpeakerPeripheral implements IPeripheral if( clock - lastPlayTime != 0 || notesThisTick.get() >= ComputerCraft.maxNotesPerTick ) return false; } - World world = getWorld(); - Vec3d pos = getPosition(); + Level world = getWorld(); + Vec3 pos = getPosition(); - float actualVolume = MathHelper.clamp( volume, 0.0f, 3.0f ); + float actualVolume = Mth.clamp( volume, 0.0f, 3.0f ); float range = actualVolume * 16; context.issueMainThreadTask( () -> { @@ -142,9 +142,9 @@ public abstract class SpeakerPeripheral implements IPeripheral if( isNote ) { - server.getPlayerManager().sendToAround( - null, pos.x, pos.y, pos.z, range, world.getRegistryKey(), - new PlaySoundIdS2CPacket( name, SoundCategory.RECORDS, pos, actualVolume, pitch ) + server.getPlayerList().broadcast( + null, pos.x, pos.y, pos.z, range, world.dimension(), + new ClientboundCustomSoundPacket( name, SoundSource.RECORDS, pos, actualVolume, pitch ) ); } else @@ -161,9 +161,9 @@ public abstract class SpeakerPeripheral implements IPeripheral return true; } - public abstract World getWorld(); + public abstract Level getWorld(); - public abstract Vec3d getPosition(); + public abstract Vec3 getPosition(); /** * Plays a note block note through the speaker. @@ -186,10 +186,10 @@ public abstract class SpeakerPeripheral implements IPeripheral float volume = (float) checkFinite( 1, volumeA.orElse( 1.0 ) ); float pitch = (float) checkFinite( 2, pitchA.orElse( 1.0 ) ); - Instrument instrument = null; - for( Instrument testInstrument : Instrument.values() ) + NoteBlockInstrument instrument = null; + for( NoteBlockInstrument testInstrument : NoteBlockInstrument.values() ) { - if( testInstrument.asString() + if( testInstrument.getSerializedName() .equalsIgnoreCase( name ) ) { instrument = testInstrument; @@ -205,7 +205,7 @@ public abstract class SpeakerPeripheral implements IPeripheral // If the resource location for note block notes changes, this method call will need to be updated boolean success = playSound( context, - instrument.getSound().getId(), + instrument.getSoundEvent().getLocation(), volume, (float) Math.pow( 2.0, (pitch - 12.0) / 12.0 ), true ); diff --git a/src/main/java/dan200/computercraft/shared/peripheral/speaker/TileSpeaker.java b/src/main/java/dan200/computercraft/shared/peripheral/speaker/TileSpeaker.java index 2a0de631e..336d81ca2 100644 --- a/src/main/java/dan200/computercraft/shared/peripheral/speaker/TileSpeaker.java +++ b/src/main/java/dan200/computercraft/shared/peripheral/speaker/TileSpeaker.java @@ -9,12 +9,12 @@ package dan200.computercraft.shared.peripheral.speaker; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.peripheral.IPeripheralTile; import dan200.computercraft.shared.common.TileGeneric; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,7 +33,7 @@ public class TileSpeaker extends TileGeneric implements IPeripheralTile peripheral = new Peripheral( this ); } - public static void tick( World world, BlockPos pos, BlockState state, TileSpeaker tileSpeaker ) + public static void tick( Level world, BlockPos pos, BlockState state, TileSpeaker tileSpeaker ) { tileSpeaker.peripheral.update(); } @@ -55,16 +55,16 @@ public class TileSpeaker extends TileGeneric implements IPeripheralTile } @Override - public World getWorld() + public Level getWorld() { - return speaker.getWorld(); + return speaker.getLevel(); } @Override - public Vec3d getPosition() + public Vec3 getPosition() { - BlockPos pos = speaker.getPos(); - return new Vec3d( pos.getX(), pos.getY(), pos.getZ() ); + BlockPos pos = speaker.getBlockPos(); + return new Vec3( pos.getX(), pos.getY(), pos.getZ() ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java b/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java index fec1ce9ef..847b37d19 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java +++ b/src/main/java/dan200/computercraft/shared/pocket/apis/PocketAPI.java @@ -14,11 +14,11 @@ import dan200.computercraft.shared.pocket.core.PocketServerComputer; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.ItemStorage; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.core.NonNullList; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; /** * Control the current pocket computer, adding or removing upgrades. @@ -63,20 +63,20 @@ public class PocketAPI implements ILuaAPI public final Object[] equipBack() { Entity entity = computer.getEntity(); - if( !(entity instanceof PlayerEntity) ) + if( !(entity instanceof Player) ) { return new Object[] { false, "Cannot find player" }; } - PlayerEntity player = (PlayerEntity) entity; - PlayerInventory inventory = player.getInventory(); + Player player = (Player) entity; + Inventory inventory = player.getInventory(); IPocketUpgrade previousUpgrade = computer.getUpgrade(); // Attempt to find the upgrade, starting in the main segment, and then looking in the opposite // one. We start from the position the item is currently in and loop round to the start. - IPocketUpgrade newUpgrade = findUpgrade( inventory.main, inventory.selectedSlot, previousUpgrade ); + IPocketUpgrade newUpgrade = findUpgrade( inventory.items, inventory.selected, previousUpgrade ); if( newUpgrade == null ) { - newUpgrade = findUpgrade( inventory.offHand, 0, previousUpgrade ); + newUpgrade = findUpgrade( inventory.offhand, 0, previousUpgrade ); } if( newUpgrade == null ) { @@ -89,10 +89,10 @@ public class PocketAPI implements ILuaAPI ItemStack stack = previousUpgrade.getCraftingItem(); if( !stack.isEmpty() ) { - stack = InventoryUtil.storeItems( stack, ItemStorage.wrap( inventory ), inventory.selectedSlot ); + stack = InventoryUtil.storeItems( stack, ItemStorage.wrap( inventory ), inventory.selected ); if( !stack.isEmpty() ) { - WorldUtil.dropItemStack( stack, player.getEntityWorld(), player.getPos() ); + WorldUtil.dropItemStack( stack, player.getCommandSenderWorld(), player.position() ); } } } @@ -103,7 +103,7 @@ public class PocketAPI implements ILuaAPI return new Object[] { true }; } - private static IPocketUpgrade findUpgrade( DefaultedList inv, int start, IPocketUpgrade previous ) + private static IPocketUpgrade findUpgrade( NonNullList inv, int start, IPocketUpgrade previous ) { for( int i = 0; i < inv.size(); i++ ) { @@ -116,7 +116,7 @@ public class PocketAPI implements ILuaAPI { // Consume an item from this stack and exit the loop invStack = invStack.copy(); - invStack.decrement( 1 ); + invStack.shrink( 1 ); inv.set( (i + start) % inv.size(), invStack.isEmpty() ? ItemStack.EMPTY : invStack ); return newUpgrade; @@ -138,12 +138,12 @@ public class PocketAPI implements ILuaAPI public final Object[] unequipBack() { Entity entity = computer.getEntity(); - if( !(entity instanceof PlayerEntity) ) + if( !(entity instanceof Player) ) { return new Object[] { false, "Cannot find player" }; } - PlayerEntity player = (PlayerEntity) entity; - PlayerInventory inventory = player.getInventory(); + Player player = (Player) entity; + Inventory inventory = player.getInventory(); IPocketUpgrade previousUpgrade = computer.getUpgrade(); if( previousUpgrade == null ) @@ -156,10 +156,10 @@ public class PocketAPI implements ILuaAPI ItemStack stack = previousUpgrade.getCraftingItem(); if( !stack.isEmpty() ) { - stack = InventoryUtil.storeItems( stack, ItemStorage.wrap( inventory ), inventory.selectedSlot ); + stack = InventoryUtil.storeItems( stack, ItemStorage.wrap( inventory ), inventory.selected ); if( stack.isEmpty() ) { - WorldUtil.dropItemStack( stack, player.getEntityWorld(), player.getPos() ); + WorldUtil.dropItemStack( stack, player.getCommandSenderWorld(), player.position() ); } } diff --git a/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java b/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java index 56b2e615a..59abef12b 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java +++ b/src/main/java/dan200/computercraft/shared/pocket/core/PocketServerComputer.java @@ -17,15 +17,15 @@ import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.pocket.items.ItemPocketComputer; import dan200.computercraft.shared.util.NBTUtil; -import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.util.Identifier; -import net.minecraft.world.World; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -40,7 +40,7 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces private Entity entity; private ItemStack stack; - public PocketServerComputer( World world, int computerID, String label, int instanceID, ComputerFamily family ) + public PocketServerComputer( Level world, int computerID, String label, int instanceID, ComputerFamily family ) { super( world, computerID, label, instanceID, family, ComputerCraft.pocketTermWidth, ComputerCraft.pocketTermHeight ); } @@ -55,15 +55,15 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces return null; } - if( entity instanceof PlayerEntity ) + if( entity instanceof Player ) { - PlayerInventory inventory = ((PlayerEntity) entity).getInventory(); - return inventory.main.contains( stack ) || inventory.offHand.contains( stack ) ? entity : null; + Inventory inventory = ((Player) entity).getInventory(); + return inventory.items.contains( stack ) || inventory.offhand.contains( stack ) ? entity : null; } else if( entity instanceof LivingEntity ) { LivingEntity living = (LivingEntity) entity; - return living.getMainHandStack() == stack || living.getOffHandStack() == stack ? entity : null; + return living.getMainHandItem() == stack || living.getOffhandItem() == stack ? entity : null; } else { @@ -87,14 +87,14 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces @Override public int getLight() { - NbtCompound tag = getUserData(); + CompoundTag tag = getUserData(); return tag.contains( NBT_LIGHT, NBTUtil.TAG_ANY_NUMERIC ) ? tag.getInt( NBT_LIGHT ) : -1; } @Override public void setLight( int colour ) { - NbtCompound tag = getUserData(); + CompoundTag tag = getUserData(); if( colour >= 0 && colour <= 0xFFFFFF ) { if( !tag.contains( NBT_LIGHT, NBTUtil.TAG_ANY_NUMERIC ) || tag.getInt( NBT_LIGHT ) != colour ) @@ -112,7 +112,7 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces @Nonnull @Override - public NbtCompound getUpgradeNBTData() + public CompoundTag getUpgradeNBTData() { return ItemPocketComputer.getUpgradeInfo( stack ); } @@ -120,9 +120,9 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces @Override public void updateUpgradeNBTData() { - if( entity instanceof PlayerEntity ) + if( entity instanceof Player ) { - ((PlayerEntity) entity).getInventory().markDirty(); + ((Player) entity).getInventory().setChanged(); } } @@ -135,7 +135,7 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces @Nonnull @Override - public Map getUpgrades() + public Map getUpgrades() { return upgrade == null ? Collections.emptyMap() : Collections.singletonMap( upgrade.getUpgradeID(), getPeripheral( ComputerSide.BACK ) ); } @@ -172,12 +172,12 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces { if( entity != null ) { - setWorld( entity.getEntityWorld() ); - setPosition( entity.getBlockPos() ); + setWorld( entity.getCommandSenderWorld() ); + setPosition( entity.blockPosition() ); } // If a new entity has picked it up then rebroadcast the terminal to them - if( entity != this.entity && entity instanceof ServerPlayerEntity ) + if( entity != this.entity && entity instanceof ServerPlayer ) { markTerminalChanged(); } @@ -197,11 +197,11 @@ public class PocketServerComputer extends ServerComputer implements IPocketAcces { super.broadcastState( force ); - if( (hasTerminalChanged() || force) && entity instanceof ServerPlayerEntity ) + if( (hasTerminalChanged() || force) && entity instanceof ServerPlayer ) { // Broadcast the state to the current entity if they're not already interacting with it. - ServerPlayerEntity player = (ServerPlayerEntity) entity; - if( player.networkHandler != null && !isInteracting( player ) ) + ServerPlayer player = (ServerPlayer) entity; + if( player.connection != null && !isInteracting( player ) ) { NetworkHandler.sendToPlayer( player, createTerminalPacket() ); } diff --git a/src/main/java/dan200/computercraft/shared/pocket/inventory/PocketComputerMenuProvider.java b/src/main/java/dan200/computercraft/shared/pocket/inventory/PocketComputerMenuProvider.java index 2e1a066c2..8cef2a65c 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/inventory/PocketComputerMenuProvider.java +++ b/src/main/java/dan200/computercraft/shared/pocket/inventory/PocketComputerMenuProvider.java @@ -10,31 +10,31 @@ import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.computer.inventory.ComputerMenuWithoutInventory; import dan200.computercraft.shared.pocket.items.ItemPocketComputer; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerFactory; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.text.Text; -import net.minecraft.util.Hand; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class PocketComputerMenuProvider implements NamedScreenHandlerFactory, ExtendedScreenHandlerFactory +public class PocketComputerMenuProvider implements MenuProvider, ExtendedScreenHandlerFactory { private final ServerComputer computer; - private final Text name; + private final Component name; private final ItemPocketComputer item; - private final Hand hand; + private final InteractionHand hand; private final boolean isTypingOnly; - public PocketComputerMenuProvider( ServerComputer computer, ItemStack stack, ItemPocketComputer item, Hand hand, boolean isTypingOnly ) + public PocketComputerMenuProvider( ServerComputer computer, ItemStack stack, ItemPocketComputer item, InteractionHand hand, boolean isTypingOnly ) { this.computer = computer; - name = stack.getName(); + name = stack.getHoverName(); this.item = item; this.hand = hand; this.isTypingOnly = isTypingOnly; @@ -43,19 +43,19 @@ public class PocketComputerMenuProvider implements NamedScreenHandlerFactory, Ex @Nonnull @Override - public Text getDisplayName() + public Component getDisplayName() { return name; } @Nullable @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory inventory, @Nonnull PlayerEntity entity ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory inventory, @Nonnull Player entity ) { return new ComputerMenuWithoutInventory( isTypingOnly ? ComputerCraftRegistry.ModContainers.POCKET_COMPUTER_NO_TERM : ComputerCraftRegistry.ModContainers.POCKET_COMPUTER, id, inventory, p -> { - ItemStack stack = p.getStackInHand( hand ); + ItemStack stack = p.getItemInHand( hand ); return stack.getItem() == item && ItemPocketComputer.getServerComputer( stack ) == computer; }, computer, item.getFamily() @@ -63,9 +63,9 @@ public class PocketComputerMenuProvider implements NamedScreenHandlerFactory, Ex } @Override - public void writeScreenOpeningData( ServerPlayerEntity player, PacketByteBuf packetByteBuf ) + public void writeScreenOpeningData( ServerPlayer player, FriendlyByteBuf packetByteBuf ) { packetByteBuf.writeInt( computer.getInstanceID() ); - packetByteBuf.writeEnumConstant( computer.getFamily() ); + packetByteBuf.writeEnum( computer.getFamily() ); } } diff --git a/src/main/java/dan200/computercraft/shared/pocket/items/ItemPocketComputer.java b/src/main/java/dan200/computercraft/shared/pocket/items/ItemPocketComputer.java index 69d586869..b98426359 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/items/ItemPocketComputer.java +++ b/src/main/java/dan200/computercraft/shared/pocket/items/ItemPocketComputer.java @@ -26,23 +26,23 @@ import dan200.computercraft.shared.pocket.core.PocketServerComputer; import dan200.computercraft.shared.pocket.inventory.PocketComputerMenuProvider; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.item.TooltipContext; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Formatting; -import net.minecraft.util.Hand; -import net.minecraft.util.TypedActionResult; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.ChatFormatting; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.Container; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -58,7 +58,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I private final ComputerFamily family; - public ItemPocketComputer( Settings settings, ComputerFamily family ) + public ItemPocketComputer( Properties settings, ComputerFamily family ) { super( settings ); this.family = family; @@ -92,7 +92,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I ClientComputer computer = getClientComputer( stack ); if( computer != null && computer.isOn() ) { - NbtCompound computerNBT = computer.getUserData(); + CompoundTag computerNBT = computer.getUserData(); if( computerNBT != null && computerNBT.contains( NBT_LIGHT ) ) { return computerNBT.getInt( NBT_LIGHT ); @@ -103,7 +103,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I public static void setUpgrade( @Nonnull ItemStack stack, IPocketUpgrade upgrade ) { - NbtCompound compound = stack.getOrCreateNbt(); + CompoundTag compound = stack.getOrCreateTag(); if( upgrade == null ) { @@ -119,9 +119,9 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I compound.remove( NBT_UPGRADE_INFO ); } - public static NbtCompound getUpgradeInfo( @Nonnull ItemStack stack ) + public static CompoundTag getUpgradeInfo( @Nonnull ItemStack stack ) { - return stack.getOrCreateSubNbt( NBT_UPGRADE_INFO ); + return stack.getOrCreateTagElement( NBT_UPGRADE_INFO ); } // @Nullable @@ -142,10 +142,10 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I @Nonnull @Override - public TypedActionResult use( World world, PlayerEntity player, @Nonnull Hand hand ) + public InteractionResultHolder use( Level world, Player player, @Nonnull InteractionHand hand ) { - ItemStack stack = player.getStackInHand( hand ); - if( !world.isClient ) + ItemStack stack = player.getItemInHand( hand ); + if( !world.isClientSide ) { PocketServerComputer computer = createServerComputer( world, player.getInventory(), player, stack ); @@ -164,20 +164,20 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I if( !stop && computer != null ) { - boolean isTypingOnly = hand == Hand.OFF_HAND; + boolean isTypingOnly = hand == InteractionHand.OFF_HAND; new ComputerContainerData( computer ).open( player, new PocketComputerMenuProvider( computer, stack, this, hand, isTypingOnly ) ); } } - return new TypedActionResult<>( ActionResult.SUCCESS, stack ); + return new InteractionResultHolder<>( InteractionResult.SUCCESS, stack ); } @Override - public void inventoryTick( @Nonnull ItemStack stack, World world, @Nonnull Entity entity, int slotNum, boolean selected ) + public void inventoryTick( @Nonnull ItemStack stack, Level world, @Nonnull Entity entity, int slotNum, boolean selected ) { - if( !world.isClient ) + if( !world.isClientSide ) { // Server side - Inventory inventory = entity instanceof PlayerEntity ? ((PlayerEntity) entity).getInventory() : null; + Container inventory = entity instanceof Player ? ((Player) entity).getInventory() : null; PocketServerComputer computer = createServerComputer( world, inventory, entity, stack ); if( computer != null ) { @@ -195,7 +195,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I setComputerID( stack, id ); if( inventory != null ) { - inventory.markDirty(); + inventory.setChanged(); } } @@ -206,7 +206,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I setLabel( stack, label ); if( inventory != null ) { - inventory.markDirty(); + inventory.setChanged(); } } @@ -225,27 +225,27 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I } @Override - public void appendTooltip( @Nonnull ItemStack stack, @Nullable World world, @Nonnull List list, TooltipContext flag ) + public void appendHoverText( @Nonnull ItemStack stack, @Nullable Level world, @Nonnull List list, TooltipFlag flag ) { if( flag.isAdvanced() || getLabel( stack ) == null ) { int id = getComputerID( stack ); if( id >= 0 ) { - list.add( new TranslatableText( "gui.computercraft.tooltip.computer_id", id ).formatted( Formatting.GRAY ) ); + list.add( new TranslatableComponent( "gui.computercraft.tooltip.computer_id", id ).withStyle( ChatFormatting.GRAY ) ); } } } @Nonnull @Override - public Text getName( @Nonnull ItemStack stack ) + public Component getName( @Nonnull ItemStack stack ) { - String baseString = getTranslationKey( stack ); + String baseString = getDescriptionId( stack ); IPocketUpgrade upgrade = getUpgrade( stack ); if( upgrade != null ) { - return new TranslatableText( baseString + ".upgraded", new TranslatableText( upgrade.getUnlocalisedAdjective() ) ); + return new TranslatableComponent( baseString + ".upgraded", new TranslatableComponent( upgrade.getUnlocalisedAdjective() ) ); } else { @@ -256,9 +256,9 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I // IComputerItem implementation @Override - public void appendStacks( @Nonnull ItemGroup group, @Nonnull DefaultedList stacks ) + public void fillItemCategory( @Nonnull CreativeModeTab group, @Nonnull NonNullList stacks ) { - if( !isIn( group ) ) + if( !allowdedIn( group ) ) { return; } @@ -274,31 +274,31 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I ItemStack result = new ItemStack( this ); if( id >= 0 ) { - result.getOrCreateNbt() + result.getOrCreateTag() .putInt( NBT_ID, id ); } if( label != null ) { - result.setCustomName( new LiteralText( label ) ); + result.setHoverName( new TextComponent( label ) ); } if( upgrade != null ) { - result.getOrCreateNbt() + result.getOrCreateTag() .putString( NBT_UPGRADE, upgrade.getUpgradeID() .toString() ); } if( colour != -1 ) { - result.getOrCreateNbt() + result.getOrCreateTag() .putInt( NBT_COLOUR, colour ); } return result; } - public PocketServerComputer createServerComputer( final World world, Inventory inventory, Entity entity, @Nonnull ItemStack stack ) + public PocketServerComputer createServerComputer( final Level world, Container inventory, Entity entity, @Nonnull ItemStack stack ) { - if( world.isClient ) + if( world.isClientSide ) { return null; } @@ -332,7 +332,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I ComputerCraft.serverComputerRegistry.add( instanceID, computer ); if( inventory != null ) { - inventory.markDirty(); + inventory.setChanged(); } } computer.setWorld( world ); @@ -341,7 +341,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I public static IPocketUpgrade getUpgrade( @Nonnull ItemStack stack ) { - NbtCompound compound = stack.getNbt(); + CompoundTag compound = stack.getTag(); return compound != null && compound.contains( NBT_UPGRADE ) ? PocketUpgrades.get( compound.getString( NBT_UPGRADE ) ) : null; } @@ -350,7 +350,7 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I private static void setComputerID( @Nonnull ItemStack stack, int computerID ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_ID, computerID ); } @@ -377,11 +377,11 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I { if( label != null ) { - stack.setCustomName( new LiteralText( label ) ); + stack.setHoverName( new TextComponent( label ) ); } else { - stack.removeCustomName(); + stack.resetHoverName(); } return true; } @@ -402,30 +402,30 @@ public class ItemPocketComputer extends Item implements IComputerItem, IMedia, I private static int getInstanceID( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_INSTANCE ) ? nbt.getInt( NBT_INSTANCE ) : -1; } private static int getSessionID( @Nonnull ItemStack stack ) { - NbtCompound nbt = stack.getNbt(); + CompoundTag nbt = stack.getTag(); return nbt != null && nbt.contains( NBT_SESSION ) ? nbt.getInt( NBT_SESSION ) : -1; } private static void setInstanceID( @Nonnull ItemStack stack, int instanceID ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_INSTANCE, instanceID ); } private static void setSessionID( @Nonnull ItemStack stack, int sessionID ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_SESSION, sessionID ); } @Override - public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull World world ) + public IMount createDataMount( @Nonnull ItemStack stack, @Nonnull Level world ) { int id = getComputerID( stack ); if( id >= 0 ) diff --git a/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItemFactory.java b/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItemFactory.java index ac2d7303d..dec881201 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItemFactory.java +++ b/src/main/java/dan200/computercraft/shared/pocket/items/PocketComputerItemFactory.java @@ -9,7 +9,7 @@ package dan200.computercraft.shared.pocket.items; import dan200.computercraft.api.pocket.IPocketUpgrade; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; diff --git a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModem.java b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModem.java index 6ba68d559..2d069d423 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModem.java +++ b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModem.java @@ -11,8 +11,8 @@ import dan200.computercraft.api.pocket.AbstractPocketUpgrade; import dan200.computercraft.api.pocket.IPocketAccess; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.peripheral.modem.ModemState; -import net.minecraft.entity.Entity; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.Entity; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -23,7 +23,7 @@ public class PocketModem extends AbstractPocketUpgrade public PocketModem( boolean advanced ) { - super( new Identifier( "computercraft", advanced ? "wireless_modem_advanced" : "wireless_modem_normal" ), + super( new ResourceLocation( "computercraft", advanced ? "wireless_modem_advanced" : "wireless_modem_normal" ), advanced ? ComputerCraftRegistry.ModBlocks.WIRELESS_MODEM_ADVANCED : ComputerCraftRegistry.ModBlocks.WIRELESS_MODEM_NORMAL ); this.advanced = advanced; } @@ -49,7 +49,7 @@ public class PocketModem extends AbstractPocketUpgrade if( entity != null ) { - modem.setLocation( entity.getEntityWorld(), entity.getCameraPosVec( 1 ) ); + modem.setLocation( entity.getCommandSenderWorld(), entity.getEyePosition( 1 ) ); } ModemState state = modem.getModemState(); diff --git a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModemPeripheral.java b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModemPeripheral.java index d43c860b4..7ed7f6939 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModemPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketModemPeripheral.java @@ -3,28 +3,27 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.pocket.peripherals; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.peripheral.modem.ModemState; import dan200.computercraft.shared.peripheral.modem.wireless.WirelessModemPeripheral; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; public class PocketModemPeripheral extends WirelessModemPeripheral { - private World world = null; - private Vec3d position = Vec3d.ZERO; + private Level world = null; + private Vec3 position = Vec3.ZERO; public PocketModemPeripheral( boolean advanced ) { super( new ModemState(), advanced ); } - void setLocation( World world, Vec3d position ) + void setLocation( Level world, Vec3 position ) { this.position = position; this.world = world; @@ -32,14 +31,14 @@ public class PocketModemPeripheral extends WirelessModemPeripheral @Nonnull @Override - public World getWorld() + public Level getLevel() { return world; } @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { return position; } diff --git a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeaker.java b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeaker.java index b5c98c7ad..8e775eb9d 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeaker.java +++ b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeaker.java @@ -10,8 +10,8 @@ import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.api.pocket.AbstractPocketUpgrade; import dan200.computercraft.api.pocket.IPocketAccess; import dan200.computercraft.shared.ComputerCraftRegistry; -import net.minecraft.entity.Entity; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.Entity; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -20,7 +20,7 @@ public class PocketSpeaker extends AbstractPocketUpgrade { public PocketSpeaker() { - super( new Identifier( "computercraft", "speaker" ), ComputerCraftRegistry.ModBlocks.SPEAKER ); + super( new ResourceLocation( "computercraft", "speaker" ), ComputerCraftRegistry.ModBlocks.SPEAKER ); } @Nullable @@ -43,7 +43,7 @@ public class PocketSpeaker extends AbstractPocketUpgrade Entity entity = access.getEntity(); if( entity != null ) { - speaker.setLocation( entity.getEntityWorld(), entity.getCameraPosVec( 1 ) ); + speaker.setLocation( entity.getCommandSenderWorld(), entity.getEyePosition( 1 ) ); } speaker.update(); diff --git a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeakerPeripheral.java b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeakerPeripheral.java index 315abd72c..366d9ac58 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeakerPeripheral.java +++ b/src/main/java/dan200/computercraft/shared/pocket/peripherals/PocketSpeakerPeripheral.java @@ -8,28 +8,28 @@ package dan200.computercraft.shared.pocket.peripherals; import dan200.computercraft.api.peripheral.IPeripheral; import dan200.computercraft.shared.peripheral.speaker.UpgradeSpeakerPeripheral; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; public class PocketSpeakerPeripheral extends UpgradeSpeakerPeripheral { - private World world = null; - private Vec3d position = Vec3d.ZERO; + private Level world = null; + private Vec3 position = Vec3.ZERO; - void setLocation( World world, Vec3d position ) + void setLocation( Level world, Vec3 position ) { this.position = position; this.world = world; } @Override - public World getWorld() + public Level getWorld() { return world; } @Override - public Vec3d getPosition() + public Vec3 getPosition() { return world != null ? position : null; } diff --git a/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java b/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java index 279a2ad1c..a5c7e78a5 100644 --- a/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java +++ b/src/main/java/dan200/computercraft/shared/pocket/recipes/PocketComputerUpgradeRecipe.java @@ -11,41 +11,41 @@ import dan200.computercraft.shared.PocketUpgrades; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.pocket.items.ItemPocketComputer; import dan200.computercraft.shared.pocket.items.PocketComputerItemFactory; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.SpecialCraftingRecipe; -import net.minecraft.recipe.SpecialRecipeSerializer; -import net.minecraft.util.Identifier; -import net.minecraft.world.World; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; -public final class PocketComputerUpgradeRecipe extends SpecialCraftingRecipe +public final class PocketComputerUpgradeRecipe extends CustomRecipe { - public static final RecipeSerializer SERIALIZER = new SpecialRecipeSerializer<>( PocketComputerUpgradeRecipe::new ); + public static final RecipeSerializer SERIALIZER = new SimpleRecipeSerializer<>( PocketComputerUpgradeRecipe::new ); - private PocketComputerUpgradeRecipe( Identifier identifier ) + private PocketComputerUpgradeRecipe( ResourceLocation identifier ) { super( identifier ); } @Nonnull @Override - public ItemStack getOutput() + public ItemStack getResultItem() { return PocketComputerItemFactory.create( -1, null, -1, ComputerFamily.NORMAL, null ); } @Override - public boolean matches( @Nonnull CraftingInventory inventory, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inventory, @Nonnull Level world ) { - return !craft( inventory ).isEmpty(); + return !assemble( inventory ).isEmpty(); } @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inventory ) + public ItemStack assemble( @Nonnull CraftingContainer inventory ) { // Scan the grid for a pocket computer ItemStack computer = ItemStack.EMPTY; @@ -56,7 +56,7 @@ public final class PocketComputerUpgradeRecipe extends SpecialCraftingRecipe { for( int x = 0; x < inventory.getWidth(); x++ ) { - ItemStack item = inventory.getStack( x + y * inventory.getWidth() ); + ItemStack item = inventory.getItem( x + y * inventory.getWidth() ); if( !item.isEmpty() && item.getItem() instanceof ItemPocketComputer ) { computer = item; @@ -84,7 +84,7 @@ public final class PocketComputerUpgradeRecipe extends SpecialCraftingRecipe { for( int x = 0; x < inventory.getWidth(); x++ ) { - ItemStack item = inventory.getStack( x + y * inventory.getWidth() ); + ItemStack item = inventory.getItem( x + y * inventory.getWidth() ); if( x == computerX && y == computerY ) { continue; @@ -119,7 +119,7 @@ public final class PocketComputerUpgradeRecipe extends SpecialCraftingRecipe } @Override - public boolean fits( int x, int y ) + public boolean canCraftInDimensions( int x, int y ) { return x >= 2 && y >= 2; } diff --git a/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java b/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java index cdbdc0c66..5e875d045 100644 --- a/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java +++ b/src/main/java/dan200/computercraft/shared/proxy/ComputerCraftProxyCommon.java @@ -28,7 +28,6 @@ import dan200.computercraft.shared.peripheral.generic.methods.InventoryMethods; import dan200.computercraft.shared.peripheral.modem.wired.BlockCable; import dan200.computercraft.shared.peripheral.modem.wireless.WirelessNetwork; import dan200.computercraft.shared.turtle.FurnaceRefuelHandler; -import dan200.computercraft.shared.turtle.SignInspectHandler; import dan200.computercraft.shared.util.Config; import dan200.computercraft.shared.util.TickScheduler; import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback; @@ -36,14 +35,14 @@ import net.fabricmc.fabric.api.event.lifecycle.v1.ServerBlockEntityEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.CommandBlockBlockEntity; -import net.minecraft.item.Item; -import net.minecraft.item.MusicDiscItem; -import net.minecraft.loot.condition.LootConditionType; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.RecordItem; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.CommandBlockEntity; +import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType; public final class ComputerCraftProxyCommon { @@ -70,8 +69,8 @@ public final class ComputerCraftProxyCommon ComputerCraftAPI.registerPeripheralProvider( ( world, pos, side ) -> { BlockEntity tile = world.getBlockEntity( pos ); - return ComputerCraft.enableCommandBlock && tile instanceof CommandBlockBlockEntity ? - new CommandBlockPeripheral( (CommandBlockBlockEntity) tile ) : null; + return ComputerCraft.enableCommandBlock && tile instanceof CommandBlockEntity ? + new CommandBlockPeripheral( (CommandBlockEntity) tile ) : null; } ); // Register bundled power providers @@ -84,7 +83,7 @@ public final class ComputerCraftProxyCommon { return (IMedia) item; } - if( item instanceof MusicDiscItem ) + if( item instanceof RecordItem ) { return RecordMedia.INSTANCE; } @@ -126,7 +125,10 @@ public final class ComputerCraftProxyCommon } ); PlayerBlockBreakEvents.BEFORE.register( ( world, player, pos, state, blockEntity ) -> { - if ( state.getBlock() instanceof BlockCable blockCable ) return blockCable.removedByPlayer( state, world, pos, player, false, null ); + if( state.getBlock() instanceof BlockCable blockCable ) + { + return blockCable.removedByPlayer( state, world, pos, player, false, null ); + } return true; } ); @@ -136,7 +138,6 @@ public final class ComputerCraftProxyCommon TurtleEvent.EVENT_BUS.register( FurnaceRefuelHandler.INSTANCE ); TurtleEvent.EVENT_BUS.register( new TurtlePermissions() ); - TurtleEvent.EVENT_BUS.register( new SignInspectHandler() ); } public static void registerLoot() @@ -146,8 +147,8 @@ public final class ComputerCraftProxyCommon registerCondition( "has_id", HasComputerIdLootCondition.TYPE ); } - private static void registerCondition( String name, LootConditionType serializer ) + private static void registerCondition( String name, LootItemConditionType serializer ) { - Registry.register( Registry.LOOT_CONDITION_TYPE, new Identifier( ComputerCraft.MOD_ID, name ), serializer ); + Registry.register( Registry.LOOT_CONDITION_TYPE, new ResourceLocation( ComputerCraft.MOD_ID, name ), serializer ); } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/FurnaceRefuelHandler.java b/src/main/java/dan200/computercraft/shared/turtle/FurnaceRefuelHandler.java index 6ca4aaadd..c8f3ad0a0 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/FurnaceRefuelHandler.java +++ b/src/main/java/dan200/computercraft/shared/turtle/FurnaceRefuelHandler.java @@ -12,9 +12,9 @@ import dan200.computercraft.api.turtle.event.TurtleRefuelEvent; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.ItemStorage; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.block.entity.FurnaceBlockEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.FurnaceBlockEntity; import javax.annotation.Nonnull; @@ -44,14 +44,14 @@ public final class FurnaceRefuelHandler implements TurtleRefuelEvent.Handler // Store the replacement item in the inventory Item replacementStack = stack.getItem() - .getRecipeRemainder(); + .getCraftingRemainingItem(); if( replacementStack != null ) { ItemStack remainder = InventoryUtil.storeItems( new ItemStack( replacementStack ), storage, turtle.getSelectedSlot() ); if( !remainder.isEmpty() ) { WorldUtil.dropItemStack( remainder, - turtle.getWorld(), + turtle.getLevel(), turtle.getPosition(), turtle.getDirection() .getOpposite() ); @@ -63,7 +63,7 @@ public final class FurnaceRefuelHandler implements TurtleRefuelEvent.Handler private static int getFuelPerItem( @Nonnull ItemStack stack ) { - int burnTime = FurnaceBlockEntity.createFuelTimeMap() + int burnTime = FurnaceBlockEntity.getFuel() .getOrDefault( stack.getItem(), 0 ); return (burnTime * 5) / 100; } diff --git a/src/main/java/dan200/computercraft/shared/turtle/SignInspectHandler.java b/src/main/java/dan200/computercraft/shared/turtle/SignInspectHandler.java deleted file mode 100644 index f54c6f882..000000000 --- a/src/main/java/dan200/computercraft/shared/turtle/SignInspectHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * This file is part of ComputerCraft - http://www.computercraft.info - * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. - * Send enquiries to dratcliffe@gmail.com - */ -package dan200.computercraft.shared.turtle; - -import com.google.common.eventbus.Subscribe; -import dan200.computercraft.api.turtle.event.TurtleBlockEvent; -import dan200.computercraft.fabric.mixin.SignBlockEntityAccess; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.SignBlockEntity; - -import java.util.HashMap; -import java.util.Map; - -public class SignInspectHandler -{ - @Subscribe - public void onTurtleInspect( TurtleBlockEvent.Inspect event ) - { - BlockEntity be = event.getWorld().getBlockEntity( event.getPos() ); - if( be instanceof SignBlockEntity ) - { - SignBlockEntity sbe = (SignBlockEntity) be; - Map textTable = new HashMap<>(); - for( int k = 0; k < 4; k++ ) - { - textTable.put( k + 1, ((SignBlockEntityAccess) sbe).getTexts()[k].asString() ); - } - event.getData().put( "text", textTable ); - } - } -} diff --git a/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java b/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java index 801f62d12..3da20374e 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java +++ b/src/main/java/dan200/computercraft/shared/turtle/apis/TurtleAPI.java @@ -11,15 +11,13 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.api.turtle.TurtleSide; -import dan200.computercraft.api.turtle.event.TurtleActionEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; -import dan200.computercraft.api.turtle.event.TurtleInspectItemEvent; import dan200.computercraft.core.apis.IAPIEnvironment; import dan200.computercraft.core.asm.TaskCallback; import dan200.computercraft.core.tracking.TrackingField; import dan200.computercraft.shared.peripheral.generic.data.ItemData; +import dan200.computercraft.shared.peripheral.generic.methods.InventoryMethods; import dan200.computercraft.shared.turtle.core.*; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import java.util.HashMap; import java.util.Map; @@ -331,7 +329,7 @@ public class TurtleAPI implements ILuaAPI { int actualSlot = checkSlot( slot ).orElse( turtle.getSelectedSlot() ); return turtle.getInventory() - .getStack( actualSlot ) + .getItem( actualSlot ) .getCount(); } @@ -354,8 +352,8 @@ public class TurtleAPI implements ILuaAPI { int actualSlot = checkSlot( slot ).orElse( turtle.getSelectedSlot() ); ItemStack stack = turtle.getInventory() - .getStack( actualSlot ); - return stack.isEmpty() ? 64 : Math.min( stack.getMaxCount(), 64 ) - stack.getCount(); + .getItem( actualSlot ); + return stack.isEmpty() ? 64 : Math.min( stack.getMaxStackSize(), 64 ) - stack.getCount(); } /** @@ -763,7 +761,7 @@ public class TurtleAPI implements ILuaAPI private Object[] getItemDetail( int slot, boolean detailed ) { ItemStack stack = turtle.getInventory() - .getStack( slot ); + .getItem( slot ); if( stack.isEmpty() ) { return new Object[] { null }; @@ -773,12 +771,6 @@ public class TurtleAPI implements ILuaAPI ? ItemData.fill( new HashMap<>(), stack ) : ItemData.fillBasicSafe( new HashMap<>(), stack ); - TurtleActionEvent event = new TurtleInspectItemEvent( turtle, stack, table, detailed ); - if( TurtleEvent.post( event ) ) - { - return new Object[] { false, event.getFailureMessage() }; - } - return new Object[] { table }; } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java index 942214057..72b3f477b 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/BlockTurtle.java @@ -14,61 +14,65 @@ import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.turtle.core.TurtleBrain; import dan200.computercraft.shared.turtle.items.ITurtleItem; import dan200.computercraft.shared.turtle.items.TurtleItemFactory; -import net.minecraft.block.*; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.BlockEntityTicker; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.fluid.FluidState; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.item.ItemStack; -import net.minecraft.state.StateManager; -import net.minecraft.state.property.DirectionProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.util.shape.VoxelShapes; -import net.minecraft.world.BlockView; -import net.minecraft.world.World; -import net.minecraft.world.WorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.RenderShape; +import net.minecraft.world.level.block.SimpleWaterloggedBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.DirectionProperty; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static dan200.computercraft.shared.util.WaterloggableHelpers.*; -import static net.minecraft.state.property.Properties.WATERLOGGED; +import static net.minecraft.world.level.block.state.properties.BlockStateProperties.WATERLOGGED; -public class BlockTurtle extends BlockComputerBase implements Waterloggable +public class BlockTurtle extends BlockComputerBase implements SimpleWaterloggedBlock { - public static final DirectionProperty FACING = Properties.HORIZONTAL_FACING; + public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; - private static final VoxelShape DEFAULT_SHAPE = VoxelShapes.cuboid( 0.125, 0.125, 0.125, 0.875, 0.875, 0.875 ); + private static final VoxelShape DEFAULT_SHAPE = Shapes.box( 0.125, 0.125, 0.125, 0.875, 0.875, 0.875 ); - public BlockTurtle( Settings settings, ComputerFamily family, BlockEntityType type ) + public BlockTurtle( Properties settings, ComputerFamily family, BlockEntityType type ) { super( settings, family, type ); - setDefaultState( getStateManager().getDefaultState() - .with( FACING, Direction.NORTH ) - .with( WATERLOGGED, false ) ); + registerDefaultState( getStateDefinition().any() + .setValue( FACING, Direction.NORTH ) + .setValue( WATERLOGGED, false ) ); } @Nonnull @Override @Deprecated - public BlockRenderType getRenderType( @Nonnull BlockState state ) + public RenderShape getRenderShape( @Nonnull BlockState state ) { - return BlockRenderType.ENTITYBLOCK_ANIMATED; + return RenderShape.ENTITYBLOCK_ANIMATED; } @Nonnull @Override @Deprecated - public BlockState getStateForNeighborUpdate( @Nonnull BlockState state, @Nonnull Direction side, @Nonnull BlockState otherState, - @Nonnull WorldAccess world, @Nonnull BlockPos pos, @Nonnull BlockPos otherPos ) + public BlockState updateShape( @Nonnull BlockState state, @Nonnull Direction side, @Nonnull BlockState otherState, + @Nonnull LevelAccessor world, @Nonnull BlockPos pos, @Nonnull BlockPos otherPos ) { updateWaterloggedPostPlacement( state, world, pos ); return state; @@ -85,15 +89,15 @@ public class BlockTurtle extends BlockComputerBase implements Waterl @Nonnull @Override @Deprecated - public VoxelShape getOutlineShape( @Nonnull BlockState state, BlockView world, @Nonnull BlockPos pos, @Nonnull ShapeContext context ) + public VoxelShape getShape( @Nonnull BlockState state, BlockGetter world, @Nonnull BlockPos pos, @Nonnull CollisionContext context ) { BlockEntity tile = world.getBlockEntity( pos ); - Vec3d offset = tile instanceof TileTurtle ? ((TileTurtle) tile).getRenderOffset( 1.0f ) : Vec3d.ZERO; - return offset.equals( Vec3d.ZERO ) ? DEFAULT_SHAPE : DEFAULT_SHAPE.offset( offset.x, offset.y, offset.z ); + Vec3 offset = tile instanceof TileTurtle ? ((TileTurtle) tile).getRenderOffset( 1.0f ) : Vec3.ZERO; + return offset.equals( Vec3.ZERO ) ? DEFAULT_SHAPE : DEFAULT_SHAPE.move( offset.x, offset.y, offset.z ); } @Override - public float getBlastResistance() + public float getExplosionResistance() { // TODO Implement below functionality return 2000; @@ -101,14 +105,14 @@ public class BlockTurtle extends BlockComputerBase implements Waterl @Nullable @Override - public BlockState getPlacementState( ItemPlacementContext placement ) + public BlockState getStateForPlacement( BlockPlaceContext placement ) { - return getDefaultState().with( FACING, placement.getPlayerFacing() ) - .with( WATERLOGGED, getWaterloggedStateForPlacement( placement ) ); + return defaultBlockState().setValue( FACING, placement.getHorizontalDirection() ) + .setValue( WATERLOGGED, getWaterloggedStateForPlacement( placement ) ); } @Override - protected void appendProperties( StateManager.Builder builder ) + protected void createBlockStateDefinition( StateDefinition.Builder builder ) { builder.add( FACING, WATERLOGGED ); } @@ -133,17 +137,17 @@ public class BlockTurtle extends BlockComputerBase implements Waterl // } @Override - public void onPlaced( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable LivingEntity player, @Nonnull ItemStack stack ) + public void setPlacedBy( @Nonnull Level world, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nullable LivingEntity player, @Nonnull ItemStack stack ) { - super.onPlaced( world, pos, state, player, stack ); + super.setPlacedBy( world, pos, state, player, stack ); BlockEntity tile = world.getBlockEntity( pos ); - if( !world.isClient && tile instanceof TileTurtle turtle ) + if( !world.isClientSide && tile instanceof TileTurtle turtle ) { - if( player instanceof PlayerEntity ) + if( player instanceof Player ) { - ((TileTurtle) tile).setOwningPlayer( ((PlayerEntity) player).getGameProfile() ); + ((TileTurtle) tile).setOwningPlayer( ((Player) player).getGameProfile() ); } if( stack.getItem() instanceof ITurtleItem ) @@ -169,7 +173,7 @@ public class BlockTurtle extends BlockComputerBase implements Waterl } // Set overlay - Identifier overlay = item.getOverlay( stack ); + ResourceLocation overlay = item.getOverlay( stack ); if( overlay != null ) { ((TurtleBrain) turtle.getAccess()).setOverlay( overlay ); @@ -180,7 +184,7 @@ public class BlockTurtle extends BlockComputerBase implements Waterl public BlockEntityType getTypeByFamily( ComputerFamily family ) { - if ( family == ComputerFamily.ADVANCED ) + if( family == ComputerFamily.ADVANCED ) { return ComputerCraftRegistry.ModTiles.TURTLE_ADVANCED; } @@ -189,15 +193,15 @@ public class BlockTurtle extends BlockComputerBase implements Waterl @Nullable @Override - public BlockEntity createBlockEntity( BlockPos pos, BlockState state ) + public BlockEntity newBlockEntity( BlockPos pos, BlockState state ) { return new TileTurtle( getTypeByFamily( getFamily() ), pos, state, getFamily() ); } @Nullable @Override - public BlockEntityTicker getTicker( World world, BlockState state, BlockEntityType type ) + public BlockEntityTicker getTicker( Level world, BlockState state, BlockEntityType type ) { - return world.isClient ? BlockTurtle.checkType( type, getTypeByFamily( getFamily() ), ( world1, pos, state1, computer ) -> computer.clientTick() ) : super.getTicker( world, state, type ); + return world.isClientSide ? BlockTurtle.createTickerHelper( type, getTypeByFamily( getFamily() ), ( world1, pos, state1, computer ) -> computer.clientTick() ) : super.getTicker( world, state, type ); } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/ITurtleTile.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/ITurtleTile.java index 38224df84..8076f0445 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/ITurtleTile.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/ITurtleTile.java @@ -3,27 +3,26 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.blocks; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.shared.computer.blocks.IComputerTile; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.Vec3d; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; public interface ITurtleTile extends IComputerTile { int getColour(); - Identifier getOverlay(); + ResourceLocation getOverlay(); ITurtleUpgrade getUpgrade( TurtleSide side ); ITurtleAccess getAccess(); - Vec3d getRenderOffset( float f ); + Vec3 getRenderOffset( float f ); float getRenderYaw( float f ); diff --git a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java index ba6112a82..e8aa67876 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java +++ b/src/main/java/dan200/computercraft/shared/turtle/blocks/TileTurtle.java @@ -22,40 +22,40 @@ import dan200.computercraft.shared.turtle.apis.TurtleAPI; import dan200.computercraft.shared.turtle.core.TurtleBrain; import dan200.computercraft.shared.turtle.inventory.ContainerTurtle; import dan200.computercraft.shared.util.*; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntityType; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.DyeItem; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtList; -import net.minecraft.screen.ScreenHandler; -import net.minecraft.util.ActionResult; -import net.minecraft.util.DyeColor; -import net.minecraft.util.Hand; -import net.minecraft.util.Identifier; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.DyeItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; public class TileTurtle extends TileComputerBase - implements ITurtleTile, DefaultInventory + implements ITurtleTile, DefaultInventory { public static final int INVENTORY_SIZE = 16; public static final int INVENTORY_WIDTH = 4; public static final int INVENTORY_HEIGHT = 4; - private final DefaultedList inventory = DefaultedList - .ofSize( INVENTORY_SIZE, ItemStack.EMPTY ); - private final DefaultedList previousInventory = DefaultedList - .ofSize( INVENTORY_SIZE, ItemStack.EMPTY ); + private final NonNullList inventory = NonNullList + .withSize( INVENTORY_SIZE, ItemStack.EMPTY ); + private final NonNullList previousInventory = NonNullList + .withSize( INVENTORY_SIZE, ItemStack.EMPTY ); private boolean inventoryChanged = false; private TurtleBrain brain = new TurtleBrain( this ); private MoveState moveState = MoveState.NOT_MOVED; @@ -83,15 +83,15 @@ public class TileTurtle extends TileComputerBase super.destroy(); // Drop contents - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { - int size = size(); + int size = getContainerSize(); for( int i = 0; i < size; i++ ) { - ItemStack stack = getStack( i ); + ItemStack stack = getItem( i ); if( !stack.isEmpty() ) { - WorldUtil.dropItemStack( stack, getWorld(), getPos() ); + WorldUtil.dropItemStack( stack, getLevel(), getBlockPos() ); } } } @@ -101,7 +101,7 @@ public class TileTurtle extends TileComputerBase // Just turn off any redstone we had on for( Direction dir : DirectionUtil.FACINGS ) { - RedstoneUtil.propagateRedstoneOutput( getWorld(), getPos(), dir ); + RedstoneUtil.propagateRedstoneOutput( getLevel(), getBlockPos(), dir ); } } } @@ -112,7 +112,7 @@ public class TileTurtle extends TileComputerBase } @Override - public int size() + public int getContainerSize() { return INVENTORY_SIZE; } @@ -132,22 +132,22 @@ public class TileTurtle extends TileComputerBase @Nonnull @Override - public ItemStack getStack( int slot ) + public ItemStack getItem( int slot ) { return slot >= 0 && slot < INVENTORY_SIZE ? inventory.get( slot ) - : ItemStack.EMPTY; + : ItemStack.EMPTY; } @Nonnull @Override - public ItemStack removeStack( int slot, int count ) + public ItemStack removeItem( int slot, int count ) { if( count == 0 ) { return ItemStack.EMPTY; } - ItemStack stack = getStack( slot ); + ItemStack stack = getItem( slot ); if( stack.isEmpty() ) { return ItemStack.EMPTY; @@ -155,7 +155,7 @@ public class TileTurtle extends TileComputerBase if( stack.getCount() <= count ) { - setStack( slot, ItemStack.EMPTY ); + setItem( slot, ItemStack.EMPTY ); return stack; } @@ -166,18 +166,18 @@ public class TileTurtle extends TileComputerBase @Nonnull @Override - public ItemStack removeStack( int slot ) + public ItemStack removeItemNoUpdate( int slot ) { - ItemStack result = getStack( slot ); - setStack( slot, ItemStack.EMPTY ); + ItemStack result = getItem( slot ); + setItem( slot, ItemStack.EMPTY ); return result; } @Override - public void setStack( int i, @Nonnull ItemStack stack ) + public void setItem( int i, @Nonnull ItemStack stack ) { if( i >= 0 && i < INVENTORY_SIZE - && !InventoryUtil.areItemsEqual( stack, inventory.get( i ) ) ) + && !InventoryUtil.areItemsEqual( stack, inventory.get( i ) ) ) { inventory.set( i, stack ); onInventoryDefinitelyChanged(); @@ -185,66 +185,66 @@ public class TileTurtle extends TileComputerBase } @Override - public boolean canPlayerUse( @Nonnull PlayerEntity player ) + public boolean stillValid( @Nonnull Player player ) { return isUsable( player, false ); } private void onInventoryDefinitelyChanged() { - super.markDirty(); + super.setChanged(); inventoryChanged = true; } @Override - protected boolean canNameWithTag( PlayerEntity player ) + protected boolean canNameWithTag( Player player ) { return true; } @Nonnull @Override - public ActionResult onActivate( PlayerEntity player, Hand hand, BlockHitResult hit ) + public InteractionResult onActivate( Player player, InteractionHand hand, BlockHitResult hit ) { // Apply dye - ItemStack currentItem = player.getStackInHand( hand ); + ItemStack currentItem = player.getItemInHand( hand ); if( !currentItem.isEmpty() ) { if( currentItem.getItem() instanceof DyeItem ) { // Dye to change turtle colour - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { - DyeColor dye = ((DyeItem) currentItem.getItem()).getColor(); + DyeColor dye = ((DyeItem) currentItem.getItem()).getDyeColor(); if( brain.getDyeColour() != dye ) { brain.setDyeColour( dye ); if( !player.isCreative() ) { - currentItem.decrement( 1 ); + currentItem.shrink( 1 ); } } } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } else if( currentItem.getItem() == Items.WATER_BUCKET - && brain.getColour() != -1 ) + && brain.getColour() != -1 ) { // Water to remove turtle colour - if( !getWorld().isClient ) + if( !getLevel().isClientSide ) { if( brain.getColour() != -1 ) { brain.setColour( -1 ); if( !player.isCreative() ) { - player.setStackInHand( hand, - new ItemStack( Items.BUCKET ) ); - player.getInventory().markDirty(); + player.setItemInHand( hand, + new ItemStack( Items.BUCKET ) ); + player.getInventory().setChanged(); } } } - return ActionResult.SUCCESS; + return InteractionResult.SUCCESS; } } @@ -271,7 +271,7 @@ public class TileTurtle extends TileComputerBase } @Override - public void serverTick( ) + public void serverTick() { super.serverTick(); brain.update(); @@ -284,9 +284,9 @@ public class TileTurtle extends TileComputerBase } inventoryChanged = false; - for( int n = 0; n < size(); n++ ) + for( int n = 0; n < getContainerSize(); n++ ) { - previousInventory.set( n, getStack( n ).copy() ); + previousInventory.set( n, getItem( n ).copy() ); } } } @@ -298,21 +298,21 @@ public class TileTurtle extends TileComputerBase @Override protected void updateBlockState( ComputerState newState ) - { } + {} @Nonnull @Override - public NbtCompound writeNbt( @Nonnull NbtCompound nbt ) + public CompoundTag save( @Nonnull CompoundTag nbt ) { // Write inventory - NbtList nbttaglist = new NbtList(); + ListTag nbttaglist = new ListTag(); for( int i = 0; i < INVENTORY_SIZE; i++ ) { if( !inventory.get( i ).isEmpty() ) { - NbtCompound tag = new NbtCompound(); + CompoundTag tag = new CompoundTag(); tag.putByte( "Slot", (byte) i ); - inventory.get( i ).writeNbt( tag ); + inventory.get( i ).save( tag ); nbttaglist.add( tag ); } } @@ -321,27 +321,27 @@ public class TileTurtle extends TileComputerBase // Write brain nbt = brain.writeToNBT( nbt ); - return super.writeNbt( nbt ); + return super.save( nbt ); } // IDirectionalTile @Override - public void readNbt( @Nonnull NbtCompound nbt ) + public void load( @Nonnull CompoundTag nbt ) { - super.readNbt( nbt ); + super.load( nbt ); // Read inventory - NbtList nbttaglist = nbt.getList( "Items", NBTUtil.TAG_COMPOUND ); + ListTag nbttaglist = nbt.getList( "Items", NBTUtil.TAG_COMPOUND ); inventory.clear(); previousInventory.clear(); for( int i = 0; i < nbttaglist.size(); i++ ) { - NbtCompound tag = nbttaglist.getCompound( i ); + CompoundTag tag = nbttaglist.getCompound( i ); int slot = tag.getByte( "Slot" ) & 0xff; - if( slot < size() ) + if( slot < getContainerSize() ) { - inventory.set( slot, ItemStack.fromNbt( tag ) ); + inventory.set( slot, ItemStack.of( tag ) ); previousInventory.set( slot, inventory.get( slot ).copy() ); } } @@ -361,30 +361,30 @@ public class TileTurtle extends TileComputerBase @Override public Direction getDirection() { - return getCachedState().get( BlockTurtle.FACING ); + return getBlockState().getValue( BlockTurtle.FACING ); } @Override protected ServerComputer createComputer( int instanceID, int id ) { - ServerComputer computer = new ServerComputer( getWorld(), id, label, instanceID, - getFamily(), ComputerCraft.turtleTermWidth, - ComputerCraft.turtleTermHeight ); - computer.setPosition( getPos() ); + ServerComputer computer = new ServerComputer( getLevel(), id, label, instanceID, + getFamily(), ComputerCraft.turtleTermWidth, + ComputerCraft.turtleTermHeight ); + computer.setPosition( getBlockPos() ); computer.addAPI( new TurtleAPI( computer.getAPIEnvironment(), getAccess() ) ); brain.setupComputer( computer ); return computer; } @Override - protected void writeDescription( @Nonnull NbtCompound nbt ) + protected void writeDescription( @Nonnull CompoundTag nbt ) { super.writeDescription( nbt ); brain.writeDescription( nbt ); } @Override - protected void readDescription( @Nonnull NbtCompound nbt ) + protected void readDescription( @Nonnull CompoundTag nbt ) { super.readDescription( nbt ); brain.readDescription( nbt ); @@ -402,7 +402,7 @@ public class TileTurtle extends TileComputerBase { dir = Direction.NORTH; } - world.setBlockState( pos, getCachedState().with( BlockTurtle.FACING, dir ) ); + level.setBlockAndUpdate( worldPosition, getBlockState().setValue( BlockTurtle.FACING, dir ) ); updateOutput(); updateInput(); onTileEntityChange(); @@ -410,13 +410,13 @@ public class TileTurtle extends TileComputerBase public void onTileEntityChange() { - super.markDirty(); + super.setChanged(); } private boolean hasPeripheralUpgradeOnSide( ComputerSide side ) { ITurtleUpgrade upgrade; - switch ( side ) + switch( side ) { case RIGHT: upgrade = getUpgrade( TurtleSide.RIGHT ); @@ -433,7 +433,7 @@ public class TileTurtle extends TileComputerBase // IInventory @Override - protected double getInteractRange( PlayerEntity player ) + protected double getInteractRange( Player player ) { return 12.0; } @@ -462,7 +462,7 @@ public class TileTurtle extends TileComputerBase } @Override - public Identifier getOverlay() + public ResourceLocation getOverlay() { return brain.getOverlay(); } @@ -480,7 +480,7 @@ public class TileTurtle extends TileComputerBase } @Override - public Vec3d getRenderOffset( float f ) + public Vec3 getRenderOffset( float f ) { return brain.getRenderOffset( f ); } @@ -500,20 +500,20 @@ public class TileTurtle extends TileComputerBase void setOwningPlayer( GameProfile player ) { brain.setOwningPlayer( player ); - markDirty(); + setChanged(); } // Networking stuff @Override - public void markDirty() + public void setChanged() { - super.markDirty(); + super.setChanged(); if( !inventoryChanged ) { - for( int n = 0; n < size(); n++ ) + for( int n = 0; n < getContainerSize(); n++ ) { - if( !ItemStack.areEqual( getStack( n ), previousInventory.get( n ) ) ) + if( !ItemStack.matches( getItem( n ), previousInventory.get( n ) ) ) { inventoryChanged = true; break; @@ -523,7 +523,7 @@ public class TileTurtle extends TileComputerBase } @Override - public void clear() + public void clearContent() { boolean changed = false; for( int i = 0; i < INVENTORY_SIZE; i++ ) @@ -558,8 +558,8 @@ public class TileTurtle extends TileComputerBase @Nullable @Override - public ScreenHandler createMenu( int id, @Nonnull PlayerInventory inventory, - @Nonnull PlayerEntity player ) + public AbstractContainerMenu createMenu( int id, @Nonnull Inventory inventory, + @Nonnull Player player ) { return new ContainerTurtle( id, inventory, brain ); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/InteractDirection.java b/src/main/java/dan200/computercraft/shared/turtle/core/InteractDirection.java index 2f22305e1..02f489575 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/InteractDirection.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/InteractDirection.java @@ -7,7 +7,7 @@ package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleAccess; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; public enum InteractDirection { diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/MoveDirection.java b/src/main/java/dan200/computercraft/shared/turtle/core/MoveDirection.java index 0364db549..b4bc5872b 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/MoveDirection.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/MoveDirection.java @@ -7,7 +7,7 @@ package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleAccess; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; public enum MoveDirection { diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java index 391ea0f3e..57f7c76e5 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleBrain.java @@ -20,24 +20,24 @@ import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.core.ServerComputer; import dan200.computercraft.shared.turtle.blocks.TileTurtle; import dan200.computercraft.shared.util.*; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.entity.MovementType; -import net.minecraft.fluid.FluidState; -import net.minecraft.inventory.Inventory; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.particle.ParticleTypes; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.tag.FluidTags; -import net.minecraft.util.DyeColor; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.Container; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySelector; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -62,17 +62,17 @@ public class TurtleBrain implements ITurtleAccess private final Queue commandQueue = new ArrayDeque<>(); private final Map upgrades = new EnumMap<>( TurtleSide.class ); private final Map peripherals = new EnumMap<>( TurtleSide.class ); - private final Map upgradeNBTData = new EnumMap<>( TurtleSide.class ); + private final Map upgradeNBTData = new EnumMap<>( TurtleSide.class ); TurtlePlayer cachedPlayer; private TileTurtle owner; - private final Inventory inventory = (InventoryDelegate) () -> owner; + private final Container inventory = (InventoryDelegate) () -> owner; private ComputerProxy proxy; private GameProfile owningPlayer; private int commandsIssued = 0; private int selectedSlot = 0; private int fuelLevel = 0; private int colourHex = -1; - private Identifier overlay = null; + private ResourceLocation overlay = null; private TurtleAnimation animation = TurtleAnimation.NONE; private int animationProgress = 0; private int lastAnimationProgress = 0; @@ -160,8 +160,8 @@ public class TurtleBrain implements ITurtleAccess public void update() { - World world = getWorld(); - if( !world.isClient ) + Level world = getLevel(); + if( !world.isClientSide ) { // Advance movement updateCommands(); @@ -187,31 +187,31 @@ public class TurtleBrain implements ITurtleAccess @Nonnull @Override - public World getWorld() + public Level getLevel() { - return owner.getWorld(); + return owner.getLevel(); } @Nonnull @Override public BlockPos getPosition() { - return owner.getPos(); + return owner.getBlockPos(); } @Override - public boolean teleportTo( @Nonnull World world, @Nonnull BlockPos pos ) + public boolean teleportTo( @Nonnull Level world, @Nonnull BlockPos pos ) { - if( world.isClient || getWorld().isClient ) + if( world.isClientSide || getLevel().isClientSide ) { throw new UnsupportedOperationException( "Cannot teleport on the client" ); } // Cache info about the old turtle (so we don't access this after we delete ourselves) - World oldWorld = getWorld(); + Level oldWorld = getLevel(); TileTurtle oldOwner = owner; - BlockPos oldPos = owner.getPos(); - BlockState oldBlock = owner.getCachedState(); + BlockPos oldPos = owner.getBlockPos(); + BlockState oldBlock = owner.getBlockState(); if( oldWorld == world && oldPos.equals( pos ) ) { @@ -220,14 +220,14 @@ public class TurtleBrain implements ITurtleAccess } // Ensure the chunk is loaded - if( !world.isChunkLoaded( pos ) ) + if( !world.hasChunkAt( pos ) ) { return false; } // Ensure we're inside the world border if( !world.getWorldBorder() - .contains( pos ) ) + .isWithinBounds( pos ) ) { return false; } @@ -238,14 +238,14 @@ public class TurtleBrain implements ITurtleAccess // We only mark this as waterlogged when travelling into a source block. This prevents us from spreading // fluid by creating a new source when moving into a block, causing the next block to be almost full and // then moving into that. - .with( WATERLOGGED, existingFluid.isIn( FluidTags.WATER ) && existingFluid.isStill() ); + .setValue( WATERLOGGED, existingFluid.is( FluidTags.WATER ) && existingFluid.isSource() ); oldOwner.notifyMoveStart(); try { // Create a new turtle - if( world.setBlockState( pos, newState, 0 ) ) + if( world.setBlock( pos, newState, 0 ) ) { Block block = world.getBlockState( pos ) .getBlock(); @@ -255,7 +255,7 @@ public class TurtleBrain implements ITurtleAccess if( newTile instanceof TileTurtle newTurtle ) { // Copy the old turtle state into the new turtle - newTurtle.setWorld( world ); + newTurtle.setLevel( world ); newTurtle.transferStateFrom( oldOwner ); newTurtle.createServerComputer() .setWorld( world ); @@ -288,17 +288,17 @@ public class TurtleBrain implements ITurtleAccess @Nonnull @Override - public Vec3d getVisualPosition( float f ) + public Vec3 getVisualPosition( float f ) { - Vec3d offset = getRenderOffset( f ); - BlockPos pos = owner.getPos(); - return new Vec3d( pos.getX() + 0.5 + offset.x, pos.getY() + 0.5 + offset.y, pos.getZ() + 0.5 + offset.z ); + Vec3 offset = getRenderOffset( f ); + BlockPos pos = owner.getBlockPos(); + return new Vec3( pos.getX() + 0.5 + offset.x, pos.getY() + 0.5 + offset.y, pos.getZ() + 0.5 + offset.z ); } @Override public float getVisualYaw( float f ) { - float yaw = getDirection().asRotation(); + float yaw = getDirection().toYRot(); switch( animation ) { case TURN_LEFT: @@ -341,12 +341,12 @@ public class TurtleBrain implements ITurtleAccess @Override public void setSelectedSlot( int slot ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { throw new UnsupportedOperationException( "Cannot set the slot on the client" ); } - if( slot >= 0 && slot < owner.size() ) + if( slot >= 0 && slot < owner.getContainerSize() ) { selectedSlot = slot; owner.onTileEntityChange(); @@ -419,7 +419,7 @@ public class TurtleBrain implements ITurtleAccess @Override public boolean consumeFuel( int fuel ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { throw new UnsupportedOperationException( "Cannot consume fuel on the client" ); } @@ -441,7 +441,7 @@ public class TurtleBrain implements ITurtleAccess @Override public void addFuel( int fuel ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { throw new UnsupportedOperationException( "Cannot add fuel on the client" ); } @@ -454,7 +454,7 @@ public class TurtleBrain implements ITurtleAccess @Override public MethodResult executeCommand( @Nonnull ITurtleCommand command ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { throw new UnsupportedOperationException( "Cannot run commands on the client" ); } @@ -474,7 +474,7 @@ public class TurtleBrain implements ITurtleAccess @Override public void playAnimation( @Nonnull TurtleAnimation animation ) { - if( getWorld().isClient ) + if( getLevel().isClientSide ) { throw new UnsupportedOperationException( "Cannot play animations on the client" ); } @@ -528,7 +528,7 @@ public class TurtleBrain implements ITurtleAccess } // Notify clients and create peripherals - if( owner.getWorld() != null ) + if( owner.getLevel() != null ) { updatePeripherals( owner.createServerComputer() ); owner.updateBlock(); @@ -543,12 +543,12 @@ public class TurtleBrain implements ITurtleAccess @Nonnull @Override - public NbtCompound getUpgradeNBTData( TurtleSide side ) + public CompoundTag getUpgradeNBTData( TurtleSide side ) { - NbtCompound nbt = upgradeNBTData.get( side ); + CompoundTag nbt = upgradeNBTData.get( side ); if( nbt == null ) { - upgradeNBTData.put( side, nbt = new NbtCompound() ); + upgradeNBTData.put( side, nbt = new CompoundTag() ); } return nbt; } @@ -561,7 +561,7 @@ public class TurtleBrain implements ITurtleAccess @Nonnull @Override - public Inventory getInventory() + public Container getInventory() { return inventory; } @@ -646,7 +646,7 @@ public class TurtleBrain implements ITurtleAccess { if( animation != TurtleAnimation.NONE ) { - World world = getWorld(); + Level world = getLevel(); if( ComputerCraft.turtlesCanPush ) { @@ -681,57 +681,57 @@ public class TurtleBrain implements ITurtleAccess float pushFrac = 1.0f - (float) (animationProgress + 1) / ANIM_DURATION; float push = Math.max( pushFrac + 0.0125f, 0.0f ); - if( moveDir.getOffsetX() < 0 ) + if( moveDir.getStepX() < 0 ) { - minX += moveDir.getOffsetX() * push; + minX += moveDir.getStepX() * push; } else { - maxX -= moveDir.getOffsetX() * push; + maxX -= moveDir.getStepX() * push; } - if( moveDir.getOffsetY() < 0 ) + if( moveDir.getStepY() < 0 ) { - minY += moveDir.getOffsetY() * push; + minY += moveDir.getStepY() * push; } else { - maxY -= moveDir.getOffsetY() * push; + maxY -= moveDir.getStepY() * push; } - if( moveDir.getOffsetZ() < 0 ) + if( moveDir.getStepZ() < 0 ) { - minZ += moveDir.getOffsetZ() * push; + minZ += moveDir.getStepZ() * push; } else { - maxZ -= moveDir.getOffsetZ() * push; + maxZ -= moveDir.getStepZ() * push; } - Box aabb = new Box( minX, minY, minZ, maxX, maxY, maxZ ); - List list = world.getEntitiesByClass( Entity.class, aabb, EntityPredicates.EXCEPT_SPECTATOR ); + AABB aabb = new AABB( minX, minY, minZ, maxX, maxY, maxZ ); + List list = world.getEntitiesOfClass( Entity.class, aabb, EntitySelector.NO_SPECTATORS ); if( !list.isEmpty() ) { double pushStep = 1.0f / ANIM_DURATION; - double pushStepX = moveDir.getOffsetX() * pushStep; - double pushStepY = moveDir.getOffsetY() * pushStep; - double pushStepZ = moveDir.getOffsetZ() * pushStep; + double pushStepX = moveDir.getStepX() * pushStep; + double pushStepY = moveDir.getStepY() * pushStep; + double pushStepZ = moveDir.getStepZ() * pushStep; for( Entity entity : list ) { - entity.move( MovementType.PISTON, new Vec3d( pushStepX, pushStepY, pushStepZ ) ); + entity.move( MoverType.PISTON, new Vec3( pushStepX, pushStepY, pushStepZ ) ); } } } } // Advance valentines day easter egg - if( world.isClient && animation == TurtleAnimation.MOVE_FORWARD && animationProgress == 4 ) + if( world.isClientSide && animation == TurtleAnimation.MOVE_FORWARD && animationProgress == 4 ) { // Spawn love pfx if valentines day Holiday currentHoliday = HolidayUtil.getCurrentHoliday(); if( currentHoliday == Holiday.VALENTINES ) { - Vec3d position = getVisualPosition( 1.0f ); + Vec3 position = getVisualPosition( 1.0f ); if( position != null ) { double x = position.x + world.random.nextGaussian() * 0.1; @@ -759,7 +759,7 @@ public class TurtleBrain implements ITurtleAccess } } - public Vec3d getRenderOffset( float f ) + public Vec3 getRenderOffset( float f ) { switch( animation ) { @@ -787,9 +787,9 @@ public class TurtleBrain implements ITurtleAccess } double distance = -1.0 + getAnimationFraction( f ); - return new Vec3d( distance * dir.getOffsetX(), distance * dir.getOffsetY(), distance * dir.getOffsetZ() ); + return new Vec3( distance * dir.getStepX(), distance * dir.getStepY(), distance * dir.getStepZ() ); default: - return Vec3d.ZERO; + return Vec3.ZERO; } } @@ -800,7 +800,7 @@ public class TurtleBrain implements ITurtleAccess return previous + (next - previous) * f; } - public void readFromNBT( NbtCompound nbt ) + public void readFromNBT( CompoundTag nbt ) { readCommon( nbt ); @@ -810,7 +810,7 @@ public class TurtleBrain implements ITurtleAccess // Read owner if( nbt.contains( "Owner", NBTUtil.TAG_COMPOUND ) ) { - NbtCompound owner = nbt.getCompound( "Owner" ); + CompoundTag owner = nbt.getCompound( "Owner" ); owningPlayer = new GameProfile( new UUID( owner.getLong( "UpperId" ), owner.getLong( "LowerId" ) ), owner.getString( "Name" ) ); } else @@ -824,12 +824,12 @@ public class TurtleBrain implements ITurtleAccess * * @param nbt The tag to read from */ - private void readCommon( NbtCompound nbt ) + private void readCommon( CompoundTag nbt ) { // Read fields colourHex = nbt.contains( NBT_COLOUR ) ? nbt.getInt( NBT_COLOUR ) : -1; fuelLevel = nbt.contains( NBT_FUEL ) ? nbt.getInt( NBT_FUEL ) : 0; - overlay = nbt.contains( NBT_OVERLAY ) ? new Identifier( nbt.getString( NBT_OVERLAY ) ) : null; + overlay = nbt.contains( NBT_OVERLAY ) ? new ResourceLocation( nbt.getString( NBT_OVERLAY ) ) : null; // Read upgrades setUpgrade( TurtleSide.LEFT, nbt.contains( NBT_LEFT_UPGRADE ) ? TurtleUpgrades.get( nbt.getString( NBT_LEFT_UPGRADE ) ) : null ); @@ -851,7 +851,7 @@ public class TurtleBrain implements ITurtleAccess } } - public NbtCompound writeToNBT( NbtCompound nbt ) + public CompoundTag writeToNBT( CompoundTag nbt ) { writeCommon( nbt ); @@ -861,7 +861,7 @@ public class TurtleBrain implements ITurtleAccess // Write owner if( owningPlayer != null ) { - NbtCompound owner = new NbtCompound(); + CompoundTag owner = new CompoundTag(); nbt.put( "Owner", owner ); owner.putLong( "UpperId", owningPlayer.getId() @@ -874,7 +874,7 @@ public class TurtleBrain implements ITurtleAccess return nbt; } - private void writeCommon( NbtCompound nbt ) + private void writeCommon( CompoundTag nbt ) { nbt.putInt( NBT_FUEL, fuelLevel ); if( colourHex != -1 ) @@ -917,7 +917,7 @@ public class TurtleBrain implements ITurtleAccess .toString() : null; } - public void readDescription( NbtCompound nbt ) + public void readDescription( CompoundTag nbt ) { readCommon( nbt ); @@ -931,18 +931,18 @@ public class TurtleBrain implements ITurtleAccess } } - public void writeDescription( NbtCompound nbt ) + public void writeDescription( CompoundTag nbt ) { writeCommon( nbt ); nbt.putInt( "Animation", animation.ordinal() ); } - public Identifier getOverlay() + public ResourceLocation getOverlay() { return overlay; } - public void setOverlay( Identifier overlay ) + public void setOverlay( ResourceLocation overlay ) { if( !Objects.equal( this.overlay, overlay ) ) { diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java index 17f203329..dfa7d90d7 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCommandQueueEntry.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleCommand; diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareCommand.java index b362f5d8b..d5acdc3d2 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareCommand.java @@ -9,13 +9,13 @@ package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleCommandResult; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; import javax.annotation.Nonnull; import java.util.List; @@ -38,15 +38,15 @@ public class TurtleCompareCommand implements ITurtleCommand // Get currently selected stack ItemStack selectedStack = turtle.getInventory() - .getStack( turtle.getSelectedSlot() ); + .getItem( turtle.getSelectedSlot() ); // Get stack representing thing in front - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos oldPosition = turtle.getPosition(); - BlockPos newPosition = oldPosition.offset( direction ); + BlockPos newPosition = oldPosition.relative( direction ); ItemStack lookAtStack = ItemStack.EMPTY; - if( !world.isAir( newPosition ) ) + if( !world.isEmptyBlock( newPosition ) ) { BlockState lookAtState = world.getBlockState( newPosition ); Block lookAtBlock = lookAtState.getBlock(); @@ -56,7 +56,7 @@ public class TurtleCompareCommand implements ITurtleCommand // (try 5 times to try and beat random number generators) for( int i = 0; i < 5 && lookAtStack.isEmpty(); i++ ) { - List drops = Block.getDroppedStacks( lookAtState, (ServerWorld) world, newPosition, world.getBlockEntity( newPosition ) ); + List drops = Block.getDrops( lookAtState, (ServerLevel) world, newPosition, world.getBlockEntity( newPosition ) ); if( !drops.isEmpty() ) { for( ItemStack drop : drops ) diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareToCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareToCommand.java index e5a638828..c2f0261c3 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareToCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCompareToCommand.java @@ -10,7 +10,7 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.shared.util.InventoryUtil; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -28,9 +28,9 @@ public class TurtleCompareToCommand implements ITurtleCommand public TurtleCommandResult execute( @Nonnull ITurtleAccess turtle ) { ItemStack selectedStack = turtle.getInventory() - .getStack( turtle.getSelectedSlot() ); + .getItem( turtle.getSelectedSlot() ); ItemStack stack = turtle.getInventory() - .getStack( slot ); + .getItem( slot ); if( InventoryUtil.areItemsStackable( selectedStack, stack ) ) { return TurtleCommandResult.success(); diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCraftCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCraftCommand.java index 8b6d63e17..ac7e7652d 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCraftCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleCraftCommand.java @@ -13,7 +13,7 @@ import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.shared.turtle.upgrades.TurtleInventoryCrafting; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import java.util.List; @@ -33,7 +33,7 @@ public class TurtleCraftCommand implements ITurtleCommand { // Craft the item TurtleInventoryCrafting crafting = new TurtleInventoryCrafting( turtle ); - List results = crafting.doCrafting( turtle.getWorld(), limit ); + List results = crafting.doCrafting( turtle.getLevel(), limit ); if( results == null ) { return TurtleCommandResult.failure( "No matching recipes" ); @@ -45,7 +45,7 @@ public class TurtleCraftCommand implements ITurtleCommand ItemStack remainder = InventoryUtil.storeItems( stack, turtle.getItemHandler(), turtle.getSelectedSlot() ); if( !remainder.isEmpty() ) { - WorldUtil.dropItemStack( remainder, turtle.getWorld(), turtle.getPosition(), turtle.getDirection() ); + WorldUtil.dropItemStack( remainder, turtle.getLevel(), turtle.getPosition(), turtle.getDirection() ); } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDetectCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDetectCommand.java index cbc97f931..e422cbdb2 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDetectCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDetectCommand.java @@ -10,9 +10,9 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; @@ -33,10 +33,10 @@ public class TurtleDetectCommand implements ITurtleCommand Direction direction = this.direction.toWorldDir( turtle ); // Check if thing in front is air or not - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos oldPosition = turtle.getPosition(); - BlockPos newPosition = oldPosition.offset( direction ); + BlockPos newPosition = oldPosition.relative( direction ); - return !WorldUtil.isLiquidBlock( world, newPosition ) && !world.isAir( newPosition ) ? TurtleCommandResult.success() : TurtleCommandResult.failure(); + return !WorldUtil.isLiquidBlock( world, newPosition ) && !world.isEmptyBlock( newPosition ) ? TurtleCommandResult.success() : TurtleCommandResult.failure(); } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDropCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDropCommand.java index bd53b9c66..a035ba148 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDropCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleDropCommand.java @@ -10,16 +10,14 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; -import dan200.computercraft.api.turtle.event.TurtleEvent; -import dan200.computercraft.api.turtle.event.TurtleInventoryEvent; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.ItemStorage; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.Container; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; @@ -56,21 +54,12 @@ public class TurtleDropCommand implements ITurtleCommand } // Get inventory for thing in front - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos oldPosition = turtle.getPosition(); - BlockPos newPosition = oldPosition.offset( direction ); + BlockPos newPosition = oldPosition.relative( direction ); Direction side = direction.getOpposite(); - Inventory inventory = InventoryUtil.getInventory( world, newPosition, side ); - - // Fire the event, restoring the inventory and exiting if it is cancelled. - TurtlePlayer player = TurtlePlaceCommand.createPlayer( turtle, oldPosition, direction ); - TurtleInventoryEvent.Drop event = new TurtleInventoryEvent.Drop( turtle, player, world, newPosition, inventory, stack ); - if( TurtleEvent.post( event ) ) - { - InventoryUtil.storeItems( stack, turtle.getItemHandler(), turtle.getSelectedSlot() ); - return TurtleCommandResult.failure( event.getFailureMessage() ); - } + Container inventory = InventoryUtil.getInventory( world, newPosition, side ); if( inventory != null ) { @@ -97,7 +86,7 @@ public class TurtleDropCommand implements ITurtleCommand { // Drop the item into the world WorldUtil.dropItemStack( stack, world, oldPosition, direction ); - world.syncGlobalEvent( 1000, newPosition, 0 ); + world.globalLevelEvent( 1000, newPosition, 0 ); turtle.playAnimation( TurtleAnimation.WAIT ); return TurtleCommandResult.success(); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java index d289efc40..b87bc201f 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleEquipCommand.java @@ -7,16 +7,13 @@ package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.*; -import dan200.computercraft.api.turtle.event.TurtleAction; -import dan200.computercraft.api.turtle.event.TurtleActionEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; import dan200.computercraft.shared.TurtleUpgrades; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.ItemStorage; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.world.Container; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -36,8 +33,8 @@ public class TurtleEquipCommand implements ITurtleCommand // Determine the upgrade to equipLeft ITurtleUpgrade newUpgrade; ItemStack newUpgradeStack; - Inventory inventory = turtle.getInventory(); - ItemStack selectedStack = inventory.getStack( turtle.getSelectedSlot() ); + Container inventory = turtle.getInventory(); + ItemStack selectedStack = inventory.getItem( turtle.getSelectedSlot() ); if( !selectedStack.isEmpty() ) { newUpgradeStack = selectedStack.copy(); @@ -66,12 +63,6 @@ public class TurtleEquipCommand implements ITurtleCommand oldUpgradeStack = null; } - TurtleActionEvent event = new TurtleActionEvent( turtle, TurtleAction.EQUIP ); - if( TurtleEvent.post( event ) ) - { - return TurtleCommandResult.failure( event.getFailureMessage() ); - } - // Do the swapping: if( newUpgradeStack != null ) { @@ -86,7 +77,7 @@ public class TurtleEquipCommand implements ITurtleCommand { // If there's no room for the items, drop them BlockPos position = turtle.getPosition(); - WorldUtil.dropItemStack( remainder, turtle.getWorld(), position, turtle.getDirection() ); + WorldUtil.dropItemStack( remainder, turtle.getLevel(), position, turtle.getDirection() ); } } turtle.setUpgrade( side, newUpgrade ); diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleInspectCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleInspectCommand.java index 5e781b23a..1dee94820 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleInspectCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleInspectCommand.java @@ -9,14 +9,12 @@ package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleCommandResult; -import dan200.computercraft.api.turtle.event.TurtleBlockEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; import dan200.computercraft.shared.peripheral.generic.data.BlockData; -import net.minecraft.block.BlockState; -import net.minecraft.state.property.Property; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; import javax.annotation.Nonnull; import java.util.HashMap; @@ -39,9 +37,9 @@ public class TurtleInspectCommand implements ITurtleCommand Direction direction = this.direction.toWorldDir( turtle ); // Check if thing in front is air or not - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos oldPosition = turtle.getPosition(); - BlockPos newPosition = oldPosition.offset( direction ); + BlockPos newPosition = oldPosition.relative( direction ); BlockState state = world.getBlockState( newPosition ); if( state.isAir() ) @@ -51,14 +49,6 @@ public class TurtleInspectCommand implements ITurtleCommand Map table = BlockData.fill( new HashMap<>(), state ); - // Fire the event, exiting if it is cancelled - TurtlePlayer turtlePlayer = TurtlePlaceCommand.createPlayer( turtle, oldPosition, direction ); - TurtleBlockEvent.Inspect event = new TurtleBlockEvent.Inspect( turtle, turtlePlayer, world, newPosition, state, table ); - if( TurtleEvent.post( event ) ) - { - return TurtleCommandResult.failure( event.getFailureMessage() ); - } - return TurtleCommandResult.success( new Object[] { table } ); } @@ -72,6 +62,6 @@ public class TurtleInspectCommand implements ITurtleCommand { return value; } - return property.name( value ); + return property.getName( value ); } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleMoveCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleMoveCommand.java index 60e58e7dd..0d6956fae 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleMoveCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleMoveCommand.java @@ -11,25 +11,23 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; -import dan200.computercraft.api.turtle.event.TurtleBlockEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; import dan200.computercraft.shared.TurtlePermissions; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.block.BlockState; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Direction; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.util.shape.VoxelShapes; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; import javax.annotation.Nonnull; import java.util.List; public class TurtleMoveCommand implements ITurtleCommand { - private static final Box EMPTY_BOX = new Box( 0, 0, 0, 0, 0, 0 ); + private static final AABB EMPTY_BOX = new AABB( 0, 0, 0, 0, 0, 0 ); private final MoveDirection direction; public TurtleMoveCommand( MoveDirection direction ) @@ -45,9 +43,9 @@ public class TurtleMoveCommand implements ITurtleCommand Direction direction = this.direction.toWorldDir( turtle ); // Check if we can move - World oldWorld = turtle.getWorld(); + Level oldWorld = turtle.getLevel(); BlockPos oldPosition = turtle.getPosition(); - BlockPos newPosition = oldPosition.offset( direction ); + BlockPos newPosition = oldPosition.relative( direction ); TurtlePlayer turtlePlayer = TurtlePlaceCommand.createPlayer( turtle, oldPosition, direction ); TurtleCommandResult canEnterResult = canEnter( turtlePlayer, oldWorld, newPosition ); @@ -58,7 +56,7 @@ public class TurtleMoveCommand implements ITurtleCommand // Check existing block is air or replaceable BlockState state = oldWorld.getBlockState( newPosition ); - if( !oldWorld.isAir( newPosition ) && !WorldUtil.isLiquidBlock( oldWorld, newPosition ) && !state.getMaterial() + if( !oldWorld.isEmptyBlock( newPosition ) && !WorldUtil.isLiquidBlock( oldWorld, newPosition ) && !state.getMaterial() .isReplaceable() ) { return TurtleCommandResult.failure( "Movement obstructed" ); @@ -66,9 +64,9 @@ public class TurtleMoveCommand implements ITurtleCommand // Check there isn't anything in the way VoxelShape collision = state.getCollisionShape( oldWorld, oldPosition ) - .offset( newPosition.getX(), newPosition.getY(), newPosition.getZ() ); + .move( newPosition.getX(), newPosition.getY(), newPosition.getZ() ); - if( !oldWorld.intersectsEntities( null, collision ) ) + if( !oldWorld.isUnobstructed( null, collision ) ) { if( !ComputerCraft.turtlesCanPush || this.direction == MoveDirection.UP || this.direction == MoveDirection.DOWN ) { @@ -76,24 +74,18 @@ public class TurtleMoveCommand implements ITurtleCommand } // Check there is space for all the pushable entities to be pushed - List list = oldWorld.getEntitiesByClass( Entity.class, getBox( collision ), x -> x != null && x.isAlive() && x.inanimate ); + List list = oldWorld.getEntitiesOfClass( Entity.class, getBox( collision ), x -> x != null && x.isAlive() && x.blocksBuilding ); for( Entity entity : list ) { - Box pushedBB = entity.getBoundingBox() - .offset( direction.getOffsetX(), direction.getOffsetY(), direction.getOffsetZ() ); - if( !oldWorld.intersectsEntities( null, VoxelShapes.cuboid( pushedBB ) ) ) + AABB pushedBB = entity.getBoundingBox() + .move( direction.getStepX(), direction.getStepY(), direction.getStepZ() ); + if( !oldWorld.isUnobstructed( null, Shapes.create( pushedBB ) ) ) { return TurtleCommandResult.failure( "Movement obstructed" ); } } } - TurtleBlockEvent.Move moveEvent = new TurtleBlockEvent.Move( turtle, turtlePlayer, oldWorld, newPosition ); - if( TurtleEvent.post( moveEvent ) ) - { - return TurtleCommandResult.failure( moveEvent.getFailureMessage() ); - } - // Check fuel level if( turtle.isFuelNeeded() && turtle.getFuelLevel() < 1 ) { @@ -129,13 +121,13 @@ public class TurtleMoveCommand implements ITurtleCommand return TurtleCommandResult.success(); } - private static TurtleCommandResult canEnter( TurtlePlayer turtlePlayer, World world, BlockPos position ) + private static TurtleCommandResult canEnter( TurtlePlayer turtlePlayer, Level world, BlockPos position ) { - if( world.isOutOfHeightLimit( position ) ) + if( world.isOutsideBuildHeight( position ) ) { return TurtleCommandResult.failure( position.getY() < 0 ? "Too low to move" : "Too high to move" ); } - if( !world.isInBuildLimit( position ) ) + if( !world.isInWorldBounds( position ) ) { return TurtleCommandResult.failure( "Cannot leave the world" ); } @@ -146,12 +138,12 @@ public class TurtleMoveCommand implements ITurtleCommand return TurtleCommandResult.failure( "Cannot enter protected area" ); } - if( !world.isChunkLoaded( position ) ) + if( !world.hasChunkAt( position ) ) { return TurtleCommandResult.failure( "Cannot leave loaded world" ); } if( !world.getWorldBorder() - .contains( position ) ) + .isWithinBounds( position ) ) { return TurtleCommandResult.failure( "Cannot pass the world border" ); } @@ -159,8 +151,8 @@ public class TurtleMoveCommand implements ITurtleCommand return TurtleCommandResult.success(); } - private static Box getBox( VoxelShape shape ) + private static AABB getBox( VoxelShape shape ) { - return shape.isEmpty() ? EMPTY_BOX : shape.getBoundingBox(); + return shape.isEmpty() ? EMPTY_BOX : shape.bounds(); } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java index ea6c02a5a..edf5d8181 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlaceCommand.java @@ -11,28 +11,28 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; -import dan200.computercraft.api.turtle.event.TurtleBlockEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; import dan200.computercraft.shared.TurtlePermissions; import dan200.computercraft.shared.util.DirectionUtil; import dan200.computercraft.shared.util.DropConsumer; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.block.BlockState; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.*; -import net.minecraft.text.LiteralText; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.TypedActionResult; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.*; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; @@ -53,7 +53,7 @@ public class TurtlePlaceCommand implements ITurtleCommand { // Create a fake player, and orient it appropriately BlockPos playerPosition = turtle.getPosition() - .offset( direction ); + .relative( direction ); TurtlePlayer turtlePlayer = createPlayer( turtle, playerPosition, direction ); return deploy( stack, turtle, turtlePlayer, direction, extraArguments, outErrorMessage ); @@ -65,7 +65,7 @@ public class TurtlePlaceCommand implements ITurtleCommand { // Get thing to place ItemStack stack = turtle.getInventory() - .getStack( turtle.getSelectedSlot() ); + .getItem( turtle.getSelectedSlot() ); if( stack.isEmpty() ) { return TurtleCommandResult.failure( "No items to place" ); @@ -74,19 +74,13 @@ public class TurtlePlaceCommand implements ITurtleCommand // Remember old block Direction direction = this.direction.toWorldDir( turtle ); BlockPos coordinates = turtle.getPosition() - .offset( direction ); + .relative( direction ); // Create a fake player, and orient it appropriately BlockPos playerPosition = turtle.getPosition() - .offset( direction ); + .relative( direction ); TurtlePlayer turtlePlayer = createPlayer( turtle, playerPosition, direction ); - TurtleBlockEvent.Place place = new TurtleBlockEvent.Place( turtle, turtlePlayer, turtle.getWorld(), coordinates, stack ); - if( TurtleEvent.post( place ) ) - { - return TurtleCommandResult.failure( place.getFailureMessage() ); - } - // Do the deploying String[] errorMessage = new String[1]; ItemStack remainder = deploy( stack, turtle, turtlePlayer, direction, extraArguments, errorMessage ); @@ -94,9 +88,9 @@ public class TurtlePlaceCommand implements ITurtleCommand { // Put the remaining items back turtle.getInventory() - .setStack( turtle.getSelectedSlot(), remainder ); + .setItem( turtle.getSelectedSlot(), remainder ); turtle.getInventory() - .markDirty(); + .setChanged(); // Animate and return success turtle.playAnimation( TurtleAnimation.WAIT ); @@ -138,7 +132,7 @@ public class TurtlePlaceCommand implements ITurtleCommand // Deploy on the block immediately in front BlockPos position = turtle.getPosition(); - BlockPos newPosition = position.offset( direction ); + BlockPos newPosition = position.relative( direction ); remainder = deployOnBlock( stack, turtle, turtlePlayer, newPosition, direction.getOpposite(), extraArguments, true, outErrorMessage ); if( remainder != stack ) { @@ -149,7 +143,7 @@ public class TurtlePlaceCommand implements ITurtleCommand remainder = deployOnBlock( stack, turtle, turtlePlayer, - newPosition.offset( direction ), + newPosition.relative( direction ), direction.getOpposite(), extraArguments, false, @@ -162,7 +156,7 @@ public class TurtlePlaceCommand implements ITurtleCommand if( direction.getAxis() != Direction.Axis.Y ) { // Deploy down on the block in front - remainder = deployOnBlock( stack, turtle, turtlePlayer, newPosition.down(), Direction.UP, extraArguments, false, outErrorMessage ); + remainder = deployOnBlock( stack, turtle, turtlePlayer, newPosition.below(), Direction.UP, extraArguments, false, outErrorMessage ); if( remainder != stack ) { return remainder; @@ -186,32 +180,32 @@ public class TurtlePlaceCommand implements ITurtleCommand if( turtle.getPosition() .equals( position ) ) { - posX += 0.48 * direction.getOffsetX(); - posY += 0.48 * direction.getOffsetY(); - posZ += 0.48 * direction.getOffsetZ(); + posX += 0.48 * direction.getStepX(); + posY += 0.48 * direction.getStepY(); + posZ += 0.48 * direction.getStepZ(); } if( direction.getAxis() != Direction.Axis.Y ) { - turtlePlayer.setYaw( direction.asRotation() ); - turtlePlayer.setPitch( 0.0f ); + turtlePlayer.setYRot( direction.toYRot() ); + turtlePlayer.setXRot( 0.0f ); } else { - turtlePlayer.setYaw( turtle.getDirection() - .asRotation() ); - turtlePlayer.setPitch( DirectionUtil.toPitchAngle( direction ) ); + turtlePlayer.setYRot( turtle.getDirection() + .toYRot() ); + turtlePlayer.setXRot( DirectionUtil.toPitchAngle( direction ) ); } - turtlePlayer.setPos( posX, posY, posZ ); - turtlePlayer.prevX = posX; - turtlePlayer.prevY = posY; - turtlePlayer.prevZ = posZ; - turtlePlayer.prevPitch = turtlePlayer.getPitch(); - turtlePlayer.prevYaw = turtlePlayer.getYaw(); + turtlePlayer.setPosRaw( posX, posY, posZ ); + turtlePlayer.xo = posX; + turtlePlayer.yo = posY; + turtlePlayer.zo = posZ; + turtlePlayer.xRotO = turtlePlayer.getXRot(); + turtlePlayer.yRotO = turtlePlayer.getYRot(); - turtlePlayer.headYaw = turtlePlayer.getYaw(); - turtlePlayer.prevHeadYaw = turtlePlayer.headYaw; + turtlePlayer.yHeadRot = turtlePlayer.getYRot(); + turtlePlayer.yHeadRotO = turtlePlayer.yHeadRot; } @Nonnull @@ -219,11 +213,11 @@ public class TurtlePlaceCommand implements ITurtleCommand Object[] extraArguments, String[] outErrorMessage ) { // See if there is an entity present - final World world = turtle.getWorld(); + final Level world = turtle.getLevel(); final BlockPos position = turtle.getPosition(); - Vec3d turtlePos = turtlePlayer.getPos(); - Vec3d rayDir = turtlePlayer.getRotationVec( 1.0f ); - Pair hit = WorldUtil.rayTraceEntities( world, turtlePos, rayDir, 1.5 ); + Vec3 turtlePos = turtlePlayer.position(); + Vec3 rayDir = turtlePlayer.getViewVector( 1.0f ); + Pair hit = WorldUtil.rayTraceEntities( world, turtlePos, rayDir, 1.5 ); if( hit == null ) { return stack; @@ -235,27 +229,27 @@ public class TurtlePlaceCommand implements ITurtleCommand // Start claiming entity drops Entity hitEntity = hit.getKey(); - Vec3d hitPos = hit.getValue(); + Vec3 hitPos = hit.getValue(); DropConsumer.set( hitEntity, drop -> InventoryUtil.storeItems( drop, turtle.getItemHandler(), turtle.getSelectedSlot() ) ); // Place on the entity boolean placed = false; - ActionResult cancelResult = hitEntity.interactAt( turtlePlayer, hitPos, Hand.MAIN_HAND ); + InteractionResult cancelResult = hitEntity.interactAt( turtlePlayer, hitPos, InteractionHand.MAIN_HAND ); - if( cancelResult != null && cancelResult.isAccepted() ) + if( cancelResult != null && cancelResult.consumesAction() ) { placed = true; } else { - cancelResult = hitEntity.interact( turtlePlayer, Hand.MAIN_HAND ); - if( cancelResult != null && cancelResult.isAccepted() ) + cancelResult = hitEntity.interact( turtlePlayer, InteractionHand.MAIN_HAND ); + if( cancelResult != null && cancelResult.consumesAction() ) { placed = true; } else if( hitEntity instanceof LivingEntity ) { - placed = stackCopy.useOnEntity( turtlePlayer, (LivingEntity) hitEntity, Hand.MAIN_HAND ).isAccepted(); + placed = stackCopy.interactLivingEntity( turtlePlayer, (LivingEntity) hitEntity, InteractionHand.MAIN_HAND ).consumesAction(); if( placed ) turtlePlayer.loadInventory( stackCopy ); } } @@ -273,7 +267,7 @@ public class TurtlePlaceCommand implements ITurtleCommand // Put everything we collected into the turtles inventory, then return ItemStack remainder = turtlePlayer.unloadInventory( turtle ); - if( !placed && ItemStack.areEqual( stack, remainder ) ) + if( !placed && ItemStack.matches( stack, remainder ) ) { return stack; } @@ -293,26 +287,26 @@ public class TurtlePlaceCommand implements ITurtleCommand { // Re-orient the fake player Direction playerDir = side.getOpposite(); - BlockPos playerPosition = position.offset( side ); + BlockPos playerPosition = position.relative( side ); orientPlayer( turtle, turtlePlayer, playerPosition, playerDir ); ItemStack stackCopy = stack.copy(); turtlePlayer.loadInventory( stackCopy ); // Calculate where the turtle would hit the block - float hitX = 0.5f + side.getOffsetX() * 0.5f; - float hitY = 0.5f + side.getOffsetY() * 0.5f; - float hitZ = 0.5f + side.getOffsetZ() * 0.5f; + float hitX = 0.5f + side.getStepX() * 0.5f; + float hitY = 0.5f + side.getStepY() * 0.5f; + float hitZ = 0.5f + side.getStepZ() * 0.5f; if( Math.abs( hitY - 0.5f ) < 0.01f ) { hitY = 0.45f; } // Check if there's something suitable to place onto - BlockHitResult hit = new BlockHitResult( new Vec3d( hitX, hitY, hitZ ), side, position, false ); - ItemUsageContext context = new ItemUsageContext( turtlePlayer, Hand.MAIN_HAND, hit ); - ItemPlacementContext placementContext = new ItemPlacementContext( context ); - if( !canDeployOnBlock( new ItemPlacementContext( context ), turtle, turtlePlayer, position, side, allowReplace, outErrorMessage ) ) + BlockHitResult hit = new BlockHitResult( new Vec3( hitX, hitY, hitZ ), side, position, false ); + UseOnContext context = new UseOnContext( turtlePlayer, InteractionHand.MAIN_HAND, hit ); + BlockPlaceContext placementContext = new BlockPlaceContext( context ); + if( !canDeployOnBlock( new BlockPlaceContext( context ), turtle, turtlePlayer, position, side, allowReplace, outErrorMessage ) ) { return stack; } @@ -322,23 +316,23 @@ public class TurtlePlaceCommand implements ITurtleCommand // Do the deploying (put everything in the players inventory) boolean placed = false; - BlockEntity existingTile = turtle.getWorld() + BlockEntity existingTile = turtle.getLevel() .getBlockEntity( position ); - if( stackCopy.useOnBlock( context ).isAccepted() ) + if( stackCopy.useOn( context ).consumesAction() ) { placed = true; turtlePlayer.loadInventory( stackCopy ); } - if( !placed && (item instanceof BucketItem || item instanceof BoatItem || item instanceof LilyPadItem || item instanceof GlassBottleItem) ) + if( !placed && (item instanceof BucketItem || item instanceof BoatItem || item instanceof WaterLilyBlockItem || item instanceof BottleItem) ) { - TypedActionResult result = stackCopy.use( turtle.getWorld(), turtlePlayer, Hand.MAIN_HAND ); + InteractionResultHolder result = stackCopy.use( turtle.getLevel(), turtlePlayer, InteractionHand.MAIN_HAND ); if( result.getResult() - .isAccepted() && !ItemStack.areEqual( stack, result.getValue() ) ) + .consumesAction() && !ItemStack.matches( stack, result.getObject() ) ) { placed = true; - turtlePlayer.loadInventory( result.getValue() ); + turtlePlayer.loadInventory( result.getObject() ); } } @@ -347,11 +341,11 @@ public class TurtlePlaceCommand implements ITurtleCommand { if( extraArguments != null && extraArguments.length >= 1 && extraArguments[0] instanceof String ) { - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockEntity tile = world.getBlockEntity( position ); if( tile == null || tile == existingTile ) { - tile = world.getBlockEntity( position.offset( side ) ); + tile = world.getBlockEntity( position.relative( side ) ); } if( tile instanceof SignBlockEntity ) { @@ -365,27 +359,27 @@ public class TurtlePlaceCommand implements ITurtleCommand { if( split[i - firstLine].length() > 15 ) { - signTile.setTextOnRow( i, new LiteralText( split[i - firstLine].substring( 0, 15 ) ) ); + signTile.setMessage( i, new TextComponent( split[i - firstLine].substring( 0, 15 ) ) ); } else { - signTile.setTextOnRow( i, new LiteralText( split[i - firstLine] ) ); + signTile.setMessage( i, new TextComponent( split[i - firstLine] ) ); } } else { - signTile.setTextOnRow( i, new LiteralText( "" ) ); + signTile.setMessage( i, new TextComponent( "" ) ); } } - signTile.markDirty(); - world.updateListeners( tile.getPos(), tile.getCachedState(), tile.getCachedState(), 3 ); + signTile.setChanged(); + world.sendBlockUpdated( tile.getBlockPos(), tile.getBlockState(), tile.getBlockState(), 3 ); } } } // Put everything we collected into the turtles inventory, then return ItemStack remainder = turtlePlayer.unloadInventory( turtle ); - if( !placed && ItemStack.areEqual( stack, remainder ) ) + if( !placed && ItemStack.matches( stack, remainder ) ) { return stack; } @@ -399,11 +393,11 @@ public class TurtlePlaceCommand implements ITurtleCommand } } - private static boolean canDeployOnBlock( @Nonnull ItemPlacementContext context, ITurtleAccess turtle, TurtlePlayer player, BlockPos position, + private static boolean canDeployOnBlock( @Nonnull BlockPlaceContext context, ITurtleAccess turtle, TurtlePlayer player, BlockPos position, Direction side, boolean allowReplaceable, String[] outErrorMessage ) { - World world = turtle.getWorld(); - if( !world.isInBuildLimit( position ) || world.isAir( position ) || (context.getStack() + Level world = turtle.getLevel(); + if( !world.isInWorldBounds( position ) || world.isEmptyBlock( position ) || (context.getItemInHand() .getItem() instanceof BlockItem && WorldUtil.isLiquidBlock( world, position )) ) { @@ -412,7 +406,7 @@ public class TurtlePlaceCommand implements ITurtleCommand BlockState state = world.getBlockState( position ); - boolean replaceable = state.canReplace( context ); + boolean replaceable = state.canBeReplaced( context ); if( !allowReplaceable && replaceable ) { return false; @@ -422,7 +416,7 @@ public class TurtlePlaceCommand implements ITurtleCommand { // Check spawn protection boolean editable = replaceable ? TurtlePermissions.isBlockEditable( world, position, player ) : TurtlePermissions.isBlockEditable( world, - position.offset( + position.relative( side ), player ); if( !editable ) diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java index 896ade7a6..fc7830834 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtlePlayer.java @@ -14,21 +14,21 @@ import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.util.FakeNetHandler; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.WorldUtil; -import net.minecraft.block.entity.SignBlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityDimensions; -import net.minecraft.entity.EntityPose; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.effect.StatusEffectInstance; -import net.minecraft.entity.passive.HorseBaseEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.NamedScreenHandlerFactory; -import net.minecraft.server.network.ServerPlayerEntity; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.Container; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.animal.horse.AbstractHorse; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -41,18 +41,18 @@ public final class TurtlePlayer extends FakePlayer private static final GameProfile DEFAULT_PROFILE = new GameProfile( UUID.fromString( "0d0c4ca0-4ff1-11e4-916c-0800200c9a66" ), "[ComputerCraft]" ); // TODO [M3R1-01] Fix Turtle not giving player achievement for actions - private TurtlePlayer( ServerWorld world, GameProfile name ) + private TurtlePlayer( ServerLevel world, GameProfile name ) { super( world, name ); } private static TurtlePlayer create( ITurtleAccess turtle ) { - ServerWorld world = (ServerWorld) turtle.getWorld(); + ServerLevel world = (ServerLevel) turtle.getLevel(); GameProfile profile = turtle.getOwningPlayer(); TurtlePlayer player = new TurtlePlayer( world, getProfile( profile ) ); - player.networkHandler = new FakeNetHandler( player ); + player.connection = new FakeNetHandler( player ); player.setState( turtle ); if( profile != null && profile.getId() != null ) @@ -60,8 +60,8 @@ public final class TurtlePlayer extends FakePlayer // Constructing a player overrides the "active player" variable in advancements. As fake players cannot // get advancements, this prevents a normal player who has placed a turtle from getting advancements. // We try to locate the "actual" player and restore them. - ServerPlayerEntity actualPlayer = world.getServer().getPlayerManager().getPlayer( player.getUuid() ); - if( actualPlayer != null ) player.getAdvancementTracker().setOwner( actualPlayer ); + ServerPlayer actualPlayer = world.getServer().getPlayerList().getPlayer( player.getUUID() ); + if( actualPlayer != null ) player.getAdvancements().setPlayer( actualPlayer ); } return player; @@ -74,20 +74,20 @@ public final class TurtlePlayer extends FakePlayer private void setState( ITurtleAccess turtle ) { - if( currentScreenHandler != playerScreenHandler ) + if( containerMenu != inventoryMenu ) { - ComputerCraft.log.warn( "Turtle has open container ({})", currentScreenHandler ); - closeHandledScreen(); + ComputerCraft.log.warn( "Turtle has open container ({})", containerMenu ); + closeContainer(); } BlockPos position = turtle.getPosition(); - setPos( position.getX() + 0.5, position.getY() + 0.5, position.getZ() + 0.5 ); + setPosRaw( position.getX() + 0.5, position.getY() + 0.5, position.getZ() + 0.5 ); - setYaw( turtle.getDirection() - .asRotation() ); - setPitch( 0.0f ); + setYRot( turtle.getDirection() + .toYRot() ); + setXRot( 0.0f ); - getInventory().clear(); + getInventory().clearContent(); } public static TurtlePlayer get( ITurtleAccess access ) @@ -96,7 +96,7 @@ public final class TurtlePlayer extends FakePlayer TurtleBrain brain = (TurtleBrain) access; TurtlePlayer player = brain.cachedPlayer; - if( player == null || player.getGameProfile() != getProfile( access.getOwningPlayer() ) || player.getEntityWorld() != access.getWorld() ) + if( player == null || player.getGameProfile() != getProfile( access.getOwningPlayer() ) || player.getCommandSenderWorld() != access.getLevel() ) { player = brain.cachedPlayer = create( brain ); } @@ -111,34 +111,34 @@ public final class TurtlePlayer extends FakePlayer public void loadInventory( @Nonnull ItemStack currentStack ) { // Load up the fake inventory - getInventory().selectedSlot = 0; - getInventory().setStack( 0, currentStack ); + getInventory().selected = 0; + getInventory().setItem( 0, currentStack ); } public ItemStack unloadInventory( ITurtleAccess turtle ) { // Get the item we placed with - ItemStack results = getInventory().getStack( 0 ); - getInventory().setStack( 0, ItemStack.EMPTY ); + ItemStack results = getInventory().getItem( 0 ); + getInventory().setItem( 0, ItemStack.EMPTY ); // Store (or drop) anything else we found BlockPos dropPosition = turtle.getPosition(); Direction dropDirection = turtle.getDirection() .getOpposite(); - for( int i = 0; i < getInventory().size(); i++ ) + for( int i = 0; i < getInventory().getContainerSize(); i++ ) { - ItemStack stack = getInventory().getStack( i ); + ItemStack stack = getInventory().getItem( i ); if( !stack.isEmpty() ) { ItemStack remainder = InventoryUtil.storeItems( stack, turtle.getItemHandler(), turtle.getSelectedSlot() ); if( !remainder.isEmpty() ) { - WorldUtil.dropItemStack( remainder, turtle.getWorld(), dropPosition, dropDirection ); + WorldUtil.dropItemStack( remainder, turtle.getLevel(), dropPosition, dropDirection ); } - getInventory().setStack( i, ItemStack.EMPTY ); + getInventory().setItem( i, ItemStack.EMPTY ); } } - getInventory().markDirty(); + getInventory().setChanged(); return results; } @@ -150,30 +150,30 @@ public final class TurtlePlayer extends FakePlayer } @Override - public float getEyeHeight( @Nonnull EntityPose pose ) + public float getEyeHeight( @Nonnull Pose pose ) { return 0; } @Override - public Vec3d getPos() + public Vec3 position() { - return new Vec3d( getX(), getY(), getZ() ); + return new Vec3( getX(), getY(), getZ() ); } @Override - public float getActiveEyeHeight( @Nonnull EntityPose pose, @Nonnull EntityDimensions size ) + public float getStandingEyeHeight( @Nonnull Pose pose, @Nonnull EntityDimensions size ) { return 0; } @Override - public void enterCombat() + public void onEnterCombat() { } @Override - public void endCombat() + public void onLeaveCombat() { } @@ -189,30 +189,30 @@ public final class TurtlePlayer extends FakePlayer } @Override - public void openEditSignScreen( @Nonnull SignBlockEntity signTile ) + public void openTextEdit( @Nonnull SignBlockEntity signTile ) { } //region Code which depends on the connection @Nonnull @Override - public OptionalInt openHandledScreen( @Nullable NamedScreenHandlerFactory prover ) + public OptionalInt openMenu( @Nullable MenuProvider prover ) { return OptionalInt.empty(); } @Override - public void openHorseInventory( @Nonnull HorseBaseEntity horse, @Nonnull Inventory inventory ) + public void openHorseInventory( @Nonnull AbstractHorse horse, @Nonnull Container inventory ) { } @Override - public void closeHandledScreen() + public void closeContainer() { } @Override - protected void onStatusEffectRemoved( @Nonnull StatusEffectInstance effect ) + protected void onEffectRemoved( @Nonnull MobEffectInstance effect ) { } //endregion diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleRefuelCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleRefuelCommand.java index d97e28ad8..7a913666a 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleRefuelCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleRefuelCommand.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleAccess; @@ -12,7 +11,7 @@ import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.api.turtle.event.TurtleEvent; import dan200.computercraft.api.turtle.event.TurtleRefuelEvent; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -30,27 +29,16 @@ public class TurtleRefuelCommand implements ITurtleCommand public TurtleCommandResult execute( @Nonnull ITurtleAccess turtle ) { int slot = turtle.getSelectedSlot(); - ItemStack stack = turtle.getInventory() - .getStack( slot ); - if( stack.isEmpty() ) - { - return TurtleCommandResult.failure( "No items to combust" ); - } + ItemStack stack = turtle.getInventory().getItem( slot ); + if( stack.isEmpty() ) return TurtleCommandResult.failure( "No items to combust" ); TurtleRefuelEvent event = new TurtleRefuelEvent( turtle, stack ); - if( TurtleEvent.post( event ) ) - { - return TurtleCommandResult.failure( event.getFailureMessage() ); - } - if( event.getHandler() == null ) - { - return TurtleCommandResult.failure( "Items not combustible" ); - } + TurtleEvent.EVENT_BUS.post( event ); + if( event.getHandler() == null ) return TurtleCommandResult.failure( "Items not combustible" ); if( limit != 0 ) { - turtle.addFuel( event.getHandler() - .refuel( turtle, stack, slot, limit ) ); + turtle.addFuel( event.getHandler().refuel( turtle, stack, slot, limit ) ); turtle.playAnimation( TurtleAnimation.WAIT ); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleSuckCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleSuckCommand.java index f8aa7ffe8..54138dc99 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleSuckCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleSuckCommand.java @@ -10,18 +10,16 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; -import dan200.computercraft.api.turtle.event.TurtleEvent; -import dan200.computercraft.api.turtle.event.TurtleInventoryEvent; import dan200.computercraft.shared.util.InventoryUtil; import dan200.computercraft.shared.util.ItemStorage; -import net.minecraft.entity.ItemEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.Container; +import net.minecraft.world.entity.EntitySelector; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; import javax.annotation.Nonnull; import java.util.List; @@ -52,20 +50,12 @@ public class TurtleSuckCommand implements ITurtleCommand Direction direction = this.direction.toWorldDir( turtle ); // Get inventory for thing in front - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos turtlePosition = turtle.getPosition(); - BlockPos blockPosition = turtlePosition.offset( direction ); + BlockPos blockPosition = turtlePosition.relative( direction ); Direction side = direction.getOpposite(); - Inventory inventory = InventoryUtil.getInventory( world, blockPosition, side ); - - // Fire the event, exiting if it is cancelled. - TurtlePlayer player = TurtlePlaceCommand.createPlayer( turtle, turtlePosition, direction ); - TurtleInventoryEvent.Suck event = new TurtleInventoryEvent.Suck( turtle, player, world, blockPosition, inventory ); - if( TurtleEvent.post( event ) ) - { - return TurtleCommandResult.failure( event.getFailureMessage() ); - } + Container inventory = InventoryUtil.getInventory( world, blockPosition, side ); if( inventory != null ) { @@ -98,13 +88,13 @@ public class TurtleSuckCommand implements ITurtleCommand else { // Suck up loose items off the ground - Box aabb = new Box( blockPosition.getX(), + AABB aabb = new AABB( blockPosition.getX(), blockPosition.getY(), blockPosition.getZ(), blockPosition.getX() + 1.0, blockPosition.getY() + 1.0, blockPosition.getZ() + 1.0 ); - List list = world.getEntitiesByClass( ItemEntity.class, aabb, EntityPredicates.VALID_ENTITY ); + List list = world.getEntitiesOfClass( ItemEntity.class, aabb, EntitySelector.ENTITY_STILL_ALIVE ); if( list.isEmpty() ) { return TurtleCommandResult.failure( "No items to take" ); @@ -113,7 +103,7 @@ public class TurtleSuckCommand implements ITurtleCommand for( ItemEntity entity : list ) { // Suck up the item - ItemStack stack = entity.getStack() + ItemStack stack = entity.getItem() .copy(); ItemStack storeStack; @@ -139,20 +129,20 @@ public class TurtleSuckCommand implements ITurtleCommand } else if( remainder.isEmpty() ) { - entity.setStack( leaveStack ); + entity.setItem( leaveStack ); } else if( leaveStack.isEmpty() ) { - entity.setStack( remainder ); + entity.setItem( remainder ); } else { - leaveStack.increment( remainder.getCount() ); - entity.setStack( leaveStack ); + leaveStack.grow( remainder.getCount() ); + entity.setItem( leaveStack ); } // Play fx - world.syncGlobalEvent( 1000, turtlePosition, 0 ); // BLOCK_DISPENSER_DISPENSE + world.globalLevelEvent( 1000, turtlePosition, 0 ); // BLOCK_DISPENSER_DISPENSE turtle.playAnimation( TurtleAnimation.WAIT ); return TurtleCommandResult.success(); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTransferToCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTransferToCommand.java index 608d3196e..8f69559cf 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTransferToCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTransferToCommand.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.core; import dan200.computercraft.api.turtle.ITurtleAccess; @@ -11,7 +10,7 @@ import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; import dan200.computercraft.shared.util.InventoryUtil; -import net.minecraft.item.ItemStack; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; diff --git a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTurnCommand.java b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTurnCommand.java index fd669ac8d..78c27ecf3 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTurnCommand.java +++ b/src/main/java/dan200/computercraft/shared/turtle/core/TurtleTurnCommand.java @@ -10,9 +10,6 @@ import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.api.turtle.ITurtleCommand; import dan200.computercraft.api.turtle.TurtleAnimation; import dan200.computercraft.api.turtle.TurtleCommandResult; -import dan200.computercraft.api.turtle.event.TurtleAction; -import dan200.computercraft.api.turtle.event.TurtleActionEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; import javax.annotation.Nonnull; @@ -29,22 +26,16 @@ public class TurtleTurnCommand implements ITurtleCommand @Override public TurtleCommandResult execute( @Nonnull ITurtleAccess turtle ) { - TurtleActionEvent event = new TurtleActionEvent( turtle, TurtleAction.TURN ); - if( TurtleEvent.post( event ) ) - { - return TurtleCommandResult.failure( event.getFailureMessage() ); - } - switch( direction ) { case LEFT: turtle.setDirection( turtle.getDirection() - .rotateYCounterclockwise() ); + .getCounterClockWise() ); turtle.playAnimation( TurtleAnimation.TURN_LEFT ); return TurtleCommandResult.success(); case RIGHT: turtle.setDirection( turtle.getDirection() - .rotateYClockwise() ); + .getClockWise() ); turtle.playAnimation( TurtleAnimation.TURN_RIGHT ); return TurtleCommandResult.success(); default: diff --git a/src/main/java/dan200/computercraft/shared/turtle/inventory/ContainerTurtle.java b/src/main/java/dan200/computercraft/shared/turtle/inventory/ContainerTurtle.java index 17a06de7c..144ceb4c8 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/inventory/ContainerTurtle.java +++ b/src/main/java/dan200/computercraft/shared/turtle/inventory/ContainerTurtle.java @@ -15,15 +15,15 @@ import dan200.computercraft.shared.network.container.ComputerContainerData; import dan200.computercraft.shared.turtle.blocks.TileTurtle; import dan200.computercraft.shared.turtle.core.TurtleBrain; import dan200.computercraft.shared.util.SingleIntArray; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SimpleInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.screen.ArrayPropertyDelegate; -import net.minecraft.screen.PropertyDelegate; -import net.minecraft.screen.slot.Slot; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ContainerData; +import net.minecraft.world.inventory.SimpleContainerData; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import java.util.function.Predicate; @@ -35,13 +35,13 @@ public class ContainerTurtle extends ContainerComputerBase public static final int TURTLE_START_X = ComputerSidebar.WIDTH + 175; public static final int PLAYER_START_X = ComputerSidebar.WIDTH + BORDER; - private final PropertyDelegate properties; + private final ContainerData properties; - public ContainerTurtle( int id, PlayerInventory player, TurtleBrain turtle ) + public ContainerTurtle( int id, Inventory player, TurtleBrain turtle ) { this( id, p -> turtle.getOwner() - .canPlayerUse( p ), + .stillValid( p ), turtle.getOwner() .createServerComputer(), turtle.getFamily(), @@ -50,13 +50,13 @@ public class ContainerTurtle extends ContainerComputerBase (SingleIntArray) turtle::getSelectedSlot ); } - private ContainerTurtle( int id, Predicate canUse, IComputer computer, ComputerFamily family, PlayerInventory playerInventory, - Inventory inventory, PropertyDelegate properties ) + private ContainerTurtle( int id, Predicate canUse, IComputer computer, ComputerFamily family, Inventory playerInventory, + Container inventory, ContainerData properties ) { super( ComputerCraftRegistry.ModContainers.TURTLE, id, canUse, computer, family ); this.properties = properties; - addProperties( properties ); + addDataSlots( properties ); // Turtle inventory for( int y = 0; y < 4; y++ ) @@ -83,20 +83,20 @@ public class ContainerTurtle extends ContainerComputerBase } } - public ContainerTurtle( int id, PlayerInventory player, PacketByteBuf packetByteBuf ) + public ContainerTurtle( int id, Inventory player, FriendlyByteBuf packetByteBuf ) { this( id, player, new ComputerContainerData( packetByteBuf ) ); } - public ContainerTurtle( int id, PlayerInventory player, ComputerContainerData data ) + public ContainerTurtle( int id, Inventory player, ComputerContainerData data ) { this( id, x -> true, getComputer( player, data ), data.getFamily(), player, - new SimpleInventory( TileTurtle.INVENTORY_SIZE ), - new ArrayPropertyDelegate( 1 ) ); + new SimpleContainer( TileTurtle.INVENTORY_SIZE ), + new SimpleContainerData( 1 ) ); } public int getSelectedSlot() @@ -106,7 +106,7 @@ public class ContainerTurtle extends ContainerComputerBase @Nonnull @Override - public ItemStack transferSlot( @Nonnull PlayerEntity player, int slotNum ) + public ItemStack quickMoveStack( @Nonnull Player player, int slotNum ) { if( slotNum >= 0 && slotNum < 16 ) { @@ -120,31 +120,31 @@ public class ContainerTurtle extends ContainerComputerBase } @Nonnull - private ItemStack tryItemMerge( PlayerEntity player, int slotNum, int firstSlot, int lastSlot, boolean reverse ) + private ItemStack tryItemMerge( Player player, int slotNum, int firstSlot, int lastSlot, boolean reverse ) { Slot slot = slots.get( slotNum ); ItemStack originalStack = ItemStack.EMPTY; - if( slot != null && slot.hasStack() ) + if( slot != null && slot.hasItem() ) { - ItemStack clickedStack = slot.getStack(); + ItemStack clickedStack = slot.getItem(); originalStack = clickedStack.copy(); - if( !insertItem( clickedStack, firstSlot, lastSlot, reverse ) ) + if( !moveItemStackTo( clickedStack, firstSlot, lastSlot, reverse ) ) { return ItemStack.EMPTY; } if( clickedStack.isEmpty() ) { - slot.setStack( ItemStack.EMPTY ); + slot.set( ItemStack.EMPTY ); } else { - slot.markDirty(); + slot.setChanged(); } if( clickedStack.getCount() != originalStack.getCount() ) { - slot.onTakeItem( player, clickedStack ); + slot.onTake( player, clickedStack ); } else { diff --git a/src/main/java/dan200/computercraft/shared/turtle/items/ITurtleItem.java b/src/main/java/dan200/computercraft/shared/turtle/items/ITurtleItem.java index 349fc3cab..9a6cfce7c 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/items/ITurtleItem.java +++ b/src/main/java/dan200/computercraft/shared/turtle/items/ITurtleItem.java @@ -3,15 +3,14 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.items; import dan200.computercraft.api.turtle.ITurtleUpgrade; import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.shared.common.IColouredItem; import dan200.computercraft.shared.computer.items.IComputerItem; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -24,5 +23,5 @@ public interface ITurtleItem extends IComputerItem, IColouredItem int getFuelLevel( @Nonnull ItemStack stack ); @Nullable - Identifier getOverlay( @Nonnull ItemStack stack ); + ResourceLocation getOverlay( @Nonnull ItemStack stack ); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/items/ItemTurtle.java b/src/main/java/dan200/computercraft/shared/turtle/items/ItemTurtle.java index 4193f3e32..fe08e07ed 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/items/ItemTurtle.java +++ b/src/main/java/dan200/computercraft/shared/turtle/items/ItemTurtle.java @@ -13,14 +13,14 @@ import dan200.computercraft.shared.common.IColouredItem; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.items.ItemComputerBase; import dan200.computercraft.shared.turtle.blocks.BlockTurtle; -import net.minecraft.item.ItemGroup; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; -import net.minecraft.util.Identifier; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -28,15 +28,15 @@ import static dan200.computercraft.shared.turtle.core.TurtleBrain.*; public class ItemTurtle extends ItemComputerBase implements ITurtleItem { - public ItemTurtle( BlockTurtle block, Settings settings ) + public ItemTurtle( BlockTurtle block, Properties settings ) { super( block, settings ); } @Override - public void appendStacks( @Nonnull ItemGroup group, @Nonnull DefaultedList list ) + public void fillItemCategory( @Nonnull CreativeModeTab group, @Nonnull NonNullList list ) { - if( !isIn( group ) ) + if( !allowdedIn( group ) ) { return; } @@ -50,34 +50,34 @@ public class ItemTurtle extends ItemComputerBase implements ITurtleItem .forEach( list::add ); } - public ItemStack create( int id, String label, int colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, int fuelLevel, Identifier overlay ) + public ItemStack create( int id, String label, int colour, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, int fuelLevel, ResourceLocation overlay ) { // Build the stack ItemStack stack = new ItemStack( this ); if( label != null ) { - stack.setCustomName( new LiteralText( label ) ); + stack.setHoverName( new TextComponent( label ) ); } if( id >= 0 ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_ID, id ); } IColouredItem.setColourBasic( stack, colour ); if( fuelLevel > 0 ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putInt( NBT_FUEL, fuelLevel ); } if( overlay != null ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putString( NBT_OVERLAY, overlay.toString() ); } if( leftUpgrade != null ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putString( NBT_LEFT_UPGRADE, leftUpgrade.getUpgradeID() .toString() ); @@ -85,7 +85,7 @@ public class ItemTurtle extends ItemComputerBase implements ITurtleItem if( rightUpgrade != null ) { - stack.getOrCreateNbt() + stack.getOrCreateTag() .putString( NBT_RIGHT_UPGRADE, rightUpgrade.getUpgradeID() .toString() ); @@ -96,28 +96,28 @@ public class ItemTurtle extends ItemComputerBase implements ITurtleItem @Nonnull @Override - public Text getName( @Nonnull ItemStack stack ) + public Component getName( @Nonnull ItemStack stack ) { - String baseString = getTranslationKey( stack ); + String baseString = getDescriptionId( stack ); ITurtleUpgrade left = getUpgrade( stack, TurtleSide.LEFT ); ITurtleUpgrade right = getUpgrade( stack, TurtleSide.RIGHT ); if( left != null && right != null ) { - return new TranslatableText( baseString + ".upgraded_twice", - new TranslatableText( right.getUnlocalisedAdjective() ), - new TranslatableText( left.getUnlocalisedAdjective() ) ); + return new TranslatableComponent( baseString + ".upgraded_twice", + new TranslatableComponent( right.getUnlocalisedAdjective() ), + new TranslatableComponent( left.getUnlocalisedAdjective() ) ); } else if( left != null ) { - return new TranslatableText( baseString + ".upgraded", new TranslatableText( left.getUnlocalisedAdjective() ) ); + return new TranslatableComponent( baseString + ".upgraded", new TranslatableComponent( left.getUnlocalisedAdjective() ) ); } else if( right != null ) { - return new TranslatableText( baseString + ".upgraded", new TranslatableText( right.getUnlocalisedAdjective() ) ); + return new TranslatableComponent( baseString + ".upgraded", new TranslatableComponent( right.getUnlocalisedAdjective() ) ); } else { - return new TranslatableText( baseString ); + return new TranslatableComponent( baseString ); } } @@ -148,7 +148,7 @@ public class ItemTurtle extends ItemComputerBase implements ITurtleItem @Override public ITurtleUpgrade getUpgrade( @Nonnull ItemStack stack, @Nonnull TurtleSide side ) { - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); if( tag == null ) { return null; @@ -161,15 +161,15 @@ public class ItemTurtle extends ItemComputerBase implements ITurtleItem @Override public int getFuelLevel( @Nonnull ItemStack stack ) { - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); return tag != null && tag.contains( NBT_FUEL ) ? tag.getInt( NBT_FUEL ) : 0; } @Override - public Identifier getOverlay( @Nonnull ItemStack stack ) + public ResourceLocation getOverlay( @Nonnull ItemStack stack ) { - NbtCompound tag = stack.getNbt(); - return tag != null && tag.contains( NBT_OVERLAY ) ? new Identifier( tag.getString( NBT_OVERLAY ) ) : null; + CompoundTag tag = stack.getTag(); + return tag != null && tag.contains( NBT_OVERLAY ) ? new ResourceLocation( tag.getString( NBT_OVERLAY ) ) : null; } @Override diff --git a/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItemFactory.java b/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItemFactory.java index 9d604502f..f829b2dde 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItemFactory.java +++ b/src/main/java/dan200/computercraft/shared/turtle/items/TurtleItemFactory.java @@ -12,8 +12,8 @@ import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.turtle.blocks.ITurtleTile; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -38,7 +38,7 @@ public final class TurtleItemFactory @Nonnull public static ItemStack create( int id, String label, int colour, ComputerFamily family, ITurtleUpgrade leftUpgrade, ITurtleUpgrade rightUpgrade, - int fuelLevel, Identifier overlay ) + int fuelLevel, ResourceLocation overlay ) { switch( family ) { diff --git a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java index 3fda22471..7a3c94d61 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleRecipe.java @@ -10,11 +10,11 @@ import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.computer.items.IComputerItem; import dan200.computercraft.shared.computer.recipe.ComputerFamilyRecipe; import dan200.computercraft.shared.turtle.items.TurtleItemFactory; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.util.Identifier; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.core.NonNullList; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; import javax.annotation.Nonnull; @@ -24,13 +24,13 @@ public final class TurtleRecipe extends ComputerFamilyRecipe new ComputerFamilyRecipe.Serializer() { @Override - protected TurtleRecipe create( Identifier identifier, String group, int width, int height, DefaultedList ingredients, ItemStack result, ComputerFamily family ) + protected TurtleRecipe create( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result, ComputerFamily family ) { return new TurtleRecipe( identifier, group, width, height, ingredients, result, family ); } }; - private TurtleRecipe( Identifier identifier, String group, int width, int height, DefaultedList ingredients, ItemStack result, + private TurtleRecipe( ResourceLocation identifier, String group, int width, int height, NonNullList ingredients, ItemStack result, ComputerFamily family ) { super( identifier, group, width, height, ingredients, result, family ); diff --git a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java index fc297291a..53d73c2f6 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/recipes/TurtleUpgradeRecipe.java @@ -12,41 +12,41 @@ import dan200.computercraft.shared.TurtleUpgrades; import dan200.computercraft.shared.computer.core.ComputerFamily; import dan200.computercraft.shared.turtle.items.ITurtleItem; import dan200.computercraft.shared.turtle.items.TurtleItemFactory; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.SpecialCraftingRecipe; -import net.minecraft.recipe.SpecialRecipeSerializer; -import net.minecraft.util.Identifier; -import net.minecraft.world.World; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CustomRecipe; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; -public final class TurtleUpgradeRecipe extends SpecialCraftingRecipe +public final class TurtleUpgradeRecipe extends CustomRecipe { - public static final RecipeSerializer SERIALIZER = new SpecialRecipeSerializer<>( TurtleUpgradeRecipe::new ); + public static final RecipeSerializer SERIALIZER = new SimpleRecipeSerializer<>( TurtleUpgradeRecipe::new ); - private TurtleUpgradeRecipe( Identifier id ) + private TurtleUpgradeRecipe( ResourceLocation id ) { super( id ); } @Nonnull @Override - public ItemStack getOutput() + public ItemStack getResultItem() { return TurtleItemFactory.create( -1, null, -1, ComputerFamily.NORMAL, null, null, 0, null ); } @Override - public boolean matches( @Nonnull CraftingInventory inventory, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inventory, @Nonnull Level world ) { - return !craft( inventory ).isEmpty(); + return !assemble( inventory ).isEmpty(); } @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inventory ) + public ItemStack assemble( @Nonnull CraftingContainer inventory ) { // Scan the grid for a row containing a turtle and 1 or 2 items ItemStack leftItem = ItemStack.EMPTY; @@ -61,7 +61,7 @@ public final class TurtleUpgradeRecipe extends SpecialCraftingRecipe boolean finishedRow = false; for( int x = 0; x < inventory.getWidth(); x++ ) { - ItemStack item = inventory.getStack( x + y * inventory.getWidth() ); + ItemStack item = inventory.getItem( x + y * inventory.getWidth() ); if( !item.isEmpty() ) { if( finishedRow ) @@ -119,7 +119,7 @@ public final class TurtleUpgradeRecipe extends SpecialCraftingRecipe // Turtle is already found, just check this row is empty for( int x = 0; x < inventory.getWidth(); x++ ) { - ItemStack item = inventory.getStack( x + y * inventory.getWidth() ); + ItemStack item = inventory.getItem( x + y * inventory.getWidth() ); if( !item.isEmpty() ) { return ItemStack.EMPTY; @@ -171,12 +171,12 @@ public final class TurtleUpgradeRecipe extends SpecialCraftingRecipe String label = itemTurtle.getLabel( turtle ); int fuelLevel = itemTurtle.getFuelLevel( turtle ); int colour = itemTurtle.getColour( turtle ); - Identifier overlay = itemTurtle.getOverlay( turtle ); + ResourceLocation overlay = itemTurtle.getOverlay( turtle ); return TurtleItemFactory.create( computerID, label, colour, family, upgrades[0], upgrades[1], fuelLevel, overlay ); } @Override - public boolean fits( int x, int y ) + public boolean canCraftInDimensions( int x, int y ) { return x >= 3 && y >= 1; } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java index 635536c0f..744c04a8c 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleAxe.java @@ -3,26 +3,25 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.upgrades; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; public class TurtleAxe extends TurtleTool { - public TurtleAxe( Identifier id, String adjective, Item item ) + public TurtleAxe( ResourceLocation id, String adjective, Item item ) { super( id, adjective, item ); } - public TurtleAxe( Identifier id, Item item ) + public TurtleAxe( ResourceLocation id, Item item ) { super( id, item ); } - public TurtleAxe( Identifier id, ItemStack craftItem, ItemStack toolItem ) + public TurtleAxe( ResourceLocation id, ItemStack craftItem, ItemStack toolItem ) { super( id, craftItem, toolItem ); } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java index 88d668a87..f80b95859 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleCraftingTable.java @@ -14,21 +14,21 @@ import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleUpgradeType; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.block.Blocks; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.util.Identifier; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.Blocks; import javax.annotation.Nonnull; public class TurtleCraftingTable extends AbstractTurtleUpgrade { @Environment( EnvType.CLIENT ) - private ModelIdentifier leftModel; + private ModelResourceLocation leftModel; @Environment( EnvType.CLIENT ) - private ModelIdentifier rightModel; + private ModelResourceLocation rightModel; - public TurtleCraftingTable( Identifier id ) + public TurtleCraftingTable( ResourceLocation id ) { super( id, TurtleUpgradeType.PERIPHERAL, Blocks.CRAFTING_TABLE ); } @@ -53,8 +53,8 @@ public class TurtleCraftingTable extends AbstractTurtleUpgrade { if( leftModel == null ) { - leftModel = new ModelIdentifier( "computercraft:turtle_crafting_table_left", "inventory" ); - rightModel = new ModelIdentifier( "computercraft:turtle_crafting_table_right", "inventory" ); + leftModel = new ModelResourceLocation( "computercraft:turtle_crafting_table_left", "inventory" ); + rightModel = new ModelResourceLocation( "computercraft:turtle_crafting_table_right", "inventory" ); } } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java index 1676455c6..c3098a2af 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleHoe.java @@ -12,30 +12,30 @@ import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleVerb; import dan200.computercraft.shared.turtle.core.TurtlePlaceCommand; import dan200.computercraft.shared.turtle.core.TurtlePlayer; -import net.minecraft.block.BlockState; -import net.minecraft.block.Material; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; import javax.annotation.Nonnull; public class TurtleHoe extends TurtleTool { - public TurtleHoe( Identifier id, String adjective, Item item ) + public TurtleHoe( ResourceLocation id, String adjective, Item item ) { super( id, adjective, item ); } - public TurtleHoe( Identifier id, Item item ) + public TurtleHoe( ResourceLocation id, Item item ) { super( id, item ); } - public TurtleHoe( Identifier id, ItemStack craftItem, ItemStack toolItem ) + public TurtleHoe( ResourceLocation id, ItemStack craftItem, ItemStack toolItem ) { super( id, craftItem, toolItem ); } @@ -57,7 +57,7 @@ public class TurtleHoe extends TurtleTool } @Override - protected boolean canBreakBlock( BlockState state, World world, BlockPos pos, TurtlePlayer player ) + protected boolean canBreakBlock( BlockState state, Level world, BlockPos pos, TurtlePlayer player ) { if( !super.canBreakBlock( state, world, pos, player ) ) { @@ -65,6 +65,6 @@ public class TurtleHoe extends TurtleTool } Material material = state.getMaterial(); - return material == Material.PLANT || material == Material.CACTUS || material == Material.GOURD || material == Material.LEAVES || material == Material.UNDERWATER_PLANT || material == Material.REPLACEABLE_PLANT; + return material == Material.PLANT || material == Material.CACTUS || material == Material.VEGETABLE || material == Material.LEAVES || material == Material.WATER_PLANT || material == Material.REPLACEABLE_PLANT; } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java index 2b36437fd..bfc6a5c00 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleInventoryCrafting.java @@ -3,20 +3,19 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.turtle.upgrades; import dan200.computercraft.api.turtle.ITurtleAccess; import dan200.computercraft.shared.turtle.blocks.TileTurtle; import dan200.computercraft.shared.turtle.core.TurtlePlayer; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.recipe.Recipe; -import net.minecraft.recipe.RecipeType; -import net.minecraft.server.world.ServerWorld; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -24,11 +23,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -public class TurtleInventoryCrafting extends CraftingInventory +public class TurtleInventoryCrafting extends CraftingContainer { private final ITurtleAccess turtle; - private int xStart; - private int yStart; + private int xStart = 0; + private int yStart = 0; @SuppressWarnings( "ConstantConditions" ) public TurtleInventoryCrafting( ITurtleAccess turtle ) @@ -37,12 +36,10 @@ public class TurtleInventoryCrafting extends CraftingInventory // avoid throwing any NPEs. super( null, 0, 0 ); this.turtle = turtle; - xStart = 0; - yStart = 0; } @Nullable - private Recipe tryCrafting( int xStart, int yStart ) + private Recipe tryCrafting( int xStart, int yStart ) { this.xStart = xStart; this.yStart = yStart; @@ -52,11 +49,10 @@ public class TurtleInventoryCrafting extends CraftingInventory { for( int y = 0; y < TileTurtle.INVENTORY_HEIGHT; y++ ) { - if( x < this.xStart || x >= this.xStart + 3 || y < this.yStart || y >= this.yStart + 3 ) + if( x < this.xStart || x >= this.xStart + 3 || + y < this.yStart || y >= this.yStart + 3 ) { - if( !turtle.getInventory() - .getStack( x + y * TileTurtle.INVENTORY_WIDTH ) - .isEmpty() ) + if( !turtle.getInventory().getItem( x + y * TileTurtle.INVENTORY_WIDTH ).isEmpty() ) { return null; } @@ -65,86 +61,60 @@ public class TurtleInventoryCrafting extends CraftingInventory } // Check the actual crafting - return turtle.getWorld() - .getRecipeManager() - .getFirstMatch( RecipeType.CRAFTING, this, turtle.getWorld() ) - .orElse( null ); + return turtle.getLevel().getRecipeManager().getRecipeFor( RecipeType.CRAFTING, this, turtle.getLevel() ).orElse( null ); } @Nullable - public List doCrafting( World world, int maxCount ) + public List doCrafting( Level world, int maxCount ) { - if( world.isClient || !(world instanceof ServerWorld) ) - { - return null; - } + if( world.isClientSide || !(world instanceof ServerLevel) ) return null; // Find out what we can craft - Recipe recipe = tryCrafting( 0, 0 ); - if( recipe == null ) - { - recipe = tryCrafting( 0, 1 ); - } - if( recipe == null ) - { - recipe = tryCrafting( 1, 0 ); - } - if( recipe == null ) - { - recipe = tryCrafting( 1, 1 ); - } - if( recipe == null ) - { - return null; - } + Recipe recipe = tryCrafting( 0, 0 ); + if( recipe == null ) recipe = tryCrafting( 0, 1 ); + if( recipe == null ) recipe = tryCrafting( 1, 0 ); + if( recipe == null ) recipe = tryCrafting( 1, 1 ); + if( recipe == null ) return null; // Special case: craft(0) just returns an empty list if crafting was possible - if( maxCount == 0 ) - { - return Collections.emptyList(); - } + if( maxCount == 0 ) return Collections.emptyList(); TurtlePlayer player = TurtlePlayer.get( turtle ); ArrayList results = new ArrayList<>(); for( int i = 0; i < maxCount && recipe.matches( this, world ); i++ ) { - ItemStack result = recipe.craft( this ); - if( result.isEmpty() ) - { - break; - } + ItemStack result = recipe.assemble( this ); + if( result.isEmpty() ) break; results.add( result ); - result.onCraft( world, player, result.getCount() ); - DefaultedList remainders = recipe.getRemainder( this ); + result.onCraftedBy( world, player, result.getCount() ); + + NonNullList remainders = recipe.getRemainingItems( this ); for( int slot = 0; slot < remainders.size(); slot++ ) { - ItemStack existing = getStack( slot ); + ItemStack existing = getItem( slot ); ItemStack remainder = remainders.get( slot ); if( !existing.isEmpty() ) { - removeStack( slot, 1 ); - existing = getStack( slot ); + removeItem( slot, 1 ); + existing = getItem( slot ); } - if( remainder.isEmpty() ) - { - continue; - } + if( remainder.isEmpty() ) continue; // Either update the current stack or add it to the remainder list (to be inserted into the inventory // afterwards). if( existing.isEmpty() ) { - setStack( slot, remainder ); + setItem( slot, remainder ); } - else if( ItemStack.areItemsEqualIgnoreDamage( existing, remainder ) && ItemStack.areNbtEqual( existing, remainder ) ) + else if( ItemStack.isSame( existing, remainder ) && ItemStack.tagMatches( existing, remainder ) ) { - remainder.increment( existing.getCount() ); - setStack( slot, remainder ); + remainder.grow( existing.getCount() ); + setItem( slot, remainder ); } else { @@ -156,27 +126,12 @@ public class TurtleInventoryCrafting extends CraftingInventory return results; } - @Override - public int getMaxCountPerStack() - { - return turtle.getInventory() - .getMaxCountPerStack(); - } - @Override public int getWidth() { return 3; } - @Override - public boolean isValid( int i, @Nonnull ItemStack stack ) - { - i = modifyIndex( i ); - return turtle.getInventory() - .isValid( i, stack ); - } - @Override public int getHeight() { @@ -187,75 +142,82 @@ public class TurtleInventoryCrafting extends CraftingInventory { int x = xStart + index % getWidth(); int y = yStart + index / getHeight(); - return x >= 0 && x < TileTurtle.INVENTORY_WIDTH && y >= 0 && y < TileTurtle.INVENTORY_HEIGHT ? x + y * TileTurtle.INVENTORY_WIDTH : -1; + return x >= 0 && x < TileTurtle.INVENTORY_WIDTH && y >= 0 && y < TileTurtle.INVENTORY_HEIGHT + ? x + y * TileTurtle.INVENTORY_WIDTH + : -1; } // IInventory implementation @Override - public int size() + public int getContainerSize() { return getWidth() * getHeight(); } @Nonnull @Override - public ItemStack getStack( int i ) + public ItemStack getItem( int i ) { i = modifyIndex( i ); - return turtle.getInventory() - .getStack( i ); + return turtle.getInventory().getItem( i ); } @Nonnull @Override - public ItemStack removeStack( int i ) + public ItemStack removeItemNoUpdate( int i ) { i = modifyIndex( i ); - return turtle.getInventory() - .removeStack( i ); + return turtle.getInventory().removeItemNoUpdate( i ); } @Nonnull @Override - public ItemStack removeStack( int i, int size ) + public ItemStack removeItem( int i, int size ) { i = modifyIndex( i ); - return turtle.getInventory() - .removeStack( i, size ); + return turtle.getInventory().removeItem( i, size ); } @Override - public void setStack( int i, @Nonnull ItemStack stack ) + public void setItem( int i, @Nonnull ItemStack stack ) { i = modifyIndex( i ); - turtle.getInventory() - .setStack( i, stack ); + turtle.getInventory().setItem( i, stack ); } - @Override - public void markDirty() + public int getMaxStackSize() { - turtle.getInventory() - .markDirty(); + return turtle.getInventory().getMaxStackSize(); } @Override - public boolean canPlayerUse( @Nonnull PlayerEntity player ) + public void setChanged() + { + turtle.getInventory().setChanged(); + } + + @Override + public boolean stillValid( @Nonnull Player player ) { return true; } + @Override + public boolean canPlaceItem( int i, @Nonnull ItemStack stack ) + { + i = modifyIndex( i ); + return turtle.getInventory().canPlaceItem( i, stack ); + } @Override - public void clear() + public void clearContent() { - for( int i = 0; i < size(); i++ ) + for( int i = 0; i < getContainerSize(); i++ ) { int j = modifyIndex( i ); - turtle.getInventory() - .setStack( j, ItemStack.EMPTY ); + turtle.getInventory().setItem( j, ItemStack.EMPTY ); } } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java index 9ef5b0b6a..74edc1935 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleModem.java @@ -14,13 +14,13 @@ import dan200.computercraft.shared.peripheral.modem.ModemState; import dan200.computercraft.shared.peripheral.modem.wireless.WirelessModemPeripheral; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; @@ -28,15 +28,15 @@ public class TurtleModem extends AbstractTurtleUpgrade { private final boolean advanced; @Environment( EnvType.CLIENT ) - private ModelIdentifier leftOffModel; + private ModelResourceLocation leftOffModel; @Environment( EnvType.CLIENT ) - private ModelIdentifier rightOffModel; + private ModelResourceLocation rightOffModel; @Environment( EnvType.CLIENT ) - private ModelIdentifier leftOnModel; + private ModelResourceLocation leftOnModel; @Environment( EnvType.CLIENT ) - private ModelIdentifier rightOnModel; + private ModelResourceLocation rightOnModel; - public TurtleModem( boolean advanced, Identifier id ) + public TurtleModem( boolean advanced, ResourceLocation id ) { super( id, TurtleUpgradeType.PERIPHERAL, @@ -67,7 +67,7 @@ public class TurtleModem extends AbstractTurtleUpgrade boolean active = false; if( turtle != null ) { - NbtCompound turtleNBT = turtle.getUpgradeNBTData( side ); + CompoundTag turtleNBT = turtle.getUpgradeNBTData( side ); active = turtleNBT.contains( "active" ) && turtleNBT.getBoolean( "active" ); } @@ -81,17 +81,17 @@ public class TurtleModem extends AbstractTurtleUpgrade { if( advanced ) { - leftOffModel = new ModelIdentifier( "computercraft:turtle_modem_advanced_off_left", "inventory" ); - rightOffModel = new ModelIdentifier( "computercraft:turtle_modem_advanced_off_right", "inventory" ); - leftOnModel = new ModelIdentifier( "computercraft:turtle_modem_advanced_on_left", "inventory" ); - rightOnModel = new ModelIdentifier( "computercraft:turtle_modem_advanced_on_right", "inventory" ); + leftOffModel = new ModelResourceLocation( "computercraft:turtle_modem_advanced_off_left", "inventory" ); + rightOffModel = new ModelResourceLocation( "computercraft:turtle_modem_advanced_off_right", "inventory" ); + leftOnModel = new ModelResourceLocation( "computercraft:turtle_modem_advanced_on_left", "inventory" ); + rightOnModel = new ModelResourceLocation( "computercraft:turtle_modem_advanced_on_right", "inventory" ); } else { - leftOffModel = new ModelIdentifier( "computercraft:turtle_modem_normal_off_left", "inventory" ); - rightOffModel = new ModelIdentifier( "computercraft:turtle_modem_normal_off_right", "inventory" ); - leftOnModel = new ModelIdentifier( "computercraft:turtle_modem_normal_on_left", "inventory" ); - rightOnModel = new ModelIdentifier( "computercraft:turtle_modem_normal_on_right", "inventory" ); + leftOffModel = new ModelResourceLocation( "computercraft:turtle_modem_normal_off_left", "inventory" ); + rightOffModel = new ModelResourceLocation( "computercraft:turtle_modem_normal_off_right", "inventory" ); + leftOnModel = new ModelResourceLocation( "computercraft:turtle_modem_normal_on_left", "inventory" ); + rightOnModel = new ModelResourceLocation( "computercraft:turtle_modem_normal_on_right", "inventory" ); } } } @@ -100,7 +100,7 @@ public class TurtleModem extends AbstractTurtleUpgrade public void update( @Nonnull ITurtleAccess turtle, @Nonnull TurtleSide side ) { // Advance the modem - if( !turtle.getWorld().isClient ) + if( !turtle.getLevel().isClientSide ) { IPeripheral peripheral = turtle.getPeripheral( side ); if( peripheral instanceof Peripheral ) @@ -128,17 +128,17 @@ public class TurtleModem extends AbstractTurtleUpgrade @Nonnull @Override - public World getWorld() + public Level getLevel() { - return turtle.getWorld(); + return turtle.getLevel(); } @Nonnull @Override - public Vec3d getPosition() + public Vec3 getPosition() { BlockPos turtlePos = turtle.getPosition(); - return new Vec3d( turtlePos.getX(), turtlePos.getY(), turtlePos.getZ() ); + return new Vec3( turtlePos.getX(), turtlePos.getY(), turtlePos.getZ() ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java index f08164bb2..a9684cedf 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleShovel.java @@ -12,30 +12,30 @@ import dan200.computercraft.api.turtle.TurtleSide; import dan200.computercraft.api.turtle.TurtleVerb; import dan200.computercraft.shared.turtle.core.TurtlePlaceCommand; import dan200.computercraft.shared.turtle.core.TurtlePlayer; -import net.minecraft.block.BlockState; -import net.minecraft.block.Material; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; import javax.annotation.Nonnull; public class TurtleShovel extends TurtleTool { - public TurtleShovel( Identifier id, String adjective, Item item ) + public TurtleShovel( ResourceLocation id, String adjective, Item item ) { super( id, adjective, item ); } - public TurtleShovel( Identifier id, Item item ) + public TurtleShovel( ResourceLocation id, Item item ) { super( id, item ); } - public TurtleShovel( Identifier id, ItemStack craftItem, ItemStack toolItem ) + public TurtleShovel( ResourceLocation id, ItemStack craftItem, ItemStack toolItem ) { super( id, craftItem, toolItem ); } @@ -57,7 +57,7 @@ public class TurtleShovel extends TurtleTool } @Override - protected boolean canBreakBlock( BlockState state, World world, BlockPos pos, TurtlePlayer player ) + protected boolean canBreakBlock( BlockState state, Level world, BlockPos pos, TurtlePlayer player ) { if( !super.canBreakBlock( state, world, pos, player ) ) { @@ -65,6 +65,6 @@ public class TurtleShovel extends TurtleTool } Material material = state.getMaterial(); - return material == Material.SOIL || material == Material.AGGREGATE || material == Material.SNOW_LAYER || material == Material.ORGANIC_PRODUCT || material == Material.SNOW_BLOCK || material == Material.PLANT || material == Material.CACTUS || material == Material.GOURD || material == Material.LEAVES || material == Material.REPLACEABLE_PLANT; + return material == Material.DIRT || material == Material.SAND || material == Material.TOP_SNOW || material == Material.CLAY || material == Material.SNOW || material == Material.PLANT || material == Material.CACTUS || material == Material.VEGETABLE || material == Material.LEAVES || material == Material.REPLACEABLE_PLANT; } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSpeaker.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSpeaker.java index fe87ef4a3..e31884bed 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSpeaker.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSpeaker.java @@ -15,22 +15,22 @@ import dan200.computercraft.shared.ComputerCraftRegistry; import dan200.computercraft.shared.peripheral.speaker.UpgradeSpeakerPeripheral; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.core.BlockPos; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; public class TurtleSpeaker extends AbstractTurtleUpgrade { @Environment( EnvType.CLIENT ) - private ModelIdentifier leftModel; + private ModelResourceLocation leftModel; @Environment( EnvType.CLIENT ) - private ModelIdentifier rightModel; + private ModelResourceLocation rightModel; - public TurtleSpeaker( Identifier id ) + public TurtleSpeaker( ResourceLocation id ) { super( id, TurtleUpgradeType.PERIPHERAL, ComputerCraftRegistry.ModBlocks.SPEAKER ); } @@ -55,8 +55,8 @@ public class TurtleSpeaker extends AbstractTurtleUpgrade { if( leftModel == null ) { - leftModel = new ModelIdentifier( "computercraft:turtle_speaker_upgrade_left", "inventory" ); - rightModel = new ModelIdentifier( "computercraft:turtle_speaker_upgrade_right", "inventory" ); + leftModel = new ModelResourceLocation( "computercraft:turtle_speaker_upgrade_left", "inventory" ); + rightModel = new ModelResourceLocation( "computercraft:turtle_speaker_upgrade_right", "inventory" ); } } @@ -81,16 +81,16 @@ public class TurtleSpeaker extends AbstractTurtleUpgrade } @Override - public World getWorld() + public Level getWorld() { - return turtle.getWorld(); + return turtle.getLevel(); } @Override - public Vec3d getPosition() + public Vec3 getPosition() { BlockPos pos = turtle.getPosition(); - return new Vec3d( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); + return new Vec3( pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5 ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java index 7c41f9b46..e5fc53abc 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleSword.java @@ -7,27 +7,27 @@ package dan200.computercraft.shared.turtle.upgrades; import dan200.computercraft.shared.turtle.core.TurtlePlayer; -import net.minecraft.block.BlockState; -import net.minecraft.block.Material; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; public class TurtleSword extends TurtleTool { - public TurtleSword( Identifier id, String adjective, Item item ) + public TurtleSword( ResourceLocation id, String adjective, Item item ) { super( id, adjective, item ); } - public TurtleSword( Identifier id, Item item ) + public TurtleSword( ResourceLocation id, Item item ) { super( id, item ); } - public TurtleSword( Identifier id, ItemStack craftItem, ItemStack toolItem ) + public TurtleSword( ResourceLocation id, ItemStack craftItem, ItemStack toolItem ) { super( id, craftItem, toolItem ); } @@ -39,7 +39,7 @@ public class TurtleSword extends TurtleTool } @Override - protected boolean canBreakBlock( BlockState state, World world, BlockPos pos, TurtlePlayer player ) + protected boolean canBreakBlock( BlockState state, Level world, BlockPos pos, TurtlePlayer player ) { if( !super.canBreakBlock( state, world, pos, player ) ) { @@ -47,6 +47,6 @@ public class TurtleSword extends TurtleTool } Material material = state.getMaterial(); - return material == Material.PLANT || material == Material.LEAVES || material == Material.REPLACEABLE_PLANT || material == Material.WOOL || material == Material.COBWEB; + return material == Material.PLANT || material == Material.LEAVES || material == Material.REPLACEABLE_PLANT || material == Material.WOOL || material == Material.WEB; } } diff --git a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java index c5bbd31f4..d18ff84a5 100644 --- a/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java +++ b/src/main/java/dan200/computercraft/shared/turtle/upgrades/TurtleTool.java @@ -6,12 +6,11 @@ package dan200.computercraft.shared.turtle.upgrades; +import com.mojang.math.Matrix4f; +import com.mojang.math.Transformation; import dan200.computercraft.ComputerCraft; import dan200.computercraft.api.client.TransformedModel; import dan200.computercraft.api.turtle.*; -import dan200.computercraft.api.turtle.event.TurtleAttackEvent; -import dan200.computercraft.api.turtle.event.TurtleBlockEvent; -import dan200.computercraft.api.turtle.event.TurtleEvent; import dan200.computercraft.fabric.mixininterface.IMatrix4f; import dan200.computercraft.shared.TurtlePermissions; import dan200.computercraft.shared.turtle.core.TurtleBrain; @@ -24,22 +23,24 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.event.player.AttackEntityCallback; import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.entity.attribute.EntityAttributes; -import net.minecraft.entity.damage.DamageSource; -import net.minecraft.entity.decoration.ArmorStandEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.util.ActionResult; -import net.minecraft.util.Hand; -import net.minecraft.util.Identifier; -import net.minecraft.util.math.*; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; @@ -53,19 +54,19 @@ public class TurtleTool extends AbstractTurtleUpgrade private static final int TAG_LIST = 9; private static final int TAG_COMPOUND = 10; - public TurtleTool( Identifier id, String adjective, Item item ) + public TurtleTool( ResourceLocation id, String adjective, Item item ) { super( id, TurtleUpgradeType.TOOL, adjective, item ); this.item = new ItemStack( item ); } - public TurtleTool( Identifier id, Item item ) + public TurtleTool( ResourceLocation id, Item item ) { super( id, TurtleUpgradeType.TOOL, item ); this.item = new ItemStack( item ); } - public TurtleTool( Identifier id, ItemStack craftItem, ItemStack toolItem ) + public TurtleTool( ResourceLocation id, ItemStack craftItem, ItemStack toolItem ) { super( id, TurtleUpgradeType.TOOL, craftItem ); item = toolItem; @@ -74,12 +75,12 @@ public class TurtleTool extends AbstractTurtleUpgrade @Override public boolean isItemSuitable( @Nonnull ItemStack stack ) { - NbtCompound tag = stack.getNbt(); + CompoundTag tag = stack.getTag(); if( tag == null || tag.isEmpty() ) 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.hasEnchantments() || stack.hasCustomName() ) return false; + if( stack.isDamaged() || stack.isEnchanted() || stack.hasCustomHoverName() ) return false; return !tag.contains( "AttributeModifiers", TAG_LIST ) || tag.getList( "AttributeModifiers", TAG_COMPOUND ).isEmpty(); } @@ -110,7 +111,7 @@ public class TurtleTool extends AbstractTurtleUpgrade private TurtleCommandResult attack( ITurtleAccess turtle, Direction direction, TurtleSide side ) { // Create a fake player, and orient it appropriately - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos position = turtle.getPosition(); BlockEntity turtleBlock = turtle instanceof TurtleBrain ? ((TurtleBrain) turtle).getOwner() : world.getBlockEntity( position ); if( turtleBlock == null ) return TurtleCommandResult.failure( "Turtle has vanished from existence." ); @@ -118,9 +119,9 @@ public class TurtleTool extends AbstractTurtleUpgrade final TurtlePlayer turtlePlayer = TurtlePlaceCommand.createPlayer( turtle, position, direction ); // See if there is an entity present - Vec3d turtlePos = turtlePlayer.getPos(); - Vec3d rayDir = turtlePlayer.getRotationVec( 1.0f ); - Pair hit = WorldUtil.rayTraceEntities( world, turtlePos, rayDir, 1.5 ); + Vec3 turtlePos = turtlePlayer.position(); + Vec3 rayDir = turtlePlayer.getViewVector( 1.0f ); + Pair hit = WorldUtil.rayTraceEntities( world, turtlePos, rayDir, 1.5 ); if( hit != null ) { // Load up the turtle's inventoryf @@ -133,44 +134,38 @@ public class TurtleTool extends AbstractTurtleUpgrade if( AttackEntityCallback.EVENT.invoker() .interact( turtlePlayer, world, - Hand.MAIN_HAND, + InteractionHand.MAIN_HAND, hitEntity, - null ) == ActionResult.FAIL || !hitEntity.isAttackable() ) + null ) == InteractionResult.FAIL || !hitEntity.isAttackable() ) { return TurtleCommandResult.failure( "Nothing to attack here" ); } - TurtleAttackEvent attackEvent = new TurtleAttackEvent( turtle, turtlePlayer, hitEntity, this, side ); - if( TurtleEvent.post( attackEvent ) ) - { - return TurtleCommandResult.failure( attackEvent.getFailureMessage() ); - } - // Start claiming entity drops DropConsumer.set( hitEntity, turtleDropConsumer( turtleBlock, turtle ) ); // Attack the entity boolean attacked = false; - if( !hitEntity.handleAttack( turtlePlayer ) ) + if( !hitEntity.skipAttackInteraction( turtlePlayer ) ) { - float damage = (float) turtlePlayer.getAttributeValue( EntityAttributes.GENERIC_ATTACK_DAMAGE ); + float damage = (float) turtlePlayer.getAttributeValue( Attributes.ATTACK_DAMAGE ); damage *= getDamageMultiplier(); if( damage > 0.0f ) { - DamageSource source = DamageSource.player( turtlePlayer ); - if( hitEntity instanceof ArmorStandEntity ) + DamageSource source = DamageSource.playerAttack( turtlePlayer ); + if( hitEntity instanceof ArmorStand ) { // Special case for armor stands: attack twice to guarantee destroy - hitEntity.damage( source, damage ); + hitEntity.hurt( source, damage ); if( hitEntity.isAlive() ) { - hitEntity.damage( source, damage ); + hitEntity.hurt( source, damage ); } attacked = true; } else { - if( hitEntity.damage( source, damage ) ) + if( hitEntity.hurt( source, damage ) ) { attacked = true; } @@ -195,15 +190,15 @@ public class TurtleTool extends AbstractTurtleUpgrade private TurtleCommandResult dig( ITurtleAccess turtle, Direction direction, TurtleSide side ) { // Get ready to dig - World world = turtle.getWorld(); + Level world = turtle.getLevel(); BlockPos turtlePosition = turtle.getPosition(); BlockEntity turtleBlock = turtle instanceof TurtleBrain ? ((TurtleBrain) turtle).getOwner() : world.getBlockEntity( turtlePosition ); if( turtleBlock == null ) return TurtleCommandResult.failure( "Turtle has vanished from existence." ); - BlockPos blockPosition = turtlePosition.offset( direction ); + BlockPos blockPosition = turtlePosition.relative( direction ); - if( world.isAir( blockPosition ) || WorldUtil.isLiquidBlock( world, blockPosition ) ) + if( world.isEmptyBlock( blockPosition ) || WorldUtil.isLiquidBlock( world, blockPosition ) ) { return TurtleCommandResult.failure( "Nothing to dig here" ); } @@ -227,13 +222,6 @@ public class TurtleTool extends AbstractTurtleUpgrade return TurtleCommandResult.failure( "Unbreakable block detected" ); } - // Fire the dig event, checking whether it was cancelled. - TurtleBlockEvent.Dig digEvent = new TurtleBlockEvent.Dig( turtle, turtlePlayer, world, blockPosition, state, this, side ); - if( TurtleEvent.post( digEvent ) ) - { - return TurtleCommandResult.failure( digEvent.getFailureMessage() ); - } - if( !PlayerBlockBreakEvents.BEFORE.invoker().beforeBlockBreak( world, turtlePlayer, blockPosition, state, null ) ) { return TurtleCommandResult.failure( "Break cancelled" ); @@ -248,19 +236,19 @@ public class TurtleTool extends AbstractTurtleUpgrade // to consult there before making any changes. // Play the destruction sound and particles - world.syncWorldEvent( 2001, blockPosition, Block.getRawIdFromState( state ) ); + world.levelEvent( 2001, blockPosition, Block.getId( state ) ); // Destroy the block state.getBlock() - .onBreak( world, blockPosition, state, turtlePlayer ); + .playerWillDestroy( world, blockPosition, state, turtlePlayer ); if( world.removeBlock( blockPosition, false ) ) { state.getBlock() - .onBroken( world, blockPosition, state ); - if( turtlePlayer.canHarvest( state ) ) + .destroy( world, blockPosition, state ); + if( turtlePlayer.hasCorrectToolForDrops( state ) ) { state.getBlock() - .afterBreak( world, turtlePlayer, blockPosition, state, tile, turtlePlayer.getMainHandStack() ); + .playerDestroy( world, turtlePlayer, blockPosition, state, tile, turtlePlayer.getMainHandItem() ); } } @@ -287,24 +275,24 @@ public class TurtleTool extends AbstractTurtleUpgrade for( ItemStack remainder : extra ) { WorldUtil.dropItemStack( remainder, - turtle.getWorld(), + turtle.getLevel(), turtle.getPosition(), direction ); } } - protected boolean canBreakBlock( BlockState state, World world, BlockPos pos, TurtlePlayer player ) + protected boolean canBreakBlock( BlockState state, Level world, BlockPos pos, TurtlePlayer player ) { Block block = state.getBlock(); - return !state.isAir() && block != Blocks.BEDROCK && state.calcBlockBreakingDelta( player, world, pos ) > 0; + return !state.isAir() && block != Blocks.BEDROCK && state.getDestroyProgress( player, world, pos ) > 0; } private static class Transforms { - static final AffineTransformation leftTransform = getMatrixFor( -0.40625f ); - static final AffineTransformation rightTransform = getMatrixFor( 0.40625f ); + static final Transformation leftTransform = getMatrixFor( -0.40625f ); + static final Transformation rightTransform = getMatrixFor( 0.40625f ); - private static AffineTransformation getMatrixFor( float offset ) + private static Transformation getMatrixFor( float offset ) { Matrix4f matrix = new Matrix4f(); ((IMatrix4f) (Object) matrix).setFloatArray( new float[] { @@ -313,7 +301,7 @@ public class TurtleTool extends AbstractTurtleUpgrade 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, } ); - return new AffineTransformation( matrix ); + return new Transformation( matrix ); } } } diff --git a/src/main/java/dan200/computercraft/shared/util/ColourTracker.java b/src/main/java/dan200/computercraft/shared/util/ColourTracker.java index da0e00bb1..c0d1532a0 100644 --- a/src/main/java/dan200/computercraft/shared/util/ColourTracker.java +++ b/src/main/java/dan200/computercraft/shared/util/ColourTracker.java @@ -6,7 +6,7 @@ package dan200.computercraft.shared.util; -import net.minecraft.util.DyeColor; +import net.minecraft.world.item.DyeColor; /** * A reimplementation of the colour system in {@link ArmorDyeRecipe}, but bundled together as an object. diff --git a/src/main/java/dan200/computercraft/shared/util/ColourUtils.java b/src/main/java/dan200/computercraft/shared/util/ColourUtils.java index 92a1a13fc..cb288ef30 100644 --- a/src/main/java/dan200/computercraft/shared/util/ColourUtils.java +++ b/src/main/java/dan200/computercraft/shared/util/ColourUtils.java @@ -6,10 +6,10 @@ package dan200.computercraft.shared.util; -import net.minecraft.item.DyeItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.DyeColor; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.DyeItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nullable; @@ -21,6 +21,6 @@ public final class ColourUtils public static DyeColor getStackColour( ItemStack stack ) { Item item = stack.getItem(); - return item instanceof DyeItem ? ((DyeItem) item).getColor() : null; + return item instanceof DyeItem ? ((DyeItem) item).getDyeColor() : null; } } diff --git a/src/main/java/dan200/computercraft/shared/util/CommentedConfigSpec.java b/src/main/java/dan200/computercraft/shared/util/CommentedConfigSpec.java index 830eb4a5a..e41d1bcc8 100644 --- a/src/main/java/dan200/computercraft/shared/util/CommentedConfigSpec.java +++ b/src/main/java/dan200/computercraft/shared/util/CommentedConfigSpec.java @@ -32,7 +32,7 @@ public class CommentedConfigSpec extends ConfigSpec @Override public int correct( Config config ) { - return correct( config, ( action, path, incorrectValue, correctedValue ) -> { } ); + return correct( config, ( action, path, incorrectValue, correctedValue ) -> {} ); } @Override diff --git a/src/main/java/dan200/computercraft/shared/util/Config.java b/src/main/java/dan200/computercraft/shared/util/Config.java index 241f0282d..1f46afc71 100644 --- a/src/main/java/dan200/computercraft/shared/util/Config.java +++ b/src/main/java/dan200/computercraft/shared/util/Config.java @@ -13,19 +13,21 @@ import com.electronwill.nightconfig.core.file.FileNotFoundAction; import com.google.common.base.CaseFormat; import com.google.common.base.Converter; import dan200.computercraft.ComputerCraft; -import dan200.computercraft.api.turtle.event.TurtleAction; import dan200.computercraft.core.apis.http.options.Action; import dan200.computercraft.core.apis.http.options.AddressRuleConfig; -import dan200.computercraft.fabric.mixin.WorldSavePathAccess; +import dan200.computercraft.fabric.mixin.LevelResourceAccess; import dan200.computercraft.shared.peripheral.monitor.MonitorRenderer; import net.fabricmc.loader.FabricLoader; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.WorldSavePath; +import net.minecraft.world.level.storage.LevelResource; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -41,7 +43,7 @@ public final class Config public static CommentedFileConfig serverConfig; public static CommentedFileConfig clientConfig; - private static final WorldSavePath serverDir = WorldSavePathAccess.createWorldSavePath( "serverconfig" ); + private static final LevelResource serverDir = LevelResourceAccess.create( "serverconfig" ); private static final String serverFileName = "computercraft-server.toml"; private static Path serverPath = null; @@ -208,10 +210,6 @@ public final class Config serverSpec.comment( "turtle.can_push", "If set to true, Turtles will push entities out of the way instead of stopping if there is space to do so" ); serverSpec.define( "turtle.can_push", ComputerCraft.turtlesCanPush ); - - serverSpec.comment( "turtle.disabled_actions", - "A list of turtle actions which are disabled." ); - serverSpec.defineList( "turtle.disabled_actions", Collections.emptyList(), x -> x instanceof String && getAction( (String) x ) != null ); } { // Terminal sizes @@ -283,7 +281,7 @@ public final class Config public static void serverStarting( MinecraftServer server ) { - serverPath = server.getSavePath( serverDir ).resolve( serverFileName ); + serverPath = server.getWorldPath( serverDir ).resolve( serverFileName ); try( CommentedFileConfig config = buildFileConfig( serverPath ) ) { @@ -301,7 +299,7 @@ public final class Config serverPath = null; } - public static void clientStarted( MinecraftClient client ) + public static void clientStarted( Minecraft client ) { try( CommentedFileConfig config = buildFileConfig( clientPath ) ) { @@ -372,12 +370,6 @@ public final class Config ComputerCraft.turtlesObeyBlockProtection = serverConfig.get( "turtle.obey_block_protection" ); ComputerCraft.turtlesCanPush = serverConfig.get( "turtle.can_push" ); - ComputerCraft.turtleDisabledActions.clear(); - for( String value : serverConfig.>get( "turtle.disabled_actions" ) ) - { - ComputerCraft.turtleDisabledActions.add( getAction( value ) ); - } - // Terminal Size ComputerCraft.computerTermWidth = serverConfig.get( "term_sizes.computer.width" ); ComputerCraft.computerTermHeight = serverConfig.get( "term_sizes.computer.height" ); @@ -397,16 +389,4 @@ public final class Config } private static final Converter converter = CaseFormat.LOWER_CAMEL.converterTo( CaseFormat.UPPER_UNDERSCORE ); - - private static TurtleAction getAction( String value ) - { - try - { - return TurtleAction.valueOf( converter.convert( value ) ); - } - catch( IllegalArgumentException e ) - { - return null; - } - } } diff --git a/src/main/java/dan200/computercraft/shared/util/DefaultInventory.java b/src/main/java/dan200/computercraft/shared/util/DefaultInventory.java index 857fafd34..f8af29947 100644 --- a/src/main/java/dan200/computercraft/shared/util/DefaultInventory.java +++ b/src/main/java/dan200/computercraft/shared/util/DefaultInventory.java @@ -3,35 +3,34 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.util; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; -public interface DefaultInventory extends Inventory +public interface DefaultInventory extends Container { @Override - default int getMaxCountPerStack() + default int getMaxStackSize() { return 64; } @Override - default void onOpen( @Nonnull PlayerEntity player ) + default void startOpen( @Nonnull Player player ) { } @Override - default void onClose( @Nonnull PlayerEntity player ) + default void stopOpen( @Nonnull Player player ) { } @Override - default boolean isValid( int slot, @Nonnull ItemStack stack ) + default boolean canPlaceItem( int slot, @Nonnull ItemStack stack ) { return true; } diff --git a/src/main/java/dan200/computercraft/shared/util/DefaultSidedInventory.java b/src/main/java/dan200/computercraft/shared/util/DefaultSidedInventory.java index 706a0047b..7a94909a6 100644 --- a/src/main/java/dan200/computercraft/shared/util/DefaultSidedInventory.java +++ b/src/main/java/dan200/computercraft/shared/util/DefaultSidedInventory.java @@ -3,26 +3,25 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.util; -import net.minecraft.inventory.SidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; +import net.minecraft.world.WorldlyContainer; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public interface DefaultSidedInventory extends DefaultInventory, SidedInventory +public interface DefaultSidedInventory extends DefaultInventory, WorldlyContainer { @Override - default boolean canInsert( int slot, @Nonnull ItemStack stack, @Nullable Direction side ) + default boolean canPlaceItemThroughFace( int slot, @Nonnull ItemStack stack, @Nullable Direction side ) { - return isValid( slot, stack ); + return canPlaceItem( slot, stack ); } @Override - default boolean canExtract( int slot, @Nonnull ItemStack stack, @Nonnull Direction side ) + default boolean canTakeItemThroughFace( int slot, @Nonnull ItemStack stack, @Nonnull Direction side ) { return true; } diff --git a/src/main/java/dan200/computercraft/shared/util/DirectionUtil.java b/src/main/java/dan200/computercraft/shared/util/DirectionUtil.java index 9f6cb01a9..5744d00e4 100644 --- a/src/main/java/dan200/computercraft/shared/util/DirectionUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/DirectionUtil.java @@ -7,7 +7,7 @@ package dan200.computercraft.shared.util; import dan200.computercraft.core.computer.ComputerSide; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; public final class DirectionUtil { @@ -30,11 +30,11 @@ public final class DirectionUtil { return ComputerSide.BACK; } - if( dir == front.rotateYCounterclockwise() ) + if( dir == front.getCounterClockWise() ) { return ComputerSide.LEFT; } - if( dir == front.rotateYClockwise() ) + if( dir == front.getClockWise() ) { return ComputerSide.RIGHT; } diff --git a/src/main/java/dan200/computercraft/shared/util/DropConsumer.java b/src/main/java/dan200/computercraft/shared/util/DropConsumer.java index 43bb89d84..7ceba6b3f 100644 --- a/src/main/java/dan200/computercraft/shared/util/DropConsumer.java +++ b/src/main/java/dan200/computercraft/shared/util/DropConsumer.java @@ -6,12 +6,12 @@ package dan200.computercraft.shared.util; -import net.minecraft.entity.Entity; -import net.minecraft.entity.ItemEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; import java.lang.ref.WeakReference; import java.util.ArrayList; @@ -22,9 +22,9 @@ public final class DropConsumer { private static Function dropConsumer; private static List remainingDrops; - private static WeakReference dropWorld; + private static WeakReference dropWorld; private static BlockPos dropPos; - private static Box dropBounds; + private static AABB dropBounds; private static WeakReference dropEntity; private DropConsumer() @@ -36,18 +36,18 @@ public final class DropConsumer dropConsumer = consumer; remainingDrops = new ArrayList<>(); dropEntity = new WeakReference<>( entity ); - dropWorld = new WeakReference<>( entity.world ); + dropWorld = new WeakReference<>( entity.level ); dropPos = null; - dropBounds = new Box( entity.getBlockPos() ).expand( 2, 2, 2 ); + dropBounds = new AABB( entity.blockPosition() ).inflate( 2, 2, 2 ); } - public static void set( World world, BlockPos pos, Function consumer ) + public static void set( Level world, BlockPos pos, Function consumer ) { dropConsumer = consumer; remainingDrops = new ArrayList<>( 2 ); dropEntity = null; dropWorld = new WeakReference<>( world ); - dropBounds = new Box( pos ).expand( 2, 2, 2 ); + dropBounds = new AABB( pos ).inflate( 2, 2, 2 ); } public static List clear() @@ -63,7 +63,7 @@ public final class DropConsumer return remainingStacks; } - public static boolean onHarvestDrops( World world, BlockPos pos, ItemStack stack ) + public static boolean onHarvestDrops( Level world, BlockPos pos, ItemStack stack ) { if( dropWorld != null && dropWorld.get() == world && dropPos != null && dropPos.equals( pos ) ) { @@ -85,9 +85,9 @@ public final class DropConsumer public static boolean onEntitySpawn( Entity entity ) { // Capture any nearby item spawns - if( dropWorld != null && dropWorld.get() == entity.getEntityWorld() && entity instanceof ItemEntity && dropBounds.contains( entity.getPos() ) ) + if( dropWorld != null && dropWorld.get() == entity.getCommandSenderWorld() && entity instanceof ItemEntity && dropBounds.contains( entity.position() ) ) { - handleDrops( ((ItemEntity) entity).getStack() ); + handleDrops( ((ItemEntity) entity).getItem() ); return true; } return false; diff --git a/src/main/java/dan200/computercraft/shared/util/FakeNetHandler.java b/src/main/java/dan200/computercraft/shared/util/FakeNetHandler.java index c955ae361..38a8eecd1 100644 --- a/src/main/java/dan200/computercraft/shared/util/FakeNetHandler.java +++ b/src/main/java/dan200/computercraft/shared/util/FakeNetHandler.java @@ -10,24 +10,24 @@ import dan200.computercraft.api.turtle.FakePlayer; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; -import net.minecraft.network.ClientConnection; -import net.minecraft.network.NetworkSide; -import net.minecraft.network.NetworkState; -import net.minecraft.network.Packet; -import net.minecraft.network.listener.PacketListener; -import net.minecraft.network.packet.c2s.play.*; -import net.minecraft.server.network.ServerPlayNetworkHandler; -import net.minecraft.text.Text; +import net.minecraft.network.Connection; +import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.PacketListener; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.game.*; +import net.minecraft.server.network.ServerGamePacketListenerImpl; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.crypto.Cipher; -public class FakeNetHandler extends ServerPlayNetworkHandler +public class FakeNetHandler extends ServerGamePacketListenerImpl { public FakeNetHandler( @Nonnull FakePlayer player ) { - super( player.getServerWorld() + super( player.getLevel() .getServer(), new FakeNetworkManager(), player ); } @@ -37,208 +37,208 @@ public class FakeNetHandler extends ServerPlayNetworkHandler } @Override - public void disconnect( @Nonnull Text reason ) + public void disconnect( @Nonnull Component reason ) { } @Override - public void onPlayerInput( @Nonnull PlayerInputC2SPacket packet ) + public void handlePlayerInput( @Nonnull ServerboundPlayerInputPacket packet ) { } @Override - public void onVehicleMove( @Nonnull VehicleMoveC2SPacket packet ) + public void handleMoveVehicle( @Nonnull ServerboundMoveVehiclePacket packet ) { } @Override - public void onTeleportConfirm( @Nonnull TeleportConfirmC2SPacket packet ) + public void handleAcceptTeleportPacket( @Nonnull ServerboundAcceptTeleportationPacket packet ) { } @Override - public void onAdvancementTab( @Nonnull AdvancementTabC2SPacket packet ) + public void handleSeenAdvancements( @Nonnull ServerboundSeenAdvancementsPacket packet ) { } @Override - public void onRequestCommandCompletions( @Nonnull RequestCommandCompletionsC2SPacket packet ) + public void handleCustomCommandSuggestions( @Nonnull ServerboundCommandSuggestionPacket packet ) { } @Override - public void onUpdateCommandBlock( @Nonnull UpdateCommandBlockC2SPacket packet ) + public void handleSetCommandBlock( @Nonnull ServerboundSetCommandBlockPacket packet ) { } @Override - public void onUpdateCommandBlockMinecart( @Nonnull UpdateCommandBlockMinecartC2SPacket packet ) + public void handleSetCommandMinecart( @Nonnull ServerboundSetCommandMinecartPacket packet ) { } @Override - public void onPickFromInventory( @Nonnull PickFromInventoryC2SPacket packet ) + public void handlePickItem( @Nonnull ServerboundPickItemPacket packet ) { } @Override - public void onRenameItem( @Nonnull RenameItemC2SPacket packet ) + public void handleRenameItem( @Nonnull ServerboundRenameItemPacket packet ) { } @Override - public void onUpdateBeacon( @Nonnull UpdateBeaconC2SPacket packet ) + public void handleSetBeaconPacket( @Nonnull ServerboundSetBeaconPacket packet ) { } @Override - public void onStructureBlockUpdate( @Nonnull UpdateStructureBlockC2SPacket packet ) + public void handleSetStructureBlock( @Nonnull ServerboundSetStructureBlockPacket packet ) { } @Override - public void onJigsawUpdate( @Nonnull UpdateJigsawC2SPacket packet ) + public void handleSetJigsawBlock( @Nonnull ServerboundSetJigsawBlockPacket packet ) { } @Override - public void onJigsawGenerating( JigsawGeneratingC2SPacket packet ) + public void handleJigsawGenerate( ServerboundJigsawGeneratePacket packet ) { } @Override - public void onMerchantTradeSelect( SelectMerchantTradeC2SPacket packet ) + public void handleSelectTrade( ServerboundSelectTradePacket packet ) { } @Override - public void onBookUpdate( @Nonnull BookUpdateC2SPacket packet ) + public void handleEditBook( @Nonnull ServerboundEditBookPacket packet ) { } @Override - public void onRecipeBookData( RecipeBookDataC2SPacket packet ) + public void handleRecipeBookSeenRecipePacket( ServerboundRecipeBookSeenRecipePacket packet ) { } @Override - public void onRecipeCategoryOptions( RecipeCategoryOptionsC2SPacket packet ) + public void handleRecipeBookChangeSettingsPacket( ServerboundRecipeBookChangeSettingsPacket packet ) { - super.onRecipeCategoryOptions( packet ); + super.handleRecipeBookChangeSettingsPacket( packet ); } @Override - public void onQueryEntityNbt( @Nonnull QueryEntityNbtC2SPacket packet ) + public void handleEntityTagQuery( @Nonnull ServerboundEntityTagQuery packet ) { } @Override - public void onQueryBlockNbt( @Nonnull QueryBlockNbtC2SPacket packet ) + public void handleBlockEntityTagQuery( @Nonnull ServerboundBlockEntityTagQuery packet ) { } @Override - public void onPlayerMove( @Nonnull PlayerMoveC2SPacket packet ) + public void handleMovePlayer( @Nonnull ServerboundMovePlayerPacket packet ) { } @Override - public void onPlayerAction( @Nonnull PlayerActionC2SPacket packet ) + public void handlePlayerAction( @Nonnull ServerboundPlayerActionPacket packet ) { } @Override - public void onPlayerInteractBlock( @Nonnull PlayerInteractBlockC2SPacket packet ) + public void handleUseItemOn( @Nonnull ServerboundUseItemOnPacket packet ) { } @Override - public void onPlayerInteractItem( @Nonnull PlayerInteractItemC2SPacket packet ) + public void handleUseItem( @Nonnull ServerboundUseItemPacket packet ) { } @Override - public void onSpectatorTeleport( @Nonnull SpectatorTeleportC2SPacket packet ) + public void handleTeleportToEntityPacket( @Nonnull ServerboundTeleportToEntityPacket packet ) { } @Override - public void onResourcePackStatus( @Nonnull ResourcePackStatusC2SPacket packet ) + public void handleResourcePackResponse( @Nonnull ServerboundResourcePackPacket packet ) { } @Override - public void onBoatPaddleState( @Nonnull BoatPaddleStateC2SPacket packet ) + public void handlePaddleBoat( @Nonnull ServerboundPaddleBoatPacket packet ) { } @Override - public void onDisconnected( @Nonnull Text reason ) + public void onDisconnect( @Nonnull Component reason ) { } @Override - public void sendPacket( @Nonnull Packet packet ) + public void send( @Nonnull Packet packet ) { } @Override - public void sendPacket( @Nonnull Packet packet, @Nullable GenericFutureListener> whenSent ) + public void send( @Nonnull Packet packet, @Nullable GenericFutureListener> whenSent ) { } @Override - public void onUpdateSelectedSlot( @Nonnull UpdateSelectedSlotC2SPacket packet ) + public void handleSetCarriedItem( @Nonnull ServerboundSetCarriedItemPacket packet ) { } @Override - public void onGameMessage( @Nonnull ChatMessageC2SPacket packet ) + public void handleChat( @Nonnull ServerboundChatPacket packet ) { } @Override - public void onHandSwing( @Nonnull HandSwingC2SPacket packet ) + public void handleAnimate( @Nonnull ServerboundSwingPacket packet ) { } @Override - public void onClientCommand( @Nonnull ClientCommandC2SPacket packet ) + public void handlePlayerCommand( @Nonnull ServerboundPlayerCommandPacket packet ) { } @Override - public void onPlayerInteractEntity( @Nonnull PlayerInteractEntityC2SPacket packet ) + public void handleInteract( @Nonnull ServerboundInteractPacket packet ) { } @Override - public void onClientStatus( @Nonnull ClientStatusC2SPacket packet ) + public void handleClientCommand( @Nonnull ServerboundClientCommandPacket packet ) { } @Override - public void onCloseHandledScreen( CloseHandledScreenC2SPacket packet ) + public void handleContainerClose( ServerboundContainerClosePacket packet ) { } @Override - public void onClickSlot( ClickSlotC2SPacket packet ) + public void handleContainerClick( ServerboundContainerClickPacket packet ) { } @Override - public void onCraftRequest( @Nonnull CraftRequestC2SPacket packet ) + public void handlePlaceRecipe( @Nonnull ServerboundPlaceRecipePacket packet ) { } @Override - public void onButtonClick( @Nonnull ButtonClickC2SPacket packet ) + public void handleContainerButtonClick( @Nonnull ServerboundContainerButtonClickPacket packet ) { } @Override - public void onCreativeInventoryAction( @Nonnull CreativeInventoryActionC2SPacket packet ) + public void handleSetCreativeModeSlot( @Nonnull ServerboundSetCreativeModeSlotPacket packet ) { } @@ -248,48 +248,48 @@ public class FakeNetHandler extends ServerPlayNetworkHandler // } @Override - public void onSignUpdate( @Nonnull UpdateSignC2SPacket packet ) + public void handleSignUpdate( @Nonnull ServerboundSignUpdatePacket packet ) { } @Override - public void onKeepAlive( @Nonnull KeepAliveC2SPacket packet ) + public void handleKeepAlive( @Nonnull ServerboundKeepAlivePacket packet ) { } @Override - public void onPlayerAbilities( @Nonnull UpdatePlayerAbilitiesC2SPacket packet ) + public void handlePlayerAbilities( @Nonnull ServerboundPlayerAbilitiesPacket packet ) { } @Override - public void onClientSettings( @Nonnull ClientSettingsC2SPacket packet ) + public void handleClientInformation( @Nonnull ServerboundClientInformationPacket packet ) { } @Override - public void onCustomPayload( @Nonnull CustomPayloadC2SPacket packet ) + public void handleCustomPayload( @Nonnull ServerboundCustomPayloadPacket packet ) { } @Override - public void onUpdateDifficulty( @Nonnull UpdateDifficultyC2SPacket packet ) + public void handleChangeDifficulty( @Nonnull ServerboundChangeDifficultyPacket packet ) { } @Override - public void onUpdateDifficultyLock( @Nonnull UpdateDifficultyLockC2SPacket packet ) + public void handleLockDifficulty( @Nonnull ServerboundLockDifficultyPacket packet ) { } - private static class FakeNetworkManager extends ClientConnection + private static class FakeNetworkManager extends Connection { private PacketListener handler; - private Text closeReason; + private Component closeReason; FakeNetworkManager() { - super( NetworkSide.CLIENTBOUND ); + super( PacketFlow.CLIENTBOUND ); } @Override @@ -298,7 +298,7 @@ public class FakeNetHandler extends ServerPlayNetworkHandler } @Override - public void setState( @Nonnull NetworkState state ) + public void setProtocol( @Nonnull ConnectionProtocol state ) { } @@ -318,7 +318,7 @@ public class FakeNetHandler extends ServerPlayNetworkHandler } @Override - public void setPacketListener( @Nonnull PacketListener handler ) + public void setListener( @Nonnull PacketListener handler ) { this.handler = handler; } @@ -339,13 +339,13 @@ public class FakeNetHandler extends ServerPlayNetworkHandler } @Override - public void disconnect( @Nonnull Text message ) + public void disconnect( @Nonnull Component message ) { closeReason = message; } @Override - public void setupEncryption( Cipher cipher, Cipher cipher2 ) + public void setEncryptionKey( Cipher cipher, Cipher cipher2 ) { } @@ -358,13 +358,13 @@ public class FakeNetHandler extends ServerPlayNetworkHandler @Nullable @Override - public Text getDisconnectReason() + public Component getDisconnectedReason() { return closeReason; } @Override - public void disableAutoRead() + public void setReadOnly() { } } diff --git a/src/main/java/dan200/computercraft/shared/util/IDAssigner.java b/src/main/java/dan200/computercraft/shared/util/IDAssigner.java index 6a10e44fa..19a37cb91 100644 --- a/src/main/java/dan200/computercraft/shared/util/IDAssigner.java +++ b/src/main/java/dan200/computercraft/shared/util/IDAssigner.java @@ -10,10 +10,10 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import dan200.computercraft.ComputerCraft; -import dan200.computercraft.fabric.mixin.WorldSavePathAccess; +import dan200.computercraft.fabric.mixin.LevelResourceAccess; import me.shedaniel.cloth.api.utils.v1.GameInstanceUtils; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.WorldSavePath; +import net.minecraft.world.level.storage.LevelResource; import java.io.File; import java.io.Reader; @@ -28,7 +28,7 @@ import java.util.Map; public final class IDAssigner { - private static final WorldSavePath FOLDER = WorldSavePathAccess.createWorldSavePath( ComputerCraft.MOD_ID ); + private static final LevelResource FOLDER = LevelResourceAccess.create( ComputerCraft.MOD_ID ); private static final Gson GSON = new GsonBuilder().setPrettyPrinting() .create(); private static final Type ID_TOKEN = new TypeToken>() @@ -116,7 +116,7 @@ public final class IDAssigner public static File getDir() { return GameInstanceUtils.getServer() - .getSavePath( FOLDER ) + .getWorldPath( FOLDER ) .toFile(); } } diff --git a/src/main/java/dan200/computercraft/shared/util/ImpostorRecipe.java b/src/main/java/dan200/computercraft/shared/util/ImpostorRecipe.java index a9e8a3f2f..e9c39bc97 100644 --- a/src/main/java/dan200/computercraft/shared/util/ImpostorRecipe.java +++ b/src/main/java/dan200/computercraft/shared/util/ImpostorRecipe.java @@ -7,16 +7,16 @@ package dan200.computercraft.shared.util; import com.google.gson.JsonObject; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.ShapedRecipe; -import net.minecraft.util.Identifier; -import net.minecraft.util.JsonHelper; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.core.NonNullList; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.GsonHelper; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.ShapedRecipe; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; @@ -25,47 +25,47 @@ public final class ImpostorRecipe extends ShapedRecipe public static final RecipeSerializer SERIALIZER = new RecipeSerializer() { @Override - public ImpostorRecipe read( @Nonnull Identifier identifier, @Nonnull JsonObject json ) + public ImpostorRecipe fromJson( @Nonnull ResourceLocation identifier, @Nonnull JsonObject json ) { - String group = JsonHelper.getString( json, "group", "" ); - ShapedRecipe recipe = RecipeSerializer.SHAPED.read( identifier, json ); - JsonObject resultObject = JsonHelper.getObject( json, "result" ); - ItemStack itemStack = ShapedRecipe.outputFromJson( resultObject ); + String group = GsonHelper.getAsString( json, "group", "" ); + ShapedRecipe recipe = RecipeSerializer.SHAPED_RECIPE.fromJson( identifier, json ); + JsonObject resultObject = GsonHelper.getAsJsonObject( json, "result" ); + ItemStack itemStack = ShapedRecipe.itemStackFromJson( resultObject ); RecipeUtil.setNbt( itemStack, resultObject ); return new ImpostorRecipe( identifier, group, recipe.getWidth(), recipe.getHeight(), recipe.getIngredients(), itemStack ); } @Override - public ImpostorRecipe read( @Nonnull Identifier identifier, @Nonnull PacketByteBuf buf ) + public ImpostorRecipe fromNetwork( @Nonnull ResourceLocation identifier, @Nonnull FriendlyByteBuf buf ) { int width = buf.readVarInt(); int height = buf.readVarInt(); - String group = buf.readString( Short.MAX_VALUE ); - DefaultedList items = DefaultedList.ofSize( width * height, Ingredient.EMPTY ); + String group = buf.readUtf( Short.MAX_VALUE ); + NonNullList items = NonNullList.withSize( width * height, Ingredient.EMPTY ); for( int k = 0; k < items.size(); ++k ) { - items.set( k, Ingredient.fromPacket( buf ) ); + items.set( k, Ingredient.fromNetwork( buf ) ); } - ItemStack result = buf.readItemStack(); + ItemStack result = buf.readItem(); return new ImpostorRecipe( identifier, group, width, height, items, result ); } @Override - public void write( @Nonnull PacketByteBuf buf, @Nonnull ImpostorRecipe recipe ) + public void toNetwork( @Nonnull FriendlyByteBuf buf, @Nonnull ImpostorRecipe recipe ) { buf.writeVarInt( recipe.getWidth() ); buf.writeVarInt( recipe.getHeight() ); - buf.writeString( recipe.getGroup() ); + buf.writeUtf( recipe.getGroup() ); for( Ingredient ingredient : recipe.getIngredients() ) { - ingredient.write( buf ); + ingredient.toNetwork( buf ); } - buf.writeItemStack( recipe.getOutput() ); + buf.writeItem( recipe.getResultItem() ); } }; private final String group; - private ImpostorRecipe( @Nonnull Identifier id, @Nonnull String group, int width, int height, DefaultedList ingredients, + private ImpostorRecipe( @Nonnull ResourceLocation id, @Nonnull String group, int width, int height, NonNullList ingredients, @Nonnull ItemStack result ) { super( id, group, width, height, ingredients, result ); @@ -87,14 +87,14 @@ public final class ImpostorRecipe extends ShapedRecipe } @Override - public boolean matches( @Nonnull CraftingInventory inv, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inv, @Nonnull Level world ) { return false; } @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inventory ) + public ItemStack assemble( @Nonnull CraftingContainer inventory ) { return ItemStack.EMPTY; } diff --git a/src/main/java/dan200/computercraft/shared/util/ImpostorShapelessRecipe.java b/src/main/java/dan200/computercraft/shared/util/ImpostorShapelessRecipe.java index c2191843a..9b35f3146 100644 --- a/src/main/java/dan200/computercraft/shared/util/ImpostorShapelessRecipe.java +++ b/src/main/java/dan200/computercraft/shared/util/ImpostorShapelessRecipe.java @@ -9,17 +9,17 @@ package dan200.computercraft.shared.util; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; -import net.minecraft.inventory.CraftingInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.network.PacketByteBuf; -import net.minecraft.recipe.Ingredient; -import net.minecraft.recipe.RecipeSerializer; -import net.minecraft.recipe.ShapedRecipe; -import net.minecraft.recipe.ShapelessRecipe; -import net.minecraft.util.Identifier; -import net.minecraft.util.JsonHelper; -import net.minecraft.util.collection.DefaultedList; -import net.minecraft.world.World; +import net.minecraft.core.NonNullList; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.GsonHelper; +import net.minecraft.world.inventory.CraftingContainer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.ShapedRecipe; +import net.minecraft.world.item.crafting.ShapelessRecipe; +import net.minecraft.world.level.Level; import javax.annotation.Nonnull; @@ -28,10 +28,10 @@ public final class ImpostorShapelessRecipe extends ShapelessRecipe public static final RecipeSerializer SERIALIZER = new RecipeSerializer() { @Override - public ImpostorShapelessRecipe read( @Nonnull Identifier id, @Nonnull JsonObject json ) + public ImpostorShapelessRecipe fromJson( @Nonnull ResourceLocation id, @Nonnull JsonObject json ) { - String s = JsonHelper.getString( json, "group", "" ); - DefaultedList ingredients = readIngredients( JsonHelper.getArray( json, "ingredients" ) ); + String s = GsonHelper.getAsString( json, "group", "" ); + NonNullList ingredients = readIngredients( GsonHelper.getAsJsonArray( json, "ingredients" ) ); if( ingredients.isEmpty() ) { @@ -41,15 +41,15 @@ public final class ImpostorShapelessRecipe extends ShapelessRecipe { throw new JsonParseException( "Too many ingredients for shapeless recipe the max is 9" ); } - JsonObject resultObject = JsonHelper.getObject( json, "result" ); - ItemStack itemStack = ShapedRecipe.outputFromJson( resultObject ); + JsonObject resultObject = GsonHelper.getAsJsonObject( json, "result" ); + ItemStack itemStack = ShapedRecipe.itemStackFromJson( resultObject ); RecipeUtil.setNbt( itemStack, resultObject ); return new ImpostorShapelessRecipe( id, s, itemStack, ingredients ); } - private DefaultedList readIngredients( JsonArray arrays ) + private NonNullList readIngredients( JsonArray arrays ) { - DefaultedList items = DefaultedList.of(); + NonNullList items = NonNullList.create(); for( int i = 0; i < arrays.size(); ++i ) { Ingredient ingredient = Ingredient.fromJson( arrays.get( i ) ); @@ -63,38 +63,38 @@ public final class ImpostorShapelessRecipe extends ShapelessRecipe } @Override - public ImpostorShapelessRecipe read( @Nonnull Identifier id, PacketByteBuf buffer ) + public ImpostorShapelessRecipe fromNetwork( @Nonnull ResourceLocation id, FriendlyByteBuf buffer ) { - String s = buffer.readString( 32767 ); + String s = buffer.readUtf( 32767 ); int i = buffer.readVarInt(); - DefaultedList items = DefaultedList.ofSize( i, Ingredient.EMPTY ); + NonNullList items = NonNullList.withSize( i, Ingredient.EMPTY ); for( int j = 0; j < items.size(); j++ ) { - items.set( j, Ingredient.fromPacket( buffer ) ); + items.set( j, Ingredient.fromNetwork( buffer ) ); } - ItemStack result = buffer.readItemStack(); + ItemStack result = buffer.readItem(); return new ImpostorShapelessRecipe( id, s, result, items ); } @Override - public void write( @Nonnull PacketByteBuf buffer, @Nonnull ImpostorShapelessRecipe recipe ) + public void toNetwork( @Nonnull FriendlyByteBuf buffer, @Nonnull ImpostorShapelessRecipe recipe ) { - buffer.writeString( recipe.getGroup() ); + buffer.writeUtf( recipe.getGroup() ); buffer.writeVarInt( recipe.getIngredients() .size() ); for( Ingredient ingredient : recipe.getIngredients() ) { - ingredient.write( buffer ); + ingredient.toNetwork( buffer ); } - buffer.writeItemStack( recipe.getOutput() ); + buffer.writeItem( recipe.getResultItem() ); } }; private final String group; - private ImpostorShapelessRecipe( @Nonnull Identifier id, @Nonnull String group, @Nonnull ItemStack result, DefaultedList ingredients ) + private ImpostorShapelessRecipe( @Nonnull ResourceLocation id, @Nonnull String group, @Nonnull ItemStack result, NonNullList ingredients ) { super( id, group, result, ingredients ); this.group = group; @@ -115,14 +115,14 @@ public final class ImpostorShapelessRecipe extends ShapelessRecipe } @Override - public boolean matches( @Nonnull CraftingInventory inv, @Nonnull World world ) + public boolean matches( @Nonnull CraftingContainer inv, @Nonnull Level world ) { return false; } @Nonnull @Override - public ItemStack craft( @Nonnull CraftingInventory inventory ) + public ItemStack assemble( @Nonnull CraftingContainer inventory ) { return ItemStack.EMPTY; } diff --git a/src/main/java/dan200/computercraft/shared/util/InventoryDelegate.java b/src/main/java/dan200/computercraft/shared/util/InventoryDelegate.java index 41af4a582..88c548cb1 100644 --- a/src/main/java/dan200/computercraft/shared/util/InventoryDelegate.java +++ b/src/main/java/dan200/computercraft/shared/util/InventoryDelegate.java @@ -6,10 +6,10 @@ package dan200.computercraft.shared.util; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; import java.util.Set; @@ -21,15 +21,15 @@ import java.util.Set; * inventories which change their backing store. */ @FunctionalInterface -public interface InventoryDelegate extends Inventory +public interface InventoryDelegate extends Container { @Override - default int size() + default int getContainerSize() { - return getInventory().size(); + return getInventory().getContainerSize(); } - Inventory getInventory(); + Container getInventory(); @Override default boolean isEmpty() @@ -39,82 +39,82 @@ public interface InventoryDelegate extends Inventory @Nonnull @Override - default ItemStack getStack( int slot ) + default ItemStack getItem( int slot ) { - return getInventory().getStack( slot ); + return getInventory().getItem( slot ); } @Nonnull @Override - default ItemStack removeStack( int slot, int count ) + default ItemStack removeItem( int slot, int count ) { - return getInventory().removeStack( slot, count ); + return getInventory().removeItem( slot, count ); } @Nonnull @Override - default ItemStack removeStack( int slot ) + default ItemStack removeItemNoUpdate( int slot ) { - return getInventory().removeStack( slot ); + return getInventory().removeItemNoUpdate( slot ); } @Override - default void setStack( int slot, @Nonnull ItemStack stack ) + default void setItem( int slot, @Nonnull ItemStack stack ) { - getInventory().setStack( slot, stack ); + getInventory().setItem( slot, stack ); } @Override - default int getMaxCountPerStack() + default int getMaxStackSize() { - return getInventory().getMaxCountPerStack(); + return getInventory().getMaxStackSize(); } @Override - default void markDirty() + default void setChanged() { - getInventory().markDirty(); + getInventory().setChanged(); } @Override - default boolean canPlayerUse( @Nonnull PlayerEntity player ) + default boolean stillValid( @Nonnull Player player ) { - return getInventory().canPlayerUse( player ); + return getInventory().stillValid( player ); } @Override - default void onOpen( @Nonnull PlayerEntity player ) + default void startOpen( @Nonnull Player player ) { - getInventory().onOpen( player ); + getInventory().startOpen( player ); } @Override - default void onClose( @Nonnull PlayerEntity player ) + default void stopOpen( @Nonnull Player player ) { - getInventory().onClose( player ); + getInventory().stopOpen( player ); } @Override - default boolean isValid( int slot, @Nonnull ItemStack stack ) + default boolean canPlaceItem( int slot, @Nonnull ItemStack stack ) { - return getInventory().isValid( slot, stack ); + return getInventory().canPlaceItem( slot, stack ); } @Override - default int count( @Nonnull Item stack ) + default int countItem( @Nonnull Item stack ) { - return getInventory().count( stack ); + return getInventory().countItem( stack ); } @Override - default boolean containsAny( @Nonnull Set set ) + default boolean hasAnyOf( @Nonnull Set set ) { - return getInventory().containsAny( set ); + return getInventory().hasAnyOf( set ); } @Override - default void clear() + default void clearContent() { - getInventory().clear(); + getInventory().clearContent(); } } diff --git a/src/main/java/dan200/computercraft/shared/util/InventoryUtil.java b/src/main/java/dan200/computercraft/shared/util/InventoryUtil.java index 9d836718b..c520c0646 100644 --- a/src/main/java/dan200/computercraft/shared/util/InventoryUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/InventoryUtil.java @@ -6,19 +6,19 @@ package dan200.computercraft.shared.util; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.ChestBlock; -import net.minecraft.block.InventoryProvider; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.block.entity.ChestBlockEntity; -import net.minecraft.entity.Entity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.Container; +import net.minecraft.world.WorldlyContainerHolder; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.ChestBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; @@ -30,12 +30,12 @@ public final class InventoryUtil public static boolean areItemsStackable( @Nonnull ItemStack a, @Nonnull ItemStack b ) { - return a == b || (a.getItem() == b.getItem() && ItemStack.areNbtEqual( a, b )); + return a == b || (a.getItem() == b.getItem() && ItemStack.tagMatches( a, b )); } // Methods for finding inventories: - public static Inventory getInventory( World world, BlockPos pos, Direction side ) + public static Container getInventory( Level world, BlockPos pos, Direction side ) { // Look for tile with inventory int y = pos.getY(); @@ -44,16 +44,16 @@ public final class InventoryUtil // Check if block is InventoryProvider BlockState blockState = world.getBlockState( pos ); Block block = blockState.getBlock(); - if( block instanceof InventoryProvider ) + if( block instanceof WorldlyContainerHolder ) { - return ((InventoryProvider) block).getInventory( blockState, world, pos ); + return ((WorldlyContainerHolder) block).getContainer( blockState, world, pos ); } // Check if block is BlockEntity w/ Inventory if( blockState.hasBlockEntity() ) { BlockEntity tileEntity = world.getBlockEntity( pos ); - Inventory inventory = getInventory( tileEntity ); + Container inventory = getInventory( tileEntity ); if( inventory != null ) { return inventory; @@ -62,36 +62,36 @@ public final class InventoryUtil } // Look for entity with inventory - Vec3d vecStart = new Vec3d( pos.getX() + 0.5 + 0.6 * side.getOffsetX(), - pos.getY() + 0.5 + 0.6 * side.getOffsetY(), - pos.getZ() + 0.5 + 0.6 * side.getOffsetZ() ); + Vec3 vecStart = new Vec3( pos.getX() + 0.5 + 0.6 * side.getStepX(), + pos.getY() + 0.5 + 0.6 * side.getStepY(), + pos.getZ() + 0.5 + 0.6 * side.getStepZ() ); Direction dir = side.getOpposite(); - Vec3d vecDir = new Vec3d( dir.getOffsetX(), dir.getOffsetY(), dir.getOffsetZ() ); - Pair hit = WorldUtil.rayTraceEntities( world, vecStart, vecDir, 1.1 ); + Vec3 vecDir = new Vec3( dir.getStepX(), dir.getStepY(), dir.getStepZ() ); + Pair hit = WorldUtil.rayTraceEntities( world, vecStart, vecDir, 1.1 ); if( hit != null ) { Entity entity = hit.getKey(); - if( entity instanceof Inventory ) + if( entity instanceof Container ) { - return (Inventory) entity; + return (Container) entity; } } return null; } - public static Inventory getInventory( BlockEntity tileEntity ) + public static Container getInventory( BlockEntity tileEntity ) { - World world = tileEntity.getWorld(); - BlockPos pos = tileEntity.getPos(); + Level world = tileEntity.getLevel(); + BlockPos pos = tileEntity.getBlockPos(); BlockState blockState = world.getBlockState( pos ); Block block = blockState.getBlock(); - if( tileEntity instanceof Inventory ) + if( tileEntity instanceof Container ) { - Inventory inventory = (Inventory) tileEntity; + Container inventory = (Container) tileEntity; if( inventory instanceof ChestBlockEntity && block instanceof ChestBlock ) { - return ChestBlock.getInventory( (ChestBlock) block, blockState, world, pos, true ); + return ChestBlock.getContainer( (ChestBlock) block, blockState, world, pos, true ); } return inventory; } @@ -131,7 +131,7 @@ public final class InventoryUtil public static boolean areItemsEqual( @Nonnull ItemStack a, @Nonnull ItemStack b ) { - return a == b || ItemStack.areEqual( a, b ); + return a == b || ItemStack.matches( a, b ); } @Nonnull @@ -173,11 +173,11 @@ public final class InventoryUtil { // If we've extracted for this first time, then limit the count to the maximum stack size. partialStack = extracted; - count = Math.min( count, extracted.getMaxCount() ); + count = Math.min( count, extracted.getMaxStackSize() ); } else { - partialStack.increment( extracted.getCount() ); + partialStack.grow( extracted.getCount() ); } } diff --git a/src/main/java/dan200/computercraft/shared/util/InvisibleSlot.java b/src/main/java/dan200/computercraft/shared/util/InvisibleSlot.java index 1e36de8ca..cea2cb706 100644 --- a/src/main/java/dan200/computercraft/shared/util/InvisibleSlot.java +++ b/src/main/java/dan200/computercraft/shared/util/InvisibleSlot.java @@ -5,34 +5,34 @@ */ package dan200.computercraft.shared.util; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.slot.Slot; +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; public class InvisibleSlot extends Slot { - public InvisibleSlot( Inventory container, int slot ) + public InvisibleSlot( Container container, int slot ) { super( container, slot, 0, 0 ); } @Override - public boolean canInsert( @Nonnull ItemStack stack ) + public boolean mayPlace( @Nonnull ItemStack stack ) { return false; } @Override - public boolean canTakeItems( @Nonnull PlayerEntity player ) + public boolean mayPickup( @Nonnull Player player ) { return false; } @Override - public boolean isEnabled() + public boolean isActive() { return false; } diff --git a/src/main/java/dan200/computercraft/shared/util/ItemStorage.java b/src/main/java/dan200/computercraft/shared/util/ItemStorage.java index 2868ad395..dcca803fe 100644 --- a/src/main/java/dan200/computercraft/shared/util/ItemStorage.java +++ b/src/main/java/dan200/computercraft/shared/util/ItemStorage.java @@ -5,10 +5,10 @@ */ package dan200.computercraft.shared.util; -import net.minecraft.inventory.Inventory; -import net.minecraft.inventory.SidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.Direction; +import net.minecraft.core.Direction; +import net.minecraft.world.Container; +import net.minecraft.world.WorldlyContainer; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; @@ -17,24 +17,24 @@ import javax.annotation.Nonnull; */ public interface ItemStorage { - static ItemStorage wrap( Inventory inventory ) + static ItemStorage wrap( Container inventory ) { return new InventoryWrapper( inventory ); } - static ItemStorage wrap( @Nonnull SidedInventory inventory, @Nonnull Direction facing ) + static ItemStorage wrap( @Nonnull WorldlyContainer inventory, @Nonnull Direction facing ) { return new SidedInventoryWrapper( inventory, facing ); } - static ItemStorage wrap( @Nonnull Inventory inventory, @Nonnull Direction facing ) + static ItemStorage wrap( @Nonnull Container inventory, @Nonnull Direction facing ) { - return inventory instanceof SidedInventory ? new SidedInventoryWrapper( (SidedInventory) inventory, facing ) : new InventoryWrapper( inventory ); + return inventory instanceof WorldlyContainer ? new SidedInventoryWrapper( (WorldlyContainer) inventory, facing ) : new InventoryWrapper( inventory ); } static boolean areStackable( @Nonnull ItemStack a, @Nonnull ItemStack b ) { - return a == b || (a.getItem() == b.getItem() && ItemStack.areNbtEqual( a, b )); + return a == b || (a.getItem() == b.getItem() && ItemStack.tagMatches( a, b )); } int size(); @@ -55,9 +55,9 @@ public interface ItemStorage class InventoryWrapper implements ItemStorage { - private final Inventory inventory; + private final Container inventory; - InventoryWrapper( Inventory inventory ) + InventoryWrapper( Container inventory ) { this.inventory = inventory; } @@ -65,21 +65,21 @@ public interface ItemStorage @Override public int size() { - return inventory.size(); + return inventory.getContainerSize(); } @Override @Nonnull public ItemStack getStack( int slot ) { - return inventory.getStack( slot ); + return inventory.getItem( slot ); } @Override @Nonnull public ItemStack take( int slot, int limit, @Nonnull ItemStack filter, boolean simulate ) { - ItemStack existing = inventory.getStack( slot ); + ItemStack existing = inventory.getItem( slot ); if( existing.isEmpty() || !canExtract( slot, existing ) || (!filter.isEmpty() && !areStackable( existing, filter )) ) { return ItemStack.EMPTY; @@ -114,23 +114,23 @@ public interface ItemStorage private void setAndDirty( int slot, @Nonnull ItemStack stack ) { - inventory.setStack( slot, stack ); - inventory.markDirty(); + inventory.setItem( slot, stack ); + inventory.setChanged(); } @Override @Nonnull public ItemStack store( int slot, @Nonnull ItemStack stack, boolean simulate ) { - if( stack.isEmpty() || !inventory.isValid( slot, stack ) ) + if( stack.isEmpty() || !inventory.canPlaceItem( slot, stack ) ) { return stack; } - ItemStack existing = inventory.getStack( slot ); + ItemStack existing = inventory.getItem( slot ); if( existing.isEmpty() ) { - int limit = Math.min( stack.getMaxCount(), inventory.getMaxCountPerStack() ); + int limit = Math.min( stack.getMaxStackSize(), inventory.getMaxStackSize() ); if( limit <= 0 ) { return stack; @@ -157,7 +157,7 @@ public interface ItemStorage } else if( areStackable( stack, existing ) ) { - int limit = Math.min( existing.getMaxCount(), inventory.getMaxCountPerStack() ) - existing.getCount(); + int limit = Math.min( existing.getMaxStackSize(), inventory.getMaxStackSize() ) - existing.getCount(); if( limit <= 0 ) { return stack; @@ -167,7 +167,7 @@ public interface ItemStorage { if( !simulate ) { - existing.increment( stack.getCount() ); + existing.grow( stack.getCount() ); setAndDirty( slot, existing ); } return ItemStack.EMPTY; @@ -175,10 +175,10 @@ public interface ItemStorage else { stack = stack.copy(); - stack.decrement( limit ); + stack.shrink( limit ); if( !simulate ) { - existing.increment( limit ); + existing.grow( limit ); setAndDirty( slot, existing ); } return stack; @@ -193,10 +193,10 @@ public interface ItemStorage class SidedInventoryWrapper extends InventoryWrapper { - private final SidedInventory inventory; + private final WorldlyContainer inventory; private final Direction facing; - SidedInventoryWrapper( SidedInventory inventory, Direction facing ) + SidedInventoryWrapper( WorldlyContainer inventory, Direction facing ) { super( inventory ); this.inventory = inventory; @@ -206,20 +206,20 @@ public interface ItemStorage @Override protected boolean canExtract( int slot, ItemStack stack ) { - return super.canExtract( slot, stack ) && inventory.canExtract( slot, stack, facing ); + return super.canExtract( slot, stack ) && inventory.canTakeItemThroughFace( slot, stack, facing ); } @Override public int size() { - return inventory.getAvailableSlots( facing ).length; + return inventory.getSlotsForFace( facing ).length; } @Nonnull @Override public ItemStack take( int slot, int limit, @Nonnull ItemStack filter, boolean simulate ) { - int[] slots = inventory.getAvailableSlots( facing ); + int[] slots = inventory.getSlotsForFace( facing ); return slot >= 0 && slot < slots.length ? super.take( slots[slot], limit, filter, simulate ) : ItemStack.EMPTY; } @@ -227,14 +227,14 @@ public interface ItemStorage @Override public ItemStack store( int slot, @Nonnull ItemStack stack, boolean simulate ) { - int[] slots = inventory.getAvailableSlots( facing ); + int[] slots = inventory.getSlotsForFace( facing ); if( slot < 0 || slot >= slots.length ) { return stack; } int mappedSlot = slots[slot]; - if( !inventory.canInsert( slot, stack, facing ) ) + if( !inventory.canPlaceItemThroughFace( slot, stack, facing ) ) { return stack; } diff --git a/src/main/java/dan200/computercraft/shared/util/NBTUtil.java b/src/main/java/dan200/computercraft/shared/util/NBTUtil.java index 38d4fb494..80d3c67f3 100644 --- a/src/main/java/dan200/computercraft/shared/util/NBTUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/NBTUtil.java @@ -40,7 +40,7 @@ public final class NBTUtil private NBTUtil() {} - private static NbtElement toNBTTag( Object object ) + private static Tag toNBTTag( Object object ) { if( object == null ) { @@ -48,25 +48,25 @@ public final class NBTUtil } if( object instanceof Boolean ) { - return NbtByte.of( (byte) ((boolean) (Boolean) object ? 1 : 0) ); + return ByteTag.valueOf( (byte) ((boolean) (Boolean) object ? 1 : 0) ); } if( object instanceof Number ) { - return NbtDouble.of( ((Number) object).doubleValue() ); + return DoubleTag.valueOf( ((Number) object).doubleValue() ); } if( object instanceof String ) { - return NbtString.of( object.toString() ); + return StringTag.valueOf( object.toString() ); } if( object instanceof Map ) { Map m = (Map) object; - NbtCompound nbt = new NbtCompound(); + CompoundTag nbt = new CompoundTag(); int i = 0; for( Map.Entry entry : m.entrySet() ) { - NbtElement key = toNBTTag( entry.getKey() ); - NbtElement value = toNBTTag( entry.getKey() ); + Tag key = toNBTTag( entry.getKey() ); + Tag value = toNBTTag( entry.getKey() ); if( key != null && value != null ) { nbt.put( "k" + i, key ); @@ -81,18 +81,18 @@ public final class NBTUtil return null; } - public static NbtCompound encodeObjects( Object[] objects ) + public static CompoundTag encodeObjects( Object[] objects ) { if( objects == null || objects.length <= 0 ) { return null; } - NbtCompound nbt = new NbtCompound(); + CompoundTag nbt = new CompoundTag(); nbt.putInt( "len", objects.length ); for( int i = 0; i < objects.length; i++ ) { - NbtElement child = toNBTTag( objects[i] ); + Tag child = toNBTTag( objects[i] ); if( child != null ) { nbt.put( Integer.toString( i ), child ); @@ -101,23 +101,23 @@ public final class NBTUtil return nbt; } - private static Object fromNBTTag( NbtElement tag ) + private static Object fromNBTTag( Tag tag ) { if( tag == null ) { return null; } - switch( tag.getType() ) + switch( tag.getId() ) { case TAG_BYTE: - return ((NbtByte) tag).byteValue() > 0; + return ((ByteTag) tag).getAsByte() > 0; case TAG_DOUBLE: - return ((NbtDouble) tag).doubleValue(); + return ((DoubleTag) tag).getAsDouble(); default: case TAG_STRING: - return tag.asString(); + return tag.getAsString(); case TAG_COMPOUND: - NbtCompound c = (NbtCompound) tag; + CompoundTag c = (CompoundTag) tag; int len = c.getInt( "len" ); Map map = new HashMap<>( len ); for( int i = 0; i < len; i++ ) @@ -133,31 +133,31 @@ public final class NBTUtil } } - public static Object toLua( NbtElement tag ) + public static Object toLua( Tag tag ) { if( tag == null ) { return null; } - byte typeID = tag.getType(); + byte typeID = tag.getId(); switch( typeID ) { case TAG_BYTE: case TAG_SHORT: case TAG_INT: case TAG_LONG: - return ((AbstractNbtNumber) tag).longValue(); + return ((NumericTag) tag).getAsLong(); case TAG_FLOAT: case TAG_DOUBLE: - return ((AbstractNbtNumber) tag).doubleValue(); + return ((NumericTag) tag).getAsDouble(); case TAG_STRING: // String - return tag.asString(); + return tag.getAsString(); case TAG_COMPOUND: // Compound { - NbtCompound compound = (NbtCompound) tag; - Map map = new HashMap<>( compound.getSize() ); - for( String key : compound.getKeys() ) + CompoundTag compound = (CompoundTag) tag; + Map map = new HashMap<>( compound.size() ); + for( String key : compound.getAllKeys() ) { Object value = toLua( compound.get( key ) ); if( value != null ) @@ -169,7 +169,7 @@ public final class NBTUtil } case TAG_LIST: { - NbtList list = (NbtList) tag; + ListTag list = (ListTag) tag; Map map = new HashMap<>( list.size() ); for( int i = 0; i < list.size(); i++ ) { @@ -179,7 +179,7 @@ public final class NBTUtil } case TAG_BYTE_ARRAY: { - byte[] array = ((NbtByteArray) tag).getByteArray(); + byte[] array = ((ByteArrayTag) tag).getAsByteArray(); Map map = new HashMap<>( array.length ); for( int i = 0; i < array.length; i++ ) { @@ -188,7 +188,7 @@ public final class NBTUtil return map; } case TAG_INT_ARRAY: - int[] array = ((NbtIntArray) tag).getIntArray(); + int[] array = ((IntArrayTag) tag).getAsIntArray(); Map map = new HashMap<>( array.length ); for( int i = 0; i < array.length; i++ ) { @@ -201,7 +201,7 @@ public final class NBTUtil } } - public static Object[] decodeObjects( NbtCompound tag ) + public static Object[] decodeObjects( CompoundTag tag ) { int len = tag.getInt( "len" ); if( len <= 0 ) @@ -222,7 +222,7 @@ public final class NBTUtil } @Nullable - public static String getNBTHash( @Nullable NbtCompound tag ) + public static String getNBTHash( @Nullable CompoundTag tag ) { if( tag == null ) { diff --git a/src/main/java/dan200/computercraft/shared/util/Palette.java b/src/main/java/dan200/computercraft/shared/util/Palette.java index 2b4d65b52..4f4713f30 100644 --- a/src/main/java/dan200/computercraft/shared/util/Palette.java +++ b/src/main/java/dan200/computercraft/shared/util/Palette.java @@ -6,8 +6,8 @@ package dan200.computercraft.shared.util; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.network.PacketByteBuf; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; public class Palette { @@ -61,7 +61,7 @@ public class Palette return null; } - public void write( PacketByteBuf buffer ) + public void write( FriendlyByteBuf buffer ) { for( double[] colour : colours ) { @@ -72,7 +72,7 @@ public class Palette } } - public void read( PacketByteBuf buffer ) + public void read( FriendlyByteBuf buffer ) { for( double[] colour : colours ) { @@ -83,7 +83,7 @@ public class Palette } } - public NbtCompound writeToNBT( NbtCompound nbt ) + public CompoundTag writeToNBT( CompoundTag nbt ) { int[] rgb8 = new int[colours.length]; @@ -105,7 +105,7 @@ public class Palette return (r << 16) | (g << 8) | b; } - public void readFromNBT( NbtCompound nbt ) + public void readFromNBT( CompoundTag nbt ) { if( !nbt.contains( "term_palette" ) ) { diff --git a/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java b/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java index 167933b8e..24babefbc 100644 --- a/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/RecipeUtil.java @@ -11,11 +11,11 @@ import com.google.common.collect.Sets; import com.google.gson.*; import com.mojang.brigadier.exceptions.CommandSyntaxException; import dan200.computercraft.shared.computer.core.ComputerFamily; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.StringNbtReader; -import net.minecraft.recipe.Ingredient; -import net.minecraft.util.JsonHelper; -import net.minecraft.util.collection.DefaultedList; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.TagParser; +import net.minecraft.util.GsonHelper; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; import java.util.Map; import java.util.Set; @@ -25,12 +25,13 @@ import java.util.Set; public final class RecipeUtil { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + private RecipeUtil() {} public static ShapedTemplate getTemplate( JsonObject json ) { Map ingMap = Maps.newHashMap(); - for( Map.Entry entry : JsonHelper.getObject( json, "key" ) + for( Map.Entry entry : GsonHelper.getAsJsonObject( json, "key" ) .entrySet() ) { if( entry.getKey() @@ -49,7 +50,7 @@ public final class RecipeUtil ingMap.put( ' ', Ingredient.EMPTY ); - JsonArray patternJ = JsonHelper.getArray( json, "pattern" ); + JsonArray patternJ = GsonHelper.getAsJsonArray( json, "pattern" ); if( patternJ.size() == 0 ) { @@ -59,7 +60,7 @@ public final class RecipeUtil String[] pattern = new String[patternJ.size()]; for( int x = 0; x < pattern.length; x++ ) { - String line = JsonHelper.asString( patternJ.get( x ), "pattern[" + x + "]" ); + String line = GsonHelper.convertToString( patternJ.get( x ), "pattern[" + x + "]" ); if( x > 0 && pattern[0].length() != line.length() ) { throw new JsonSyntaxException( "Invalid pattern: each row must be the same width" ); @@ -69,7 +70,7 @@ public final class RecipeUtil int width = pattern[0].length(); int height = pattern.length; - DefaultedList ingredients = DefaultedList.ofSize( width * height, Ingredient.EMPTY ); + NonNullList ingredients = NonNullList.withSize( width * height, Ingredient.EMPTY ); Set missingKeys = Sets.newHashSet( ingMap.keySet() ); missingKeys.remove( ' ' ); @@ -99,7 +100,7 @@ public final class RecipeUtil public static ComputerFamily getFamily( JsonObject json, String name ) { - String familyName = JsonHelper.getString( json, name ); + String familyName = GsonHelper.getAsString( json, name ); for( ComputerFamily family : ComputerFamily.values() ) { if( family.name() @@ -115,11 +116,11 @@ public final class RecipeUtil public static void setNbt( ItemStack itemStack, JsonObject result ) { JsonElement nbtElement = result.get( "nbt" ); - if ( nbtElement != null ) + if( nbtElement != null ) { try { - itemStack.setNbt( StringNbtReader.parse( nbtElement.isJsonObject() ? GSON.toJson( nbtElement ) : JsonHelper.asString( nbtElement, "nbt" ) ) ); + itemStack.setTag( TagParser.parseTag( nbtElement.isJsonObject() ? GSON.toJson( nbtElement ) : GsonHelper.convertToString( nbtElement, "nbt" ) ) ); } catch( CommandSyntaxException e ) { @@ -132,9 +133,9 @@ public final class RecipeUtil { public final int width; public final int height; - public final DefaultedList ingredients; + public final NonNullList ingredients; - public ShapedTemplate( int width, int height, DefaultedList ingredients ) + public ShapedTemplate( int width, int height, NonNullList ingredients ) { this.width = width; this.height = height; diff --git a/src/main/java/dan200/computercraft/shared/util/RecordUtil.java b/src/main/java/dan200/computercraft/shared/util/RecordUtil.java index 30de0b841..4e56e3bb5 100644 --- a/src/main/java/dan200/computercraft/shared/util/RecordUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/RecordUtil.java @@ -3,24 +3,23 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.util; import dan200.computercraft.shared.network.NetworkHandler; import dan200.computercraft.shared.network.NetworkMessage; import dan200.computercraft.shared.network.client.PlayRecordClientMessage; -import net.minecraft.sound.SoundEvent; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; public final class RecordUtil { private RecordUtil() {} - public static void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos ) + public static void playRecord( SoundEvent record, String recordInfo, Level world, BlockPos pos ) { NetworkMessage packet = record != null ? new PlayRecordClientMessage( pos, record, recordInfo ) : new PlayRecordClientMessage( pos ); - NetworkHandler.sendToAllAround( packet, world, Vec3d.ofCenter( pos ), 64 ); + NetworkHandler.sendToAllAround( packet, world, Vec3.atCenterOf( pos ), 64 ); } } diff --git a/src/main/java/dan200/computercraft/shared/util/RedstoneUtil.java b/src/main/java/dan200/computercraft/shared/util/RedstoneUtil.java index ca27dcde5..5de8bdd7f 100644 --- a/src/main/java/dan200/computercraft/shared/util/RedstoneUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/RedstoneUtil.java @@ -6,19 +6,19 @@ package dan200.computercraft.shared.util; -import net.minecraft.block.BlockState; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; public final class RedstoneUtil { - public static void propagateRedstoneOutput( World world, BlockPos pos, Direction side ) + public static void propagateRedstoneOutput( Level world, BlockPos pos, Direction side ) { // Propagate ordinary output. See BlockRedstoneDiode.notifyNeighbors BlockState block = world.getBlockState( pos ); - BlockPos neighbourPos = pos.offset( side ); - world.updateNeighbor( neighbourPos, block.getBlock(), pos ); - world.updateNeighborsExcept( neighbourPos, block.getBlock(), side.getOpposite() ); + BlockPos neighbourPos = pos.relative( side ); + world.neighborChanged( neighbourPos, block.getBlock(), pos ); + world.updateNeighborsAtExceptFromFacing( neighbourPos, block.getBlock(), side.getOpposite() ); } } diff --git a/src/main/java/dan200/computercraft/shared/util/SingleIntArray.java b/src/main/java/dan200/computercraft/shared/util/SingleIntArray.java index 4e9141232..1329f1352 100644 --- a/src/main/java/dan200/computercraft/shared/util/SingleIntArray.java +++ b/src/main/java/dan200/computercraft/shared/util/SingleIntArray.java @@ -6,10 +6,10 @@ package dan200.computercraft.shared.util; -import net.minecraft.screen.PropertyDelegate; +import net.minecraft.world.inventory.ContainerData; @FunctionalInterface -public interface SingleIntArray extends PropertyDelegate +public interface SingleIntArray extends ContainerData { @Override default int get( int property ) @@ -25,7 +25,7 @@ public interface SingleIntArray extends PropertyDelegate } @Override - default int size() + default int getCount() { return 1; } diff --git a/src/main/java/dan200/computercraft/shared/util/TickScheduler.java b/src/main/java/dan200/computercraft/shared/util/TickScheduler.java index 98e3a8036..3ba67807b 100644 --- a/src/main/java/dan200/computercraft/shared/util/TickScheduler.java +++ b/src/main/java/dan200/computercraft/shared/util/TickScheduler.java @@ -8,9 +8,9 @@ package dan200.computercraft.shared.util; import com.google.common.collect.MapMaker; import dan200.computercraft.shared.common.TileGeneric; -import net.minecraft.block.entity.BlockEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; import java.util.Collections; import java.util.Iterator; @@ -30,8 +30,8 @@ public final class TickScheduler public static void schedule( TileGeneric tile ) { - World world = tile.getWorld(); - if( world != null && !world.isClient ) + Level world = tile.getLevel(); + if( world != null && !world.isClientSide ) { toTick.add( tile ); } @@ -45,14 +45,14 @@ public final class TickScheduler BlockEntity tile = iterator.next(); iterator.remove(); - World world = tile.getWorld(); - BlockPos pos = tile.getPos(); + Level world = tile.getLevel(); + BlockPos pos = tile.getBlockPos(); - if( world != null && pos != null && world.isChunkLoaded( pos ) && world.getBlockEntity( pos ) == tile ) + if( world != null && pos != null && world.hasChunkAt( pos ) && world.getBlockEntity( pos ) == tile ) { - world.getBlockTickScheduler() - .schedule( pos, - tile.getCachedState() + world.getBlockTicks() + .scheduleTick( pos, + tile.getBlockState() .getBlock(), 0 ); } diff --git a/src/main/java/dan200/computercraft/shared/util/ValidatingSlot.java b/src/main/java/dan200/computercraft/shared/util/ValidatingSlot.java index aa1e50940..42ca181d4 100644 --- a/src/main/java/dan200/computercraft/shared/util/ValidatingSlot.java +++ b/src/main/java/dan200/computercraft/shared/util/ValidatingSlot.java @@ -3,24 +3,23 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.util; -import net.minecraft.inventory.Inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.screen.slot.Slot; +import net.minecraft.world.Container; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; import javax.annotation.Nonnull; public class ValidatingSlot extends Slot { - public ValidatingSlot( Inventory inventoryIn, int index, int xPosition, int yPosition ) + public ValidatingSlot( Container inventoryIn, int index, int xPosition, int yPosition ) { super( inventoryIn, index, xPosition, yPosition ); } @Override - public boolean canInsert( @Nonnull ItemStack stack ) + public boolean mayPlace( @Nonnull ItemStack stack ) { return true; // inventory.isItemValidForSlot( slotNumber, stack ); } diff --git a/src/main/java/dan200/computercraft/shared/util/WaterloggableHelpers.java b/src/main/java/dan200/computercraft/shared/util/WaterloggableHelpers.java index 7703ab8ef..414c88c3e 100644 --- a/src/main/java/dan200/computercraft/shared/util/WaterloggableHelpers.java +++ b/src/main/java/dan200/computercraft/shared/util/WaterloggableHelpers.java @@ -6,14 +6,14 @@ package dan200.computercraft.shared.util; -import net.minecraft.block.BlockState; -import net.minecraft.fluid.FluidState; -import net.minecraft.fluid.Fluids; -import net.minecraft.item.ItemPlacementContext; -import net.minecraft.state.property.BooleanProperty; -import net.minecraft.state.property.Properties; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.WorldAccess; +import net.minecraft.core.BlockPos; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.block.state.properties.BooleanProperty; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Fluids; /** * Represents a block which can be filled with water @@ -22,43 +22,43 @@ import net.minecraft.world.WorldAccess; */ public final class WaterloggableHelpers { - public static final BooleanProperty WATERLOGGED = Properties.WATERLOGGED; + public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; private WaterloggableHelpers() { } /** - * Call from {@link net.minecraft.block.Block#getFluidState(BlockState)}. + * Call from {@link net.minecraft.world.level.block.Block#getFluidState(BlockState)}. * * @param state The current state * @return This waterlogged block's current fluid */ public static FluidState getWaterloggedFluidState( BlockState state ) { - return state.get( WATERLOGGED ) ? Fluids.WATER.getStill( false ) : Fluids.EMPTY.getDefaultState(); + return state.getValue( WATERLOGGED ) ? Fluids.WATER.getSource( false ) : Fluids.EMPTY.defaultFluidState(); } /** - * Call from {@link net.minecraft.block.Block#updatePostPlacement(BlockState, Direction, BlockState, IWorld, BlockPos, BlockPos)}. + * Call from {@link net.minecraft.world.level.block.Block#updatePostPlacement(BlockState, Direction, BlockState, IWorld, BlockPos, BlockPos)}. * * @param state The current state * @param world The position of this block * @param pos The world this block exists in */ - public static void updateWaterloggedPostPlacement( BlockState state, WorldAccess world, BlockPos pos ) + public static void updateWaterloggedPostPlacement( BlockState state, LevelAccessor world, BlockPos pos ) { - if( state.get( WATERLOGGED ) ) + if( state.getValue( WATERLOGGED ) ) { - world.getFluidTickScheduler() - .schedule( pos, Fluids.WATER, Fluids.WATER.getTickRate( world ) ); + world.getLiquidTicks() + .scheduleTick( pos, Fluids.WATER, Fluids.WATER.getTickDelay( world ) ); } } - public static boolean getWaterloggedStateForPlacement( ItemPlacementContext context ) + public static boolean getWaterloggedStateForPlacement( BlockPlaceContext context ) { - return context.getWorld() - .getFluidState( context.getBlockPos() ) - .getFluid() == Fluids.WATER; + return context.getLevel() + .getFluidState( context.getClickedPos() ) + .getType() == Fluids.WATER; } } diff --git a/src/main/java/dan200/computercraft/shared/util/WorldUtil.java b/src/main/java/dan200/computercraft/shared/util/WorldUtil.java index 33c153401..42bb791b3 100644 --- a/src/main/java/dan200/computercraft/shared/util/WorldUtil.java +++ b/src/main/java/dan200/computercraft/shared/util/WorldUtil.java @@ -8,17 +8,18 @@ package dan200.computercraft.shared.util; import com.google.common.base.Predicate; import com.google.common.collect.MapMaker; -import net.minecraft.entity.*; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.RaycastContext; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.VoxelShape; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; @@ -28,15 +29,15 @@ import java.util.Map; public final class WorldUtil { @SuppressWarnings( "Guava" ) - private static final Predicate CAN_COLLIDE = x -> x != null && x.isAlive() && x.collides(); + private static final Predicate CAN_COLLIDE = x -> x != null && x.isAlive() && x.isPickable(); - private static final Map entityCache = new MapMaker().weakKeys() + private static final Map entityCache = new MapMaker().weakKeys() .weakValues() .makeMap(); - public static boolean isLiquidBlock( World world, BlockPos pos ) + public static boolean isLiquidBlock( Level world, BlockPos pos ) { - if( !world.isInBuildLimit( pos ) ) + if( !world.isInWorldBounds( pos ) ) { return false; } @@ -45,33 +46,33 @@ public final class WorldUtil .isLiquid(); } - public static boolean isVecInside( VoxelShape shape, Vec3d vec ) + public static boolean isVecInside( VoxelShape shape, Vec3 vec ) { if( shape.isEmpty() ) { return false; } // AxisAlignedBB.contains, but without strict inequalities. - Box bb = shape.getBoundingBox(); + AABB bb = shape.bounds(); return vec.x >= bb.minX && vec.x <= bb.maxX && vec.y >= bb.minY && vec.y <= bb.maxY && vec.z >= bb.minZ && vec.z <= bb.maxZ; } - public static Pair rayTraceEntities( World world, Vec3d vecStart, Vec3d vecDir, double distance ) + public static Pair rayTraceEntities( Level world, Vec3 vecStart, Vec3 vecDir, double distance ) { - Vec3d vecEnd = vecStart.add( vecDir.x * distance, vecDir.y * distance, vecDir.z * distance ); + Vec3 vecEnd = vecStart.add( vecDir.x * distance, vecDir.y * distance, vecDir.z * distance ); // Raycast for blocks Entity collisionEntity = getEntity( world ); - collisionEntity.setPosition( vecStart.x, vecStart.y, vecStart.z ); - RaycastContext context = new RaycastContext( vecStart, + collisionEntity.setPos( vecStart.x, vecStart.y, vecStart.z ); + ClipContext context = new ClipContext( vecStart, vecEnd, - RaycastContext.ShapeType.COLLIDER, - RaycastContext.FluidHandling.NONE, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, collisionEntity ); - HitResult result = world.raycast( context ); + HitResult result = world.clip( context ); if( result != null && result.getType() == HitResult.Type.BLOCK ) { - distance = vecStart.distanceTo( result.getPos() ); + distance = vecStart.distanceTo( result.getLocation() ); vecEnd = vecStart.add( vecDir.x * distance, vecDir.y * distance, vecDir.z * distance ); } @@ -79,7 +80,7 @@ public final class WorldUtil float xStretch = Math.abs( vecDir.x ) > 0.25f ? 0.0f : 1.0f; float yStretch = Math.abs( vecDir.y ) > 0.25f ? 0.0f : 1.0f; float zStretch = Math.abs( vecDir.z ) > 0.25f ? 0.0f : 1.0f; - Box bigBox = new Box( Math.min( vecStart.x, vecEnd.x ) - 0.375f * xStretch, + AABB bigBox = new AABB( Math.min( vecStart.x, vecEnd.x ) - 0.375f * xStretch, Math.min( vecStart.y, vecEnd.y ) - 0.375f * yStretch, Math.min( vecStart.z, vecEnd.z ) - 0.375f * zStretch, Math.max( vecStart.x, vecEnd.x ) + 0.375f * xStretch, @@ -88,10 +89,10 @@ public final class WorldUtil Entity closest = null; double closestDist = 99.0; - List list = world.getEntitiesByClass( Entity.class, bigBox, CAN_COLLIDE ); + List list = world.getEntitiesOfClass( Entity.class, bigBox, CAN_COLLIDE ); for( Entity entity : list ) { - Box littleBox = entity.getBoundingBox(); + AABB littleBox = entity.getBoundingBox(); if( littleBox.contains( vecStart ) ) { closest = entity; @@ -99,7 +100,7 @@ public final class WorldUtil continue; } - Vec3d littleBoxResult = littleBox.raycast( vecStart, vecEnd ) + Vec3 littleBoxResult = littleBox.clip( vecStart, vecEnd ) .orElse( null ); if( littleBoxResult != null ) { @@ -121,13 +122,13 @@ public final class WorldUtil } if( closest != null && closestDist <= distance ) { - Vec3d closestPos = vecStart.add( vecDir.x * closestDist, vecDir.y * closestDist, vecDir.z * closestDist ); + Vec3 closestPos = vecStart.add( vecDir.x * closestDist, vecDir.y * closestDist, vecDir.z * closestDist ); return Pair.of( closest, closestPos ); } return null; } - private static synchronized Entity getEntity( World world ) + private static synchronized Entity getEntity( Level world ) { // TODO: It'd be nice if we could avoid this. Maybe always use the turtle player (if it's available). Entity entity = entityCache.get( world ); @@ -140,45 +141,45 @@ public final class WorldUtil { @Nonnull @Override - public EntityDimensions getDimensions( @Nonnull EntityPose pose ) + public EntityDimensions getDimensions( @Nonnull Pose pose ) { return EntityDimensions.fixed( 0, 0 ); } }; - entity.noClip = true; - entity.calculateDimensions(); + entity.noPhysics = true; + entity.refreshDimensions(); entityCache.put( world, entity ); return entity; } - public static Vec3d getRayEnd( PlayerEntity player ) + public static Vec3 getRayEnd( Player player ) { double reach = 5; - Vec3d look = player.getRotationVector(); + Vec3 look = player.getLookAngle(); return getRayStart( player ).add( look.x * reach, look.y * reach, look.z * reach ); } - public static Vec3d getRayStart( LivingEntity entity ) + public static Vec3 getRayStart( LivingEntity entity ) { - return entity.getCameraPosVec( 1 ); + return entity.getEyePosition( 1 ); } - public static void dropItemStack( @Nonnull ItemStack stack, World world, BlockPos pos ) + public static void dropItemStack( @Nonnull ItemStack stack, Level world, BlockPos pos ) { dropItemStack( stack, world, pos, null ); } - public static void dropItemStack( @Nonnull ItemStack stack, World world, BlockPos pos, Direction direction ) + public static void dropItemStack( @Nonnull ItemStack stack, Level world, BlockPos pos, Direction direction ) { double xDir; double yDir; double zDir; if( direction != null ) { - xDir = direction.getOffsetX(); - yDir = direction.getOffsetY(); - zDir = direction.getOffsetZ(); + xDir = direction.getStepX(); + yDir = direction.getStepY(); + zDir = direction.getStepZ(); } else { @@ -190,23 +191,23 @@ public final class WorldUtil double xPos = pos.getX() + 0.5 + xDir * 0.4; double yPos = pos.getY() + 0.5 + yDir * 0.4; double zPos = pos.getZ() + 0.5 + zDir * 0.4; - dropItemStack( stack, world, new Vec3d( xPos, yPos, zPos ), xDir, yDir, zDir ); + dropItemStack( stack, world, new Vec3( xPos, yPos, zPos ), xDir, yDir, zDir ); } - public static void dropItemStack( @Nonnull ItemStack stack, World world, Vec3d pos, double xDir, double yDir, double zDir ) + public static void dropItemStack( @Nonnull ItemStack stack, Level world, Vec3 pos, double xDir, double yDir, double zDir ) { ItemEntity item = new ItemEntity( world, pos.x, pos.y, pos.z, stack.copy() ); - item.setVelocity( xDir * 0.7 + world.getRandom() + item.setDeltaMovement( xDir * 0.7 + world.getRandom() .nextFloat() * 0.2 - 0.1, yDir * 0.7 + world.getRandom() .nextFloat() * 0.2 - 0.1, zDir * 0.7 + world.getRandom() .nextFloat() * 0.2 - 0.1 ); - item.setToDefaultPickupDelay(); - world.spawnEntity( item ); + item.setDefaultPickUpDelay(); + world.addFreshEntity( item ); } - public static void dropItemStack( @Nonnull ItemStack stack, World world, Vec3d pos ) + public static void dropItemStack( @Nonnull ItemStack stack, Level world, Vec3 pos ) { dropItemStack( stack, world, pos, 0.0, 0.0, 0.0 ); } diff --git a/src/main/java/dan200/computercraft/shared/wired/WiredNetwork.java b/src/main/java/dan200/computercraft/shared/wired/WiredNetwork.java index ccbf63218..34db6a87f 100644 --- a/src/main/java/dan200/computercraft/shared/wired/WiredNetwork.java +++ b/src/main/java/dan200/computercraft/shared/wired/WiredNetwork.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.wired; import com.google.common.collect.ImmutableMap; @@ -11,8 +10,8 @@ import dan200.computercraft.api.network.Packet; import dan200.computercraft.api.network.wired.IWiredNetwork; import dan200.computercraft.api.network.wired.IWiredNode; import dan200.computercraft.api.peripheral.IPeripheral; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import javax.annotation.Nonnull; import java.util.*; @@ -36,21 +35,299 @@ public final class WiredNetwork implements IWiredNetwork this.nodes = nodes; } + @Override + public boolean connect( @Nonnull IWiredNode nodeU, @Nonnull IWiredNode nodeV ) + { + WiredNode wiredU = checkNode( nodeU ); + WiredNode wiredV = checkNode( nodeV ); + if( nodeU == nodeV ) throw new IllegalArgumentException( "Cannot add a connection to oneself." ); + + lock.writeLock().lock(); + try + { + if( nodes == null ) throw new IllegalStateException( "Cannot add a connection to an empty network." ); + + boolean hasU = wiredU.network == this; + boolean hasV = wiredV.network == this; + if( !hasU && !hasV ) throw new IllegalArgumentException( "Neither node is in the network." ); + + // We're going to assimilate a node. Copy across all edges and vertices. + if( !hasU || !hasV ) + { + WiredNetwork other = hasU ? wiredV.network : wiredU.network; + other.lock.writeLock().lock(); + try + { + // Cache several properties for iterating over later + Map otherPeripherals = other.peripherals; + Map thisPeripherals = otherPeripherals.isEmpty() ? peripherals : new HashMap<>( peripherals ); + + Collection thisNodes = otherPeripherals.isEmpty() ? nodes : new ArrayList<>( nodes ); + Collection otherNodes = other.nodes; + + // Move all nodes across into this network, destroying the original nodes. + nodes.addAll( otherNodes ); + for( WiredNode node : otherNodes ) node.network = this; + other.nodes = null; + + // Move all peripherals across, + other.peripherals = null; + peripherals.putAll( otherPeripherals ); + + if( !thisPeripherals.isEmpty() ) + { + WiredNetworkChange.added( thisPeripherals ).broadcast( otherNodes ); + } + + if( !otherPeripherals.isEmpty() ) + { + WiredNetworkChange.added( otherPeripherals ).broadcast( thisNodes ); + } + } + finally + { + other.lock.writeLock().unlock(); + } + } + + boolean added = wiredU.neighbours.add( wiredV ); + if( added ) wiredV.neighbours.add( wiredU ); + + InvariantChecker.checkNetwork( this ); + InvariantChecker.checkNode( wiredU ); + InvariantChecker.checkNode( wiredV ); + + return added; + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean disconnect( @Nonnull IWiredNode nodeU, @Nonnull IWiredNode nodeV ) + { + WiredNode wiredU = checkNode( nodeU ); + WiredNode wiredV = checkNode( nodeV ); + if( nodeU == nodeV ) throw new IllegalArgumentException( "Cannot remove a connection to oneself." ); + + lock.writeLock().lock(); + try + { + boolean hasU = wiredU.network == this; + boolean hasV = wiredV.network == this; + if( !hasU || !hasV ) throw new IllegalArgumentException( "One node is not in the network." ); + + // If there was no connection to remove then split. + if( !wiredU.neighbours.remove( wiredV ) ) return false; + wiredV.neighbours.remove( wiredU ); + + // Determine if there is still some connection from u to v. + // Note this is an inlining of reachableNodes which short-circuits + // if all nodes are reachable. + Queue enqueued = new ArrayDeque<>(); + HashSet reachableU = new HashSet<>(); + + reachableU.add( wiredU ); + enqueued.add( wiredU ); + + while( !enqueued.isEmpty() ) + { + WiredNode node = enqueued.remove(); + for( WiredNode neighbour : node.neighbours ) + { + // If we can reach wiredV from wiredU then abort. + if( neighbour == wiredV ) return true; + + // Otherwise attempt to enqueue this neighbour as well. + if( reachableU.add( neighbour ) ) enqueued.add( neighbour ); + } + } + + // Create a new network with all U-reachable nodes/edges and remove them + // from the existing graph. + WiredNetwork networkU = new WiredNetwork( reachableU ); + networkU.lock.writeLock().lock(); + try + { + // Remove nodes from this network + nodes.removeAll( reachableU ); + + // Set network and transfer peripherals + for( WiredNode node : reachableU ) + { + node.network = networkU; + networkU.peripherals.putAll( node.peripherals ); + peripherals.keySet().removeAll( node.peripherals.keySet() ); + } + + // Broadcast changes + if( !peripherals.isEmpty() ) WiredNetworkChange.removed( peripherals ).broadcast( networkU.nodes ); + if( !networkU.peripherals.isEmpty() ) + { + WiredNetworkChange.removed( networkU.peripherals ).broadcast( nodes ); + } + + InvariantChecker.checkNetwork( this ); + InvariantChecker.checkNetwork( networkU ); + InvariantChecker.checkNode( wiredU ); + InvariantChecker.checkNode( wiredV ); + + return true; + } + finally + { + networkU.lock.writeLock().unlock(); + } + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean remove( @Nonnull IWiredNode node ) + { + WiredNode wired = checkNode( node ); + + lock.writeLock().lock(); + try + { + // If we're the empty graph then just abort: nodes must have _some_ network. + if( nodes == null ) return false; + if( nodes.size() <= 1 ) return false; + if( wired.network != this ) return false; + + HashSet neighbours = wired.neighbours; + + // Remove this node and move into a separate network. + nodes.remove( wired ); + for( WiredNode neighbour : neighbours ) neighbour.neighbours.remove( wired ); + + WiredNetwork wiredNetwork = new WiredNetwork( wired ); + + // If we're a leaf node in the graph (only one neighbour) then we don't need to + // check for network splitting + if( neighbours.size() == 1 ) + { + // Broadcast our simple peripheral changes + removeSingleNode( wired, wiredNetwork ); + InvariantChecker.checkNode( wired ); + InvariantChecker.checkNetwork( wiredNetwork ); + return true; + } + + HashSet reachable = reachableNodes( neighbours.iterator().next() ); + + // If all nodes are reachable then exit. + if( reachable.size() == nodes.size() ) + { + // Broadcast our simple peripheral changes + removeSingleNode( wired, wiredNetwork ); + InvariantChecker.checkNode( wired ); + InvariantChecker.checkNetwork( wiredNetwork ); + return true; + } + + // A split may cause 2..neighbours.size() separate networks, so we + // iterate through our neighbour list, generating child networks. + neighbours.removeAll( reachable ); + ArrayList maximals = new ArrayList<>( neighbours.size() + 1 ); + maximals.add( wiredNetwork ); + maximals.add( new WiredNetwork( reachable ) ); + + while( !neighbours.isEmpty() ) + { + reachable = reachableNodes( neighbours.iterator().next() ); + neighbours.removeAll( reachable ); + maximals.add( new WiredNetwork( reachable ) ); + } + + for( WiredNetwork network : maximals ) network.lock.writeLock().lock(); + + try + { + // We special case the original node: detaching all peripherals when needed. + wired.network = wiredNetwork; + wired.peripherals = Collections.emptyMap(); + + // Ensure every network is finalised + for( WiredNetwork network : maximals ) + { + for( WiredNode child : network.nodes ) + { + child.network = network; + network.peripherals.putAll( child.peripherals ); + } + } + + for( WiredNetwork network : maximals ) InvariantChecker.checkNetwork( network ); + InvariantChecker.checkNode( wired ); + + // Then broadcast network changes once all nodes are finalised + for( WiredNetwork network : maximals ) + { + WiredNetworkChange.changeOf( peripherals, network.peripherals ).broadcast( network.nodes ); + } + } + finally + { + for( WiredNetwork network : maximals ) network.lock.writeLock().unlock(); + } + + nodes.clear(); + peripherals.clear(); + + return true; + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public void updatePeripherals( @Nonnull IWiredNode node, @Nonnull Map newPeripherals ) + { + WiredNode wired = checkNode( node ); + Objects.requireNonNull( peripherals, "peripherals cannot be null" ); + + lock.writeLock().lock(); + try + { + if( wired.network != this ) throw new IllegalStateException( "Node is not on this network" ); + + Map oldPeripherals = wired.peripherals; + WiredNetworkChange change = WiredNetworkChange.changeOf( oldPeripherals, newPeripherals ); + if( change.isEmpty() ) return; + + wired.peripherals = ImmutableMap.copyOf( newPeripherals ); + + // Detach the old peripherals then remove them. + peripherals.keySet().removeAll( change.peripheralsRemoved().keySet() ); + + // Add the new peripherals and attach them + peripherals.putAll( change.peripheralsAdded() ); + + change.broadcast( nodes ); + } + finally + { + lock.writeLock().unlock(); + } + } + static void transmitPacket( WiredNode start, Packet packet, double range, boolean interdimensional ) { Map points = new HashMap<>(); TreeSet transmitTo = new TreeSet<>(); { - TransmitPoint startEntry = start.element.getWorld() != packet.getSender() - .getWorld() ? new TransmitPoint( start, - Double.POSITIVE_INFINITY, - true ) : new TransmitPoint( start, - start.element.getPosition() - .distanceTo( - packet.getSender() - .getPosition() ), - false ); + TransmitPoint startEntry = start.element.getLevel() != packet.sender().getLevel() + ? new TransmitPoint( start, Double.POSITIVE_INFINITY, true ) + : new TransmitPoint( start, start.element.getPosition().distanceTo( packet.sender().getPosition() ), false ); points.put( start, startEntry ); transmitTo.add( startEntry ); } @@ -59,15 +336,15 @@ public final class WiredNetwork implements IWiredNetwork TransmitPoint point; while( (point = transmitTo.pollFirst()) != null ) { - World world = point.node.element.getWorld(); - Vec3d position = point.node.element.getPosition(); + Level world = point.node.element.getLevel(); + Vec3 position = point.node.element.getPosition(); for( WiredNode neighbour : point.node.neighbours ) { TransmitPoint neighbourPoint = points.get( neighbour ); boolean newInterdimensional; double newDistance; - if( world != neighbour.element.getWorld() ) + if( world != neighbour.element.getLevel() ) { newInterdimensional = true; newDistance = Double.POSITIVE_INFINITY; @@ -101,378 +378,9 @@ public final class WiredNetwork implements IWiredNetwork } } - @Override - public boolean connect( @Nonnull IWiredNode nodeU, @Nonnull IWiredNode nodeV ) - { - WiredNode wiredU = checkNode( nodeU ); - WiredNode wiredV = checkNode( nodeV ); - if( nodeU == nodeV ) - { - throw new IllegalArgumentException( "Cannot add a connection to oneself." ); - } - - lock.writeLock() - .lock(); - try - { - if( nodes == null ) - { - throw new IllegalStateException( "Cannot add a connection to an empty network." ); - } - - boolean hasU = wiredU.network == this; - boolean hasV = wiredV.network == this; - if( !hasU && !hasV ) - { - throw new IllegalArgumentException( "Neither node is in the network." ); - } - - // We're going to assimilate a node. Copy across all edges and vertices. - if( !hasU || !hasV ) - { - WiredNetwork other = hasU ? wiredV.network : wiredU.network; - other.lock.writeLock() - .lock(); - try - { - // Cache several properties for iterating over later - Map otherPeripherals = other.peripherals; - Map thisPeripherals = otherPeripherals.isEmpty() ? peripherals : new HashMap<>( peripherals ); - - Collection thisNodes = otherPeripherals.isEmpty() ? nodes : new ArrayList<>( nodes ); - Collection otherNodes = other.nodes; - - // Move all nodes across into this network, destroying the original nodes. - nodes.addAll( otherNodes ); - for( WiredNode node : otherNodes ) - { - node.network = this; - } - other.nodes = null; - - // Move all peripherals across, - other.peripherals = null; - peripherals.putAll( otherPeripherals ); - - if( !thisPeripherals.isEmpty() ) - { - WiredNetworkChange.added( thisPeripherals ) - .broadcast( otherNodes ); - } - - if( !otherPeripherals.isEmpty() ) - { - WiredNetworkChange.added( otherPeripherals ) - .broadcast( thisNodes ); - } - } - finally - { - other.lock.writeLock() - .unlock(); - } - } - - boolean added = wiredU.neighbours.add( wiredV ); - if( added ) - { - wiredV.neighbours.add( wiredU ); - } - - InvariantChecker.checkNetwork( this ); - InvariantChecker.checkNode( wiredU ); - InvariantChecker.checkNode( wiredV ); - - return added; - } - finally - { - lock.writeLock() - .unlock(); - } - } - - @Override - public boolean disconnect( @Nonnull IWiredNode nodeU, @Nonnull IWiredNode nodeV ) - { - WiredNode wiredU = checkNode( nodeU ); - WiredNode wiredV = checkNode( nodeV ); - if( nodeU == nodeV ) - { - throw new IllegalArgumentException( "Cannot remove a connection to oneself." ); - } - - lock.writeLock() - .lock(); - try - { - boolean hasU = wiredU.network == this; - boolean hasV = wiredV.network == this; - if( !hasU || !hasV ) - { - throw new IllegalArgumentException( "One node is not in the network." ); - } - - // If there was no connection to remove then split. - if( !wiredU.neighbours.remove( wiredV ) ) - { - return false; - } - wiredV.neighbours.remove( wiredU ); - - // Determine if there is still some connection from u to v. - // Note this is an inlining of reachableNodes which short-circuits - // if all nodes are reachable. - Queue enqueued = new ArrayDeque<>(); - HashSet reachableU = new HashSet<>(); - - reachableU.add( wiredU ); - enqueued.add( wiredU ); - - while( !enqueued.isEmpty() ) - { - WiredNode node = enqueued.remove(); - for( WiredNode neighbour : node.neighbours ) - { - // If we can reach wiredV from wiredU then abort. - if( neighbour == wiredV ) - { - return true; - } - - // Otherwise attempt to enqueue this neighbour as well. - if( reachableU.add( neighbour ) ) - { - enqueued.add( neighbour ); - } - } - } - - // Create a new network with all U-reachable nodes/edges and remove them - // from the existing graph. - WiredNetwork networkU = new WiredNetwork( reachableU ); - networkU.lock.writeLock() - .lock(); - try - { - // Remove nodes from this network - nodes.removeAll( reachableU ); - - // Set network and transfer peripherals - for( WiredNode node : reachableU ) - { - node.network = networkU; - networkU.peripherals.putAll( node.peripherals ); - peripherals.keySet() - .removeAll( node.peripherals.keySet() ); - } - - // Broadcast changes - if( !peripherals.isEmpty() ) - { - WiredNetworkChange.removed( peripherals ) - .broadcast( networkU.nodes ); - } - if( !networkU.peripherals.isEmpty() ) - { - WiredNetworkChange.removed( networkU.peripherals ) - .broadcast( nodes ); - } - - InvariantChecker.checkNetwork( this ); - InvariantChecker.checkNetwork( networkU ); - InvariantChecker.checkNode( wiredU ); - InvariantChecker.checkNode( wiredV ); - - return true; - } - finally - { - networkU.lock.writeLock() - .unlock(); - } - } - finally - { - lock.writeLock() - .unlock(); - } - } - - @Override - public boolean remove( @Nonnull IWiredNode node ) - { - WiredNode wired = checkNode( node ); - - lock.writeLock() - .lock(); - try - { - // If we're the empty graph then just abort: nodes must have _some_ network. - if( nodes == null ) - { - return false; - } - if( nodes.size() <= 1 ) - { - return false; - } - if( wired.network != this ) - { - return false; - } - - HashSet neighbours = wired.neighbours; - - // Remove this node and move into a separate network. - nodes.remove( wired ); - for( WiredNode neighbour : neighbours ) - { - neighbour.neighbours.remove( wired ); - } - - WiredNetwork wiredNetwork = new WiredNetwork( wired ); - - // If we're a leaf node in the graph (only one neighbour) then we don't need to - // check for network splitting - if( neighbours.size() == 1 ) - { - // Broadcast our simple peripheral changes - removeSingleNode( wired, wiredNetwork ); - InvariantChecker.checkNode( wired ); - InvariantChecker.checkNetwork( wiredNetwork ); - return true; - } - - HashSet reachable = reachableNodes( neighbours.iterator() - .next() ); - - // If all nodes are reachable then exit. - if( reachable.size() == nodes.size() ) - { - // Broadcast our simple peripheral changes - removeSingleNode( wired, wiredNetwork ); - InvariantChecker.checkNode( wired ); - InvariantChecker.checkNetwork( wiredNetwork ); - return true; - } - - // A split may cause 2..neighbours.size() separate networks, so we - // iterate through our neighbour list, generating child networks. - neighbours.removeAll( reachable ); - ArrayList maximals = new ArrayList<>( neighbours.size() + 1 ); - maximals.add( wiredNetwork ); - maximals.add( new WiredNetwork( reachable ) ); - - while( !neighbours.isEmpty() ) - { - reachable = reachableNodes( neighbours.iterator() - .next() ); - neighbours.removeAll( reachable ); - maximals.add( new WiredNetwork( reachable ) ); - } - - for( WiredNetwork network : maximals ) - { - network.lock.writeLock() - .lock(); - } - - try - { - // We special case the original node: detaching all peripherals when needed. - wired.network = wiredNetwork; - wired.peripherals = Collections.emptyMap(); - - // Ensure every network is finalised - for( WiredNetwork network : maximals ) - { - for( WiredNode child : network.nodes ) - { - child.network = network; - network.peripherals.putAll( child.peripherals ); - } - } - - for( WiredNetwork network : maximals ) - { - InvariantChecker.checkNetwork( network ); - } - InvariantChecker.checkNode( wired ); - - // Then broadcast network changes once all nodes are finalised - for( WiredNetwork network : maximals ) - { - WiredNetworkChange.changeOf( peripherals, network.peripherals ) - .broadcast( network.nodes ); - } - } - finally - { - for( WiredNetwork network : maximals ) - { - network.lock.writeLock() - .unlock(); - } - } - - nodes.clear(); - peripherals.clear(); - - return true; - } - finally - { - lock.writeLock() - .unlock(); - } - } - - @Override - public void updatePeripherals( @Nonnull IWiredNode node, @Nonnull Map newPeripherals ) - { - WiredNode wired = checkNode( node ); - Objects.requireNonNull( peripherals, "peripherals cannot be null" ); - - lock.writeLock() - .lock(); - try - { - if( wired.network != this ) - { - throw new IllegalStateException( "Node is not on this network" ); - } - - Map oldPeripherals = wired.peripherals; - WiredNetworkChange change = WiredNetworkChange.changeOf( oldPeripherals, newPeripherals ); - if( change.isEmpty() ) - { - return; - } - - wired.peripherals = ImmutableMap.copyOf( newPeripherals ); - - // Detach the old peripherals then remove them. - peripherals.keySet() - .removeAll( change.peripheralsRemoved() - .keySet() ); - - // Add the new peripherals and attach them - peripherals.putAll( change.peripheralsAdded() ); - - change.broadcast( nodes ); - } - finally - { - lock.writeLock() - .unlock(); - } - } - private void removeSingleNode( WiredNode wired, WiredNetwork wiredNetwork ) { - wiredNetwork.lock.writeLock() - .lock(); + wiredNetwork.lock.writeLock().lock(); try { // Cache all the old nodes. @@ -485,62 +393,16 @@ public final class WiredNetwork implements IWiredNetwork wired.peripherals = Collections.emptyMap(); // Broadcast the change - if( !peripherals.isEmpty() ) - { - WiredNetworkChange.removed( peripherals ) - .broadcast( wired ); - } + if( !peripherals.isEmpty() ) WiredNetworkChange.removed( peripherals ).broadcast( wired ); // Now remove all peripherals from this network and broadcast the change. - peripherals.keySet() - .removeAll( wiredPeripherals.keySet() ); - if( !wiredPeripherals.isEmpty() ) - { - WiredNetworkChange.removed( wiredPeripherals ) - .broadcast( nodes ); - } + peripherals.keySet().removeAll( wiredPeripherals.keySet() ); + if( !wiredPeripherals.isEmpty() ) WiredNetworkChange.removed( wiredPeripherals ).broadcast( nodes ); } finally { - wiredNetwork.lock.writeLock() - .unlock(); - } - } - - private static HashSet reachableNodes( WiredNode start ) - { - Queue enqueued = new ArrayDeque<>(); - HashSet reachable = new HashSet<>(); - - reachable.add( start ); - enqueued.add( start ); - - WiredNode node; - while( (node = enqueued.poll()) != null ) - { - for( WiredNode neighbour : node.neighbours ) - { - // Otherwise attempt to enqueue this neighbour as well. - if( reachable.add( neighbour ) ) - { - enqueued.add( neighbour ); - } - } - } - - return reachable; - } - - private static WiredNode checkNode( IWiredNode node ) - { - if( node instanceof WiredNode ) - { - return (WiredNode) node; - } - else - { - throw new IllegalArgumentException( "Unknown implementation of IWiredNode: " + node ); + wiredNetwork.lock.writeLock().unlock(); } } @@ -561,7 +423,42 @@ public final class WiredNetwork implements IWiredNetwork public int compareTo( @Nonnull TransmitPoint o ) { // Objects with the same distance are not the same object, so we must add an additional layer of ordering. - return distance == o.distance ? Integer.compare( node.hashCode(), o.node.hashCode() ) : Double.compare( distance, o.distance ); + return distance == o.distance + ? Integer.compare( node.hashCode(), o.node.hashCode() ) + : Double.compare( distance, o.distance ); } } + + private static WiredNode checkNode( IWiredNode node ) + { + if( node instanceof WiredNode ) + { + return (WiredNode) node; + } + else + { + throw new IllegalArgumentException( "Unknown implementation of IWiredNode: " + node ); + } + } + + private static HashSet reachableNodes( WiredNode start ) + { + Queue enqueued = new ArrayDeque<>(); + HashSet reachable = new HashSet<>(); + + reachable.add( start ); + enqueued.add( start ); + + WiredNode node; + while( (node = enqueued.poll()) != null ) + { + for( WiredNode neighbour : node.neighbours ) + { + // Otherwise attempt to enqueue this neighbour as well. + if( reachable.add( neighbour ) ) enqueued.add( neighbour ); + } + } + + return reachable; + } } diff --git a/src/main/java/dan200/computercraft/shared/wired/WiredNode.java b/src/main/java/dan200/computercraft/shared/wired/WiredNode.java index 03cd63820..c6426ca18 100644 --- a/src/main/java/dan200/computercraft/shared/wired/WiredNode.java +++ b/src/main/java/dan200/computercraft/shared/wired/WiredNode.java @@ -3,7 +3,6 @@ * Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission. * Send enquiries to dratcliffe@gmail.com */ - package dan200.computercraft.shared.wired; import dan200.computercraft.api.network.IPacketReceiver; @@ -20,12 +19,14 @@ import java.util.concurrent.locks.Lock; public final class WiredNode implements IWiredNode { - final IWiredElement element; - final HashSet neighbours = new HashSet<>(); - Map peripherals = Collections.emptyMap(); - volatile WiredNetwork network; private Set receivers; + final IWiredElement element; + Map peripherals = Collections.emptyMap(); + + final HashSet neighbours = new HashSet<>(); + volatile WiredNetwork network; + public WiredNode( IWiredElement element ) { this.element = element; @@ -35,19 +36,37 @@ public final class WiredNode implements IWiredNode @Override public synchronized void addReceiver( @Nonnull IPacketReceiver receiver ) { - if( receivers == null ) - { - receivers = new HashSet<>(); - } + if( receivers == null ) receivers = new HashSet<>(); receivers.add( receiver ); } @Override public synchronized void removeReceiver( @Nonnull IPacketReceiver receiver ) { - if( receivers != null ) + if( receivers != null ) receivers.remove( receiver ); + } + + synchronized void tryTransmit( Packet packet, double packetDistance, boolean packetInterdimensional, double range, boolean interdimensional ) + { + if( receivers == null ) return; + + for( IPacketReceiver receiver : receivers ) { - receivers.remove( receiver ); + if( !packetInterdimensional ) + { + double receiveRange = Math.max( range, receiver.getRange() ); // Ensure range is symmetrical + if( interdimensional || receiver.isInterdimensional() || packetDistance < receiveRange ) + { + receiver.receiveSameDimension( packet, packetDistance + element.getPosition().distanceTo( receiver.getPosition() ) ); + } + } + else + { + if( interdimensional || receiver.isInterdimensional() ) + { + receiver.receiveDifferentDimension( packet ); + } + } } } @@ -61,7 +80,7 @@ public final class WiredNode implements IWiredNode public void transmitSameDimension( @Nonnull Packet packet, double range ) { Objects.requireNonNull( packet, "packet cannot be null" ); - if( !(packet.getSender() instanceof IWiredSender) || ((IWiredSender) packet.getSender()).getNode() != this ) + if( !(packet.sender() instanceof IWiredSender) || ((IWiredSender) packet.sender()).getNode() != this ) { throw new IllegalArgumentException( "Sender is not in the network" ); } @@ -73,8 +92,7 @@ public final class WiredNode implements IWiredNode } finally { - network.lock.readLock() - .unlock(); + network.lock.readLock().unlock(); } } @@ -82,7 +100,7 @@ public final class WiredNode implements IWiredNode public void transmitInterdimensional( @Nonnull Packet packet ) { Objects.requireNonNull( packet, "packet cannot be null" ); - if( !(packet.getSender() instanceof IWiredSender) || ((IWiredSender) packet.getSender()).getNode() != this ) + if( !(packet.sender() instanceof IWiredSender) || ((IWiredSender) packet.sender()).getNode() != this ) { throw new IllegalArgumentException( "Sender is not in the network" ); } @@ -94,54 +112,7 @@ public final class WiredNode implements IWiredNode } finally { - network.lock.readLock() - .unlock(); - } - } - - private void acquireReadLock() - { - WiredNetwork currentNetwork = network; - while( true ) - { - Lock lock = currentNetwork.lock.readLock(); - lock.lock(); - if( currentNetwork == network ) - { - return; - } - - - lock.unlock(); - } - } - - synchronized void tryTransmit( Packet packet, double packetDistance, boolean packetInterdimensional, double range, boolean interdimensional ) - { - if( receivers == null ) - { - return; - } - - for( IPacketReceiver receiver : receivers ) - { - if( !packetInterdimensional ) - { - double receiveRange = Math.max( range, receiver.getRange() ); // Ensure range is symmetrical - if( interdimensional || receiver.isInterdimensional() || packetDistance < receiveRange ) - { - receiver.receiveSameDimension( packet, - packetDistance + element.getPosition() - .distanceTo( receiver.getPosition() ) ); - } - } - else - { - if( interdimensional || receiver.isInterdimensional() ) - { - receiver.receiveDifferentDimension( packet ); - } - } + network.lock.readLock().unlock(); } } @@ -162,7 +133,20 @@ public final class WiredNode implements IWiredNode @Override public String toString() { - return "WiredNode{@" + element.getPosition() + " (" + element.getClass() - .getSimpleName() + ")}"; + return "WiredNode{@" + element.getPosition() + " (" + element.getClass().getSimpleName() + ")}"; + } + + private void acquireReadLock() + { + WiredNetwork currentNetwork = network; + while( true ) + { + Lock lock = currentNetwork.lock.readLock(); + lock.lock(); + if( currentNetwork == network ) return; + + + lock.unlock(); + } } } diff --git a/src/main/resources/cc.accesswidener b/src/main/resources/cc.accesswidener index cb9b4b774..c7e7cccab 100644 --- a/src/main/resources/cc.accesswidener +++ b/src/main/resources/cc.accesswidener @@ -1,8 +1,4 @@ accessWidener v1 named -accessible class net/minecraft/client/render/RenderLayer$MultiPhase -accessible class net/minecraft/client/render/RenderLayer$MultiPhaseParameters -accessible method net/minecraft/client/render/RenderLayer of (Ljava/lang/String;Lnet/minecraft/client/render/VertexFormat;Lnet/minecraft/client/render/VertexFormat$DrawMode;IZZLnet/minecraft/client/render/RenderLayer$MultiPhaseParameters;)Lnet/minecraft/client/render/RenderLayer$MultiPhase; - -accessible class net/minecraft/client/render/RenderPhase$Shader -accessible class net/minecraft/client/render/RenderPhase$Texture +accessible class net/minecraft/client/renderer/RenderType$CompositeState +accessible method net/minecraft/client/renderer/RenderType create (Ljava/lang/String;Lcom/mojang/blaze3d/vertex/VertexFormat;Lcom/mojang/blaze3d/vertex/VertexFormat$Mode;IZZLnet/minecraft/client/renderer/RenderType$CompositeState;)Lnet/minecraft/client/renderer/RenderType$CompositeRenderType; diff --git a/src/main/resources/computercraft.mixins.json b/src/main/resources/computercraft.mixins.json index be224c3cc..8acb52d3e 100644 --- a/src/main/resources/computercraft.mixins.json +++ b/src/main/resources/computercraft.mixins.json @@ -3,26 +3,26 @@ "package": "dan200.computercraft.fabric.mixin", "compatibilityLevel": "JAVA_16", "mixins": [ + "LevelResourceAccess", "MinecraftServerAccess", + "MixinBlock", "MixinEntity", - "MixinServerWorld", - "MixinWorld", - "SignBlockEntityAccess", - "WorldSavePathAccess", - "MixinServerPlayerInteractionManager", - "MixinMatrix4f" + "MixinLevel", + "MixinMatrix4f", + "MixinServerLevel", + "MixinServerPlayerGameMode" ], "client": [ - "ChatHudAccess", - "HeldItemRendererAccess", - "MixinHeldItemRenderer", - "MixinItemFrameEntityRenderer", - "MixinMinecraftClient", - "MixinScreen", + "ChatComponentAccess", + "ItemInHandRendererAccess", + "MixinGameRenderer", - "MixinWorldRenderer", - "MixinHandledScreen" + "MixinItemFrameRenderer", + "MixinItemInHandRenderer", + "MixinLevelRenderer", + "MixinMinecraft", + "MixinScreen" ], "server": [ "MixinLanguage" diff --git a/src/main/resources/data/computercraft/lua/rom/apis/rednet.lua b/src/main/resources/data/computercraft/lua/rom/apis/rednet.lua index 3f42b6510..83f4bb6ad 100644 --- a/src/main/resources/data/computercraft/lua/rom/apis/rednet.lua +++ b/src/main/resources/data/computercraft/lua/rom/apis/rednet.lua @@ -25,9 +25,17 @@ CHANNEL_BROADCAST = 65535 --- The channel used by the Rednet API to repeat messages. CHANNEL_REPEAT = 65533 +--- The number of channels rednet reserves for computer IDs. Computers with IDs +-- greater or equal to this limit wrap around to 0. +MAX_ID_CHANNELS = 65500 + local tReceivedMessages = {} -local tReceivedMessageTimeouts = {} local tHostnames = {} +local nClearTimer + +local function id_as_channel(id) + return (id or os.getComputerID()) % MAX_ID_CHANNELS +end --[[- Opens a modem with the given @{peripheral} name, allowing it to send and receive messages over rednet. @@ -47,7 +55,7 @@ function open(modem) if peripheral.getType(modem) ~= "modem" then error("No such modem: " .. modem, 2) end - peripheral.call(modem, "open", os.getComputerID()) + peripheral.call(modem, "open", id_as_channel()) peripheral.call(modem, "open", CHANNEL_BROADCAST) end @@ -64,7 +72,7 @@ function close(modem) if peripheral.getType(modem) ~= "modem" then error("No such modem: " .. modem, 2) end - peripheral.call(modem, "close", os.getComputerID()) + peripheral.call(modem, "close", id_as_channel()) peripheral.call(modem, "close", CHANNEL_BROADCAST) else -- Close all modems @@ -87,7 +95,7 @@ function isOpen(modem) if modem then -- Check if a specific modem is open if peripheral.getType(modem) == "modem" then - return peripheral.call(modem, "isOpen", os.getComputerID()) and peripheral.call(modem, "isOpen", CHANNEL_BROADCAST) + return peripheral.call(modem, "isOpen", id_as_channel()) and peripheral.call(modem, "isOpen", CHANNEL_BROADCAST) end else -- Check if any modem is open @@ -130,14 +138,15 @@ function send(nRecipient, message, sProtocol) -- We could do other things to guarantee uniqueness, but we really don't need to -- Store it to ensure we don't get our own messages back local nMessageID = math.random(1, 2147483647) - tReceivedMessages[nMessageID] = true - tReceivedMessageTimeouts[os.startTimer(30)] = nMessageID + tReceivedMessages[nMessageID] = os.clock() + 9.5 + if not nClearTimer then nClearTimer = os.startTimer(10) end -- Create the message - local nReplyChannel = os.getComputerID() + local nReplyChannel = id_as_channel() local tMessage = { nMessageID = nMessageID, nRecipient = nRecipient, + nSender = os.getComputerID(), message = message, sProtocol = sProtocol, } @@ -145,10 +154,14 @@ function send(nRecipient, message, sProtocol) local sent = false if nRecipient == os.getComputerID() then -- Loopback to ourselves - os.queueEvent("rednet_message", nReplyChannel, message, sProtocol) + os.queueEvent("rednet_message", os.getComputerID(), message, sProtocol) sent = true else -- Send on all open modems, to the target and to repeaters + if nRecipient ~= CHANNEL_BROADCAST then + nRecipient = id_as_channel(nRecipient) + end + for _, sModem in ipairs(peripheral.getNames()) do if isOpen(sModem) then peripheral.call(sModem, "transmit", nRecipient, nReplyChannel, tMessage) @@ -390,13 +403,15 @@ function run() if sEvent == "modem_message" then -- Got a modem message, process it and add it to the rednet event queue local sModem, nChannel, nReplyChannel, tMessage = p1, p2, p3, p4 - if isOpen(sModem) and (nChannel == os.getComputerID() or nChannel == CHANNEL_BROADCAST) then + if nChannel == id_as_channel() or nChannel == CHANNEL_BROADCAST then if type(tMessage) == "table" and type(tMessage.nMessageID) == "number" and tMessage.nMessageID == tMessage.nMessageID and not tReceivedMessages[tMessage.nMessageID] + and ((tMessage.nRecipient and tMessage.nRecipient == os.getComputerID()) or nChannel == CHANNEL_BROADCAST) + and isOpen(sModem) then - tReceivedMessages[tMessage.nMessageID] = true - tReceivedMessageTimeouts[os.startTimer(30)] = tMessage.nMessageID - os.queueEvent("rednet_message", nReplyChannel, tMessage.message, tMessage.sProtocol) + tReceivedMessages[tMessage.nMessageID] = os.clock() + 9.5 + if not nClearTimer then nClearTimer = os.startTimer(10) end + os.queueEvent("rednet_message", tMessage.nSender or nReplyChannel, tMessage.message, tMessage.sProtocol) end end @@ -414,14 +429,15 @@ function run() end end - elseif sEvent == "timer" then + elseif sEvent == "timer" and p1 == nClearTimer then -- Got a timer event, use it to clear the event queue - local nTimer = p1 - local nMessage = tReceivedMessageTimeouts[nTimer] - if nMessage then - tReceivedMessageTimeouts[nTimer] = nil - tReceivedMessages[nMessage] = nil + nClearTimer = nil + local nNow, bHasMore = os.clock(), nil + for nMessageID, nDeadline in pairs(tReceivedMessages) do + if nDeadline <= nNow then tReceivedMessages[nMessageID] = nil + else bHasMore = true end end + nClearTimer = bHasMore and os.startTimer(10) end end end diff --git a/src/main/resources/data/computercraft/lua/rom/apis/window.lua b/src/main/resources/data/computercraft/lua/rom/apis/window.lua index feafa00c2..724cda155 100644 --- a/src/main/resources/data/computercraft/lua/rom/apis/window.lua +++ b/src/main/resources/data/computercraft/lua/rom/apis/window.lua @@ -265,6 +265,8 @@ function create(parent, nX, nY, nWidth, nHeight, bStartVisible) if #sTextColor ~= #sText or #sBackgroundColor ~= #sText then error("Arguments must be the same length", 2) end + sTextColor = sTextColor:lower() + sBackgroundColor = sBackgroundColor:lower() internalBlit(sText, sTextColor, sBackgroundColor) end diff --git a/src/main/resources/data/computercraft/lua/rom/help/changelog.txt b/src/main/resources/data/computercraft/lua/rom/help/changelog.md similarity index 100% rename from src/main/resources/data/computercraft/lua/rom/help/changelog.txt rename to src/main/resources/data/computercraft/lua/rom/help/changelog.md diff --git a/src/main/resources/data/computercraft/lua/rom/help/whatsnew.txt b/src/main/resources/data/computercraft/lua/rom/help/whatsnew.md similarity index 100% rename from src/main/resources/data/computercraft/lua/rom/help/whatsnew.txt rename to src/main/resources/data/computercraft/lua/rom/help/whatsnew.md diff --git a/src/main/resources/data/computercraft/lua/rom/programs/about.lua b/src/main/resources/data/computercraft/lua/rom/programs/about.lua new file mode 100644 index 000000000..37a0e2901 --- /dev/null +++ b/src/main/resources/data/computercraft/lua/rom/programs/about.lua @@ -0,0 +1,4 @@ +-- Prints information about CraftOS +term.setTextColor(colors.yellow) +print(os.version() .. " on " .. _HOST) +term.setTextColor(colors.white) diff --git a/src/main/resources/data/computercraft/lua/rom/programs/motd.lua b/src/main/resources/data/computercraft/lua/rom/programs/motd.lua index 57ab7b916..5a2e78b83 100644 --- a/src/main/resources/data/computercraft/lua/rom/programs/motd.lua +++ b/src/main/resources/data/computercraft/lua/rom/programs/motd.lua @@ -5,6 +5,8 @@ elseif date.month == 12 and date.day == 24 then print("Merry X-mas!") elseif date.month == 10 and date.day == 31 then print("OOoooOOOoooo! Spooky!") +elseif date.month == 4 and date.day == 28 then + print("Ed Balls") else local tMotd = {} diff --git a/src/main/resources/data/computercraft/lua/rom/programs/rednet/repeat.lua b/src/main/resources/data/computercraft/lua/rom/programs/rednet/repeat.lua index dfd9ca907..c5ed89984 100644 --- a/src/main/resources/data/computercraft/lua/rom/programs/rednet/repeat.lua +++ b/src/main/resources/data/computercraft/lua/rom/programs/rednet/repeat.lua @@ -14,6 +14,10 @@ else print(#tModems .. " modems found.") end +local function idAsChannel(id) + return (id or os.getComputerID()) % rednet.MAX_ID_CHANNELS +end + local function open(nChannel) for n = 1, #tModems do local sModem = tModems[n] @@ -53,7 +57,7 @@ local ok, error = pcall(function() for n = 1, #tModems do local sOtherModem = tModems[n] peripheral.call(sOtherModem, "transmit", rednet.CHANNEL_REPEAT, nReplyChannel, tMessage) - peripheral.call(sOtherModem, "transmit", tMessage.nRecipient, nReplyChannel, tMessage) + peripheral.call(sOtherModem, "transmit", idAsChannel(tMessage.nRecipient), nReplyChannel, tMessage) end -- Log the event