mirror of
https://github.com/SquidDev-CC/CC-Tweaked
synced 2025-11-06 00:22:58 +00:00
Compare commits
134 Commits
v1.13.2-1.
...
v1.12.2-1.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0dde859582 | ||
|
|
e59c043fb6 | ||
|
|
ae928c4397 | ||
|
|
da41c65128 | ||
|
|
4d18234714 | ||
|
|
d254c6464b | ||
|
|
3a5d50e572 | ||
|
|
03b6d2f1ab | ||
|
|
b0397ed3c5 | ||
|
|
fa70ebcac2 | ||
|
|
86e0330100 | ||
|
|
0ae70fed13 | ||
|
|
121802a683 | ||
|
|
08cf55e55f | ||
|
|
3c8c0d78ef | ||
|
|
c4d18aa9ca | ||
|
|
a8fadabaf1 | ||
|
|
38f9a015ca | ||
|
|
c311cdc6f5 | ||
|
|
a93e0f3284 | ||
|
|
14b3065ba4 | ||
|
|
c802290437 | ||
|
|
418420523a | ||
|
|
813e91073d | ||
|
|
7250f22ff6 | ||
|
|
db31a53bba | ||
|
|
3023f235a4 | ||
|
|
79cd8b4da5 | ||
|
|
8e4d311cd9 | ||
|
|
9bd8c86a94 | ||
|
|
cbc0c1d0b6 | ||
|
|
49c37857d4 | ||
|
|
a802f25dd6 | ||
|
|
a80302c513 | ||
|
|
1c46949da7 | ||
|
|
46d78af068 | ||
|
|
eb5cff1045 | ||
|
|
35c7792aa2 | ||
|
|
521688d630 | ||
|
|
75e2845c01 | ||
|
|
2f96283286 | ||
|
|
cbe6e9b5f5 | ||
|
|
2ab79cf474 | ||
|
|
6ce34aba79 | ||
|
|
5eeb320b60 | ||
|
|
93310850d2 | ||
|
|
a2880b12ca | ||
|
|
303b57779a | ||
|
|
6279816ecc | ||
|
|
4ae77261fa | ||
|
|
4b7d843b78 | ||
|
|
1c28df65c3 | ||
|
|
85b740f484 | ||
|
|
f9929cb27d | ||
|
|
bafab1ac07 | ||
|
|
e05c262468 | ||
|
|
7a3f7d3bba | ||
|
|
95aa48c456 | ||
|
|
904a168d5c | ||
|
|
724441eddc | ||
|
|
f68ab3edd1 | ||
|
|
29dce26bf6 | ||
|
|
717ab69093 | ||
|
|
138a2cf08f | ||
|
|
81daf82647 | ||
|
|
f3798bfb63 | ||
|
|
bc07dfad2e | ||
|
|
309cbdb8be | ||
|
|
a0e7c4a74c | ||
|
|
7d428030df | ||
|
|
00c395f689 | ||
|
|
d8e1c73d26 | ||
|
|
ffa4cc241b | ||
|
|
6f1b740c8f | ||
|
|
3406ba3ebf | ||
|
|
6b81bcf334 | ||
|
|
acac70675d | ||
|
|
56434259c1 | ||
|
|
da7e4b9016 | ||
|
|
d4b8650d21 | ||
|
|
17645a79f0 | ||
|
|
ce1f14a010 | ||
|
|
43050426de | ||
|
|
b05f60c98b | ||
|
|
c44c560f96 | ||
|
|
e839ef54af | ||
|
|
0cb659d78c | ||
|
|
9048deeb95 | ||
|
|
5592ebae7d | ||
|
|
b076c32fd1 | ||
|
|
a48f1e310f | ||
|
|
19aca001d7 | ||
|
|
114f913bf8 | ||
|
|
1c9810890a | ||
|
|
b11beb508b | ||
|
|
af8d4da594 | ||
|
|
a81db2cda6 | ||
|
|
99bdff0f92 | ||
|
|
5b0ce7410d | ||
|
|
d5ea22d1a0 | ||
|
|
210f3fa9e2 | ||
|
|
d661cfa88b | ||
|
|
68bf3a71dc | ||
|
|
3cdb12d293 | ||
|
|
ad33acd7d1 | ||
|
|
0ec3884e98 | ||
|
|
7f2471d6b2 | ||
|
|
8fafec4915 | ||
|
|
b9fd690ecb | ||
|
|
2f2ada4416 | ||
|
|
9c951c58d9 | ||
|
|
4b4b47e231 | ||
|
|
978c28a686 | ||
|
|
b867ada5e5 | ||
|
|
7071cc972b | ||
|
|
6898f932a0 | ||
|
|
2e0ef6385d | ||
|
|
f93da7ea51 | ||
|
|
1210bb8a4d | ||
|
|
48a71e96eb | ||
|
|
3bf47b5290 | ||
|
|
9e9f199e55 | ||
|
|
5a8a111857 | ||
|
|
48ba247ab4 | ||
|
|
b195cab6a7 | ||
|
|
63dc0daa09 | ||
|
|
34602ec4be | ||
|
|
f3ce44042f | ||
|
|
4205f18f0c | ||
|
|
6be330ae8d | ||
|
|
4569af2130 | ||
|
|
765c31315a | ||
|
|
0e191e42a0 | ||
|
|
ca34b2a1b8 |
@@ -11,5 +11,8 @@ insert_final_newline = true
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.sexp]
|
||||
indent_size = 2
|
||||
|
||||
[*.properties]
|
||||
insert_final_newline = false
|
||||
|
||||
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Report some misbehaviour in the mod
|
||||
|
||||
labels: bug
|
||||
---
|
||||
|
||||
<!--
|
||||
|
||||
4
.github/ISSUE_TEMPLATE/feature_request.md
vendored
4
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea or improvement
|
||||
|
||||
labels: enhancement
|
||||
---
|
||||
|
||||
<!--
|
||||
@@ -11,4 +11,4 @@ about: Suggest an idea or improvement
|
||||
|
||||
## Useful information to include:
|
||||
- Explanation of how the feature/change should work.
|
||||
- Some rationale/use case for a feature. I'd like to keep CC:T as minimal as possible, so I like have a solid justification for each feature.
|
||||
- Some rationale/use case for a feature. My general approach to designing new features is to ask yourself "what issue are we trying to solve" and _then_ "is this the best way to solve this issue?".
|
||||
|
||||
3
.github/pull_request_template.md
vendored
Normal file
3
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
## A quick checklist
|
||||
- If there's a existing issue, please link to it. If not, provide fill out the same information you would in a normal issue - reproduction steps for bugs, rationale for use-case.
|
||||
- If you're working on CraftOS, try to write a few test cases so we can ensure everything continues to work in the future. Tests live in `src/test/resources/test-rom/spec` and can be run with `./gradlew check`.
|
||||
33
.github/workflows/main-ci.yml
vendored
Normal file
33
.github/workflows/main-ci.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
name: Build
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
|
||||
- name: Set up JDK 1.8
|
||||
uses: actions/setup-java@v1
|
||||
with:
|
||||
java-version: 1.8
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew build --no-daemon
|
||||
|
||||
lint-lua:
|
||||
name: Lint Lua
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
|
||||
- name: Lint Lua code
|
||||
run: |
|
||||
test -d bin || mkdir bin
|
||||
test -f bin/illuaminate || wget -q -Obin/illuaminate https://squiddev.cc/illuaminate/bin/illuaminate
|
||||
chmod +x bin/illuaminate
|
||||
bin/illuaminate lint
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -15,3 +15,9 @@
|
||||
.idea
|
||||
.gradle
|
||||
*.DS_Store
|
||||
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
bin/
|
||||
*.launch
|
||||
|
||||
34
.luacheckrc
34
.luacheckrc
@@ -1,34 +0,0 @@
|
||||
std = "max"
|
||||
|
||||
ignore = {
|
||||
-- Allow access to undefined globals or their fields. In the future we'll
|
||||
-- define all of CC's globals within this file
|
||||
'113', '143',
|
||||
|
||||
-- FIXME: Ignore unused arguments and loop variables
|
||||
'212', '213',
|
||||
|
||||
-- Disable line is too long for now. It would be possible to clean
|
||||
-- this up in the future.
|
||||
'631',
|
||||
}
|
||||
|
||||
-- Only run the linter on ROM and bios for now, as the treasure disks
|
||||
-- are largely unsupported.
|
||||
include_files = {
|
||||
'src/main/resources/assets/computercraft/lua/rom',
|
||||
'src/main/resources/assets/computercraft/lua/bios.lua'
|
||||
}
|
||||
|
||||
files['src/main/resources/assets/computercraft/lua/bios.lua'] = {
|
||||
-- Allow declaring and mutating globals
|
||||
allow_defined_top = true,
|
||||
ignore = { '112', '121', '122', '131', '142' },
|
||||
}
|
||||
|
||||
files['src/main/resources/assets/computercraft/lua/rom/apis'] = {
|
||||
-- APIs may define globals on the top level. We'll ignore unused globals,
|
||||
-- as obviously they may be used outside that API.
|
||||
allow_defined_top = true,
|
||||
ignore = { '131' },
|
||||
}
|
||||
14
.travis.yml
14
.travis.yml
@@ -1,14 +0,0 @@
|
||||
language: java
|
||||
|
||||
script: ./gradlew build --no-daemon
|
||||
|
||||
before_cache:
|
||||
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
|
||||
- rm -fr $HOME/.gradle/caches/*/plugin-resolution/
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/.gradle/caches/
|
||||
- $HOME/.gradle/wrapper/s
|
||||
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
17
README.md
17
README.md
@@ -1,5 +1,5 @@
|
||||
# 
|
||||
[](https://travis-ci.org/SquidDev-CC/CC-Tweaked)
|
||||
[](https://github.com/SquidDev-CC/CC-Tweaked/actions "Current build status") [](https://minecraft.curseforge.com/projects/cc-tweaked "Download CC: Tweaked on CurseForge")
|
||||
|
||||
CC: Tweaked is a fork of [ComputerCraft](https://github.com/dan200/ComputerCraft), adding programmable computers,
|
||||
turtles and more to Minecraft.
|
||||
@@ -9,7 +9,7 @@ ComputerCraft has always held a fond place in my heart: it's the mod which reall
|
||||
mod which has kept me playing it for many years. However, development of the original mod has slowed, as the original
|
||||
developers have had less time to work on the mod, and moved onto other projects and commitments.
|
||||
|
||||
CC:Tweaked (or CC:T for short) is an attempt to continue ComputerCraft's legacy. It's not intended to be a competitor
|
||||
CC: Tweaked (or CC:T for short) is an attempt to continue ComputerCraft's legacy. It's not intended to be a competitor
|
||||
to CC, nor do I want to take it in a vastly different direction to the original mod. Instead, CC:T focuses on making the
|
||||
ComputerCraft experience as _solid_ as possible, ironing out any wrinkles that may have developed over time.
|
||||
|
||||
@@ -46,8 +46,17 @@ develop CC:T, you'll need to follow these steps:
|
||||
|
||||
If you want to run CC:T in a normal Minecraft instance, run `./gradlew build` and copy the `.jar` from `build/libs`.
|
||||
|
||||
## Community
|
||||
If you need help getting started with CC: Tweaked, want to show off your latest project, or just want to chat about
|
||||
ComputerCraft we have a [forum](https://forums.computercraft.cc/) and [Discord guild](https://discord.gg/H2UyJXe)!
|
||||
There's also a fairly populated, albeit quiet [IRC channel](http://webchat.esper.net/?channels=#computercraft), if
|
||||
that's more your cup of tea.
|
||||
|
||||
I'd generally recommend you don't contact me directly (email, DM, etc...) unless absolutely necessary (i.e. in order to
|
||||
report exploits). You'll get a far quicker response if you ask the whole community!
|
||||
|
||||
## Using
|
||||
If you want to depend on CC:Tweaked, we have a maven repo. However, you should be wary that some functionality is only
|
||||
If you want to depend on CC: Tweaked, we have a maven repo. However, you should be wary that some functionality is only
|
||||
exposed by CC:T's API and not vanilla ComputerCraft. If you wish to support all variations of ComputerCraft, I recommend
|
||||
using [cc.crzd.me's maven](https://cc.crzd.me/maven/) instead.
|
||||
|
||||
@@ -57,7 +66,7 @@ dependencies {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "org.squiddev:cc-tweaked:${mc_version}-${cct_version}"
|
||||
implementation "org.squiddev:cc-tweaked-${mc_version}:${cct_version}"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
167
build.gradle
167
build.gradle
@@ -5,7 +5,7 @@ buildscript {
|
||||
jcenter()
|
||||
maven {
|
||||
name = "forge"
|
||||
url = "http://files.minecraftforge.net/maven"
|
||||
url = "https://files.minecraftforge.net/maven"
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
@@ -17,7 +17,10 @@ buildscript {
|
||||
}
|
||||
|
||||
plugins {
|
||||
id 'com.matthewprenger.cursegradle' version '1.0.10'
|
||||
id "checkstyle"
|
||||
id "com.github.hierynomus.license" version "0.15.0"
|
||||
id "com.matthewprenger.cursegradle" version "1.3.0"
|
||||
id "com.github.breadmoirai.github-release" version "2.2.4"
|
||||
}
|
||||
|
||||
apply plugin: 'net.minecraftforge.gradle.forge'
|
||||
@@ -42,7 +45,7 @@ minecraft {
|
||||
repositories {
|
||||
maven {
|
||||
name "JEI"
|
||||
url "http://dvs1.progwml6.com/files/maven"
|
||||
url "https://dvs1.progwml6.com/files/maven"
|
||||
}
|
||||
maven {
|
||||
name "SquidDev"
|
||||
@@ -54,7 +57,11 @@ repositories {
|
||||
}
|
||||
maven {
|
||||
name "Amadornes"
|
||||
url "http://maven.amadornes.com/"
|
||||
url "https://maven.amadornes.com/"
|
||||
}
|
||||
maven {
|
||||
name "CraftTweaker"
|
||||
url "https://maven.blamejared.com/"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,20 +72,25 @@ configurations {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
checkstyle "com.puppycrawl.tools:checkstyle:8.25"
|
||||
|
||||
deobfProvided "CraftTweaker2:CraftTweaker2-MC1120-Main:1.12-4.1.20.554"
|
||||
deobfProvided "MCMultiPart2:MCMultiPart:2.5.3"
|
||||
deobfProvided "mezz.jei:jei_1.12.2:4.15.0.269:api"
|
||||
deobfProvided "pl.asie:Charset-Lib:0.5.4.6"
|
||||
deobfProvided "MCMultiPart2:MCMultiPart:2.5.3"
|
||||
|
||||
runtime "mezz.jei:jei_1.12.2:4.15.0.269"
|
||||
|
||||
shade 'org.squiddev:Cobalt:0.5.0-SNAPSHOT'
|
||||
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.0'
|
||||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.0'
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.2'
|
||||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.4.2'
|
||||
|
||||
deployerJars "org.apache.maven.wagon:wagon-ssh:3.0.0"
|
||||
}
|
||||
|
||||
// Compile tasks
|
||||
|
||||
javadoc {
|
||||
include "dan200/computercraft/api/**/*.java"
|
||||
}
|
||||
@@ -97,12 +109,22 @@ jar {
|
||||
from configurations.shade.collect { it.isDirectory() ? it : zipTree(it) }
|
||||
}
|
||||
|
||||
[compileJava, compileTestJava].forEach {
|
||||
it.configure {
|
||||
options.compilerArgs << "-Xlint" << "-Xlint:-processing" << "-Werror"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.nio.file.*
|
||||
import java.util.zip.*
|
||||
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonElement
|
||||
import com.hierynomus.gradle.license.tasks.LicenseCheck
|
||||
import com.hierynomus.gradle.license.tasks.LicenseFormat
|
||||
import org.ajoberstar.grgit.Grgit
|
||||
import proguard.gradle.ProGuardTask
|
||||
|
||||
@@ -115,6 +137,7 @@ task proguard(type: ProGuardTask, dependsOn: jar) {
|
||||
|
||||
// Add the main runtime jar and all non-shadowed dependencies
|
||||
libraryjars "${System.getProperty('java.home')}/lib/rt.jar"
|
||||
libraryjars "${System.getProperty('java.home')}/lib/jce.jar"
|
||||
doFirst {
|
||||
sourceSets.main.compileClasspath
|
||||
.filter { !it.name.contains("Cobalt") }
|
||||
@@ -129,9 +152,6 @@ task proguard(type: ProGuardTask, dependsOn: jar) {
|
||||
|
||||
// Preserve ComputerCraft classes - we only want to strip shadowed files.
|
||||
keep 'class dan200.computercraft.** { *; }'
|
||||
|
||||
// Preserve the constructors in Cobalt library class, as we init them via reflection
|
||||
keepclassmembers 'class org.squiddev.cobalt.lib.** { <init>(...); }'
|
||||
}
|
||||
|
||||
task proguardMove(dependsOn: proguard) {
|
||||
@@ -198,6 +218,7 @@ task compressJson(dependsOn: extractAnnotationsJar) {
|
||||
// Copy over all files in the current jar to the new one, running json files from GSON. As pretty printing
|
||||
// is turned off, they should be minified.
|
||||
new ZipFile(jarPath).withCloseable { inJar ->
|
||||
tempPath.getParentFile().mkdirs()
|
||||
new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tempPath))).withCloseable { outJar ->
|
||||
inJar.entries().each { entry ->
|
||||
if(entry.directory) {
|
||||
@@ -225,12 +246,106 @@ task compressJson(dependsOn: extractAnnotationsJar) {
|
||||
|
||||
assemble.dependsOn compressJson
|
||||
|
||||
// Check tasks
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
testLogging {
|
||||
events "skipped", "failed"
|
||||
}
|
||||
}
|
||||
|
||||
license {
|
||||
mapping("java", "SLASHSTAR_STYLE")
|
||||
strictCheck true
|
||||
|
||||
ext.year = Calendar.getInstance().get(Calendar.YEAR)
|
||||
}
|
||||
|
||||
[licenseMain, licenseFormatMain].forEach {
|
||||
it.configure {
|
||||
include("**/*.java")
|
||||
exclude("dan200/computercraft/api/**")
|
||||
header rootProject.file('config/license/main.txt')
|
||||
}
|
||||
}
|
||||
|
||||
[licenseTest, licenseFormatTest].forEach {
|
||||
it.configure {
|
||||
include("**/*.java")
|
||||
header rootProject.file('config/license/main.txt')
|
||||
}
|
||||
}
|
||||
|
||||
gradle.projectsEvaluated {
|
||||
tasks.withType(LicenseFormat) {
|
||||
outputs.upToDateWhen { false }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
task licenseAPI(type: LicenseCheck);
|
||||
task licenseFormatAPI(type: LicenseFormat);
|
||||
[licenseAPI, licenseFormatAPI].forEach {
|
||||
it.configure {
|
||||
source = sourceSets.main.java
|
||||
include("dan200/computercraft/api/**")
|
||||
header rootProject.file('config/license/api.txt')
|
||||
}
|
||||
}
|
||||
|
||||
// Upload tasks
|
||||
|
||||
task checkRelease {
|
||||
group "upload"
|
||||
description "Verifies that everything is ready for a release"
|
||||
|
||||
inputs.property "version", mod_version
|
||||
inputs.file("src/main/resources/assets/computercraft/lua/rom/help/changelog.txt")
|
||||
inputs.file("src/main/resources/assets/computercraft/lua/rom/help/whatsnew.txt")
|
||||
|
||||
doLast {
|
||||
def ok = true
|
||||
|
||||
// Check we're targetting the current version
|
||||
def whatsnew = new File("src/main/resources/assets/computercraft/lua/rom/help/whatsnew.txt").readLines()
|
||||
if (whatsnew[0] != "New features in CC: Tweaked $mod_version") {
|
||||
ok = false
|
||||
project.logger.error("Expected `whatsnew.txt' to target $mod_version.")
|
||||
}
|
||||
|
||||
// Check "read more" exists and trim it
|
||||
def idx = whatsnew.findIndexOf { it == 'Type "help changelog" to see the full version history.' }
|
||||
if (idx == -1) {
|
||||
ok = false
|
||||
project.logger.error("Must mention the changelog in whatsnew.txt")
|
||||
} else {
|
||||
whatsnew = whatsnew.getAt(0 ..< idx)
|
||||
}
|
||||
|
||||
// Check whatsnew and changelog match.
|
||||
def versionChangelog = "# " + whatsnew.join("\n")
|
||||
def changelog = new File("src/main/resources/assets/computercraft/lua/rom/help/changelog.txt").getText()
|
||||
if (!changelog.startsWith(versionChangelog)) {
|
||||
ok = false
|
||||
project.logger.error("whatsnew and changelog are not in sync")
|
||||
}
|
||||
|
||||
if (!ok) throw new IllegalStateException("Could not check release")
|
||||
}
|
||||
}
|
||||
check.dependsOn checkRelease
|
||||
|
||||
curseforge {
|
||||
apiKey = project.hasProperty('curseForgeApiKey') ? project.curseForgeApiKey : ''
|
||||
project {
|
||||
id = '282001'
|
||||
releaseType = 'release'
|
||||
changelog = "Release notes can be found on the GitHub repository (https://github.com/SquidDev-CC/CC-Tweaked/releases/tag/v${project.version})."
|
||||
changelog = "Release notes can be found on the GitHub repository (https://github.com/SquidDev-CC/CC-Tweaked/releases/tag/v${mc_version}-${mod_version})."
|
||||
|
||||
relations {
|
||||
incompatible "computercraft"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,17 +402,31 @@ uploadArchives {
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
testLogging {
|
||||
events "passed", "skipped", "failed"
|
||||
githubRelease {
|
||||
token project.hasProperty('githubApiKey') ? project.githubApiKey : ''
|
||||
owner 'SquidDev-CC'
|
||||
repo 'CC-Tweaked'
|
||||
try {
|
||||
targetCommitish = Grgit.open(dir: '.').branch.current().name
|
||||
} catch(Exception ignored) { }
|
||||
|
||||
tagName "v${mc_version}-${mod_version}"
|
||||
releaseName "[${mc_version}] ${mod_version}"
|
||||
body {
|
||||
"## " + new File("src/main/resources/assets/computercraft/lua/rom/help/whatsnew.txt")
|
||||
.readLines()
|
||||
.takeWhile { it != 'Type "help changelog" to see the full version history.' }
|
||||
.join("\n").trim()
|
||||
}
|
||||
prerelease false
|
||||
}
|
||||
|
||||
gradle.projectsEvaluated {
|
||||
tasks.withType(JavaCompile) {
|
||||
options.compilerArgs << "-Xlint" << "-Xlint:-processing" << "-Werror"
|
||||
}
|
||||
def uploadTasks = ["uploadArchives", "curseforge", "githubRelease"]
|
||||
uploadTasks.forEach { tasks.getByName(it).dependsOn checkRelease }
|
||||
|
||||
task uploadAll(dependsOn: uploadTasks) {
|
||||
group "upload"
|
||||
description "Uploads to all repositories (Maven, Curse, GitHub release)"
|
||||
}
|
||||
|
||||
runClient.outputs.upToDateWhen { false }
|
||||
|
||||
169
config/checkstyle/checkstyle.xml
Normal file
169
config/checkstyle/checkstyle.xml
Normal file
@@ -0,0 +1,169 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
<module name="Checker">
|
||||
<property name="tabWidth" value="4"/>
|
||||
<property name="charset" value="UTF-8" />
|
||||
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file" value="config/checkstyle/suppressions.xml" />
|
||||
</module>
|
||||
|
||||
<module name="TreeWalker">
|
||||
<!-- Annotations -->
|
||||
<module name="AnnotationLocation" />
|
||||
<module name="AnnotationUseStyle" />
|
||||
<module name="MissingDeprecated" />
|
||||
<module name="MissingOverride" />
|
||||
|
||||
<!-- Blocks -->
|
||||
<module name="EmptyBlock" />
|
||||
<module name="EmptyCatchBlock">
|
||||
<property name="exceptionVariableName" value="ignored" />
|
||||
</module>
|
||||
<module name="LeftCurly">
|
||||
<property name="option" value="nl" />
|
||||
<!-- The defaults, minus lambdas. -->
|
||||
<property name="tokens" value="ANNOTATION_DEF,CLASS_DEF,CTOR_DEF,ENUM_CONSTANT_DEF,ENUM_DEF,INTERFACE_DEF,LITERAL_CASE,LITERAL_CATCH,LITERAL_DEFAULT,LITERAL_DO,LITERAL_ELSE,LITERAL_FINALLY,LITERAL_FOR,LITERAL_IF,LITERAL_SWITCH,LITERAL_SYNCHRONIZED,LITERAL_TRY,LITERAL_WHILE,METHOD_DEF,OBJBLOCK,STATIC_INIT" />
|
||||
</module>
|
||||
<module name="NeedBraces">
|
||||
<property name="allowSingleLineStatement" value="true"/>
|
||||
</module>
|
||||
<module name="RightCurly">
|
||||
<property name="option" value="alone" />
|
||||
</module>
|
||||
|
||||
<!-- Class design. As if we've ever followed good practice here. -->
|
||||
<module name="FinalClass" />
|
||||
<module name="InterfaceIsType" />
|
||||
<module name="MutableException" />
|
||||
<module name="OneTopLevelClass" />
|
||||
|
||||
<!-- Coding -->
|
||||
<module name="ArrayTrailingComma" />
|
||||
<module name="EqualsHashCode" />
|
||||
<!-- FallThrough does not handle unreachable code well -->
|
||||
<module name="IllegalInstantiation" />
|
||||
<module name="IllegalThrows" />
|
||||
<module name="ModifiedControlVariable" />
|
||||
<module name="NoClone" />
|
||||
<module name="NoFinalizer" />
|
||||
<module name="OneStatementPerLine" />
|
||||
<module name="PackageDeclaration" />
|
||||
<module name="SimplifyBooleanExpression" />
|
||||
<module name="SimplifyBooleanReturn" />
|
||||
<module name="StringLiteralEquality" />
|
||||
<module name="UnnecessaryParentheses" />
|
||||
<module name="UnnecessarySemicolonAfterTypeMemberDeclaration" />
|
||||
<module name="UnnecessarySemicolonInTryWithResources" />
|
||||
<module name="UnnecessarySemicolonInEnumeration" />
|
||||
|
||||
<!-- Imports -->
|
||||
<module name="CustomImportOrder" />
|
||||
<module name="IllegalImport" />
|
||||
<module name="RedundantImport" />
|
||||
<module name="UnusedImports" />
|
||||
|
||||
<!-- Javadoc -->
|
||||
<!-- TODO: Missing* checks for the dan200.computercraft.api package? -->
|
||||
<module name="AtclauseOrder" />
|
||||
<module name="InvalidJavadocPosition" />
|
||||
<module name="JavadocBlockTagLocation" />
|
||||
<module name="JavadocMethod"/>
|
||||
<module name="JavadocType"/>
|
||||
<module name="JavadocStyle" />
|
||||
<module name="NonEmptyAtclauseDescription" />
|
||||
<module name="SingleLineJavadoc" />
|
||||
<module name="SummaryJavadocCheck"/>
|
||||
|
||||
<!-- Misc -->
|
||||
<module name="ArrayTypeStyle" />
|
||||
<module name="CommentsIndentation" />
|
||||
<module name="Indentation" />
|
||||
<module name="OuterTypeFilename" />
|
||||
|
||||
<!-- Modifiers -->
|
||||
<module name="ModifierOrder" />
|
||||
<module name="RedundantModifier" />
|
||||
|
||||
<!-- Naming -->
|
||||
<module name="ClassTypeParameterName" />
|
||||
<module name="InterfaceTypeParameterName" />
|
||||
<module name="LambdaParameterName" />
|
||||
<module name="LocalFinalVariableName" />
|
||||
<module name="LocalVariableName" />
|
||||
<!-- Allow an optional m_ on private members -->
|
||||
<module name="MemberName">
|
||||
<property name="applyToPrivate" value="false" />
|
||||
<property name="applyToPackage" value="false" />
|
||||
</module>
|
||||
<module name="MemberName">
|
||||
<property name="format" value="^(m_)?[a-z][a-zA-Z0-9]*$" />
|
||||
<property name="applyToPrivate" value="true" />
|
||||
<property name="applyToPackage" value="true" />
|
||||
</module>
|
||||
<module name="MethodName" />
|
||||
<module name="MethodTypeParameterName" />
|
||||
<module name="PackageName">
|
||||
<property name="format" value="^dan200\.computercraf(\.[a-z][a-z0-9]*)*" />
|
||||
</module>
|
||||
<module name="ParameterName" />
|
||||
<module name="StaticVariableName">
|
||||
<property name="format" value="^[a-z][a-zA-Z0-9]*|CAPABILITY(_[A-Z]+)?$" />
|
||||
<property name="applyToPrivate" value="false" />
|
||||
</module>
|
||||
<module name="StaticVariableName">
|
||||
<property name="format" value="^(s_)?[a-z][a-zA-Z0-9]*|CAPABILITY(_[A-Z]+)?$" />
|
||||
<property name="applyToPrivate" value="true" />
|
||||
</module>
|
||||
<module name="TypeName" />
|
||||
|
||||
<!-- Whitespace -->
|
||||
<module name="EmptyForInitializerPad"/>
|
||||
<module name="EmptyForIteratorPad">
|
||||
<property name="option" value="space"/>
|
||||
</module>
|
||||
<module name="GenericWhitespace" />
|
||||
<module name="MethodParamPad" />
|
||||
<module name="NoLineWrap" />
|
||||
<module name="NoWhitespaceAfter">
|
||||
<property name="tokens" value="AT,INC,DEC,UNARY_MINUS,UNARY_PLUS,BNOT,LNOT,DOT,ARRAY_DECLARATOR,INDEX_OP" />
|
||||
</module>
|
||||
<module name="NoWhitespaceBefore" />
|
||||
<!-- TODO: Decide on an OperatorWrap style. -->
|
||||
<module name="ParenPad">
|
||||
<property name="option" value="space" />
|
||||
<property name="tokens" value="ANNOTATION,ANNOTATION_FIELD_DEF,CTOR_CALL,CTOR_DEF,ENUM_CONSTANT_DEF,LITERAL_CATCH,LITERAL_DO,LITERAL_FOR,LITERAL_IF,LITERAL_NEW,LITERAL_SWITCH,LITERAL_SYNCHRONIZED,LITERAL_WHILE,METHOD_CALL,METHOD_DEF,RESOURCE_SPECIFICATION,SUPER_CTOR_CALL,LAMBDA" />
|
||||
</module>
|
||||
<module name="ParenPad">
|
||||
<property name="option" value="nospace" />
|
||||
<property name="tokens" value="DOT,EXPR,QUESTION" />
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<property name="option" value="eol" />
|
||||
<property name="tokens" value="COMMA,SEMI,ELLIPSIS,ARRAY_DECLARATOR,RBRACK,METHOD_REF" />
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<property name="option" value="nl" />
|
||||
<property name="tokens" value="DOT,AT" />
|
||||
</module>
|
||||
<module name="SingleSpaceSeparator" />
|
||||
<module name="TypecastParenPad" />
|
||||
<module name="WhitespaceAfter">
|
||||
<property name="tokens" value="COMMA" />
|
||||
</module>
|
||||
<module name="WhitespaceAround">
|
||||
<property name="allowEmptyConstructors" value="true" />
|
||||
<property name="ignoreEnhancedForColon" value="false" />
|
||||
<property name="tokens" value="ASSIGN,BAND,BAND_ASSIGN,BOR,BOR_ASSIGN,BSR,BSR_ASSIGN,BXOR,BXOR_ASSIGN,COLON,DIV,DIV_ASSIGN,DO_WHILE,EQUAL,GE,GT,LAMBDA,LAND,LCURLY,LE,LITERAL_RETURN,LOR,LT,MINUS,MINUS_ASSIGN,MOD,MOD_ASSIGN,NOT_EQUAL,PLUS,PLUS_ASSIGN,QUESTION,RCURLY,SL,SLIST,SL_ASSIGN,SR,SR_ASSIGN,STAR,STAR_ASSIGN,LITERAL_ASSERT,TYPE_EXTENSION_AND" />
|
||||
</module>
|
||||
</module>
|
||||
|
||||
<module name="FileTabCharacter" />
|
||||
<module name="NewlineAtEndOfFile" />
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="\s+$"/>
|
||||
<property name="message" value="Trailing whitespace"/>
|
||||
</module>
|
||||
</module>
|
||||
12
config/checkstyle/suppressions.xml
Normal file
12
config/checkstyle/suppressions.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
|
||||
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
||||
<suppressions>
|
||||
<!-- All the config options and method fields. -->
|
||||
<suppress checks="StaticVariableName" files=".*[\\/]ComputerCraft.java" />
|
||||
<suppress checks="StaticVariableName" files=".*[\\/]ComputerCraftAPI.java" />
|
||||
|
||||
<!-- Do not check for missing package Javadoc. -->
|
||||
<suppress checks="JavadocStyle" files=".*[\\/]package-info.java" />
|
||||
</suppressions>
|
||||
3
config/license/api.txt
Normal file
3
config/license/api.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
Copyright Daniel Ratcliffe, 2011-${year}. 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.
|
||||
3
config/license/main.txt
Normal file
3
config/license/main.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
This file is part of ComputerCraft - http://www.computercraft.info
|
||||
Copyright Daniel Ratcliffe, 2011-${year}. Do not distribute without permission.
|
||||
Send enquiries to dratcliffe@gmail.com
|
||||
@@ -1,5 +1,5 @@
|
||||
# Mod properties
|
||||
mod_version=1.82.0
|
||||
mod_version=1.86.0
|
||||
|
||||
# Minecraft properties
|
||||
mc_version=1.12.2
|
||||
|
||||
28
illuaminate.sexp
Normal file
28
illuaminate.sexp
Normal file
@@ -0,0 +1,28 @@
|
||||
; -*- mode: Lisp;-*-
|
||||
|
||||
(sources
|
||||
/src/main/resources/assets/computercraft/lua/bios.lua
|
||||
/src/main/resources/assets/computercraft/lua/rom/
|
||||
/src/test/resources/test-rom)
|
||||
|
||||
(at /
|
||||
(linters
|
||||
;; 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))
|
||||
|
||||
;; 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/assets/computercraft/lua/bios.lua
|
||||
/src/main/resources/assets/computercraft/lua/rom/apis/)
|
||||
(linters -var:unused-global)
|
||||
(lint
|
||||
(allow-toplevel-global true)))
|
||||
|
||||
;; These warnings are broken right now
|
||||
(at (bios.lua worm.lua) (linters -control:unreachable))
|
||||
@@ -72,9 +72,7 @@ import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.IBlockAccess;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.common.DimensionManager;
|
||||
import net.minecraftforge.fml.common.FMLCommonHandler;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.SidedProxy;
|
||||
import net.minecraftforge.fml.common.*;
|
||||
import net.minecraftforge.fml.common.event.*;
|
||||
import net.minecraftforge.fml.relauncher.Side;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
@@ -83,9 +81,7 @@ import java.io.*;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
@@ -394,6 +390,27 @@ public class ComputerCraft
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadFromFile( List<IMount> mounts, File file, String path, boolean allowMissing )
|
||||
{
|
||||
try
|
||||
{
|
||||
if( file.isFile() )
|
||||
{
|
||||
mounts.add( new JarMount( file, path ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
File subResource = new File( file, path );
|
||||
if( subResource.exists() ) mounts.add( new FileMount( subResource, 0 ) );
|
||||
}
|
||||
}
|
||||
catch( IOException | RuntimeException e )
|
||||
{
|
||||
if( allowMissing && e instanceof FileNotFoundException ) return;
|
||||
ComputerCraft.log.error( "Could not load mount '" + path + " 'from '" + file.getName() + "'", e );
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static IMount createResourceMount( Class<?> modClass, String domain, String subPath )
|
||||
{
|
||||
@@ -413,18 +430,26 @@ public class ComputerCraft
|
||||
}
|
||||
}
|
||||
|
||||
// Mount from mod jar
|
||||
// Mount from mod jars, preferring the specified one.
|
||||
File modJar = getContainingJar( modClass );
|
||||
Set<File> otherMods = new HashSet<>();
|
||||
for( ModContainer container : Loader.instance().getActiveModList() )
|
||||
{
|
||||
File modFile = container.getSource();
|
||||
if( modFile != null && !modFile.equals( modJar ) && modFile.exists() )
|
||||
{
|
||||
otherMods.add( container.getSource() );
|
||||
}
|
||||
}
|
||||
|
||||
for( File file : otherMods )
|
||||
{
|
||||
loadFromFile( mounts, file, subPath, true );
|
||||
}
|
||||
|
||||
if( modJar != null )
|
||||
{
|
||||
try
|
||||
{
|
||||
mounts.add( new JarMount( modJar, subPath ) );
|
||||
}
|
||||
catch( IOException | RuntimeException e )
|
||||
{
|
||||
ComputerCraft.log.error( "Could not load mount from mod jar", e );
|
||||
}
|
||||
loadFromFile( mounts, modJar, subPath, false );
|
||||
}
|
||||
|
||||
// Mount from resource packs
|
||||
@@ -434,25 +459,8 @@ public class ComputerCraft
|
||||
String[] resourcePacks = resourcePackDir.list();
|
||||
for( String resourcePackName : resourcePacks )
|
||||
{
|
||||
try
|
||||
{
|
||||
File resourcePack = new File( resourcePackDir, resourcePackName );
|
||||
if( !resourcePack.isDirectory() )
|
||||
{
|
||||
// Mount a resource pack from a jar
|
||||
mounts.add( new JarMount( resourcePack, subPath ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
// Mount a resource pack from a folder
|
||||
File subResource = new File( resourcePack, subPath );
|
||||
if( subResource.exists() ) mounts.add( new FileMount( subResource, 0 ) );
|
||||
}
|
||||
}
|
||||
catch( IOException | RuntimeException e )
|
||||
{
|
||||
ComputerCraft.log.error( "Could not load resource pack '" + resourcePackName + "'", e );
|
||||
}
|
||||
File resourcePack = new File( resourcePackDir, resourcePackName );
|
||||
loadFromFile( mounts, resourcePack, subPath, true );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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.turtle.ITurtleUpgrade;
|
||||
|
||||
@@ -32,8 +32,9 @@ import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
@@ -269,7 +270,7 @@ public final class ComputerCraftAPI
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a media provider to provide {@link IMedia} implementations for Items
|
||||
* Registers a media provider to provide {@link IMedia} implementations for Items.
|
||||
*
|
||||
* @param provider The media provider to register.
|
||||
* @see IMediaProvider
|
||||
@@ -370,7 +371,7 @@ public final class ComputerCraftAPI
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a new wired node for a given wired element
|
||||
* Construct a new wired node for a given wired element.
|
||||
*
|
||||
* @param element The element to construct it for
|
||||
* @return The element's node
|
||||
@@ -398,7 +399,7 @@ public final class ComputerCraftAPI
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the wired network element for a block in world
|
||||
* Get the wired network element for a block in world.
|
||||
*
|
||||
* @param world The world the block exists in
|
||||
* @param pos The position the block exists in
|
||||
@@ -438,45 +439,45 @@ public final class ComputerCraftAPI
|
||||
computerCraft_getVersion = findCCMethod( "getVersion", new Class<?>[] {
|
||||
} );
|
||||
computerCraft_createUniqueNumberedSaveDir = findCCMethod( "createUniqueNumberedSaveDir", new Class<?>[] {
|
||||
World.class, String.class
|
||||
World.class, String.class,
|
||||
} );
|
||||
computerCraft_createSaveDirMount = findCCMethod( "createSaveDirMount", new Class<?>[] {
|
||||
World.class, String.class, Long.TYPE
|
||||
World.class, String.class, Long.TYPE,
|
||||
} );
|
||||
computerCraft_createResourceMount = findCCMethod( "createResourceMount", new Class<?>[] {
|
||||
Class.class, String.class, String.class
|
||||
Class.class, String.class, String.class,
|
||||
} );
|
||||
computerCraft_registerPeripheralProvider = findCCMethod( "registerPeripheralProvider", new Class<?>[] {
|
||||
IPeripheralProvider.class
|
||||
IPeripheralProvider.class,
|
||||
} );
|
||||
computerCraft_registerTurtleUpgrade = findCCMethod( "registerTurtleUpgrade", new Class<?>[] {
|
||||
ITurtleUpgrade.class
|
||||
ITurtleUpgrade.class,
|
||||
} );
|
||||
computerCraft_registerBundledRedstoneProvider = findCCMethod( "registerBundledRedstoneProvider", new Class<?>[] {
|
||||
IBundledRedstoneProvider.class
|
||||
IBundledRedstoneProvider.class,
|
||||
} );
|
||||
computerCraft_getDefaultBundledRedstoneOutput = findCCMethod( "getDefaultBundledRedstoneOutput", new Class<?>[] {
|
||||
World.class, BlockPos.class, EnumFacing.class
|
||||
World.class, BlockPos.class, EnumFacing.class,
|
||||
} );
|
||||
computerCraft_registerMediaProvider = findCCMethod( "registerMediaProvider", new Class<?>[] {
|
||||
IMediaProvider.class
|
||||
IMediaProvider.class,
|
||||
} );
|
||||
computerCraft_registerPermissionProvider = findCCMethod( "registerPermissionProvider", new Class<?>[] {
|
||||
ITurtlePermissionProvider.class
|
||||
ITurtlePermissionProvider.class,
|
||||
} );
|
||||
computerCraft_registerPocketUpgrade = findCCMethod( "registerPocketUpgrade", new Class<?>[] {
|
||||
IPocketUpgrade.class
|
||||
IPocketUpgrade.class,
|
||||
} );
|
||||
computerCraft_getWirelessNetwork = findCCMethod( "getWirelessNetwork", new Class<?>[] {
|
||||
} );
|
||||
computerCraft_registerAPIFactory = findCCMethod( "registerAPIFactory", new Class<?>[] {
|
||||
ILuaAPIFactory.class
|
||||
ILuaAPIFactory.class,
|
||||
} );
|
||||
computerCraft_createWiredNodeForElement = findCCMethod( "createWiredNodeForElement", new Class<?>[] {
|
||||
IWiredElement.class
|
||||
IWiredElement.class,
|
||||
} );
|
||||
computerCraft_getWiredElementAt = findCCMethod( "getWiredElementAt", new Class<?>[] {
|
||||
IBlockAccess.class, BlockPos.class, EnumFacing.class
|
||||
IBlockAccess.class, BlockPos.class, EnumFacing.class,
|
||||
} );
|
||||
}
|
||||
catch( Exception e )
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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;
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* An {@link IOException} which occurred on a specific file.
|
||||
*
|
||||
* This may be thrown from a {@link IMount} or {@link IWritableMount} to give more information about a failure.
|
||||
*/
|
||||
public class FileOperationException extends IOException
|
||||
{
|
||||
private static final long serialVersionUID = -8809108200853029849L;
|
||||
|
||||
private final String filename;
|
||||
|
||||
public FileOperationException( @Nullable String filename, @Nonnull String message )
|
||||
{
|
||||
super( Objects.requireNonNull( message, "message cannot be null" ) );
|
||||
this.filename = filename;
|
||||
}
|
||||
|
||||
public FileOperationException( String message )
|
||||
{
|
||||
super( Objects.requireNonNull( message, "message cannot be null" ) );
|
||||
this.filename = null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String getFilename()
|
||||
{
|
||||
return filename;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ 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)}
|
||||
* {@link IComputerAccess#mount(String, IMount)}.
|
||||
*
|
||||
* Ready made implementations of this interface can be created using
|
||||
* {@link ComputerCraftAPI#createSaveDirMount(World, String, long)} or
|
||||
@@ -60,7 +60,7 @@ public interface IMount
|
||||
void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException;
|
||||
|
||||
/**
|
||||
* Returns the size of a file with a given path, in bytes
|
||||
* Returns the size of a file with a given path, in bytes.
|
||||
*
|
||||
* @param path A file path in normalised format, relative to the mount location. ie: "programs/myprogram".
|
||||
* @return The size of the file, in bytes.
|
||||
@@ -90,7 +90,6 @@ public interface IMount
|
||||
* @throws IOException If the file does not exist, or could not be opened.
|
||||
*/
|
||||
@Nonnull
|
||||
@SuppressWarnings( "deprecation" )
|
||||
default ReadableByteChannel openChannelForRead( @Nonnull String path ) throws IOException
|
||||
{
|
||||
return Channels.newChannel( openForRead( path ) );
|
||||
|
||||
@@ -67,7 +67,6 @@ public interface IWritableMount extends IMount
|
||||
* @throws IOException If the file could not be opened for writing.
|
||||
*/
|
||||
@Nonnull
|
||||
@SuppressWarnings( "deprecation" )
|
||||
default WritableByteChannel openChannelForWrite( @Nonnull String path ) throws IOException
|
||||
{
|
||||
return Channels.newChannel( openForWrite( path ) );
|
||||
@@ -94,7 +93,6 @@ public interface IWritableMount extends IMount
|
||||
* @throws IOException If the file could not be opened for writing.
|
||||
*/
|
||||
@Nonnull
|
||||
@SuppressWarnings( "deprecation" )
|
||||
default WritableByteChannel openChannelForAppend( @Nonnull String path ) throws IOException
|
||||
{
|
||||
return Channels.newChannel( openForAppend( path ) );
|
||||
|
||||
335
src/main/java/dan200/computercraft/api/lua/ArgumentHelper.java
Normal file
335
src/main/java/dan200/computercraft/api/lua/ArgumentHelper.java
Normal file
@@ -0,0 +1,335 @@
|
||||
/*
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Provides methods for extracting values and validating Lua arguments, such as those provided to
|
||||
* {@link ILuaObject#callMethod(ILuaContext, int, Object[])} or
|
||||
* {@link IPeripheral#callMethod(IComputerAccess, ILuaContext, int, Object[])}.
|
||||
*
|
||||
* This provides two sets of functions: the {@code get*} methods, which require an argument to be valid, and
|
||||
* {@code opt*}, which accept a default value and return that if the argument was not present or was {@code null}.
|
||||
* If the argument is of the wrong type, a suitable error message will be thrown, with a similar format to Lua's own
|
||||
* error messages.
|
||||
*
|
||||
* <h2>Example usage:</h2>
|
||||
* <pre>
|
||||
* {@code
|
||||
* int slot = getInt( args, 0 );
|
||||
* int amount = optInt( args, 1, 64 );
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
public final class ArgumentHelper
|
||||
{
|
||||
private ArgumentHelper()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* 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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a "bad argument" exception, from an expected type and the actual value provided.
|
||||
*
|
||||
* @param index The argument number, starting from 0.
|
||||
* @param expected The expected type for this argument.
|
||||
* @param actual The actual value provided for this argument.
|
||||
* @return The constructed exception, which should be thrown immediately.
|
||||
*/
|
||||
@Nonnull
|
||||
public static LuaException badArgumentOf( int index, @Nonnull String expected, @Nullable Object actual )
|
||||
{
|
||||
return badArgument( index, expected, getType( actual ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a "bad argument" exception, from an expected and actual type.
|
||||
*
|
||||
* @param index The argument number, starting from 0.
|
||||
* @param expected The expected type for this argument.
|
||||
* @param actual The provided type for this argument.
|
||||
* @return The constructed exception, which should be thrown immediately.
|
||||
*/
|
||||
@Nonnull
|
||||
public static LuaException badArgument( int index, @Nonnull String expected, @Nonnull String actual )
|
||||
{
|
||||
return new LuaException( "bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a double.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not a number.
|
||||
* @see #getFiniteDouble(Object[], int) if you require this to be finite (i.e. not infinite or NaN).
|
||||
*/
|
||||
public static double getDouble( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "number", "nil" );
|
||||
Object value = args[index];
|
||||
if( !(value instanceof Number) ) throw badArgumentOf( index, "number", value );
|
||||
return ((Number) value).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as an integer.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not an integer.
|
||||
*/
|
||||
public static int getInt( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
return (int) getLong( args, index );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a long.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not a long.
|
||||
*/
|
||||
public static long getLong( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "number", "nil" );
|
||||
Object value = args[index];
|
||||
if( !(value instanceof Number) ) throw badArgumentOf( index, "number", value );
|
||||
return checkFinite( index, (Number) value ).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a finite number (not infinite or NaN).
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not finite.
|
||||
*/
|
||||
public static double getFiniteDouble( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
return checkFinite( index, getDouble( args, index ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a boolean.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not a boolean.
|
||||
*/
|
||||
public static boolean getBoolean( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "boolean", "nil" );
|
||||
Object value = args[index];
|
||||
if( !(value instanceof Boolean) ) throw badArgumentOf( index, "boolean", value );
|
||||
return (Boolean) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a string.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not a string.
|
||||
*/
|
||||
@Nonnull
|
||||
public static String getString( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "string", "nil" );
|
||||
Object value = args[index];
|
||||
if( !(value instanceof String) ) throw badArgumentOf( index, "string", value );
|
||||
return (String) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a table.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @return The argument's value.
|
||||
* @throws LuaException If the value is not a table.
|
||||
*/
|
||||
@Nonnull
|
||||
public static Map<?, ?> getTable( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "table", "nil" );
|
||||
Object value = args[index];
|
||||
if( !(value instanceof Map) ) throw badArgumentOf( index, "table", value );
|
||||
return (Map<?, ?>) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a double.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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.
|
||||
*/
|
||||
public static double optDouble( @Nonnull Object[] args, int index, double def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null ) return def;
|
||||
if( !(value instanceof Number) ) throw badArgumentOf( index, "number", value );
|
||||
return ((Number) value).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as an int.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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.
|
||||
*/
|
||||
public static int optInt( @Nonnull Object[] args, int index, int def ) throws LuaException
|
||||
{
|
||||
return (int) optLong( args, index, def );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a long.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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.
|
||||
*/
|
||||
public static long optLong( @Nonnull Object[] args, int index, long def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null ) return def;
|
||||
if( !(value instanceof Number) ) throw badArgumentOf( index, "number", value );
|
||||
return checkFinite( index, (Number) value ).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a finite number (not infinite or NaN).
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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 finite.
|
||||
*/
|
||||
public static double optFiniteDouble( @Nonnull Object[] args, int index, double def ) throws LuaException
|
||||
{
|
||||
return checkFinite( index, optDouble( args, index, def ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a boolean.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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 boolean.
|
||||
*/
|
||||
public static boolean optBoolean( @Nonnull Object[] args, int index, boolean def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null ) return def;
|
||||
if( !(value instanceof Boolean) ) throw badArgumentOf( index, "boolean", value );
|
||||
return (Boolean) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a string.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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 string.
|
||||
*/
|
||||
public static String optString( @Nonnull Object[] args, int index, String def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null ) return def;
|
||||
if( !(value instanceof String) ) throw badArgumentOf( index, "string", value );
|
||||
return (String) value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an argument as a table.
|
||||
*
|
||||
* @param args The arguments to extract from.
|
||||
* @param index The index into the argument array to read from.
|
||||
* @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 table.
|
||||
*/
|
||||
public static Map<?, ?> optTable( @Nonnull Object[] args, int index, Map<Object, Object> def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null ) return def;
|
||||
if( !(value instanceof Map) ) throw badArgumentOf( index, "table", value );
|
||||
return (Map<?, ?>) value;
|
||||
}
|
||||
|
||||
private static Number checkFinite( int index, Number value ) throws LuaException
|
||||
{
|
||||
checkFinite( index, value.doubleValue() );
|
||||
return value;
|
||||
}
|
||||
|
||||
private static double checkFinite( int index, double value ) throws LuaException
|
||||
{
|
||||
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";
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ public interface IComputerSystem extends IComputerAccess
|
||||
IFileSystem getFileSystem();
|
||||
|
||||
/**
|
||||
* Get the label for this computer
|
||||
* Get the label for this computer.
|
||||
*
|
||||
* @return This computer's label, or {@code null} if it is not set.
|
||||
*/
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
package dan200.computercraft.api.peripheral;
|
||||
|
||||
import dan200.computercraft.api.lua.ArgumentHelper;
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
@@ -58,9 +59,11 @@ public interface IPeripheral
|
||||
* Lua values of type "table" will be represented by Object type Map.<br>
|
||||
* Lua values of any other type will be represented by a null object.<br>
|
||||
* This array will be empty if no arguments are passed.
|
||||
*
|
||||
* It is recommended you use {@link ArgumentHelper} in order to validate and process arguments.
|
||||
* @return An array of objects, representing values you wish to return to the lua program. Integers, Doubles, Floats,
|
||||
* Strings, Booleans, Maps and ILuaObject and null be converted to their corresponding lua type. All other types
|
||||
* will be converted to nil.
|
||||
* Strings, Booleans, Maps, ILuaObject and null be converted to their corresponding lua type. All other types will
|
||||
* be converted to nil.
|
||||
*
|
||||
* You may return null to indicate no values should be returned.
|
||||
* @throws LuaException If you throw any exception from this function, a lua error will be raised with the
|
||||
@@ -70,6 +73,7 @@ public interface IPeripheral
|
||||
* InterruptedException will be thrown. This exception must not be caught or
|
||||
* intercepted, or the computer will leak memory and end up in a broken state.
|
||||
* @see #getMethodNames
|
||||
* @see ArgumentHelper
|
||||
*/
|
||||
@Nullable
|
||||
Object[] callMethod( @Nonnull IComputerAccess computer, @Nonnull ILuaContext context, int method, @Nonnull Object[] arguments ) throws LuaException, InterruptedException;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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 net.minecraft.item.ItemStack;
|
||||
|
||||
@@ -16,7 +16,7 @@ import javax.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Wrapper class for pocket computers
|
||||
* Wrapper class for pocket computers.
|
||||
*/
|
||||
public interface IPocketAccess
|
||||
{
|
||||
|
||||
@@ -145,7 +145,9 @@ public interface ITurtleAccess
|
||||
GameProfile getOwningPlayer();
|
||||
|
||||
/**
|
||||
* Get the inventory of this turtle
|
||||
* 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()
|
||||
@@ -156,6 +158,8 @@ public interface ITurtleAccess
|
||||
/**
|
||||
* Get the inventory of this turtle as an {@link IItemHandlerModifiable}.
|
||||
*
|
||||
* Note: this inventory should only be accessed and modified on the server thread.
|
||||
*
|
||||
* @return This turtle's inventory
|
||||
* @see #getInventory()
|
||||
* @see IItemHandlerModifiable
|
||||
|
||||
@@ -109,8 +109,8 @@ public interface ITurtleUpgrade
|
||||
* 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.
|
||||
*
|
||||
* Conforming implementations should fire {@link BlockEvent.BreakEvent} and {@link TurtleBlockEvent.Dig}for digging,
|
||||
* {@link AttackEntityEvent} and {@link TurtleAttackEvent} for attacking.
|
||||
* Conforming implementations should fire {@link BlockEvent.BreakEvent} and {@link TurtleBlockEvent.Dig} for
|
||||
* digging, {@link AttackEntityEvent} and {@link TurtleAttackEvent} for attacking.
|
||||
*
|
||||
* @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.
|
||||
|
||||
@@ -12,12 +12,12 @@ package dan200.computercraft.api.turtle;
|
||||
public enum TurtleSide
|
||||
{
|
||||
/**
|
||||
* The turtle's left side (where the pickaxe usually is on a Wireless Mining Turtle)
|
||||
* The turtle's left side (where the pickaxe usually is on a Wireless Mining Turtle).
|
||||
*/
|
||||
Left,
|
||||
|
||||
/**
|
||||
* The turtle's right side (where the modem usually is on a Wireless Mining Turtle)
|
||||
* The turtle's right side (where the modem usually is on a Wireless Mining Turtle).
|
||||
*/
|
||||
Right,
|
||||
}
|
||||
|
||||
@@ -18,12 +18,12 @@ import net.minecraft.util.EnumFacing;
|
||||
public enum TurtleVerb
|
||||
{
|
||||
/**
|
||||
* The turtle called {@code turtle.dig()}, {@code turtle.digUp()} or {@code turtle.digDown()}
|
||||
* The turtle called {@code turtle.dig()}, {@code turtle.digUp()} or {@code turtle.digDown()}.
|
||||
*/
|
||||
Dig,
|
||||
|
||||
/**
|
||||
* The turtle called {@code turtle.attack()}, {@code turtle.attackUp()} or {@code turtle.attackDown()}
|
||||
* The turtle called {@code turtle.attack()}, {@code turtle.attackUp()} or {@code turtle.attackDown()}.
|
||||
*/
|
||||
Attack,
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public enum TurtleAction
|
||||
EQUIP,
|
||||
|
||||
/**
|
||||
* Inspect a block in world
|
||||
* Inspect a block in world.
|
||||
*
|
||||
* @see TurtleBlockEvent.Inspect
|
||||
*/
|
||||
|
||||
@@ -112,7 +112,7 @@ public abstract class TurtleBlockEvent extends TurtlePlayerEvent
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the upgrade doing the digging
|
||||
* Get the upgrade doing the digging.
|
||||
*
|
||||
* @return The upgrade doing the digging.
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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.ILuaContext;
|
||||
|
||||
@@ -31,7 +31,7 @@ public abstract class TurtleInventoryEvent extends TurtleBlockEvent
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the inventory being interacted with
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
* This file is part of the public ComputerCraft API - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. 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;
|
||||
|
||||
@@ -24,9 +24,10 @@ import java.io.IOException;
|
||||
|
||||
public class GuiComputer extends GuiContainer
|
||||
{
|
||||
private static final ResourceLocation BACKGROUND = new ResourceLocation( "computercraft", "textures/gui/corners.png" );
|
||||
private static final ResourceLocation BACKGROUND_ADVANCED = new ResourceLocation( "computercraft", "textures/gui/corners_advanced.png" );
|
||||
private static final ResourceLocation BACKGROUND_COMMAND = new ResourceLocation( "computercraft", "textures/gui/corners_command.png" );
|
||||
public static final ResourceLocation BACKGROUND_NORMAL = new ResourceLocation( ComputerCraft.MOD_ID, "textures/gui/corners.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" );
|
||||
|
||||
private final ComputerFamily m_family;
|
||||
private final ClientComputer m_computer;
|
||||
@@ -158,7 +159,7 @@ public class GuiComputer extends GuiContainer
|
||||
{
|
||||
case Normal:
|
||||
default:
|
||||
mc.getTextureManager().bindTexture( BACKGROUND );
|
||||
mc.getTextureManager().bindTexture( BACKGROUND_NORMAL );
|
||||
break;
|
||||
case Advanced:
|
||||
mc.getTextureManager().bindTexture( BACKGROUND_ADVANCED );
|
||||
@@ -169,12 +170,12 @@ public class GuiComputer extends GuiContainer
|
||||
}
|
||||
|
||||
drawTexturedModalRect( startX - 12, startY - 12, 12, 28, 12, 12 );
|
||||
drawTexturedModalRect( startX - 12, endY, 12, 40, 12, 16 );
|
||||
drawTexturedModalRect( startX - 12, endY, 12, 40, 12, 12 );
|
||||
drawTexturedModalRect( endX, startY - 12, 24, 28, 12, 12 );
|
||||
drawTexturedModalRect( endX, endY, 24, 40, 12, 16 );
|
||||
drawTexturedModalRect( endX, endY, 24, 40, 12, 12 );
|
||||
|
||||
drawTexturedModalRect( startX, startY - 12, 0, 0, endX - startX, 12 );
|
||||
drawTexturedModalRect( startX, endY, 0, 12, endX - startX, 16 );
|
||||
drawTexturedModalRect( startX, endY, 0, 12, endX - startX, 12 );
|
||||
|
||||
drawTexturedModalRect( startX - 12, startY, 0, 28, 12, endY - startY );
|
||||
drawTexturedModalRect( endX, startY, 36, 28, 12, endY - startY );
|
||||
|
||||
@@ -120,7 +120,7 @@ public class GuiTurtle extends GuiContainer
|
||||
int slotX = slot % 4;
|
||||
int slotY = slot / 4;
|
||||
mc.getTextureManager().bindTexture( advanced ? BACKGROUND_ADVANCED : BACKGROUND_NORMAL );
|
||||
drawTexturedModalRect( guiLeft + m_container.m_turtleInvStartX - 2 + slotX * 18, guiTop + m_container.m_playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24 );
|
||||
drawTexturedModalRect( guiLeft + m_container.turtleInvStartX - 2 + slotX * 18, guiTop + m_container.playerInvStartY - 2 + slotY * 18, 0, 217, 24, 24 );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,13 +29,13 @@ import net.minecraftforge.fml.relauncher.Side;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
|
||||
public final class RenderOverlayCable
|
||||
public final class CableHighlightRenderer
|
||||
{
|
||||
private static final float EXPAND = 0.002f;
|
||||
private static final double MIN = CableBounds.MIN - EXPAND;
|
||||
private static final double MAX = CableBounds.MAX + EXPAND;
|
||||
|
||||
private RenderOverlayCable()
|
||||
private CableHighlightRenderer()
|
||||
{
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import net.minecraft.util.math.MathHelper;
|
||||
public abstract class ItemMapLikeRenderer
|
||||
{
|
||||
/**
|
||||
* The main rendering method for the item
|
||||
* The main rendering method for the item.
|
||||
*
|
||||
* @param stack The stack to render
|
||||
* @see ItemRenderer#renderMapFirstPerson(ItemStack)
|
||||
@@ -87,7 +87,7 @@ public abstract class ItemMapLikeRenderer
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an item in the middle of the screen
|
||||
* Render an item in the middle of the screen.
|
||||
*
|
||||
* @param pitch The pitch of the player
|
||||
* @param equipProgress The equip progress of this item
|
||||
|
||||
@@ -12,32 +12,35 @@ import dan200.computercraft.client.gui.FixedWidthFontRenderer;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
import dan200.computercraft.core.terminal.TextBuffer;
|
||||
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 dan200.computercraft.shared.util.Palette;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.BufferBuilder;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.renderer.RenderItem;
|
||||
import net.minecraft.client.renderer.block.model.IBakedModel;
|
||||
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.client.renderer.texture.TextureMap;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraftforge.client.ForgeHooksClient;
|
||||
import net.minecraftforge.client.event.RenderSpecificHandEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
|
||||
import net.minecraftforge.fml.relauncher.Side;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_HEIGHT;
|
||||
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.FONT_WIDTH;
|
||||
import static dan200.computercraft.client.gui.FixedWidthFontRenderer.*;
|
||||
import static dan200.computercraft.client.gui.GuiComputer.*;
|
||||
|
||||
/**
|
||||
* Emulates map rendering for pocket computers
|
||||
* Emulates map rendering for pocket computers.
|
||||
*/
|
||||
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
|
||||
public final class ItemPocketRenderer extends ItemMapLikeRenderer
|
||||
{
|
||||
private static final int MARGIN = 2;
|
||||
private static final int FRAME = 12;
|
||||
private static final int LIGHT_HEIGHT = 8;
|
||||
|
||||
private static final ItemPocketRenderer INSTANCE = new ItemPocketRenderer();
|
||||
|
||||
private ItemPocketRenderer()
|
||||
@@ -57,115 +60,194 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
|
||||
@Override
|
||||
protected void renderItem( ItemStack stack )
|
||||
{
|
||||
ClientComputer computer = ItemPocketComputer.createClientComputer( stack );
|
||||
Terminal terminal = computer == null ? null : computer.getTerminal();
|
||||
|
||||
int termWidth, termHeight;
|
||||
if( terminal == null )
|
||||
{
|
||||
termWidth = ComputerCraft.terminalWidth_pocketComputer;
|
||||
termHeight = ComputerCraft.terminalHeight_pocketComputer;
|
||||
}
|
||||
else
|
||||
{
|
||||
termWidth = terminal.getWidth();
|
||||
termHeight = terminal.getHeight();
|
||||
}
|
||||
|
||||
int width = termWidth * FONT_WIDTH + MARGIN * 2;
|
||||
int height = termHeight * FONT_HEIGHT + MARGIN * 2;
|
||||
|
||||
// Setup various transformations. Note that these are partially adapted from the corresponding method
|
||||
// in ItemRenderer
|
||||
GlStateManager.pushMatrix();
|
||||
|
||||
GlStateManager.disableLighting();
|
||||
GlStateManager.disableDepth();
|
||||
|
||||
GlStateManager.rotate( 180f, 0f, 1f, 0f );
|
||||
GlStateManager.rotate( 180f, 0f, 0f, 1f );
|
||||
GlStateManager.scale( 0.5, 0.5, 0.5 );
|
||||
|
||||
ClientComputer computer = ItemPocketComputer.createClientComputer( stack );
|
||||
double scale = 0.75 / Math.max( width + FRAME * 2, height + FRAME * 2 + LIGHT_HEIGHT );
|
||||
GlStateManager.scale( scale, scale, 0 );
|
||||
GlStateManager.translate( -0.5 * width, -0.5 * height, 0 );
|
||||
|
||||
// Render the main frame
|
||||
ComputerFamily family = ComputerCraft.Items.pocketComputer.getFamily( stack );
|
||||
int frameColour = ComputerCraft.Items.pocketComputer.getColour( stack );
|
||||
renderFrame( family, frameColour, width, height );
|
||||
|
||||
// Render the light
|
||||
int lightColour = ItemPocketComputer.getLightState( stack );
|
||||
if( lightColour == -1 ) lightColour = Colour.Black.getHex();
|
||||
renderLight( lightColour, width, height );
|
||||
|
||||
if( computer != null && terminal != null )
|
||||
{
|
||||
// First render the background item. We use the item's model rather than a direct texture as this ensures
|
||||
// we display the pocket light and other such decorations.
|
||||
GlStateManager.pushMatrix();
|
||||
// If we've a computer and terminal then attempt to render it.
|
||||
renderTerminal( terminal, !computer.isColour(), width, height );
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise render a plain background
|
||||
Minecraft.getMinecraft().getTextureManager().bindTexture( BACKGROUND );
|
||||
|
||||
GlStateManager.scale( 1.0f, -1.0f, 1.0f );
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder buffer = tessellator.getBuffer();
|
||||
|
||||
Minecraft minecraft = Minecraft.getMinecraft();
|
||||
TextureManager textureManager = minecraft.getTextureManager();
|
||||
RenderItem renderItem = minecraft.getRenderItem();
|
||||
|
||||
// Copy of RenderItem#renderItemModelIntoGUI but without the translation or scaling
|
||||
textureManager.bindTexture( TextureMap.LOCATION_BLOCKS_TEXTURE );
|
||||
textureManager.getTexture( TextureMap.LOCATION_BLOCKS_TEXTURE ).setBlurMipmap( false, false );
|
||||
|
||||
GlStateManager.enableRescaleNormal();
|
||||
GlStateManager.enableAlpha();
|
||||
GlStateManager.alphaFunc( GL11.GL_GREATER, 0.1F );
|
||||
GlStateManager.enableBlend();
|
||||
GlStateManager.blendFunc( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA );
|
||||
GlStateManager.color( 1.0F, 1.0F, 1.0F, 1.0F );
|
||||
|
||||
IBakedModel baked = renderItem.getItemModelWithOverrides( stack, null, null );
|
||||
baked = ForgeHooksClient.handleCameraTransforms( baked, ItemCameraTransforms.TransformType.GUI, false );
|
||||
renderItem.renderItem( stack, baked );
|
||||
|
||||
GlStateManager.disableAlpha();
|
||||
GlStateManager.disableRescaleNormal();
|
||||
|
||||
GlStateManager.popMatrix();
|
||||
Colour black = Colour.Black;
|
||||
buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION );
|
||||
renderTexture( buffer, 0, 0, 0, 0, width, height, black.getR(), black.getG(), black.getB() );
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
// If we've a computer and terminal then attempt to render it.
|
||||
if( computer != null )
|
||||
GlStateManager.enableDepth();
|
||||
GlStateManager.enableLighting();
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
|
||||
private static void renderFrame( ComputerFamily family, int colour, int width, int height )
|
||||
{
|
||||
|
||||
Minecraft.getMinecraft().getTextureManager().bindTexture( colour != -1
|
||||
? BACKGROUND_COLOUR
|
||||
: family == ComputerFamily.Normal ? BACKGROUND_NORMAL : BACKGROUND_ADVANCED
|
||||
);
|
||||
|
||||
float r = ((colour >>> 16) & 0xFF) / 255.0f;
|
||||
float g = ((colour >>> 8) & 0xFF) / 255.0f;
|
||||
float b = (colour & 0xFF) / 255.0f;
|
||||
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder buffer = tessellator.getBuffer();
|
||||
buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR );
|
||||
|
||||
// Top left, middle, right
|
||||
renderTexture( buffer, -FRAME, -FRAME, 12, 28, FRAME, FRAME, r, g, b );
|
||||
renderTexture( buffer, 0, -FRAME, 0, 0, width, FRAME, r, g, b );
|
||||
renderTexture( buffer, width, -FRAME, 24, 28, FRAME, FRAME, r, g, b );
|
||||
|
||||
// Left and bright border
|
||||
renderTexture( buffer, -FRAME, 0, 0, 28, FRAME, height, r, g, b );
|
||||
renderTexture( buffer, width, 0, 36, 28, FRAME, height, r, g, b );
|
||||
|
||||
// Bottom left, middle, right. We do this in three portions: the top inner corners, an extended region for
|
||||
// lights, and then the bottom outer corners.
|
||||
renderTexture( buffer, -FRAME, height, 12, 40, FRAME, FRAME / 2, r, g, b );
|
||||
renderTexture( buffer, 0, height, 0, 12, width, FRAME / 2, r, g, b );
|
||||
renderTexture( buffer, width, height, 24, 40, FRAME, FRAME / 2, r, g, b );
|
||||
|
||||
renderTexture( buffer, -FRAME, height + FRAME / 2, 12, 44, FRAME, LIGHT_HEIGHT, FRAME, 4, r, g, b );
|
||||
renderTexture( buffer, 0, height + FRAME / 2, 0, 16, width, LIGHT_HEIGHT, FRAME, 4, r, g, b );
|
||||
renderTexture( buffer, width, height + FRAME / 2, 24, 44, FRAME, LIGHT_HEIGHT, FRAME, 4, r, g, b );
|
||||
|
||||
renderTexture( buffer, -FRAME, height + LIGHT_HEIGHT + FRAME / 2, 12, 40 + FRAME / 2, FRAME, FRAME / 2, r, g, b );
|
||||
renderTexture( buffer, 0, height + LIGHT_HEIGHT + FRAME / 2, 0, 12 + FRAME / 2, width, FRAME / 2, r, g, b );
|
||||
renderTexture( buffer, width, height + LIGHT_HEIGHT + FRAME / 2, 24, 40 + FRAME / 2, FRAME, FRAME / 2, r, g, b );
|
||||
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
private static void renderLight( int colour, int width, int height )
|
||||
{
|
||||
GlStateManager.enableBlend();
|
||||
GlStateManager.disableTexture2D();
|
||||
|
||||
float r = ((colour >>> 16) & 0xFF) / 255.0f;
|
||||
float g = ((colour >>> 8) & 0xFF) / 255.0f;
|
||||
float b = (colour & 0xFF) / 255.0f;
|
||||
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder buffer = tessellator.getBuffer();
|
||||
buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR );
|
||||
buffer.pos( width - LIGHT_HEIGHT * 2, height + LIGHT_HEIGHT + FRAME / 2.0f, 0.0D ).color( r, g, b, 1.0f ).endVertex();
|
||||
buffer.pos( width, height + LIGHT_HEIGHT + FRAME / 2.0f, 0.0D ).color( r, g, b, 1.0f ).endVertex();
|
||||
buffer.pos( width, height + FRAME / 2.0f, 0.0D ).color( r, g, b, 1.0f ).endVertex();
|
||||
buffer.pos( width - LIGHT_HEIGHT * 2, height + FRAME / 2.0f, 0.0D ).color( r, g, b, 1.0f ).endVertex();
|
||||
|
||||
tessellator.draw();
|
||||
GlStateManager.enableTexture2D();
|
||||
}
|
||||
|
||||
private static void renderTerminal( Terminal terminal, boolean greyscale, int width, int height )
|
||||
{
|
||||
synchronized( terminal )
|
||||
{
|
||||
Terminal terminal = computer.getTerminal();
|
||||
if( terminal != null )
|
||||
int termWidth = terminal.getWidth();
|
||||
int termHeight = terminal.getHeight();
|
||||
|
||||
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
|
||||
Palette palette = terminal.getPalette();
|
||||
|
||||
// Render top/bottom borders
|
||||
TextBuffer emptyLine = new TextBuffer( ' ', termWidth );
|
||||
fontRenderer.drawString(
|
||||
emptyLine, MARGIN, 0,
|
||||
terminal.getTextColourLine( 0 ), terminal.getBackgroundColourLine( 0 ), MARGIN, MARGIN, greyscale, palette
|
||||
);
|
||||
fontRenderer.drawString(
|
||||
emptyLine, MARGIN, 2 * MARGIN + (termHeight - 1) * FixedWidthFontRenderer.FONT_HEIGHT,
|
||||
terminal.getTextColourLine( termHeight - 1 ), terminal.getBackgroundColourLine( termHeight - 1 ), MARGIN, MARGIN, greyscale, palette
|
||||
);
|
||||
|
||||
// Render the actual text
|
||||
for( int line = 0; line < termWidth; line++ )
|
||||
{
|
||||
synchronized( terminal )
|
||||
{
|
||||
GlStateManager.pushMatrix();
|
||||
GlStateManager.disableDepth();
|
||||
TextBuffer text = terminal.getLine( line );
|
||||
TextBuffer colour = terminal.getTextColourLine( line );
|
||||
TextBuffer backgroundColour = terminal.getBackgroundColourLine( line );
|
||||
fontRenderer.drawString(
|
||||
text, MARGIN, MARGIN + line * FONT_HEIGHT,
|
||||
colour, backgroundColour, MARGIN, MARGIN, greyscale, palette
|
||||
);
|
||||
}
|
||||
|
||||
// Reset the position to be at the top left corner of the pocket computer
|
||||
// Note we translate towards the screen slightly too.
|
||||
GlStateManager.translate( -8 / 16.0, -8 / 16.0, 0.5 / 16.0 );
|
||||
// Translate to the top left of the screen.
|
||||
GlStateManager.translate( 4 / 16.0, 3 / 16.0, 0 );
|
||||
|
||||
// Work out the scaling required to resize the terminal in order to fit on the computer
|
||||
final int margin = 2;
|
||||
int tw = terminal.getWidth();
|
||||
int th = terminal.getHeight();
|
||||
int width = tw * FONT_WIDTH + margin * 2;
|
||||
int height = th * FONT_HEIGHT + margin * 2;
|
||||
int max = Math.max( height, width );
|
||||
|
||||
// The grid is 8 * 8 wide, so we start with a base of 1/2 (8 / 16).
|
||||
double scale = 1.0 / 2.0 / max;
|
||||
GlStateManager.scale( scale, scale, scale );
|
||||
|
||||
// The margin/start positions are determined in order for the terminal to be centred.
|
||||
int startX = (max - width) / 2 + margin;
|
||||
int startY = (max - height) / 2 + margin;
|
||||
|
||||
FixedWidthFontRenderer fontRenderer = FixedWidthFontRenderer.instance();
|
||||
boolean greyscale = !computer.isColour();
|
||||
Palette palette = terminal.getPalette();
|
||||
|
||||
// Render the actual text
|
||||
for( int line = 0; line < th; line++ )
|
||||
{
|
||||
TextBuffer text = terminal.getLine( line );
|
||||
TextBuffer colour = terminal.getTextColourLine( line );
|
||||
TextBuffer backgroundColour = terminal.getBackgroundColourLine( line );
|
||||
fontRenderer.drawString(
|
||||
text, startX, startY + line * FONT_HEIGHT,
|
||||
colour, backgroundColour, margin, margin, greyscale, palette
|
||||
);
|
||||
}
|
||||
|
||||
// And render the cursor;
|
||||
int tx = terminal.getCursorX(), ty = terminal.getCursorY();
|
||||
if( terminal.getCursorBlink() && FrameInfo.getGlobalCursorBlink() &&
|
||||
tx >= 0 && ty >= 0 && tx < tw && ty < th )
|
||||
{
|
||||
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
|
||||
fontRenderer.drawString(
|
||||
new TextBuffer( '_', 1 ), startX + FONT_WIDTH * tx, startY + FONT_HEIGHT * ty,
|
||||
cursorColour, null, 0, 0, greyscale, palette
|
||||
);
|
||||
}
|
||||
|
||||
GlStateManager.enableDepth();
|
||||
GlStateManager.popMatrix();
|
||||
}
|
||||
// And render the cursor;
|
||||
int tx = terminal.getCursorX(), ty = terminal.getCursorY();
|
||||
if( terminal.getCursorBlink() && FrameInfo.getGlobalCursorBlink() &&
|
||||
tx >= 0 && ty >= 0 && tx < termWidth && ty < termHeight )
|
||||
{
|
||||
TextBuffer cursorColour = new TextBuffer( "0123456789abcdef".charAt( terminal.getTextColour() ), 1 );
|
||||
fontRenderer.drawString(
|
||||
new TextBuffer( '_', 1 ), MARGIN + FONT_WIDTH * tx, MARGIN + FONT_HEIGHT * ty,
|
||||
cursorColour, null, 0, 0, greyscale, palette
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GlStateManager.enableLighting();
|
||||
private static void renderTexture( BufferBuilder builder, int x, int y, int textureX, int textureY, int width, int height, float r, float g, float b )
|
||||
{
|
||||
renderTexture( builder, x, y, textureX, textureY, width, height, width, height, r, g, b );
|
||||
}
|
||||
|
||||
private static void renderTexture( BufferBuilder builder, int x, int y, int textureX, int textureY, int width, int height, int textureWidth, int textureHeight, float r, float g, float b )
|
||||
{
|
||||
float scale = 1 / 255.0f;
|
||||
builder.pos( x, y + height, 0 ).tex( textureX * scale, (textureY + textureHeight) * scale ).color( r, g, b, 1.0f ).endVertex();
|
||||
builder.pos( x + width, y + height, 0 ).tex( (textureX + textureWidth) * scale, (textureY + textureHeight) * scale ).color( r, g, b, 1.0f ).endVertex();
|
||||
builder.pos( x + width, y, 0 ).tex( (textureX + textureWidth) * scale, textureY * scale ).color( r, g, b, 1.0f ).endVertex();
|
||||
builder.pos( x, y, 0 ).tex( textureX * scale, textureY * scale ).color( r, g, b, 1.0f ).endVertex();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ import static dan200.computercraft.shared.media.items.ItemPrintout.LINES_PER_PAG
|
||||
import static dan200.computercraft.shared.media.items.ItemPrintout.LINE_MAX_LENGTH;
|
||||
|
||||
/**
|
||||
* Emulates map and item-frame rendering for printouts
|
||||
* Emulates map and item-frame rendering for printouts.
|
||||
*/
|
||||
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
|
||||
public final class ItemPrintoutRenderer extends ItemMapLikeRenderer
|
||||
|
||||
@@ -94,7 +94,7 @@ public final class ModelTransformer
|
||||
private final Point3f[] before = new Point3f[4];
|
||||
private final Point3f[] after = new Point3f[4];
|
||||
|
||||
public NormalAwareTransformer( IVertexConsumer parent, Matrix4f positionMatrix, Matrix4f normalMatrix )
|
||||
NormalAwareTransformer( IVertexConsumer parent, Matrix4f positionMatrix, Matrix4f normalMatrix )
|
||||
{
|
||||
super( parent );
|
||||
this.positionMatrix = positionMatrix;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.client.render;
|
||||
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.shared.peripheral.monitor.TileMonitor;
|
||||
import net.minecraft.client.renderer.BufferBuilder;
|
||||
import net.minecraft.client.renderer.GlStateManager;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.EnumFacing;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.RayTraceResult;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
|
||||
import net.minecraftforge.fml.relauncher.Side;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.EnumSet;
|
||||
|
||||
import static net.minecraft.util.EnumFacing.*;
|
||||
|
||||
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Side.CLIENT )
|
||||
public final class MonitorHighlightRenderer
|
||||
{
|
||||
private static final float EXPAND = 0.002f;
|
||||
|
||||
private MonitorHighlightRenderer()
|
||||
{
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public static void drawHighlight( DrawBlockHighlightEvent event )
|
||||
{
|
||||
if( event.getTarget().typeOfHit != RayTraceResult.Type.BLOCK || event.getPlayer().isSneaking() ) return;
|
||||
|
||||
World world = event.getPlayer().getEntityWorld();
|
||||
BlockPos pos = event.getTarget().getBlockPos();
|
||||
|
||||
if( world.getBlockState( pos ).getBlock() != ComputerCraft.Blocks.peripheral ) return;
|
||||
|
||||
TileEntity tile = world.getTileEntity( pos );
|
||||
if( !(tile instanceof TileMonitor) ) return;
|
||||
|
||||
TileMonitor monitor = (TileMonitor) tile;
|
||||
event.setCanceled( true );
|
||||
|
||||
// Determine which sides are part of the external faces of the monitor, and so which need to be rendered.
|
||||
EnumSet<EnumFacing> faces = EnumSet.allOf( EnumFacing.class );
|
||||
EnumFacing front = monitor.getFront();
|
||||
faces.remove( front );
|
||||
if( monitor.getXIndex() != 0 ) faces.remove( monitor.getRight().getOpposite() );
|
||||
if( monitor.getXIndex() != monitor.getWidth() - 1 ) faces.remove( monitor.getRight() );
|
||||
if( monitor.getYIndex() != 0 ) faces.remove( monitor.getDown().getOpposite() );
|
||||
if( monitor.getYIndex() != monitor.getHeight() - 1 ) faces.remove( monitor.getDown() );
|
||||
|
||||
GlStateManager.enableBlend();
|
||||
GlStateManager.tryBlendFuncSeparate( GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO );
|
||||
GL11.glLineWidth( 2.0F );
|
||||
GlStateManager.disableTexture2D();
|
||||
GlStateManager.depthMask( false );
|
||||
GlStateManager.pushMatrix();
|
||||
|
||||
EntityPlayer player = event.getPlayer();
|
||||
double x = player.lastTickPosX + (player.posX - player.lastTickPosX) * event.getPartialTicks();
|
||||
double y = player.lastTickPosY + (player.posY - player.lastTickPosY) * event.getPartialTicks();
|
||||
double z = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * event.getPartialTicks();
|
||||
|
||||
GlStateManager.translate( -x + pos.getX(), -y + pos.getY(), -z + pos.getZ() );
|
||||
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder buffer = tessellator.getBuffer();
|
||||
buffer.begin( GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR );
|
||||
|
||||
// I wish I could think of a better way to do this
|
||||
if( faces.contains( NORTH ) || faces.contains( WEST ) ) line( buffer, 0, 0, 0, UP );
|
||||
if( faces.contains( SOUTH ) || faces.contains( WEST ) ) line( buffer, 0, 0, 1, UP );
|
||||
if( faces.contains( NORTH ) || faces.contains( EAST ) ) line( buffer, 1, 0, 0, UP );
|
||||
if( faces.contains( SOUTH ) || faces.contains( EAST ) ) line( buffer, 1, 0, 1, UP );
|
||||
if( faces.contains( NORTH ) || faces.contains( DOWN ) ) line( buffer, 0, 0, 0, EAST );
|
||||
if( faces.contains( SOUTH ) || faces.contains( DOWN ) ) line( buffer, 0, 0, 1, EAST );
|
||||
if( faces.contains( NORTH ) || faces.contains( UP ) ) line( buffer, 0, 1, 0, EAST );
|
||||
if( faces.contains( SOUTH ) || faces.contains( UP ) ) line( buffer, 0, 1, 1, EAST );
|
||||
if( faces.contains( WEST ) || faces.contains( DOWN ) ) line( buffer, 0, 0, 0, SOUTH );
|
||||
if( faces.contains( EAST ) || faces.contains( DOWN ) ) line( buffer, 1, 0, 0, SOUTH );
|
||||
if( faces.contains( WEST ) || faces.contains( UP ) ) line( buffer, 0, 1, 0, SOUTH );
|
||||
if( faces.contains( EAST ) || faces.contains( UP ) ) line( buffer, 1, 1, 0, SOUTH );
|
||||
|
||||
tessellator.draw();
|
||||
|
||||
GlStateManager.popMatrix();
|
||||
GlStateManager.depthMask( true );
|
||||
GlStateManager.enableTexture2D();
|
||||
GlStateManager.disableBlend();
|
||||
}
|
||||
|
||||
private static void line( BufferBuilder buffer, int x, int y, int z, EnumFacing direction )
|
||||
{
|
||||
double minX = x == 0 ? -EXPAND : 1 + EXPAND;
|
||||
double minY = y == 0 ? -EXPAND : 1 + EXPAND;
|
||||
double minZ = z == 0 ? -EXPAND : 1 + EXPAND;
|
||||
|
||||
buffer.pos( minX, minY, minZ ).color( 0, 0, 0, 0.4f ).endVertex();
|
||||
buffer.pos(
|
||||
minX + direction.getXOffset() * (1 + EXPAND * 2),
|
||||
minY + direction.getYOffset() * (1 + EXPAND * 2),
|
||||
minZ + direction.getZOffset() * (1 + EXPAND * 2)
|
||||
).color( 0, 0, 0, 0.4f ).endVertex();
|
||||
}
|
||||
}
|
||||
@@ -28,32 +28,32 @@ public final class PrintoutRenderer
|
||||
private static final double BG_SIZE = 256.0;
|
||||
|
||||
/**
|
||||
* Width of a page
|
||||
* Width of a page.
|
||||
*/
|
||||
public static final int X_SIZE = 172;
|
||||
|
||||
/**
|
||||
* Height of a page
|
||||
* Height of a page.
|
||||
*/
|
||||
public static final int Y_SIZE = 209;
|
||||
|
||||
/**
|
||||
* Padding between the left and right of a page and the text
|
||||
* Padding between the left and right of a page and the text.
|
||||
*/
|
||||
public static final int X_TEXT_MARGIN = 13;
|
||||
|
||||
/**
|
||||
* Padding between the top and bottom of a page and the text
|
||||
* Padding between the top and bottom of a page and the text.
|
||||
*/
|
||||
public static final int Y_TEXT_MARGIN = 11;
|
||||
|
||||
/**
|
||||
* Width of the extra page texture
|
||||
* Width of the extra page texture.
|
||||
*/
|
||||
private static final int X_FOLD_SIZE = 12;
|
||||
|
||||
/**
|
||||
* Size of the leather cover
|
||||
* Size of the leather cover.
|
||||
*/
|
||||
public static final int COVER_SIZE = 12;
|
||||
|
||||
|
||||
@@ -97,6 +97,8 @@ public class TileEntityCableRenderer extends TileEntitySpecialRenderer<TileCable
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the state for rendering block-breaking progress.
|
||||
*
|
||||
* @see RenderGlobal#preRenderDamagedBlocks()
|
||||
*/
|
||||
private void preRenderDamagedBlocks()
|
||||
@@ -115,6 +117,8 @@ public class TileEntityCableRenderer extends TileEntitySpecialRenderer<TileCable
|
||||
}
|
||||
|
||||
/**
|
||||
* Tear down the state for rendering block-breaking progress.
|
||||
*
|
||||
* @see RenderGlobal#postRenderDamagedBlocks()
|
||||
*/
|
||||
private void postRenderDamagedBlocks()
|
||||
|
||||
@@ -154,7 +154,7 @@ public class AddressPredicate
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the given address matches a series of patterns
|
||||
* Determine whether the given address matches a series of patterns.
|
||||
*
|
||||
* @param address The address to check.
|
||||
* @return Whether it matches any of these patterns.
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import dan200.computercraft.api.lua.ILuaAPIFactory;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class ApiFactories
|
||||
{
|
||||
@@ -25,7 +25,7 @@ public final class ApiFactories
|
||||
|
||||
public static void register( @Nonnull ILuaAPIFactory factory )
|
||||
{
|
||||
Preconditions.checkNotNull( factory, "provider cannot be null" );
|
||||
Objects.requireNonNull( factory, "provider cannot be null" );
|
||||
factories.add( factory );
|
||||
}
|
||||
|
||||
|
||||
@@ -13,256 +13,106 @@ import javax.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Various helpers for arguments
|
||||
* A stub for any mods which depended on this version of the argument helper.
|
||||
*
|
||||
* @deprecated Use {@link dan200.computercraft.api.lua.ArgumentHelper}.
|
||||
*/
|
||||
@Deprecated
|
||||
public final class ArgumentHelper
|
||||
{
|
||||
private ArgumentHelper()
|
||||
{
|
||||
throw new IllegalStateException( "Cannot instantiate singleton " + getClass().getName() );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static String getType( @Nullable Object type )
|
||||
{
|
||||
if( type == null ) return "nil";
|
||||
if( type instanceof String ) return "string";
|
||||
if( type instanceof Boolean ) return "boolean";
|
||||
if( type instanceof Number ) return "number";
|
||||
if( type instanceof Map ) return "table";
|
||||
|
||||
Class<?> klass = type.getClass();
|
||||
if( klass.isArray() )
|
||||
{
|
||||
StringBuilder name = new StringBuilder();
|
||||
while( klass.isArray() )
|
||||
{
|
||||
name.append( "[]" );
|
||||
klass = klass.getComponentType();
|
||||
}
|
||||
name.insert( 0, klass.getName() );
|
||||
return name.toString();
|
||||
}
|
||||
else
|
||||
{
|
||||
return klass.getName();
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getType( type );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static LuaException badArgument( int index, @Nonnull String expected, @Nullable Object actual )
|
||||
{
|
||||
return badArgument( index, expected, getType( actual ) );
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.badArgumentOf( index, expected, actual );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static LuaException badArgument( int index, @Nonnull String expected, @Nonnull String actual )
|
||||
{
|
||||
return new LuaException( "bad argument #" + (index + 1) + " (" + expected + " expected, got " + actual + ")" );
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.badArgument( index, expected, actual );
|
||||
}
|
||||
|
||||
public static double getNumber( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "number", "nil" );
|
||||
Object value = args[index];
|
||||
if( value instanceof Number )
|
||||
{
|
||||
return ((Number) value).doubleValue();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "number", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getDouble( args, index );
|
||||
}
|
||||
|
||||
public static int getInt( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
return (int) getLong( args, index );
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getInt( args, index );
|
||||
}
|
||||
|
||||
public static long getLong( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "number", "nil" );
|
||||
Object value = args[index];
|
||||
if( value instanceof Number )
|
||||
{
|
||||
return checkReal( index, (Number) value ).longValue();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "number", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getLong( args, index );
|
||||
}
|
||||
|
||||
public static double getReal( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
return checkReal( index, getNumber( args, index ) );
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getFiniteDouble( args, index );
|
||||
}
|
||||
|
||||
public static boolean getBoolean( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "boolean", "nil" );
|
||||
Object value = args[index];
|
||||
if( value instanceof Boolean )
|
||||
{
|
||||
return (Boolean) value;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "boolean", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getBoolean( args, index );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static String getString( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "string", "nil" );
|
||||
Object value = args[index];
|
||||
if( value instanceof String )
|
||||
{
|
||||
return (String) value;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "string", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.getString( args, index );
|
||||
}
|
||||
|
||||
@SuppressWarnings( "unchecked" )
|
||||
@Nonnull
|
||||
@SuppressWarnings( "unchecked" )
|
||||
public static Map<Object, Object> getTable( @Nonnull Object[] args, int index ) throws LuaException
|
||||
{
|
||||
if( index >= args.length ) throw badArgument( index, "table", "nil" );
|
||||
Object value = args[index];
|
||||
if( value instanceof Map )
|
||||
{
|
||||
return (Map<Object, Object>) value;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "table", value );
|
||||
}
|
||||
return (Map<Object, Object>) dan200.computercraft.api.lua.ArgumentHelper.getTable( args, index );
|
||||
}
|
||||
|
||||
public static double optNumber( @Nonnull Object[] args, int index, double def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null )
|
||||
{
|
||||
return def;
|
||||
}
|
||||
else if( value instanceof Number )
|
||||
{
|
||||
return ((Number) value).doubleValue();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "number", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.optDouble( args, index, def );
|
||||
}
|
||||
|
||||
public static int optInt( @Nonnull Object[] args, int index, int def ) throws LuaException
|
||||
{
|
||||
return (int) optLong( args, index, def );
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.optInt( args, index, def );
|
||||
}
|
||||
|
||||
public static long optLong( @Nonnull Object[] args, int index, long def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null )
|
||||
{
|
||||
return def;
|
||||
}
|
||||
else if( value instanceof Number )
|
||||
{
|
||||
return checkReal( index, (Number) value ).longValue();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "number", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.optLong( args, index, def );
|
||||
}
|
||||
|
||||
public static double optReal( @Nonnull Object[] args, int index, double def ) throws LuaException
|
||||
{
|
||||
return checkReal( index, optNumber( args, index, def ) );
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.optFiniteDouble( args, index, def );
|
||||
}
|
||||
|
||||
public static boolean optBoolean( @Nonnull Object[] args, int index, boolean def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null )
|
||||
{
|
||||
return def;
|
||||
}
|
||||
else if( value instanceof Boolean )
|
||||
{
|
||||
return (Boolean) value;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "boolean", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.optBoolean( args, index, def );
|
||||
}
|
||||
|
||||
public static String optString( @Nonnull Object[] args, int index, String def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null )
|
||||
{
|
||||
return def;
|
||||
}
|
||||
else if( value instanceof String )
|
||||
{
|
||||
return (String) value;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "string", value );
|
||||
}
|
||||
return dan200.computercraft.api.lua.ArgumentHelper.optString( args, index, def );
|
||||
}
|
||||
|
||||
@SuppressWarnings( "unchecked" )
|
||||
public static Map<Object, Object> optTable( @Nonnull Object[] args, int index, Map<Object, Object> def ) throws LuaException
|
||||
{
|
||||
Object value = index < args.length ? args[index] : null;
|
||||
if( value == null )
|
||||
{
|
||||
return def;
|
||||
}
|
||||
else if( value instanceof Map )
|
||||
{
|
||||
return (Map<Object, Object>) value;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw badArgument( index, "table", value );
|
||||
}
|
||||
}
|
||||
|
||||
private static Number checkReal( int index, Number value ) throws LuaException
|
||||
{
|
||||
checkReal( index, value.doubleValue() );
|
||||
return value;
|
||||
}
|
||||
|
||||
private static double checkReal( int index, double value ) throws LuaException
|
||||
{
|
||||
if( Double.isNaN( value ) )
|
||||
{
|
||||
throw badArgument( index, "number", "nan" );
|
||||
}
|
||||
else if( value == Double.POSITIVE_INFINITY )
|
||||
{
|
||||
throw badArgument( index, "number", "inf" );
|
||||
}
|
||||
else if( value == Double.NEGATIVE_INFINITY )
|
||||
{
|
||||
throw badArgument( index, "number", "-inf" );
|
||||
}
|
||||
else
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return (Map<Object, Object>) dan200.computercraft.api.lua.ArgumentHelper.optTable( args, index, def );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
import dan200.computercraft.api.peripheral.IComputerAccess;
|
||||
@@ -121,7 +120,7 @@ public abstract class ComputerAccess implements IComputerAccess
|
||||
@Override
|
||||
public void queueEvent( @Nonnull final String event, final Object[] arguments )
|
||||
{
|
||||
Preconditions.checkNotNull( event, "event cannot be null" );
|
||||
Objects.requireNonNull( event, "event cannot be null" );
|
||||
m_environment.queueEvent( event, arguments );
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.getString;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.getString;
|
||||
|
||||
public class FSAPI implements ILuaAPI
|
||||
{
|
||||
@@ -43,9 +43,7 @@ public class FSAPI implements ILuaAPI
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"fs"
|
||||
};
|
||||
return new String[] { "fs" };
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -23,7 +23,7 @@ import java.util.Collections;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.*;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.*;
|
||||
import static dan200.computercraft.core.apis.TableHelper.*;
|
||||
|
||||
public class HTTPAPI implements ILuaAPI
|
||||
@@ -42,9 +42,7 @@ public class HTTPAPI implements ILuaAPI
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"http"
|
||||
};
|
||||
return new String[] { "http" };
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,6 +81,7 @@ public class HTTPAPI implements ILuaAPI
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings( "resource" )
|
||||
public Object[] callMethod( @Nonnull ILuaContext context, int method, @Nonnull Object[] args ) throws LuaException
|
||||
{
|
||||
switch( method )
|
||||
@@ -90,12 +89,12 @@ public class HTTPAPI implements ILuaAPI
|
||||
case 0: // request
|
||||
{
|
||||
String address, postString, requestMethod;
|
||||
Map<Object, Object> headerTable;
|
||||
Map<?, ?> headerTable;
|
||||
boolean binary, redirect;
|
||||
|
||||
if( args.length >= 1 && args[0] instanceof Map )
|
||||
{
|
||||
Map<?, ?> options = (Map) args[0];
|
||||
Map<?, ?> options = (Map<?, ?>) args[0];
|
||||
address = getStringField( options, "url" );
|
||||
postString = optStringField( options, "body", null );
|
||||
headerTable = optTableField( options, "headers", Collections.emptyMap() );
|
||||
@@ -135,7 +134,6 @@ public class HTTPAPI implements ILuaAPI
|
||||
try
|
||||
{
|
||||
URI uri = HttpRequest.checkUri( address );
|
||||
|
||||
HttpRequest request = new HttpRequest( requests, m_apiEnvironment, address, postString, headers, binary, redirect );
|
||||
|
||||
long requestBody = request.body().readableBytes() + HttpRequest.getHeaderSize( headers );
|
||||
@@ -174,7 +172,7 @@ public class HTTPAPI implements ILuaAPI
|
||||
case 2: // websocket
|
||||
{
|
||||
String address = getString( args, 0 );
|
||||
Map<Object, Object> headerTbl = optTable( args, 1, Collections.emptyMap() );
|
||||
Map<?, ?> headerTbl = optTable( args, 1, Collections.emptyMap() );
|
||||
|
||||
if( !ComputerCraft.http_websocket_enable )
|
||||
{
|
||||
|
||||
@@ -8,6 +8,7 @@ package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.api.peripheral.IWorkMonitor;
|
||||
import dan200.computercraft.core.computer.ComputerSide;
|
||||
import dan200.computercraft.core.computer.IComputerEnvironment;
|
||||
import dan200.computercraft.core.filesystem.FileSystem;
|
||||
import dan200.computercraft.core.terminal.Terminal;
|
||||
@@ -18,16 +19,10 @@ import javax.annotation.Nullable;
|
||||
|
||||
public interface IAPIEnvironment
|
||||
{
|
||||
String[] SIDE_NAMES = new String[] {
|
||||
"bottom", "top", "back", "front", "right", "left",
|
||||
};
|
||||
|
||||
int SIDE_COUNT = 6;
|
||||
|
||||
@FunctionalInterface
|
||||
interface IPeripheralChangeListener
|
||||
{
|
||||
void onPeripheralChanged( int side, @Nullable IPeripheral newPeripheral );
|
||||
void onPeripheralChanged( ComputerSide side, @Nullable IPeripheral newPeripheral );
|
||||
}
|
||||
|
||||
int getComputerID();
|
||||
@@ -49,22 +44,22 @@ public interface IAPIEnvironment
|
||||
|
||||
void queueEvent( String event, Object[] args );
|
||||
|
||||
void setOutput( int side, int output );
|
||||
void setOutput( ComputerSide side, int output );
|
||||
|
||||
int getOutput( int side );
|
||||
int getOutput( ComputerSide side );
|
||||
|
||||
int getInput( int side );
|
||||
int getInput( ComputerSide side );
|
||||
|
||||
void setBundledOutput( int side, int output );
|
||||
void setBundledOutput( ComputerSide side, int output );
|
||||
|
||||
int getBundledOutput( int side );
|
||||
int getBundledOutput( ComputerSide side );
|
||||
|
||||
int getBundledInput( int side );
|
||||
int getBundledInput( ComputerSide side );
|
||||
|
||||
void setPeripheralChangeListener( @Nullable IPeripheralChangeListener listener );
|
||||
|
||||
@Nullable
|
||||
IPeripheral getPeripheral( int side );
|
||||
IPeripheral getPeripheral( ComputerSide side );
|
||||
|
||||
String getLabel();
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ package dan200.computercraft.core.apis;
|
||||
* This exists purely to ensure binary compatibility.
|
||||
*
|
||||
* @see dan200.computercraft.api.lua.ILuaAPI
|
||||
* @deprecated Use the version in the public API. Only exists for compatibility with CCEmuX.
|
||||
*/
|
||||
@Deprecated
|
||||
public interface ILuaAPI extends dan200.computercraft.api.lua.ILuaAPI
|
||||
|
||||
281
src/main/java/dan200/computercraft/core/apis/LuaDateTime.java
Normal file
281
src/main/java/dan200/computercraft/core/apis/LuaDateTime.java
Normal file
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.format.TextStyle;
|
||||
import java.time.temporal.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.LongUnaryOperator;
|
||||
|
||||
final class LuaDateTime
|
||||
{
|
||||
private LuaDateTime()
|
||||
{
|
||||
}
|
||||
|
||||
static void format( DateTimeFormatterBuilder formatter, String format, ZoneOffset offset ) throws LuaException
|
||||
{
|
||||
for( int i = 0; i < format.length(); )
|
||||
{
|
||||
char c;
|
||||
switch( c = format.charAt( i++ ) )
|
||||
{
|
||||
case '\n':
|
||||
formatter.appendLiteral( '\n' );
|
||||
break;
|
||||
default:
|
||||
formatter.appendLiteral( c );
|
||||
break;
|
||||
case '%':
|
||||
if( i >= format.length() ) break;
|
||||
switch( c = format.charAt( i++ ) )
|
||||
{
|
||||
default:
|
||||
throw new LuaException( "bad argument #1: invalid conversion specifier '%" + c + "'" );
|
||||
|
||||
case '%':
|
||||
formatter.appendLiteral( '%' );
|
||||
break;
|
||||
case 'a':
|
||||
formatter.appendText( ChronoField.DAY_OF_WEEK, TextStyle.SHORT );
|
||||
break;
|
||||
case 'A':
|
||||
formatter.appendText( ChronoField.DAY_OF_WEEK, TextStyle.FULL );
|
||||
break;
|
||||
case 'b':
|
||||
case 'h':
|
||||
formatter.appendText( ChronoField.MONTH_OF_YEAR, TextStyle.SHORT );
|
||||
break;
|
||||
case 'B':
|
||||
formatter.appendText( ChronoField.MONTH_OF_YEAR, TextStyle.FULL );
|
||||
break;
|
||||
case 'c':
|
||||
format( formatter, "%a %b %e %H:%M:%S %Y", offset );
|
||||
break;
|
||||
case 'C':
|
||||
formatter.appendValueReduced( CENTURY, 2, 2, 0 );
|
||||
break;
|
||||
case 'd':
|
||||
formatter.appendValue( ChronoField.DAY_OF_MONTH, 2 );
|
||||
break;
|
||||
case 'D':
|
||||
case 'x':
|
||||
format( formatter, "%m/%d/%y", offset );
|
||||
break;
|
||||
case 'e':
|
||||
formatter.padNext( 2 ).appendValue( ChronoField.DAY_OF_MONTH );
|
||||
break;
|
||||
case 'F':
|
||||
format( formatter, "%Y-%m-%d", offset );
|
||||
break;
|
||||
case 'g':
|
||||
formatter.appendValueReduced( IsoFields.WEEK_BASED_YEAR, 2, 2, 0 );
|
||||
break;
|
||||
case 'G':
|
||||
formatter.appendValue( IsoFields.WEEK_BASED_YEAR );
|
||||
break;
|
||||
case 'H':
|
||||
formatter.appendValue( ChronoField.HOUR_OF_DAY, 2 );
|
||||
break;
|
||||
case 'I':
|
||||
formatter.appendValue( ChronoField.HOUR_OF_AMPM );
|
||||
break;
|
||||
case 'j':
|
||||
formatter.appendValue( ChronoField.DAY_OF_YEAR, 3 );
|
||||
break;
|
||||
case 'm':
|
||||
formatter.appendValue( ChronoField.MONTH_OF_YEAR, 2 );
|
||||
break;
|
||||
case 'M':
|
||||
formatter.appendValue( ChronoField.MINUTE_OF_HOUR, 2 );
|
||||
break;
|
||||
case 'n':
|
||||
formatter.appendLiteral( '\n' );
|
||||
break;
|
||||
case 'p':
|
||||
formatter.appendText( ChronoField.AMPM_OF_DAY );
|
||||
break;
|
||||
case 'r':
|
||||
format( formatter, "%I:%M:%S %p", offset );
|
||||
break;
|
||||
case 'R':
|
||||
format( formatter, "%H:%M", offset );
|
||||
break;
|
||||
case 'S':
|
||||
formatter.appendValue( ChronoField.SECOND_OF_MINUTE, 2 );
|
||||
break;
|
||||
case 't':
|
||||
formatter.appendLiteral( '\t' );
|
||||
break;
|
||||
case 'T':
|
||||
case 'X':
|
||||
format( formatter, "%H:%M:%S", offset );
|
||||
break;
|
||||
case 'u':
|
||||
formatter.appendValue( ChronoField.DAY_OF_WEEK );
|
||||
break;
|
||||
case 'U':
|
||||
formatter.appendValue( ChronoField.ALIGNED_WEEK_OF_YEAR, 2 );
|
||||
break;
|
||||
case 'V':
|
||||
formatter.appendValue( IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2 );
|
||||
break;
|
||||
case 'w':
|
||||
formatter.appendValue( ZERO_WEEK );
|
||||
break;
|
||||
case 'W':
|
||||
formatter.appendValue( WeekFields.ISO.weekOfYear(), 2 );
|
||||
break;
|
||||
case 'y':
|
||||
formatter.appendValueReduced( ChronoField.YEAR, 2, 2, 0 );
|
||||
break;
|
||||
case 'Y':
|
||||
formatter.appendValue( ChronoField.YEAR );
|
||||
break;
|
||||
case 'z':
|
||||
formatter.appendOffset( "+HHMM", "+0000" );
|
||||
break;
|
||||
case 'Z':
|
||||
formatter.appendChronologyId();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static long fromTable( Map<?, ?> table ) throws LuaException
|
||||
{
|
||||
int year = getField( table, "year", -1 );
|
||||
int month = getField( table, "month", -1 );
|
||||
int day = getField( table, "day", -1 );
|
||||
int hour = getField( table, "hour", 12 );
|
||||
int minute = getField( table, "min", 12 );
|
||||
int second = getField( table, "sec", 12 );
|
||||
LocalDateTime time = LocalDateTime.of( year, month, day, hour, minute, second );
|
||||
|
||||
Boolean isDst = getBoolField( table, "isdst" );
|
||||
if( isDst != null )
|
||||
{
|
||||
boolean requireDst = isDst;
|
||||
for( ZoneOffset possibleOffset : ZoneOffset.systemDefault().getRules().getValidOffsets( time ) )
|
||||
{
|
||||
Instant instant = time.toInstant( possibleOffset );
|
||||
if( possibleOffset.getRules().getDaylightSavings( instant ).isZero() == requireDst )
|
||||
{
|
||||
return instant.getEpochSecond();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ZoneOffset offset = ZoneOffset.systemDefault().getRules().getOffset( time );
|
||||
return time.toInstant( offset ).getEpochSecond();
|
||||
}
|
||||
|
||||
static Map<String, ?> toTable( TemporalAccessor date, ZoneId offset, Instant instant )
|
||||
{
|
||||
HashMap<String, Object> table = new HashMap<>( 9 );
|
||||
table.put( "year", date.getLong( ChronoField.YEAR ) );
|
||||
table.put( "month", date.getLong( ChronoField.MONTH_OF_YEAR ) );
|
||||
table.put( "day", date.getLong( ChronoField.DAY_OF_MONTH ) );
|
||||
table.put( "hour", date.getLong( ChronoField.HOUR_OF_DAY ) );
|
||||
table.put( "min", date.getLong( ChronoField.MINUTE_OF_HOUR ) );
|
||||
table.put( "sec", date.getLong( ChronoField.SECOND_OF_MINUTE ) );
|
||||
table.put( "wday", date.getLong( WeekFields.SUNDAY_START.dayOfWeek() ) );
|
||||
table.put( "yday", date.getLong( ChronoField.DAY_OF_YEAR ) );
|
||||
table.put( "isdst", offset.getRules().isDaylightSavings( instant ) );
|
||||
return table;
|
||||
}
|
||||
|
||||
private static int getField( Map<?, ?> table, String field, int def ) throws LuaException
|
||||
{
|
||||
Object value = table.get( field );
|
||||
if( value instanceof Number ) return ((Number) value).intValue();
|
||||
if( def < 0 ) throw new LuaException( "field \"" + field + "\" missing in date table" );
|
||||
return def;
|
||||
}
|
||||
|
||||
private static Boolean getBoolField( Map<?, ?> table, String field ) throws LuaException
|
||||
{
|
||||
Object value = table.get( field );
|
||||
if( value instanceof Boolean || value == null ) return (Boolean) value;
|
||||
throw new LuaException( "field \"" + field + "\" missing in date table" );
|
||||
}
|
||||
|
||||
private static final TemporalField CENTURY = map( ChronoField.YEAR, ValueRange.of( 0, 6 ), x -> (x / 100) % 100 );
|
||||
private static final TemporalField ZERO_WEEK = map( WeekFields.SUNDAY_START.dayOfWeek(), ValueRange.of( 0, 6 ), x -> x - 1 );
|
||||
|
||||
private static TemporalField map( TemporalField field, ValueRange range, LongUnaryOperator convert )
|
||||
{
|
||||
return new TemporalField()
|
||||
{
|
||||
private final ValueRange range = ValueRange.of( 0, 99 );
|
||||
|
||||
@Override
|
||||
public TemporalUnit getBaseUnit()
|
||||
{
|
||||
return field.getBaseUnit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TemporalUnit getRangeUnit()
|
||||
{
|
||||
return field.getRangeUnit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValueRange range()
|
||||
{
|
||||
return range;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDateBased()
|
||||
{
|
||||
return field.isDateBased();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTimeBased()
|
||||
{
|
||||
return field.isTimeBased();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSupportedBy( TemporalAccessor temporal )
|
||||
{
|
||||
return field.isSupportedBy( temporal );
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValueRange rangeRefinedBy( TemporalAccessor temporal )
|
||||
{
|
||||
return range;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getFrom( TemporalAccessor temporal )
|
||||
{
|
||||
return convert.applyAsLong( temporal.getLong( field ) );
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings( "unchecked" )
|
||||
public <R extends Temporal> R adjustInto( R temporal, long newValue )
|
||||
{
|
||||
return (R) temporal.with( field, newValue );
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,14 @@ import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.shared.util.StringUtil;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.util.*;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.*;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.*;
|
||||
|
||||
public class OSAPI implements ILuaAPI
|
||||
{
|
||||
@@ -31,9 +36,9 @@ public class OSAPI implements ILuaAPI
|
||||
|
||||
private static class Timer
|
||||
{
|
||||
public int m_ticksLeft;
|
||||
int m_ticksLeft;
|
||||
|
||||
public Timer( int ticksLeft )
|
||||
Timer( int ticksLeft )
|
||||
{
|
||||
m_ticksLeft = ticksLeft;
|
||||
}
|
||||
@@ -41,10 +46,10 @@ public class OSAPI implements ILuaAPI
|
||||
|
||||
private static class Alarm implements Comparable<Alarm>
|
||||
{
|
||||
public final double m_time;
|
||||
public final int m_day;
|
||||
final double m_time;
|
||||
final int m_day;
|
||||
|
||||
public Alarm( double time, int day )
|
||||
Alarm( double time, int day )
|
||||
{
|
||||
m_time = time;
|
||||
m_day = day;
|
||||
@@ -73,9 +78,7 @@ public class OSAPI implements ILuaAPI
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"os"
|
||||
};
|
||||
return new String[] { "os" };
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -184,11 +187,12 @@ public class OSAPI implements ILuaAPI
|
||||
"day",
|
||||
"cancelTimer",
|
||||
"cancelAlarm",
|
||||
"epoch"
|
||||
"epoch",
|
||||
"date",
|
||||
};
|
||||
}
|
||||
|
||||
private float getTimeForCalendar( Calendar c )
|
||||
private static float getTimeForCalendar( Calendar c )
|
||||
{
|
||||
float time = c.get( Calendar.HOUR_OF_DAY );
|
||||
time += c.get( Calendar.MINUTE ) / 60.0f;
|
||||
@@ -196,7 +200,7 @@ public class OSAPI implements ILuaAPI
|
||||
return time;
|
||||
}
|
||||
|
||||
private int getDayForCalendar( Calendar c )
|
||||
private static int getDayForCalendar( Calendar c )
|
||||
{
|
||||
GregorianCalendar g = c instanceof GregorianCalendar ? (GregorianCalendar) c : new GregorianCalendar();
|
||||
int year = c.get( Calendar.YEAR );
|
||||
@@ -209,7 +213,7 @@ public class OSAPI implements ILuaAPI
|
||||
return day;
|
||||
}
|
||||
|
||||
private long getEpochForCalendar( Calendar c )
|
||||
private static long getEpochForCalendar( Calendar c )
|
||||
{
|
||||
return c.getTime().getTime();
|
||||
}
|
||||
@@ -225,7 +229,7 @@ public class OSAPI implements ILuaAPI
|
||||
case 1:
|
||||
{
|
||||
// startTimer
|
||||
double timer = getReal( args, 0 );
|
||||
double timer = getFiniteDouble( args, 0 );
|
||||
synchronized( m_timers )
|
||||
{
|
||||
m_timers.put( m_nextTimerToken, new Timer( (int) Math.round( timer / 0.05 ) ) );
|
||||
@@ -235,7 +239,7 @@ public class OSAPI implements ILuaAPI
|
||||
case 2:
|
||||
{
|
||||
// setAlarm
|
||||
double time = getReal( args, 0 );
|
||||
double time = getFiniteDouble( args, 0 );
|
||||
if( time < 0.0 || time >= 24.0 )
|
||||
{
|
||||
throw new LuaException( "Number out of range" );
|
||||
@@ -282,6 +286,9 @@ public class OSAPI implements ILuaAPI
|
||||
case 11:
|
||||
{
|
||||
// time
|
||||
Object value = args.length > 0 ? args[0] : null;
|
||||
if( value instanceof Map ) return new Object[] { LuaDateTime.fromTable( (Map<?, ?>) value ) };
|
||||
|
||||
String param = optString( args, 0, "ingame" );
|
||||
switch( param.toLowerCase( Locale.ROOT ) )
|
||||
{
|
||||
@@ -355,9 +362,8 @@ public class OSAPI implements ILuaAPI
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case 15:
|
||||
case 15: // epoch
|
||||
{
|
||||
// epoch
|
||||
String param = optString( args, 0, "ingame" );
|
||||
switch( param.toLowerCase( Locale.ROOT ) )
|
||||
{
|
||||
@@ -377,14 +383,39 @@ public class OSAPI implements ILuaAPI
|
||||
// Get in-game epoch
|
||||
synchronized( m_alarms )
|
||||
{
|
||||
return new Object[] {
|
||||
m_day * 86400000 + (int) (m_time * 3600000.0f)
|
||||
};
|
||||
return new Object[] { m_day * 86400000 + (int) (m_time * 3600000.0f) };
|
||||
}
|
||||
default:
|
||||
throw new LuaException( "Unsupported operation" );
|
||||
}
|
||||
}
|
||||
case 16: // date
|
||||
{
|
||||
String format = optString( args, 0, "%c" );
|
||||
long time = optLong( args, 1, Instant.now().getEpochSecond() );
|
||||
|
||||
Instant instant = Instant.ofEpochSecond( time );
|
||||
ZonedDateTime date;
|
||||
ZoneOffset offset;
|
||||
if( format.startsWith( "!" ) )
|
||||
{
|
||||
offset = ZoneOffset.UTC;
|
||||
date = ZonedDateTime.ofInstant( instant, offset );
|
||||
format = format.substring( 1 );
|
||||
}
|
||||
else
|
||||
{
|
||||
ZoneId id = ZoneId.systemDefault();
|
||||
offset = id.getRules().getOffset( instant );
|
||||
date = ZonedDateTime.ofInstant( instant, id );
|
||||
}
|
||||
|
||||
if( format.equals( "*t" ) ) return new Object[] { LuaDateTime.toTable( date, offset, instant ) };
|
||||
|
||||
DateTimeFormatterBuilder formatter = new DateTimeFormatterBuilder();
|
||||
LuaDateTime.format( formatter, format, offset );
|
||||
return new Object[] { formatter.toFormatter( Locale.ROOT ).format( date ) };
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import dan200.computercraft.api.lua.ILuaAPI;
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.core.computer.ComputerSide;
|
||||
import dan200.computercraft.core.tracking.TrackingField;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
@@ -21,7 +22,7 @@ import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.getString;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.getString;
|
||||
|
||||
public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChangeListener
|
||||
{
|
||||
@@ -35,7 +36,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
private Map<String, Integer> m_methodMap;
|
||||
private boolean m_attached;
|
||||
|
||||
public PeripheralWrapper( IPeripheral peripheral, String side )
|
||||
PeripheralWrapper( IPeripheral peripheral, String side )
|
||||
{
|
||||
super( m_environment );
|
||||
m_side = side;
|
||||
@@ -245,32 +246,33 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
// IPeripheralChangeListener
|
||||
|
||||
@Override
|
||||
public void onPeripheralChanged( int side, IPeripheral newPeripheral )
|
||||
public void onPeripheralChanged( ComputerSide side, IPeripheral newPeripheral )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
if( m_peripherals[side] != null )
|
||||
int index = side.ordinal();
|
||||
if( m_peripherals[index] != null )
|
||||
{
|
||||
// Queue a detachment
|
||||
final PeripheralWrapper wrapper = m_peripherals[side];
|
||||
final PeripheralWrapper wrapper = m_peripherals[index];
|
||||
if( wrapper.isAttached() ) wrapper.detach();
|
||||
|
||||
// Queue a detachment event
|
||||
m_environment.queueEvent( "peripheral_detach", new Object[] { IAPIEnvironment.SIDE_NAMES[side] } );
|
||||
m_environment.queueEvent( "peripheral_detach", new Object[] { side.getName() } );
|
||||
}
|
||||
|
||||
// Assign the new peripheral
|
||||
m_peripherals[side] = newPeripheral == null ? null
|
||||
: new PeripheralWrapper( newPeripheral, IAPIEnvironment.SIDE_NAMES[side] );
|
||||
m_peripherals[index] = newPeripheral == null ? null
|
||||
: new PeripheralWrapper( newPeripheral, side.getName() );
|
||||
|
||||
if( m_peripherals[side] != null )
|
||||
if( m_peripherals[index] != null )
|
||||
{
|
||||
// Queue an attachment
|
||||
final PeripheralWrapper wrapper = m_peripherals[side];
|
||||
final PeripheralWrapper wrapper = m_peripherals[index];
|
||||
if( m_running && !wrapper.isAttached() ) wrapper.attach();
|
||||
|
||||
// Queue an attachment event
|
||||
m_environment.queueEvent( "peripheral", new Object[] { IAPIEnvironment.SIDE_NAMES[side] } );
|
||||
m_environment.queueEvent( "peripheral", new Object[] { side.getName() } );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,9 +282,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"peripheral"
|
||||
};
|
||||
return new String[] { "peripheral" };
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -324,7 +324,7 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
"isPresent",
|
||||
"getType",
|
||||
"getMethods",
|
||||
"call"
|
||||
"call",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -337,16 +337,13 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
{
|
||||
// isPresent
|
||||
boolean present = false;
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
ComputerSide side = ComputerSide.valueOfInsensitive( getString( args, 0 ) );
|
||||
if( side != null )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
PeripheralWrapper p = m_peripherals[side];
|
||||
if( p != null )
|
||||
{
|
||||
present = true;
|
||||
}
|
||||
PeripheralWrapper p = m_peripherals[side.ordinal()];
|
||||
if( p != null ) present = true;
|
||||
}
|
||||
}
|
||||
return new Object[] { present };
|
||||
@@ -354,21 +351,13 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
case 1:
|
||||
{
|
||||
// getType
|
||||
String type = null;
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
ComputerSide side = ComputerSide.valueOfInsensitive( getString( args, 0 ) );
|
||||
if( side != null )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
PeripheralWrapper p = m_peripherals[side];
|
||||
if( p != null )
|
||||
{
|
||||
type = p.getType();
|
||||
}
|
||||
}
|
||||
if( type != null )
|
||||
{
|
||||
return new Object[] { type };
|
||||
PeripheralWrapper p = m_peripherals[side.ordinal()];
|
||||
if( p != null ) return new Object[] { p.getType() };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -377,12 +366,12 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
{
|
||||
// getMethods
|
||||
String[] methods = null;
|
||||
int side = parseSide( args );
|
||||
if( side >= 0 )
|
||||
ComputerSide side = ComputerSide.valueOfInsensitive( getString( args, 0 ) );
|
||||
if( side != null )
|
||||
{
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
PeripheralWrapper p = m_peripherals[side];
|
||||
PeripheralWrapper p = m_peripherals[side.ordinal()];
|
||||
if( p != null )
|
||||
{
|
||||
methods = p.getMethods();
|
||||
@@ -403,16 +392,16 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
case 3:
|
||||
{
|
||||
// call
|
||||
int side = parseSide( args );
|
||||
ComputerSide side = ComputerSide.valueOfInsensitive( getString( args, 0 ) );
|
||||
String methodName = getString( args, 1 );
|
||||
Object[] methodArgs = Arrays.copyOfRange( args, 2, args.length );
|
||||
|
||||
if( side >= 0 )
|
||||
if( side != null )
|
||||
{
|
||||
PeripheralWrapper p;
|
||||
synchronized( m_peripherals )
|
||||
{
|
||||
p = m_peripherals[side];
|
||||
p = m_peripherals[side.ordinal()];
|
||||
}
|
||||
if( p != null )
|
||||
{
|
||||
@@ -425,19 +414,4 @@ public class PeripheralAPI implements ILuaAPI, IAPIEnvironment.IPeripheralChange
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Privates
|
||||
|
||||
private int parseSide( Object[] args ) throws LuaException
|
||||
{
|
||||
String side = getString( args, 0 );
|
||||
for( int n = 0; n < IAPIEnvironment.SIDE_NAMES.length; n++ )
|
||||
{
|
||||
if( side.equals( IAPIEnvironment.SIDE_NAMES[n] ) )
|
||||
{
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,12 +9,13 @@ package dan200.computercraft.core.apis;
|
||||
import dan200.computercraft.api.lua.ILuaAPI;
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.computer.ComputerSide;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.*;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.*;
|
||||
|
||||
public class RedstoneAPI implements ILuaAPI
|
||||
{
|
||||
@@ -28,9 +29,7 @@ public class RedstoneAPI implements ILuaAPI
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"rs", "redstone"
|
||||
};
|
||||
return new String[] { "rs", "redstone" };
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -64,56 +63,40 @@ public class RedstoneAPI implements ILuaAPI
|
||||
{
|
||||
// getSides
|
||||
Map<Object, Object> table = new HashMap<>();
|
||||
for( int i = 0; i < IAPIEnvironment.SIDE_NAMES.length; i++ )
|
||||
for( int i = 0; i < ComputerSide.NAMES.length; i++ )
|
||||
{
|
||||
table.put( i + 1, IAPIEnvironment.SIDE_NAMES[i] );
|
||||
table.put( i + 1, ComputerSide.NAMES[i] );
|
||||
}
|
||||
return new Object[] { table };
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
// setOutput
|
||||
int side = parseSide( args );
|
||||
ComputerSide side = parseSide( args );
|
||||
boolean output = getBoolean( args, 1 );
|
||||
m_environment.setOutput( side, output ? 15 : 0 );
|
||||
return null;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
// getOutput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getOutput( side ) > 0 };
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
// getInput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getInput( side ) > 0 };
|
||||
}
|
||||
case 2: // getOutput
|
||||
return new Object[] { m_environment.getOutput( parseSide( args ) ) > 0 };
|
||||
case 3: // getInput
|
||||
return new Object[] { m_environment.getInput( parseSide( args ) ) > 0 };
|
||||
case 4:
|
||||
{
|
||||
// setBundledOutput
|
||||
int side = parseSide( args );
|
||||
ComputerSide side = parseSide( args );
|
||||
int output = getInt( args, 1 );
|
||||
m_environment.setBundledOutput( side, output );
|
||||
return null;
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
// getBundledOutput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getBundledOutput( side ) };
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
// getBundledInput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getBundledInput( side ) };
|
||||
}
|
||||
case 5: // getBundledOutput
|
||||
return new Object[] { m_environment.getBundledOutput( parseSide( args ) ) };
|
||||
case 6: // getBundledInput
|
||||
return new Object[] { m_environment.getBundledInput( parseSide( args ) ) };
|
||||
case 7:
|
||||
{
|
||||
// testBundledInput
|
||||
int side = parseSide( args );
|
||||
ComputerSide side = parseSide( args );
|
||||
int mask = getInt( args, 1 );
|
||||
int input = m_environment.getBundledInput( side );
|
||||
return new Object[] { (input & mask) == mask };
|
||||
@@ -122,7 +105,7 @@ public class RedstoneAPI implements ILuaAPI
|
||||
case 9:
|
||||
{
|
||||
// setAnalogOutput/setAnalogueOutput
|
||||
int side = parseSide( args );
|
||||
ComputerSide side = parseSide( args );
|
||||
int output = getInt( args, 1 );
|
||||
if( output < 0 || output > 15 )
|
||||
{
|
||||
@@ -132,34 +115,20 @@ public class RedstoneAPI implements ILuaAPI
|
||||
return null;
|
||||
}
|
||||
case 10:
|
||||
case 11:
|
||||
{
|
||||
// getAnalogOutput/getAnalogueOutput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getOutput( side ) };
|
||||
}
|
||||
case 11: // getAnalogOutput/getAnalogueOutput
|
||||
return new Object[] { m_environment.getOutput( parseSide( args ) ) };
|
||||
case 12:
|
||||
case 13:
|
||||
{
|
||||
// getAnalogInput/getAnalogueInput
|
||||
int side = parseSide( args );
|
||||
return new Object[] { m_environment.getInput( side ) };
|
||||
}
|
||||
case 13: // getAnalogInput/getAnalogueInput
|
||||
return new Object[] { m_environment.getInput( parseSide( args ) ) };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int parseSide( Object[] args ) throws LuaException
|
||||
private static ComputerSide parseSide( Object[] args ) throws LuaException
|
||||
{
|
||||
String side = getString( args, 0 );
|
||||
for( int n = 0; n < IAPIEnvironment.SIDE_NAMES.length; n++ )
|
||||
{
|
||||
if( side.equals( IAPIEnvironment.SIDE_NAMES[n] ) )
|
||||
{
|
||||
return n;
|
||||
}
|
||||
}
|
||||
throw new LuaException( "Invalid side." );
|
||||
ComputerSide side = ComputerSide.valueOfInsensitive( getString( args, 0 ) );
|
||||
if( side == null ) throw new LuaException( "Invalid side." );
|
||||
return side;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,14 +6,17 @@
|
||||
|
||||
package dan200.computercraft.core.apis;
|
||||
|
||||
import dan200.computercraft.api.lua.ArgumentHelper;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Map;
|
||||
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.getNumericType;
|
||||
|
||||
/**
|
||||
* Various helpers for tables
|
||||
* Various helpers for tables.
|
||||
*/
|
||||
public final class TableHelper
|
||||
{
|
||||
@@ -200,21 +203,7 @@ public final class TableHelper
|
||||
|
||||
private static double checkReal( @Nonnull String key, double value ) throws LuaException
|
||||
{
|
||||
if( Double.isNaN( value ) )
|
||||
{
|
||||
throw badKey( key, "number", "nan" );
|
||||
}
|
||||
else if( value == Double.POSITIVE_INFINITY )
|
||||
{
|
||||
throw badKey( key, "number", "inf" );
|
||||
}
|
||||
else if( value == Double.NEGATIVE_INFINITY )
|
||||
{
|
||||
throw badKey( key, "number", "-inf" );
|
||||
}
|
||||
else
|
||||
{
|
||||
return value;
|
||||
}
|
||||
if( !Double.isFinite( value ) ) throw badKey( key, "number", getNumericType( value ) );
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.*;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.*;
|
||||
|
||||
public class TermAPI implements ILuaAPI
|
||||
{
|
||||
@@ -33,9 +33,7 @@ public class TermAPI implements ILuaAPI
|
||||
@Override
|
||||
public String[] getNames()
|
||||
{
|
||||
return new String[] {
|
||||
"term"
|
||||
};
|
||||
return new String[] { "term" };
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -89,9 +87,7 @@ public class TermAPI implements ILuaAPI
|
||||
|
||||
public static Object[] encodeColour( int colour ) throws LuaException
|
||||
{
|
||||
return new Object[] {
|
||||
1 << colour
|
||||
};
|
||||
return new Object[] { 1 << colour };
|
||||
}
|
||||
|
||||
public static void setColour( Terminal terminal, int colour, double r, double g, double b )
|
||||
@@ -246,9 +242,9 @@ public class TermAPI implements ILuaAPI
|
||||
}
|
||||
else
|
||||
{
|
||||
double r = getReal( args, 1 );
|
||||
double g = getReal( args, 2 );
|
||||
double b = getReal( args, 3 );
|
||||
double r = getFiniteDouble( args, 1 );
|
||||
double g = getFiniteDouble( args, 2 );
|
||||
double b = getFiniteDouble( args, 3 );
|
||||
setColour( m_terminal, colour, r, g, b );
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -21,8 +21,8 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.getInt;
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.optBoolean;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.getInt;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.optBoolean;
|
||||
|
||||
public class BinaryReadableHandle extends HandleGeneric
|
||||
{
|
||||
@@ -212,6 +212,7 @@ public class BinaryReadableHandle extends HandleGeneric
|
||||
}
|
||||
}
|
||||
case 3: // close
|
||||
checkOpen();
|
||||
close();
|
||||
return null;
|
||||
case 4: // seek
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
package dan200.computercraft.core.apis.handles;
|
||||
|
||||
import com.google.common.collect.ObjectArrays;
|
||||
import dan200.computercraft.api.lua.ArgumentHelper;
|
||||
import dan200.computercraft.api.lua.ILuaContext;
|
||||
import dan200.computercraft.api.lua.LuaException;
|
||||
import dan200.computercraft.core.apis.ArgumentHelper;
|
||||
import dan200.computercraft.shared.util.StringUtil;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
@@ -73,7 +73,7 @@ public class BinaryWritableHandle extends HandleGeneric
|
||||
}
|
||||
else
|
||||
{
|
||||
throw ArgumentHelper.badArgument( 0, "string or number", args.length > 0 ? args[0] : null );
|
||||
throw ArgumentHelper.badArgumentOf( 0, "string or number", args.length > 0 ? args[0] : null );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -95,6 +95,7 @@ public class BinaryWritableHandle extends HandleGeneric
|
||||
return null;
|
||||
}
|
||||
case 2: // close
|
||||
checkOpen();
|
||||
close();
|
||||
return null;
|
||||
case 3: // seek
|
||||
|
||||
@@ -20,8 +20,8 @@ import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.optBoolean;
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.optInt;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.optBoolean;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.optInt;
|
||||
|
||||
public class EncodedReadableHandle extends HandleGeneric
|
||||
{
|
||||
@@ -152,6 +152,7 @@ public class EncodedReadableHandle extends HandleGeneric
|
||||
return null;
|
||||
}
|
||||
case 3: // close
|
||||
checkOpen();
|
||||
close();
|
||||
return null;
|
||||
default:
|
||||
|
||||
@@ -93,6 +93,7 @@ public class EncodedWritableHandle extends HandleGeneric
|
||||
return null;
|
||||
}
|
||||
case 3: // close
|
||||
checkOpen();
|
||||
close();
|
||||
return null;
|
||||
default:
|
||||
|
||||
@@ -16,8 +16,8 @@ import java.io.IOException;
|
||||
import java.nio.channels.Channel;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.optLong;
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.optString;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.optLong;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.optString;
|
||||
|
||||
public abstract class HandleGeneric implements ILuaObject
|
||||
{
|
||||
@@ -37,12 +37,17 @@ public abstract class HandleGeneric implements ILuaObject
|
||||
protected final void close()
|
||||
{
|
||||
m_open = false;
|
||||
IoUtil.closeQuietly( m_closable );
|
||||
m_closable = null;
|
||||
|
||||
Closeable closeable = m_closable;
|
||||
if( closeable != null )
|
||||
{
|
||||
IoUtil.closeQuietly( closeable );
|
||||
m_closable = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared implementation for various file handle types
|
||||
* Shared implementation for various file handle types.
|
||||
*
|
||||
* @param channel The channel to seek in
|
||||
* @param args The Lua arguments to process, like Lua's {@code file:seek}.
|
||||
|
||||
@@ -99,7 +99,7 @@ public final class NetworkUtils
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a host is allowed
|
||||
* Checks a host is allowed.
|
||||
*
|
||||
* @param host The domain to check against
|
||||
* @throws HTTPRequestException If the host is not permitted.
|
||||
|
||||
@@ -20,6 +20,8 @@ import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* A holder for one or more resources, with a lifetime.
|
||||
*
|
||||
* @param <T> The type of this resource. Should be the class extending from {@link Resource}.
|
||||
*/
|
||||
public abstract class Resource<T extends Resource<T>> implements Closeable
|
||||
{
|
||||
@@ -42,8 +44,9 @@ public abstract class Resource<T extends Resource<T>> implements Closeable
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this has been cancelled. If so, it'll clean up any
|
||||
* existing resources and cancel any pending futures.
|
||||
* Checks if this has been cancelled. If so, it'll clean up any existing resources and cancel any pending futures.
|
||||
*
|
||||
* @return Whether this resource has been closed.
|
||||
*/
|
||||
public final boolean checkClosed()
|
||||
{
|
||||
@@ -72,13 +75,15 @@ public abstract class Resource<T extends Resource<T>> implements Closeable
|
||||
*/
|
||||
protected void dispose()
|
||||
{
|
||||
@SuppressWarnings( "unchecked" ) T thisT = (T) this;
|
||||
@SuppressWarnings( "unchecked" )
|
||||
T thisT = (T) this;
|
||||
limiter.release( thisT );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a {@link WeakReference} which will close {@code this} when collected.
|
||||
*
|
||||
* @param <R> The object we are wrapping in a reference.
|
||||
* @param object The object to reference to
|
||||
* @return The weak reference.
|
||||
*/
|
||||
@@ -95,7 +100,8 @@ public abstract class Resource<T extends Resource<T>> implements Closeable
|
||||
|
||||
public boolean queue( Consumer<T> task )
|
||||
{
|
||||
@SuppressWarnings( "unchecked" ) T thisT = (T) this;
|
||||
@SuppressWarnings( "unchecked" )
|
||||
T thisT = (T) this;
|
||||
return limiter.queue( thisT, () -> task.accept( thisT ) );
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* A collection of {@link Resource}s, with an upper bound on capacity.
|
||||
*
|
||||
* @param <T> The type of the resource this group manages.
|
||||
*/
|
||||
public class ResourceGroup<T extends Resource<T>>
|
||||
{
|
||||
|
||||
@@ -12,6 +12,8 @@ import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* A {@link ResourceGroup} which will queue items when the group at capacity.
|
||||
*
|
||||
* @param <T> The type of the resource this queue manages.
|
||||
*/
|
||||
public class ResourceQueue<T extends Resource<T>> extends ResourceGroup<T>
|
||||
{
|
||||
|
||||
@@ -40,7 +40,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Represents one or more
|
||||
* Represents an in-progress HTTP request.
|
||||
*/
|
||||
public class HttpRequest extends Resource<HttpRequest>
|
||||
{
|
||||
|
||||
@@ -226,7 +226,11 @@ public final class HttpRequestHandler extends SimpleChannelInboundHandler<HttpOb
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the redirect from this response
|
||||
* Determine the redirect from this response.
|
||||
*
|
||||
* @param status The status of the HTTP response.
|
||||
* @param headers The headers of the HTTP response.
|
||||
* @return The URI to redirect to, or {@code null} if no redirect should occur.
|
||||
*/
|
||||
private URI getRedirect( HttpResponseStatus status, HttpHeaders headers )
|
||||
{
|
||||
|
||||
@@ -23,7 +23,8 @@ import javax.annotation.Nullable;
|
||||
import java.io.Closeable;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static dan200.computercraft.core.apis.ArgumentHelper.optBoolean;
|
||||
import static dan200.computercraft.api.lua.ArgumentHelper.optBoolean;
|
||||
import static dan200.computercraft.core.apis.http.websocket.Websocket.CLOSE_EVENT;
|
||||
import static dan200.computercraft.core.apis.http.websocket.Websocket.MESSAGE_EVENT;
|
||||
|
||||
public class WebsocketHandle implements ILuaObject, Closeable
|
||||
@@ -53,15 +54,18 @@ public class WebsocketHandle implements ILuaObject, Closeable
|
||||
switch( method )
|
||||
{
|
||||
case 0: // receive
|
||||
checkOpen();
|
||||
while( true )
|
||||
{
|
||||
checkOpen();
|
||||
|
||||
Object[] event = context.pullEvent( MESSAGE_EVENT );
|
||||
if( event.length >= 3 && Objects.equal( event[1], websocket.address() ) )
|
||||
Object[] event = context.pullEvent( null );
|
||||
if( event.length >= 3 && Objects.equal( event[0], MESSAGE_EVENT ) && Objects.equal( event[1], websocket.address() ) )
|
||||
{
|
||||
return Arrays.copyOfRange( event, 2, event.length );
|
||||
}
|
||||
else if( event.length >= 2 && Objects.equal( event[0], CLOSE_EVENT ) && Objects.equal( event[1], websocket.address() ) && closed )
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
case 1: // send
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package dan200.computercraft.core.computer;
|
||||
|
||||
import com.google.common.base.Objects;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
import dan200.computercraft.api.lua.ILuaAPI;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.api.peripheral.IWorkMonitor;
|
||||
@@ -222,13 +223,13 @@ public class Computer
|
||||
@Deprecated
|
||||
public IPeripheral getPeripheral( int side )
|
||||
{
|
||||
return internalEnvironment.getPeripheral( side );
|
||||
return internalEnvironment.getPeripheral( ComputerSide.valueOf( side ) );
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public void setPeripheral( int side, IPeripheral peripheral )
|
||||
{
|
||||
internalEnvironment.setPeripheral( side, peripheral );
|
||||
internalEnvironment.setPeripheral( ComputerSide.valueOf( side ), peripheral );
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@@ -238,12 +239,17 @@ public class Computer
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@SuppressWarnings( "unused" )
|
||||
public void advance( double dt )
|
||||
{
|
||||
tick();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static final String[] s_sideNames = IAPIEnvironment.SIDE_NAMES;
|
||||
public IWritableMount getRootMount()
|
||||
{
|
||||
return executor.getRootMount();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static final String[] s_sideNames = ComputerSide.NAMES;
|
||||
}
|
||||
|
||||
@@ -268,7 +268,7 @@ final class ComputerExecutor
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue an event if the computer is on
|
||||
* Queue an event if the computer is on.
|
||||
*
|
||||
* @param event The event's name
|
||||
* @param args The event's arguments
|
||||
@@ -338,7 +338,7 @@ final class ComputerExecutor
|
||||
}
|
||||
}
|
||||
|
||||
private FileSystem createFileSystem()
|
||||
IWritableMount getRootMount()
|
||||
{
|
||||
if( rootMount == null )
|
||||
{
|
||||
@@ -347,11 +347,15 @@ final class ComputerExecutor
|
||||
computer.getComputerEnvironment().getComputerSpaceLimit()
|
||||
);
|
||||
}
|
||||
return rootMount;
|
||||
}
|
||||
|
||||
private FileSystem createFileSystem()
|
||||
{
|
||||
FileSystem filesystem = null;
|
||||
try
|
||||
{
|
||||
filesystem = new FileSystem( "hdd", rootMount );
|
||||
filesystem = new FileSystem( "hdd", getRootMount() );
|
||||
|
||||
IMount romMount = getRomMount();
|
||||
if( romMount == null )
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* This file is part of ComputerCraft - http://www.computercraft.info
|
||||
* Copyright Daniel Ratcliffe, 2011-2019. Do not distribute without permission.
|
||||
* Send enquiries to dratcliffe@gmail.com
|
||||
*/
|
||||
|
||||
package dan200.computercraft.core.computer;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* A side on a computer. Unlike {@link net.minecraft.util.EnumFacing}, this is relative to the direction the computer is
|
||||
* facing..
|
||||
*/
|
||||
public enum ComputerSide
|
||||
{
|
||||
BOTTOM( "bottom" ),
|
||||
TOP( "top" ),
|
||||
BACK( "back" ),
|
||||
FRONT( "front" ),
|
||||
RIGHT( "right" ),
|
||||
LEFT( "left" );
|
||||
|
||||
public static final String[] NAMES = new String[] { "bottom", "top", "back", "front", "right", "left" };
|
||||
|
||||
public static final int COUNT = 6;
|
||||
|
||||
private static final ComputerSide[] VALUES = values();
|
||||
|
||||
private final String name;
|
||||
|
||||
ComputerSide( String name )
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
public static ComputerSide valueOf( int side )
|
||||
{
|
||||
return VALUES[side];
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static ComputerSide valueOfInsensitive( @Nonnull String name )
|
||||
{
|
||||
for( ComputerSide side : VALUES )
|
||||
{
|
||||
if( side.name.equalsIgnoreCase( name ) ) return side;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -26,12 +26,12 @@ import javax.annotation.Nullable;
|
||||
*/
|
||||
public class ComputerSystem extends ComputerAccess implements IComputerSystem
|
||||
{
|
||||
private final IAPIEnvironment m_environment;
|
||||
private final IAPIEnvironment environment;
|
||||
|
||||
ComputerSystem( IAPIEnvironment environment )
|
||||
{
|
||||
super( environment );
|
||||
this.m_environment = environment;
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -45,7 +45,7 @@ public class ComputerSystem extends ComputerAccess implements IComputerSystem
|
||||
@Override
|
||||
public IFileSystem getFileSystem()
|
||||
{
|
||||
FileSystem fs = m_environment.getFileSystem();
|
||||
FileSystem fs = environment.getFileSystem();
|
||||
return fs == null ? null : fs.getMountWrapper();
|
||||
}
|
||||
|
||||
@@ -53,6 +53,6 @@ public class ComputerSystem extends ComputerAccess implements IComputerSystem
|
||||
@Override
|
||||
public String getLabel()
|
||||
{
|
||||
return m_environment.getLabel();
|
||||
return environment.getLabel();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ import static dan200.computercraft.core.computer.TimeoutState.TIMEOUT;
|
||||
public final class ComputerThread
|
||||
{
|
||||
/**
|
||||
* How often the computer thread monitor should run, in milliseconds
|
||||
* How often the computer thread monitor should run, in milliseconds.
|
||||
*
|
||||
* @see Monitor
|
||||
*/
|
||||
@@ -83,7 +83,7 @@ public final class ComputerThread
|
||||
private static final Object threadLock = new Object();
|
||||
|
||||
/**
|
||||
* Whether the computer thread system is currently running
|
||||
* Whether the computer thread system is currently running.
|
||||
*/
|
||||
private static volatile boolean running = false;
|
||||
|
||||
@@ -105,7 +105,7 @@ public final class ComputerThread
|
||||
private static final Condition hasWork = computerLock.newCondition();
|
||||
|
||||
/**
|
||||
* Active queues to execute
|
||||
* Active queues to execute.
|
||||
*/
|
||||
private static final TreeSet<ComputerExecutor> computerQueue = new TreeSet<>( ( a, b ) -> {
|
||||
if( a == b ) return 0; // Should never happen, but let's be consistent here
|
||||
@@ -126,14 +126,13 @@ public final class ComputerThread
|
||||
private ComputerThread() {}
|
||||
|
||||
/**
|
||||
* Start the computer thread
|
||||
* Start the computer thread.
|
||||
*/
|
||||
static void start()
|
||||
{
|
||||
synchronized( threadLock )
|
||||
{
|
||||
running = true;
|
||||
if( monitor == null || !monitor.isAlive() ) (monitor = monitorFactory.newThread( new Monitor() )).start();
|
||||
|
||||
if( runners == null )
|
||||
{
|
||||
@@ -158,6 +157,8 @@ public final class ComputerThread
|
||||
runnerFactory.newThread( runners[i] = new TaskRunner() ).start();
|
||||
}
|
||||
}
|
||||
|
||||
if( monitor == null || !monitor.isAlive() ) (monitor = monitorFactory.newThread( new Monitor() )).start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +194,7 @@ public final class ComputerThread
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a computer as having work, enqueuing it on the thread
|
||||
* Mark a computer as having work, enqueuing it on the thread.
|
||||
*
|
||||
* You must be holding {@link ComputerExecutor}'s {@code queueLock} when calling this method - it should only
|
||||
* be called from {@code enqueue}.
|
||||
@@ -243,6 +244,8 @@ public final class ComputerThread
|
||||
* {@link #minimumVirtualRuntime} based on the current tasks.
|
||||
*
|
||||
* This is called before queueing tasks, to ensure that {@link #minimumVirtualRuntime} is up-to-date.
|
||||
*
|
||||
* @param current The machine which we updating runtimes from.
|
||||
*/
|
||||
private static void updateRuntimes( @Nullable ComputerExecutor current )
|
||||
{
|
||||
@@ -320,7 +323,7 @@ public final class ComputerThread
|
||||
}
|
||||
|
||||
/**
|
||||
* The scaled period for a single task
|
||||
* The scaled period for a single task.
|
||||
*
|
||||
* @return The scaled period for the task
|
||||
* @see #DEFAULT_LATENCY
|
||||
@@ -335,7 +338,7 @@ public final class ComputerThread
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the thread has computers queued up
|
||||
* Determine if the thread has computers queued up.
|
||||
*
|
||||
* @return If we have work queued up.
|
||||
*/
|
||||
@@ -368,7 +371,16 @@ public final class ComputerThread
|
||||
{
|
||||
TaskRunner runner = currentRunners[i];
|
||||
// If we've no runner, skip.
|
||||
if( runner == null ) continue;
|
||||
if( runner == null || runner.owner == null || !runner.owner.isAlive() )
|
||||
{
|
||||
if( !running ) continue;
|
||||
|
||||
// Mark the old runner as dead and start a new one.
|
||||
ComputerCraft.log.warn( "Previous runner ({}) has crashed, restarting!",
|
||||
runner != null && runner.owner != null ? runner.owner.getName() : runner );
|
||||
if( runner != null ) runner.running = false;
|
||||
runnerFactory.newThread( runners[i] = new TaskRunner() ).start();
|
||||
}
|
||||
|
||||
// If the runner has no work, skip
|
||||
ComputerExecutor executor = runner.currentExecutor.get();
|
||||
@@ -492,7 +504,7 @@ public final class ComputerThread
|
||||
{
|
||||
executor.work();
|
||||
}
|
||||
catch( Exception e )
|
||||
catch( Exception | LinkageError | VirtualMachineError e )
|
||||
{
|
||||
ComputerCraft.log.error( "Error running task on computer #" + executor.getComputer().getID(), e );
|
||||
}
|
||||
|
||||
@@ -41,17 +41,17 @@ public final class Environment implements IAPIEnvironment
|
||||
private final Computer computer;
|
||||
|
||||
private boolean internalOutputChanged = false;
|
||||
private final int[] internalOutput = new int[SIDE_COUNT];
|
||||
private final int[] internalBundledOutput = new int[SIDE_COUNT];
|
||||
private final int[] internalOutput = new int[ComputerSide.COUNT];
|
||||
private final int[] internalBundledOutput = new int[ComputerSide.COUNT];
|
||||
|
||||
private final int[] externalOutput = new int[SIDE_COUNT];
|
||||
private final int[] externalBundledOutput = new int[SIDE_COUNT];
|
||||
private final int[] externalOutput = new int[ComputerSide.COUNT];
|
||||
private final int[] externalBundledOutput = new int[ComputerSide.COUNT];
|
||||
|
||||
private boolean inputChanged = false;
|
||||
private final int[] input = new int[SIDE_COUNT];
|
||||
private final int[] bundledInput = new int[SIDE_COUNT];
|
||||
private final int[] input = new int[ComputerSide.COUNT];
|
||||
private final int[] bundledInput = new int[ComputerSide.COUNT];
|
||||
|
||||
private final IPeripheral[] peripherals = new IPeripheral[SIDE_COUNT];
|
||||
private final IPeripheral[] peripherals = new IPeripheral[ComputerSide.COUNT];
|
||||
private IPeripheralChangeListener peripheralListener = null;
|
||||
|
||||
Environment( Computer computer )
|
||||
@@ -111,85 +111,89 @@ public final class Environment implements IAPIEnvironment
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getInput( int side )
|
||||
public int getInput( ComputerSide side )
|
||||
{
|
||||
return input[side];
|
||||
return input[side.ordinal()];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBundledInput( int side )
|
||||
public int getBundledInput( ComputerSide side )
|
||||
{
|
||||
return bundledInput[side];
|
||||
return bundledInput[side.ordinal()];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOutput( int side, int output )
|
||||
public void setOutput( ComputerSide side, int output )
|
||||
{
|
||||
int index = side.ordinal();
|
||||
synchronized( internalOutput )
|
||||
{
|
||||
if( internalOutput[side] != output )
|
||||
if( internalOutput[index] != output )
|
||||
{
|
||||
internalOutput[side] = output;
|
||||
internalOutput[index] = output;
|
||||
internalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOutput( int side )
|
||||
public int getOutput( ComputerSide side )
|
||||
{
|
||||
synchronized( internalOutput )
|
||||
{
|
||||
return computer.isOn() ? internalOutput[side] : 0;
|
||||
return computer.isOn() ? internalOutput[side.ordinal()] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBundledOutput( int side, int output )
|
||||
public void setBundledOutput( ComputerSide side, int output )
|
||||
{
|
||||
int index = side.ordinal();
|
||||
synchronized( internalOutput )
|
||||
{
|
||||
if( internalBundledOutput[side] != output )
|
||||
if( internalBundledOutput[index] != output )
|
||||
{
|
||||
internalBundledOutput[side] = output;
|
||||
internalBundledOutput[index] = output;
|
||||
internalOutputChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBundledOutput( int side )
|
||||
public int getBundledOutput( ComputerSide side )
|
||||
{
|
||||
synchronized( internalOutput )
|
||||
{
|
||||
return computer.isOn() ? internalBundledOutput[side] : 0;
|
||||
return computer.isOn() ? internalBundledOutput[side.ordinal()] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getExternalRedstoneOutput( int side )
|
||||
public int getExternalRedstoneOutput( ComputerSide side )
|
||||
{
|
||||
return computer.isOn() ? externalOutput[side] : 0;
|
||||
return computer.isOn() ? externalOutput[side.ordinal()] : 0;
|
||||
}
|
||||
|
||||
public int getExternalBundledRedstoneOutput( int side )
|
||||
public int getExternalBundledRedstoneOutput( ComputerSide side )
|
||||
{
|
||||
return computer.isOn() ? externalBundledOutput[side] : 0;
|
||||
return computer.isOn() ? externalBundledOutput[side.ordinal()] : 0;
|
||||
}
|
||||
|
||||
public void setRedstoneInput( int side, int level )
|
||||
public void setRedstoneInput( ComputerSide side, int level )
|
||||
{
|
||||
if( input[side] != level )
|
||||
int index = side.ordinal();
|
||||
if( input[index] != level )
|
||||
{
|
||||
input[side] = level;
|
||||
input[index] = level;
|
||||
inputChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void setBundledRedstoneInput( int side, int combination )
|
||||
public void setBundledRedstoneInput( ComputerSide side, int combination )
|
||||
{
|
||||
if( bundledInput[side] != combination )
|
||||
int index = side.ordinal();
|
||||
if( bundledInput[index] != combination )
|
||||
{
|
||||
bundledInput[side] = combination;
|
||||
bundledInput[index] = combination;
|
||||
inputChanged = true;
|
||||
}
|
||||
}
|
||||
@@ -222,7 +226,7 @@ public final class Environment implements IAPIEnvironment
|
||||
|
||||
boolean changed = false;
|
||||
|
||||
for( int i = 0; i < SIDE_COUNT; i++ )
|
||||
for( int i = 0; i < ComputerSide.COUNT; i++ )
|
||||
{
|
||||
if( externalOutput[i] != internalOutput[i] )
|
||||
{
|
||||
@@ -255,24 +259,25 @@ public final class Environment implements IAPIEnvironment
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPeripheral getPeripheral( int side )
|
||||
public IPeripheral getPeripheral( ComputerSide side )
|
||||
{
|
||||
synchronized( peripherals )
|
||||
{
|
||||
return peripherals[side];
|
||||
return peripherals[side.ordinal()];
|
||||
}
|
||||
}
|
||||
|
||||
public void setPeripheral( int side, IPeripheral peripheral )
|
||||
public void setPeripheral( ComputerSide side, IPeripheral peripheral )
|
||||
{
|
||||
synchronized( peripherals )
|
||||
{
|
||||
IPeripheral existing = peripherals[side];
|
||||
int index = side.ordinal();
|
||||
IPeripheral existing = peripherals[index];
|
||||
if( (existing == null && peripheral != null) ||
|
||||
(existing != null && peripheral == null) ||
|
||||
(existing != null && !existing.equals( peripheral )) )
|
||||
{
|
||||
peripherals[side] = peripheral;
|
||||
peripherals[index] = peripheral;
|
||||
if( peripheralListener != null ) peripheralListener.onPeripheralChanged( side, peripheral );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ public final class MainThread
|
||||
// Of course, we'll go over the MAX_TICK_TIME most of the time, but eventually that overrun will accumulate
|
||||
// and we'll skip a whole tick - bringing the average back down again.
|
||||
currentTick++;
|
||||
budget += Math.min( budget + ComputerCraft.maxMainGlobalTime, ComputerCraft.maxMainGlobalTime );
|
||||
budget = Math.min( budget + ComputerCraft.maxMainGlobalTime, ComputerCraft.maxMainGlobalTime );
|
||||
canExecute = budget > 0;
|
||||
|
||||
// Cool down any warm computers.
|
||||
|
||||
@@ -224,7 +224,7 @@ final class MainThreadExecutor implements IWorkMonitor
|
||||
{
|
||||
state = State.COOLING;
|
||||
currentTick = MainThread.currentTick();
|
||||
budget += Math.min( budget + ComputerCraft.maxMainComputerTime, ComputerCraft.maxMainComputerTime );
|
||||
budget = Math.min( budget + ComputerCraft.maxMainComputerTime, ComputerCraft.maxMainComputerTime );
|
||||
if( budget < ComputerCraft.maxMainComputerTime ) return false;
|
||||
|
||||
state = State.COOL;
|
||||
|
||||
@@ -36,12 +36,12 @@ import java.util.concurrent.TimeUnit;
|
||||
public final class TimeoutState
|
||||
{
|
||||
/**
|
||||
* The total time a task is allowed to run before aborting in nanoseconds
|
||||
* The total time a task is allowed to run before aborting in nanoseconds.
|
||||
*/
|
||||
static final long TIMEOUT = TimeUnit.MILLISECONDS.toNanos( 7000 );
|
||||
|
||||
/**
|
||||
* The time the task is allowed to run after each abort in nanoseconds
|
||||
* The time the task is allowed to run after each abort in nanoseconds.
|
||||
*/
|
||||
static final long ABORT_TIMEOUT = TimeUnit.MILLISECONDS.toNanos( 1500 );
|
||||
|
||||
@@ -111,6 +111,8 @@ public final class TimeoutState
|
||||
|
||||
/**
|
||||
* If the machine should be passively aborted.
|
||||
*
|
||||
* @return {@code true} if we should throw a timeout error.
|
||||
*/
|
||||
public boolean isSoftAborted()
|
||||
{
|
||||
@@ -118,7 +120,9 @@ public final class TimeoutState
|
||||
}
|
||||
|
||||
/**
|
||||
* If the machine should be forcibly aborted.
|
||||
* Determine if the machine should be forcibly aborted.
|
||||
*
|
||||
* @return {@code true} if the machine should be forcibly shut down.
|
||||
*/
|
||||
public boolean isHardAborted()
|
||||
{
|
||||
@@ -146,7 +150,7 @@ public final class TimeoutState
|
||||
}
|
||||
|
||||
/**
|
||||
* Pauses the cumulative time, to be resumed by {@link #startTimer()}
|
||||
* Pauses the cumulative time, to be resumed by {@link #startTimer()}.
|
||||
*
|
||||
* @see #nanoCumulative()
|
||||
*/
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.FileOperationException;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
@@ -95,7 +96,7 @@ public class ComboMount implements IMount
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "/" + path + ": Not a directory" );
|
||||
throw new FileOperationException( path, "Not a directory" );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +111,7 @@ public class ComboMount implements IMount
|
||||
return part.getSize( path );
|
||||
}
|
||||
}
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -126,7 +127,7 @@ public class ComboMount implements IMount
|
||||
return part.openForRead( path );
|
||||
}
|
||||
}
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -141,6 +142,6 @@ public class ComboMount implements IMount
|
||||
return part.openChannelForRead( path );
|
||||
}
|
||||
}
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import dan200.computercraft.api.filesystem.FileOperationException;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
@@ -44,7 +45,7 @@ public class EmptyMount implements IMount
|
||||
@Deprecated
|
||||
public InputStream openForRead( @Nonnull String path ) throws IOException
|
||||
{
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -52,6 +53,6 @@ public class EmptyMount implements IMount
|
||||
@Deprecated
|
||||
public ReadableByteChannel openChannelForRead( @Nonnull String path ) throws IOException
|
||||
{
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
package dan200.computercraft.core.filesystem;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import dan200.computercraft.api.filesystem.FileOperationException;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
@@ -167,12 +168,12 @@ public class FileMount implements IWritableMount
|
||||
{
|
||||
if( !created() )
|
||||
{
|
||||
if( !path.isEmpty() ) throw new IOException( "/" + path + ": Not a directory" );
|
||||
if( !path.isEmpty() ) throw new FileOperationException( path, "Not a directory" );
|
||||
return;
|
||||
}
|
||||
|
||||
File file = getRealPath( path );
|
||||
if( !file.exists() || !file.isDirectory() ) throw new IOException( "/" + path + ": Not a directory" );
|
||||
if( !file.exists() || !file.isDirectory() ) throw new FileOperationException( path, "Not a directory" );
|
||||
|
||||
String[] paths = file.list();
|
||||
for( String subPath : paths )
|
||||
@@ -194,7 +195,7 @@ public class FileMount implements IWritableMount
|
||||
if( file.exists() ) return file.isDirectory() ? 0 : file.length();
|
||||
}
|
||||
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -208,7 +209,7 @@ public class FileMount implements IWritableMount
|
||||
if( file.exists() && !file.isDirectory() ) return new FileInputStream( file );
|
||||
}
|
||||
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -221,7 +222,7 @@ public class FileMount implements IWritableMount
|
||||
if( file.exists() && !file.isDirectory() ) return FileChannel.open( file.toPath(), READ_OPTIONS );
|
||||
}
|
||||
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
// IWritableMount implementation
|
||||
@@ -233,7 +234,7 @@ public class FileMount implements IWritableMount
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() )
|
||||
{
|
||||
if( !file.isDirectory() ) throw new IOException( "/" + path + ": File exists" );
|
||||
if( !file.isDirectory() ) throw new FileOperationException( path, "File exists" );
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -247,7 +248,7 @@ public class FileMount implements IWritableMount
|
||||
|
||||
if( getRemainingSpace() < dirsToCreate * MINIMUM_FILE_SIZE )
|
||||
{
|
||||
throw new IOException( "/" + path + ": Out of space" );
|
||||
throw new FileOperationException( path, "Out of space" );
|
||||
}
|
||||
|
||||
if( file.mkdirs() )
|
||||
@@ -256,14 +257,14 @@ public class FileMount implements IWritableMount
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new IOException( "/" + path + ": Access denied" );
|
||||
throw new FileOperationException( path, "Access denied" );
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete( @Nonnull String path ) throws IOException
|
||||
{
|
||||
if( path.isEmpty() ) throw new IOException( "/" + path + ": Access denied" );
|
||||
if( path.isEmpty() ) throw new FileOperationException( path, "Access denied" );
|
||||
|
||||
if( created() )
|
||||
{
|
||||
@@ -319,7 +320,7 @@ public class FileMount implements IWritableMount
|
||||
{
|
||||
create();
|
||||
File file = getRealPath( path );
|
||||
if( file.exists() && file.isDirectory() ) throw new IOException( "/" + path + ": Cannot write to directory" );
|
||||
if( file.exists() && file.isDirectory() ) throw new FileOperationException( path, "Cannot write to directory" );
|
||||
|
||||
if( file.exists() )
|
||||
{
|
||||
@@ -327,7 +328,7 @@ public class FileMount implements IWritableMount
|
||||
}
|
||||
else if( getRemainingSpace() < MINIMUM_FILE_SIZE )
|
||||
{
|
||||
throw new IOException( "/" + path + ": Out of space" );
|
||||
throw new FileOperationException( path, "Out of space" );
|
||||
}
|
||||
m_usedSpace += MINIMUM_FILE_SIZE;
|
||||
|
||||
@@ -340,12 +341,12 @@ public class FileMount implements IWritableMount
|
||||
{
|
||||
if( !created() )
|
||||
{
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
File file = getRealPath( path );
|
||||
if( !file.exists() ) throw new IOException( "/" + path + ": No such file" );
|
||||
if( file.isDirectory() ) throw new IOException( "/" + path + ": Cannot write to directory" );
|
||||
if( !file.exists() ) throw new FileOperationException( path, "No such file" );
|
||||
if( file.isDirectory() ) throw new FileOperationException( path, "Cannot write to directory" );
|
||||
|
||||
// Allowing seeking when appending is not recommended, so we use a separate channel.
|
||||
return new WritableCountingChannel(
|
||||
|
||||
@@ -8,6 +8,7 @@ package dan200.computercraft.core.filesystem;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.filesystem.FileOperationException;
|
||||
import dan200.computercraft.api.filesystem.IFileSystem;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.api.filesystem.IWritableMount;
|
||||
@@ -45,7 +46,7 @@ public class FileSystem
|
||||
m_writableMount = null;
|
||||
}
|
||||
|
||||
public MountWrapper( String label, String location, IWritableMount mount )
|
||||
MountWrapper( String label, String location, IWritableMount mount )
|
||||
{
|
||||
this( label, location, (IMount) mount );
|
||||
m_writableMount = mount;
|
||||
@@ -107,7 +108,7 @@ public class FileSystem
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,12 +123,12 @@ public class FileSystem
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Not a directory" );
|
||||
throw localExceptionOf( path, "Not a directory" );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,12 +150,12 @@ public class FileSystem
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": No such file" );
|
||||
throw localExceptionOf( path, "No such file" );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,12 +170,12 @@ public class FileSystem
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": No such file" );
|
||||
throw localExceptionOf( path, "No such file" );
|
||||
}
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,19 +183,14 @@ public class FileSystem
|
||||
|
||||
public void makeDirectory( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Access denied" );
|
||||
}
|
||||
if( m_writableMount == null ) throw exceptionOf( path, "Access denied" );
|
||||
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( m_mount.exists( path ) )
|
||||
{
|
||||
if( !m_mount.isDirectory( path ) )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": File exists" );
|
||||
}
|
||||
if( !m_mount.isDirectory( path ) ) throw localExceptionOf( path, "File exists" );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -203,16 +199,14 @@ public class FileSystem
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
public void delete( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Access denied" );
|
||||
}
|
||||
if( m_writableMount == null ) throw exceptionOf( path, "Access denied" );
|
||||
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
@@ -227,22 +221,20 @@ public class FileSystem
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
public WritableByteChannel openForWrite( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Access denied" );
|
||||
}
|
||||
if( m_writableMount == null ) throw exceptionOf( path, "Access denied" );
|
||||
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( m_mount.exists( path ) && m_mount.isDirectory( path ) )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Cannot write to directory" );
|
||||
throw localExceptionOf( path, "Cannot write to directory" );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -263,19 +255,17 @@ public class FileSystem
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
public WritableByteChannel openForAppend( String path ) throws FileSystemException
|
||||
{
|
||||
if( m_writableMount == null )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Access denied" );
|
||||
}
|
||||
if( m_writableMount == null ) throw exceptionOf( path, "Access denied" );
|
||||
|
||||
path = toLocal( path );
|
||||
try
|
||||
{
|
||||
path = toLocal( path );
|
||||
if( !m_mount.exists( path ) )
|
||||
{
|
||||
if( !path.isEmpty() )
|
||||
@@ -290,7 +280,7 @@ public class FileSystem
|
||||
}
|
||||
else if( m_mount.isDirectory( path ) )
|
||||
{
|
||||
throw new FileSystemException( "/" + path + ": Cannot write to directory" );
|
||||
throw localExceptionOf( path, "Cannot write to directory" );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -303,16 +293,36 @@ public class FileSystem
|
||||
}
|
||||
catch( IOException e )
|
||||
{
|
||||
throw new FileSystemException( e.getMessage() );
|
||||
throw localExceptionOf( e );
|
||||
}
|
||||
}
|
||||
|
||||
// private members
|
||||
|
||||
private String toLocal( String path )
|
||||
{
|
||||
return FileSystem.toLocal( path, m_location );
|
||||
}
|
||||
|
||||
private FileSystemException localExceptionOf( IOException e )
|
||||
{
|
||||
if( !m_location.isEmpty() && e instanceof FileOperationException )
|
||||
{
|
||||
FileOperationException ex = (FileOperationException) e;
|
||||
if( ex.getFilename() != null ) return localExceptionOf( ex.getFilename(), ex.getMessage() );
|
||||
}
|
||||
|
||||
return new FileSystemException( e.getMessage() );
|
||||
}
|
||||
|
||||
private FileSystemException localExceptionOf( String path, String message )
|
||||
{
|
||||
if( !m_location.isEmpty() ) path = path.isEmpty() ? m_location : m_location + "/" + path;
|
||||
return exceptionOf( path, message );
|
||||
}
|
||||
|
||||
private static FileSystemException exceptionOf( String path, String message )
|
||||
{
|
||||
return new FileSystemException( "/" + path + ": " + message );
|
||||
}
|
||||
}
|
||||
|
||||
private final FileSystemWrapperMount m_wrapper = new FileSystemWrapperMount( this );
|
||||
@@ -769,7 +779,7 @@ public class FileSystem
|
||||
|
||||
// Clean the path or illegal characters.
|
||||
final char[] specialChars = new char[] {
|
||||
'"', ':', '<', '>', '?', '|' // Sorted by ascii value (important)
|
||||
'"', ':', '<', '>', '?', '|', // Sorted by ascii value (important)
|
||||
};
|
||||
|
||||
StringBuilder cleanName = new StringBuilder();
|
||||
|
||||
@@ -9,6 +9,7 @@ package dan200.computercraft.core.filesystem;
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import dan200.computercraft.api.filesystem.FileOperationException;
|
||||
import dan200.computercraft.api.filesystem.IMount;
|
||||
import dan200.computercraft.core.apis.handles.ArrayByteChannel;
|
||||
import dan200.computercraft.shared.util.IoUtil;
|
||||
@@ -69,7 +70,7 @@ public class JarMount implements IMount
|
||||
// Cleanup any old mounts. It's unlikely that there will be any, but it's best to be safe.
|
||||
cleanup();
|
||||
|
||||
if( !jarFile.exists() || jarFile.isDirectory() ) throw new FileNotFoundException();
|
||||
if( !jarFile.exists() || jarFile.isDirectory() ) throw new FileNotFoundException( "Cannot find " + jarFile );
|
||||
|
||||
// Open the zip file
|
||||
try
|
||||
@@ -85,14 +86,14 @@ public class JarMount implements IMount
|
||||
if( zip.getEntry( subPath ) == null )
|
||||
{
|
||||
zip.close();
|
||||
throw new IOException( "Zip does not contain path" );
|
||||
throw new FileNotFoundException( "Zip does not contain path" );
|
||||
}
|
||||
|
||||
// We now create a weak reference to this mount. This is automatically added to the appropriate queue.
|
||||
new MountReference( this );
|
||||
|
||||
// Read in all the entries
|
||||
root = new FileEntry( "" );
|
||||
root = new FileEntry();
|
||||
Enumeration<? extends ZipEntry> zipEntries = zip.entries();
|
||||
while( zipEntries.hasMoreElements() )
|
||||
{
|
||||
@@ -139,7 +140,7 @@ public class JarMount implements IMount
|
||||
FileEntry nextEntry = lastEntry.children.get( part );
|
||||
if( nextEntry == null || !nextEntry.isDirectory() )
|
||||
{
|
||||
lastEntry.children.put( part, nextEntry = new FileEntry( part ) );
|
||||
lastEntry.children.put( part, nextEntry = new FileEntry() );
|
||||
}
|
||||
|
||||
lastEntry = nextEntry;
|
||||
@@ -166,7 +167,7 @@ public class JarMount implements IMount
|
||||
public void list( @Nonnull String path, @Nonnull List<String> contents ) throws IOException
|
||||
{
|
||||
FileEntry file = get( path );
|
||||
if( file == null || !file.isDirectory() ) throw new IOException( "/" + path + ": Not a directory" );
|
||||
if( file == null || !file.isDirectory() ) throw new FileOperationException( path, "Not a directory" );
|
||||
|
||||
file.list( contents );
|
||||
}
|
||||
@@ -176,7 +177,7 @@ public class JarMount implements IMount
|
||||
{
|
||||
FileEntry file = get( path );
|
||||
if( file != null ) return file.size;
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@@ -218,22 +219,15 @@ public class JarMount implements IMount
|
||||
}
|
||||
}
|
||||
|
||||
throw new IOException( "/" + path + ": No such file" );
|
||||
throw new FileOperationException( path, "No such file" );
|
||||
}
|
||||
|
||||
private static class FileEntry
|
||||
{
|
||||
final String name;
|
||||
|
||||
String path;
|
||||
long size;
|
||||
Map<String, FileEntry> children;
|
||||
|
||||
FileEntry( String name )
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
void setup( ZipEntry entry )
|
||||
{
|
||||
path = entry.getName();
|
||||
|
||||
@@ -242,7 +242,7 @@ public class CobaltLuaMachine implements ILuaMachine
|
||||
}
|
||||
catch( InterruptedException e )
|
||||
{
|
||||
throw new OrphanedThread();
|
||||
throw new InterruptedError( e );
|
||||
}
|
||||
catch( LuaException e )
|
||||
{
|
||||
@@ -550,7 +550,7 @@ public class CobaltLuaMachine implements ILuaMachine
|
||||
{
|
||||
if( ComputerCraft.logPeripheralErrors ) ComputerCraft.log.error( "Error running task", t );
|
||||
m_computer.queueEvent( "task_complete", new Object[] {
|
||||
taskID, false, "Java Exception Thrown: " + t
|
||||
taskID, false, "Java Exception Thrown: " + t,
|
||||
} );
|
||||
}
|
||||
};
|
||||
|
||||
@@ -38,7 +38,7 @@ public final class MachineResult
|
||||
public static final MachineResult TIMEOUT = new MachineResult( true, false, TimeoutState.ABORT_MESSAGE );
|
||||
|
||||
/**
|
||||
* An error with no user-friendly error message
|
||||
* An error with no user-friendly error message.
|
||||
*/
|
||||
public static final MachineResult GENERIC_ERROR = new MachineResult( true, false, null );
|
||||
|
||||
|
||||
@@ -314,6 +314,9 @@ public class Terminal
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether this terminal has changed.
|
||||
*
|
||||
* @return If this terminal is dirty.
|
||||
* @deprecated All {@code *Changed()} methods are deprecated: one should pass in a callback
|
||||
* instead.
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,7 @@ package dan200.computercraft.core.terminal;
|
||||
|
||||
public class TextBuffer
|
||||
{
|
||||
public char[] m_text;
|
||||
private final char[] m_text;
|
||||
|
||||
public TextBuffer( char c, int length )
|
||||
{
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
package dan200.computercraft.shared;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
|
||||
import dan200.computercraft.shared.common.DefaultBundledRedstoneProvider;
|
||||
@@ -16,6 +15,7 @@ import net.minecraft.world.World;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class BundledRedstone
|
||||
@@ -26,7 +26,7 @@ public final class BundledRedstone
|
||||
|
||||
public static void register( @Nonnull IBundledRedstoneProvider provider )
|
||||
{
|
||||
Preconditions.checkNotNull( provider, "provider cannot be null" );
|
||||
Objects.requireNonNull( provider, "provider cannot be null" );
|
||||
providers.add( provider );
|
||||
}
|
||||
|
||||
|
||||
@@ -54,8 +54,8 @@ public final class Config
|
||||
|
||||
private static Property httpEnable;
|
||||
private static Property httpWebsocketEnable;
|
||||
private static Property httpWhitelist;
|
||||
private static Property httpBlacklist;
|
||||
private static Property httpAllowedDomains;
|
||||
private static Property httpBlockedDomains;
|
||||
|
||||
private static Property httpTimeout;
|
||||
private static Property httpMaxRequests;
|
||||
@@ -163,30 +163,32 @@ public final class Config
|
||||
{ // HTTP
|
||||
renameProperty( CATEGORY_GENERAL, "http_enable", CATEGORY_HTTP, "enabled" );
|
||||
renameProperty( CATEGORY_GENERAL, "http_websocket_enable", CATEGORY_HTTP, "websocket_enabled" );
|
||||
renameProperty( CATEGORY_GENERAL, "http_whitelist", CATEGORY_HTTP, "whitelist" );
|
||||
renameProperty( CATEGORY_GENERAL, "http_blacklist", CATEGORY_HTTP, "blacklist" );
|
||||
renameProperty( CATEGORY_GENERAL, "http_whitelist", CATEGORY_HTTP, "allowed_domains" );
|
||||
renameProperty( CATEGORY_GENERAL, "http_blacklist", CATEGORY_HTTP, "blocked_domains" );
|
||||
renameProperty( CATEGORY_HTTP, "whitelist", CATEGORY_HTTP, "allowed_domains" );
|
||||
renameProperty( CATEGORY_HTTP, "blacklist", CATEGORY_HTTP, "blocked_domains" );
|
||||
|
||||
config.getCategory( CATEGORY_HTTP )
|
||||
.setComment( "Controls the HTTP API" );
|
||||
|
||||
httpEnable = config.get( CATEGORY_HTTP, "enabled", ComputerCraft.http_enable );
|
||||
httpEnable.setComment( "Enable the \"http\" API on Computers (see \"http_whitelist\" and \"http_blacklist\" for " +
|
||||
"more fine grained control than this)" );
|
||||
httpEnable.setComment( "Enable the \"http\" API on Computers (see \"allowed_domains\" and \"blocked_domains\" " +
|
||||
"for more fine grained control than this)" );
|
||||
|
||||
httpWebsocketEnable = config.get( CATEGORY_HTTP, "websocket_enabled", ComputerCraft.http_websocket_enable );
|
||||
httpWebsocketEnable.setComment( "Enable use of http websockets. This requires the \"http_enable\" option to also be true." );
|
||||
|
||||
httpWhitelist = config.get( CATEGORY_HTTP, "whitelist", DEFAULT_HTTP_WHITELIST );
|
||||
httpWhitelist.setComment( "A list of wildcards for domains or IP ranges that can be accessed through the " +
|
||||
httpAllowedDomains = config.get( CATEGORY_HTTP, "allowed_domains", DEFAULT_HTTP_WHITELIST );
|
||||
httpAllowedDomains.setComment( "A list of wildcards for domains or IP ranges that can be accessed through the " +
|
||||
"\"http\" API on Computers.\n" +
|
||||
"Set this to \"*\" to access to the entire internet. Example: \"*.pastebin.com\" will restrict access to " +
|
||||
"just subdomains of pastebin.com.\n" +
|
||||
"You can use domain names (\"pastebin.com\"), wilcards (\"*.pastebin.com\") or CIDR notation (\"127.0.0.0/8\")." );
|
||||
|
||||
httpBlacklist = config.get( CATEGORY_HTTP, "blacklist", DEFAULT_HTTP_BLACKLIST );
|
||||
httpBlacklist.setComment( "A list of wildcards for domains or IP ranges that cannot be accessed through the " +
|
||||
httpBlockedDomains = config.get( CATEGORY_HTTP, "blocked_domains", DEFAULT_HTTP_BLACKLIST );
|
||||
httpBlockedDomains.setComment( "A list of wildcards for domains or IP ranges that cannot be accessed through the " +
|
||||
"\"http\" API on Computers.\n" +
|
||||
"If this is empty then all whitelisted domains will be accessible. Example: \"*.github.com\" will block " +
|
||||
"If this is empty then all explicitly allowed domains will be accessible. Example: \"*.github.com\" will block " +
|
||||
"access to all subdomains of github.com.\n" +
|
||||
"You can use domain names (\"pastebin.com\"), wilcards (\"*.pastebin.com\") or CIDR notation (\"127.0.0.0/8\")." );
|
||||
|
||||
@@ -220,7 +222,7 @@ public final class Config
|
||||
|
||||
setOrder(
|
||||
CATEGORY_HTTP,
|
||||
httpEnable, httpWebsocketEnable, httpWhitelist, httpBlacklist,
|
||||
httpEnable, httpWebsocketEnable, httpAllowedDomains, httpBlockedDomains,
|
||||
httpTimeout, httpMaxRequests, httpMaxDownload, httpMaxUpload, httpMaxWebsockets, httpMaxWebsocketMessage
|
||||
);
|
||||
}
|
||||
@@ -277,7 +279,7 @@ public final class Config
|
||||
renameProperty( CATEGORY_GENERAL, "turtlesCanPush", CATEGORY_TURTLE, "can_push" );
|
||||
renameProperty( CATEGORY_GENERAL, "turtle_disabled_actions", CATEGORY_TURTLE, "disabled_actions" );
|
||||
|
||||
config.getCategory( CATEGORY_HTTP )
|
||||
config.getCategory( CATEGORY_TURTLE )
|
||||
.setComment( "Various options relating to turtles." );
|
||||
|
||||
turtlesNeedFuel = config.get( CATEGORY_TURTLE, "need_fuel", ComputerCraft.turtlesNeedFuel );
|
||||
@@ -402,7 +404,7 @@ public final class Config
|
||||
|
||||
if( oldProperty.isList() )
|
||||
{
|
||||
oldProperty.setValues( oldProperty.getStringList() );
|
||||
oldProperty.setValues( newProperty.getStringList() );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -441,8 +443,8 @@ public final class Config
|
||||
// HTTP
|
||||
ComputerCraft.http_enable = httpEnable.getBoolean();
|
||||
ComputerCraft.http_websocket_enable = httpWebsocketEnable.getBoolean();
|
||||
ComputerCraft.http_whitelist = new AddressPredicate( httpWhitelist.getStringList() );
|
||||
ComputerCraft.http_blacklist = new AddressPredicate( httpBlacklist.getStringList() );
|
||||
ComputerCraft.http_whitelist = new AddressPredicate( httpAllowedDomains.getStringList() );
|
||||
ComputerCraft.http_blacklist = new AddressPredicate( httpBlockedDomains.getStringList() );
|
||||
|
||||
ComputerCraft.httpTimeout = Math.max( 0, httpTimeout.getInt() );
|
||||
ComputerCraft.httpMaxRequests = Math.max( 1, httpMaxRequests.getInt() );
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
package dan200.computercraft.shared;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.permissions.ITurtlePermissionProvider;
|
||||
import dan200.computercraft.api.turtle.event.TurtleActionEvent;
|
||||
@@ -20,6 +19,7 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
|
||||
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID )
|
||||
public final class TurtlePermissions
|
||||
@@ -32,7 +32,7 @@ public final class TurtlePermissions
|
||||
|
||||
public static void register( @Nonnull ITurtlePermissionProvider upgrade )
|
||||
{
|
||||
Preconditions.checkNotNull( upgrade, "upgrade cannot be null" );
|
||||
Objects.requireNonNull( upgrade, "upgrade cannot be null" );
|
||||
|
||||
providers.add( upgrade );
|
||||
}
|
||||
|
||||
@@ -19,12 +19,35 @@ import net.minecraftforge.fml.common.ModContainer;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public final class TurtleUpgrades
|
||||
{
|
||||
public static class Wrapper
|
||||
{
|
||||
final ITurtleUpgrade upgrade;
|
||||
final int legacyId;
|
||||
final String id;
|
||||
final String modId;
|
||||
boolean enabled;
|
||||
|
||||
public Wrapper( ITurtleUpgrade upgrade )
|
||||
{
|
||||
ModContainer mc = Loader.instance().activeModContainer();
|
||||
|
||||
this.upgrade = upgrade;
|
||||
this.legacyId = upgrade.getLegacyUpgradeID();
|
||||
this.id = upgrade.getUpgradeID().toString();
|
||||
this.modId = mc != null && mc.getModId() != null ? mc.getModId() : null;
|
||||
this.enabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static ITurtleUpgrade[] vanilla;
|
||||
|
||||
private static final Map<String, ITurtleUpgrade> upgrades = new HashMap<>();
|
||||
private static final Int2ObjectMap<ITurtleUpgrade> legacyUpgrades = new Int2ObjectOpenHashMap<>();
|
||||
private static final IdentityHashMap<ITurtleUpgrade, String> upgradeOwners = new IdentityHashMap<>();
|
||||
private static final IdentityHashMap<ITurtleUpgrade, Wrapper> wrappers = new IdentityHashMap<>();
|
||||
|
||||
private TurtleUpgrades() {}
|
||||
|
||||
@@ -35,9 +58,7 @@ public final class TurtleUpgrades
|
||||
int id = upgrade.getLegacyUpgradeID();
|
||||
if( id >= 0 && id < 64 )
|
||||
{
|
||||
String message = getMessage( upgrade, "Legacy UpgradeID '" + id + "' is reserved by ComputerCraft" );
|
||||
ComputerCraft.log.error( message );
|
||||
throw new RuntimeException( message );
|
||||
throw registrationError( upgrade, "Legacy Upgrade ID '" + id + "' is reserved by ComputerCraft" );
|
||||
}
|
||||
|
||||
registerInternal( upgrade );
|
||||
@@ -47,58 +68,63 @@ public final class TurtleUpgrades
|
||||
{
|
||||
Objects.requireNonNull( upgrade, "upgrade cannot be null" );
|
||||
|
||||
Wrapper wrapper = new Wrapper( upgrade );
|
||||
|
||||
// Check conditions
|
||||
int legacyId = upgrade.getLegacyUpgradeID();
|
||||
int legacyId = wrapper.legacyId;
|
||||
if( legacyId >= 0 )
|
||||
{
|
||||
if( legacyId >= Short.MAX_VALUE )
|
||||
{
|
||||
String message = getMessage( upgrade, "UpgradeID '" + legacyId + "' is out of range" );
|
||||
ComputerCraft.log.error( message );
|
||||
throw new RuntimeException( message );
|
||||
throw registrationError( upgrade, "Upgrade ID '" + legacyId + "' is out of range" );
|
||||
}
|
||||
|
||||
ITurtleUpgrade existing = legacyUpgrades.get( legacyId );
|
||||
if( existing != null )
|
||||
{
|
||||
String message = getMessage( upgrade, "UpgradeID '" + legacyId + "' is already registered by '" + existing.getUnlocalisedAdjective() + " Turtle'" );
|
||||
ComputerCraft.log.error( message );
|
||||
throw new RuntimeException( message );
|
||||
throw registrationError( upgrade, "Upgrade ID '" + legacyId + "' is already registered by '" + existing.getUnlocalisedAdjective() + " Turtle'" );
|
||||
}
|
||||
}
|
||||
|
||||
String id = upgrade.getUpgradeID().toString();
|
||||
String id = wrapper.id;
|
||||
ITurtleUpgrade existing = upgrades.get( id );
|
||||
if( existing != null )
|
||||
{
|
||||
String message = getMessage( upgrade, "UpgradeID '" + id + "' is already registered by '" + existing.getUnlocalisedAdjective() + " Turtle'" );
|
||||
ComputerCraft.log.error( message );
|
||||
throw new RuntimeException( message );
|
||||
throw registrationError( upgrade, "Upgrade '" + id + "' is already registered by '" + existing.getUnlocalisedAdjective() + " Turtle'" );
|
||||
}
|
||||
|
||||
// Register
|
||||
if( legacyId >= 0 ) legacyUpgrades.put( legacyId, upgrade );
|
||||
upgrades.put( id, upgrade );
|
||||
|
||||
ModContainer mc = Loader.instance().activeModContainer();
|
||||
if( mc != null && mc.getModId() != null ) upgradeOwners.put( upgrade, mc.getModId() );
|
||||
wrappers.put( upgrade, wrapper );
|
||||
}
|
||||
|
||||
private static String getMessage( ITurtleUpgrade upgrade, String rest )
|
||||
private static RuntimeException registrationError( ITurtleUpgrade upgrade, String rest )
|
||||
{
|
||||
return "Error registering '" + upgrade.getUnlocalisedAdjective() + " Turtle'. " + rest;
|
||||
String message = "Error registering '" + upgrade.getUnlocalisedAdjective() + " Turtle'. " + rest;
|
||||
ComputerCraft.log.error( message );
|
||||
throw new IllegalArgumentException( message );
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static ITurtleUpgrade get( String id )
|
||||
{
|
||||
return upgrades.get( id );
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static ITurtleUpgrade get( int id )
|
||||
{
|
||||
return legacyUpgrades.get( id );
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static String getOwner( @Nonnull ITurtleUpgrade upgrade )
|
||||
{
|
||||
Wrapper wrapper = wrappers.get( upgrade );
|
||||
return wrapper != null ? wrapper.modId : null;
|
||||
}
|
||||
|
||||
public static ITurtleUpgrade get( @Nonnull ItemStack stack )
|
||||
{
|
||||
if( stack.isEmpty() ) return null;
|
||||
@@ -115,25 +141,24 @@ public final class TurtleUpgrades
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Iterable<ITurtleUpgrade> getVanillaUpgrades()
|
||||
public static Stream<ITurtleUpgrade> getVanillaUpgrades()
|
||||
{
|
||||
List<ITurtleUpgrade> vanilla = new ArrayList<>();
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.diamondPickaxe );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.diamondAxe );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.diamondSword );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.diamondShovel );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.diamondHoe );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.craftingTable );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.wirelessModem );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.advancedModem );
|
||||
vanilla.add( ComputerCraft.TurtleUpgrades.speaker );
|
||||
return vanilla;
|
||||
}
|
||||
if( vanilla == null )
|
||||
{
|
||||
vanilla = new ITurtleUpgrade[] {
|
||||
ComputerCraft.TurtleUpgrades.diamondPickaxe,
|
||||
ComputerCraft.TurtleUpgrades.diamondAxe,
|
||||
ComputerCraft.TurtleUpgrades.diamondSword,
|
||||
ComputerCraft.TurtleUpgrades.diamondShovel,
|
||||
ComputerCraft.TurtleUpgrades.diamondHoe,
|
||||
ComputerCraft.TurtleUpgrades.craftingTable,
|
||||
ComputerCraft.TurtleUpgrades.wirelessModem,
|
||||
ComputerCraft.TurtleUpgrades.advancedModem,
|
||||
ComputerCraft.TurtleUpgrades.speaker,
|
||||
};
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static String getOwner( @Nonnull ITurtleUpgrade upgrade )
|
||||
{
|
||||
return upgradeOwners.get( upgrade );
|
||||
return Arrays.stream( vanilla ).filter( x -> x != null && wrappers.get( x ).enabled );
|
||||
}
|
||||
|
||||
public static Iterable<ITurtleUpgrade> getUpgrades()
|
||||
@@ -145,4 +170,14 @@ public final class TurtleUpgrades
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void disable( ITurtleUpgrade upgrade )
|
||||
{
|
||||
Wrapper wrapper = wrappers.get( upgrade );
|
||||
if( !wrapper.enabled ) return;
|
||||
|
||||
wrapper.enabled = false;
|
||||
upgrades.remove( wrapper.id );
|
||||
if( wrapper.legacyId >= 0 ) legacyUpgrades.remove( wrapper.legacyId );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ package dan200.computercraft.shared.command;
|
||||
import com.google.common.collect.Sets;
|
||||
import dan200.computercraft.ComputerCraft;
|
||||
import dan200.computercraft.api.peripheral.IPeripheral;
|
||||
import dan200.computercraft.core.apis.IAPIEnvironment;
|
||||
import dan200.computercraft.core.computer.Computer;
|
||||
import dan200.computercraft.core.computer.ComputerSide;
|
||||
import dan200.computercraft.core.tracking.ComputerTracker;
|
||||
import dan200.computercraft.core.tracking.Tracking;
|
||||
import dan200.computercraft.core.tracking.TrackingContext;
|
||||
@@ -115,12 +115,12 @@ public final class CommandComputerCraft extends CommandDelegate
|
||||
table.row( header( "Position" ), linkPosition( context, computer ) );
|
||||
table.row( header( "Family" ), text( computer.getFamily().toString() ) );
|
||||
|
||||
for( int i = 0; i < 6; i++ )
|
||||
for( ComputerSide side : ComputerSide.values() )
|
||||
{
|
||||
IPeripheral peripheral = computer.getPeripheral( i );
|
||||
IPeripheral peripheral = computer.getPeripheral( side );
|
||||
if( peripheral != null )
|
||||
{
|
||||
table.row( header( "Peripheral " + IAPIEnvironment.SIDE_NAMES[i] ), text( peripheral.getType() ) );
|
||||
table.row( header( "Peripheral " + side.getName() ), text( peripheral.getType() ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A command which delegates to a series of sub commands
|
||||
* A command which delegates to a series of sub commands.
|
||||
*/
|
||||
public class CommandRoot implements ISubCommand
|
||||
{
|
||||
|
||||
@@ -22,7 +22,7 @@ import java.util.List;
|
||||
public interface ISubCommand
|
||||
{
|
||||
/**
|
||||
* Get the name of this command
|
||||
* Get the name of this command.
|
||||
*
|
||||
* @return The name of this command
|
||||
* @see ICommand#getName()
|
||||
@@ -40,7 +40,7 @@ public interface ISubCommand
|
||||
String getFullName();
|
||||
|
||||
/**
|
||||
* Get the usage of this command
|
||||
* Get the usage of this command.
|
||||
*
|
||||
* @param context The context this command is executed in
|
||||
* @return The usage of this command
|
||||
@@ -62,16 +62,17 @@ public interface ISubCommand
|
||||
boolean checkPermission( @Nonnull CommandContext context );
|
||||
|
||||
/**
|
||||
* Execute this command
|
||||
* Execute this command.
|
||||
*
|
||||
* @param context The current command context.
|
||||
* @param arguments The arguments passed @throws CommandException When an error occurs
|
||||
* @param arguments The arguments passed
|
||||
* @throws CommandException When an error occurs
|
||||
* @see ICommand#execute(MinecraftServer, ICommandSender, String[])
|
||||
*/
|
||||
void execute( @Nonnull CommandContext context, @Nonnull List<String> arguments ) throws CommandException;
|
||||
|
||||
/**
|
||||
* Get a list of possible completions
|
||||
* Get a list of possible completions.
|
||||
*
|
||||
* @param context The current command context.
|
||||
* @param arguments The arguments passed. You should complete the last one.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user