1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-10-22 17:37:38 +00:00

Compare commits

...

70 Commits

Author SHA1 Message Date
Jonathan Coates
f0ba1108d5 Merge branch 'mc-1.15.x' into mc-1.16.x 2021-05-20 19:03:56 +01:00
Jonathan Coates
5d0daf9b2d Remove dependencies from gradle 2021-05-20 19:03:30 +01:00
Jonathan Coates
8b8692ba53 Merge branch 'mc-1.15.x' into mc-1.16.x 2021-05-20 18:30:10 +01:00
Jonathan Coates
1f385f5b35 Bump version to 1.94.0 2021-05-20 18:29:57 +01:00
Jonathan Coates
34baa09b6c Set stack size when crafting coloured items
Fixes #793
2021-05-20 18:12:30 +01:00
Jonathan Coates
b21866fbff Merge pull request #794 from MCJack123/patch-7
Add the ability to call `cc.expect` directly
2021-05-20 09:23:28 +01:00
JackMacWindows
e0a288bcb9 Add the ability to call cc.expect directly 2021-05-19 20:14:13 -04:00
Jonathan Coates
4592534a18 Fix mount suggestion always being printed out 2021-05-18 09:44:11 +00:00
Lupus590
28165bfcd6 Add cc.expect.range (#790) 2021-05-17 17:49:48 +01:00
Jonathan Coates
953b94fd08 Add problem matchers for Github actions
- Add a basic problem matcher for illuaminate errors.
 - Add a script (tools/parse-reports.py) which parses the XML reports
   generated by checkstyle and junit, extracts source locations, and
   emits them in a manner which can be consumed by another set of
   matchers.

This should make it a little easier to see problems for folks who just
rely on CI to test things (though also, please don't do this if you can
help it).
2021-05-17 16:31:58 +00:00
Jonathan Coates
e10e30f82b Use a separate region for the bottom pocket computer border
This is definitely not a good solution, but it's probably the best we
can do right now given resizable computers are a thing.

Fixes #775, closes #776
2021-05-16 18:40:18 +01:00
Jonathan Coates
aeb1fa0e7e Optimise all textures
using "optipng -o7 -strip all". I ran this a few years ago and had some
issues, but aren't seeing any problems now. I don't know if this is a
graphics card change, or just optipng fixed some bugs.

These are fairly minimal changes, but hopefully save a few bytes!
2021-05-16 18:00:47 +01:00
Jonathan Coates
349a7543b0 Fix build failures
- Add license headers. Also check these during pre-commit.
 - Fix javadoc issue.
2021-05-15 21:27:48 +01:00
Jonathan Coates
3d589eda4a Expose GenericSource to the public API
- Remove the service provider code and require people to explicitly
   register these. This is definitely more ugly, but easier than people
   pulling in AutoService or similar!
 - Add an API for registering capabilities.
 - Expand the doc comments a little. Not sure how useful they'll be, but
   let's see!

There's still so much work to be done on this, but it's a "good enough"
first step.
2021-05-15 21:11:09 +01:00
Jonathan Coates
de646b66b6 Allow turtles to use compostors 2021-05-14 18:32:52 +01:00
Jonathan Coates
4f0d311df7 Add example to turtle.inspect
A pretty common but non-trivial API, so worth having something. Even if
not perfect.
2021-05-14 18:06:51 +01:00
Jonathan Coates
d6e3c9a7fa Add inventory.getItemLimit
Closes #781
2021-05-13 18:12:49 +01:00
Jonathan Coates
a7a724f134 Bump Cobalt version 2021-05-13 18:09:08 +01:00
Jonathan Coates
b0e30fdce1 Use lightGrey for folders on normal computers
This way we still get some differences between files and folders on
normal computers. I did try with just green, but I think the contrast is
too low.

Closes #656
2021-05-05 22:10:19 +01:00
Jonathan Coates
4e15afa254 Add tests for placing monitors from turtles (#691) 2021-05-05 21:49:25 +01:00
Jonathan Coates
84bac06178 Merge remote-tracking branch 'baeuric/mc-1.15.x' into mc-1.15.x 2021-05-05 21:46:47 +01:00
Jonathan Coates
1fecb995c9 Don't close file handles from ResourceMounts
Unlike short handles, we don't read these immediately, and so we can't
close it right away. Otherwise the file is considered empty!

Fixes SquidDev-CC/treasure-programs#1
2021-05-05 21:26:17 +01:00
Euric
99b719299c Defer monitor tile update when placed by another TE 2021-05-04 14:24:58 -07:00
Jonathan Coates
fb9590467d Add some examples to inventory methods
Closes #761. It's not perfect, but it's a little better. Maybe??
2021-05-04 19:23:35 +01:00
Jonathan Coates
bc8e090873 Simplify our overrides of load/loadstring
- Remove auto-prefixing of load/loadstring
 - Use Cobalt's normal load implementation, with a simple hook to
   set _ENV on the environment.
2021-05-04 18:30:28 +01:00
Jonathan Coates
cf0f67265f Correctly handle sparse arrays in cc.pretty
This also swaps the order we display mixed array/maps in, so that the
array part comes first. I think this is more sensible.

Closes #777
2021-05-04 18:05:56 +01:00
Jonathan Coates
53dd15a213 Clean up language scripts 2021-04-28 21:28:52 +01:00
Jonathan Coates
eb2d617ed8 Add a pre commit hook to lint code
This uses pre-commit [1] to check patches are well formed and run
several linters on them. We currently do some boring things (check files
are syntactically valid) as well as some project-specific ones:
 - Run illuaminate on the Lua files
 - Run checkstyle on Java

[1]: https://pre-commit.com/
2021-04-28 21:24:27 +01:00
Jonathan Coates
74dae4ec17 That's it, I'm adding pre-commit hooks 2021-04-28 08:19:09 +01:00
Jonathan Coates
abbc46877b Remove mavenLocal() repository
Hopefully should bump to the latest Cobalt version too
2021-04-28 08:05:58 +01:00
Jonathan Coates
3cb25b3525 Various VM tests
These are largely copied across from Cobalt's test suite, with some
minor tweaks. It actually exposed one bug in Cobalt, which is pretty
nice.

One interesting thing from the coroutine tests, is that Lua 5.4 (and
one assumes 5.2/5.3) doesn't allow yielding from within the error
handler of xpcall - I rather thought it might.

This doesn't add any of the PUC Lua tests yet - I got a little
distracted.

Also:
 - Allow skipping "keyword" tests, in the style of busted. This is
   implemented on the Java side for now.
 - Fix a bug with os.date("%I", _) not being 2 characters wide.
2021-04-27 22:25:46 +01:00
Jonathan Coates
f387730b88 Merge branch 'mc-1.15.x' into mc-1.16.x 2021-04-24 11:50:23 +01:00
Jonathan Coates
92b45b1868 Switch to using maven-publish
The old maven package is removed in Gradle 7.0. Instead, we publish to
squiddev.cc using WebDAV (ewww).
2021-04-24 11:26:04 +01:00
Jonathan Coates
003c7ec2e8 Fix Forge maven location
1.16 is going to be sad for a while, as I need to work out FG 4 woes.
2021-04-23 22:40:20 +01:00
Jonathan Coates
c45221a2d0 Fix checkstyle
This is gonna be 50% of my commits at this rate.
2021-04-13 13:03:26 +01:00
Jonathan Coates
8494ba8ce2 Improve UX when a resource mount cannot be found
- Add a full example of the docs. Hopefully is a little more explicit.
 - Print a warning when the mount is empty.

Closes #762
2021-04-13 13:01:28 +01:00
Jonathan Coates
058d63e77f Add citation to cc.pretty
ust to look extra pretentious.
2021-04-11 18:43:24 +01:00
Jonathan Coates
17b5bca443 Make the peripheral API examples a little clearer 2021-04-07 18:34:55 +01:00
Jonathan Coates
c3f5700494 Fix checkstyle
Today is not a good day apparently :D:.
2021-04-03 14:13:55 +01:00
Jonathan Coates
b17ff6daf0 Fix a couple of JEI issues
- Don't treat turtles/pocket computers with no upgrades as an "any"
   turtle. Otherwise getting the recipe of a crafty turtle shows the
   recipe of a normal turtle too.
 - Fix "get usage" of upgrade items not returning their recipes.
 - Fix NPEs inside JEI (closes #719)
2021-04-03 14:08:58 +01:00
Jonathan Coates
e8f5531a8c Fix checkstyle 2021-04-03 12:55:20 +01:00
Jonathan Coates
51d3b091da "Finish" documentation for several modules
- Add remaining docs for the turtle API
 - Add documentation for the fluid storage peripheral.
 - Enforce undocumented warning for most modules (only io and window
   remaining).

"Finish" in quotes, because these are clearly a long way from perfect.
I'm bad at writing docs, OK!
2021-04-03 12:45:54 +01:00
lily
9708dd6786 Fixed sortCoords for draw functions (#749) 2021-04-02 15:30:28 +01:00
Jonathan Coates
e48427dbbc Add documentation for io.setvbuf
Fixes #746.

Love how "good first issue" guarantees that nobody will do it. Not
actually true, and thank you for those people who have contributed!
2021-03-28 19:38:25 +01:00
Jonathan Coates
669b6d2d56 Merge pull request #742 from Wojbie/edit-fix
Fix missing `term.setCursorBlink(true)` in edit.lua
2021-03-19 16:48:34 +00:00
Wojbie
32d956bbe7 Fix missing term.setCursorBlink(true) in edit.lua 2021-03-19 16:07:20 +01:00
Ronan Hanley
3a147c78a8 Refactor and add tests for TextBuffer (#738) 2021-03-16 21:19:54 +00:00
Jonathan Coates
8c56b6a7be Merge branch 'mc-1.15.x' into mc-1.16.x 2021-03-12 09:26:15 +00:00
Jonathan Coates
66e42e0817 Bump version to 1.95.3 2021-03-12 09:19:16 +00:00
Jonathan Coates
0ee3d10fda Add User-Agent to Websockets
I think, haven't actually tested this :D:. Closes #730.
2021-03-12 09:14:52 +00:00
Jonathan Coates
ed0afc4068 Bump ForgeGradle version
Fixes #686
2021-03-12 08:59:31 +00:00
Wojbie
1f70ed6985 Make edit display errors/results of execution and handle require. (#723) 2021-02-23 20:50:19 +00:00
Weblate
8f3ea60c74 Translations for Portuguese (Brazil)
Co-authored-by: Matheus Medeiros Souza <mmedeiros.cbp@gmail.com>
2021-02-21 13:42:57 +00:00
Jonathan Coates
eb722a74cd Clarify the turtle.place docs a little
Closes #714
2021-02-20 20:19:22 +00:00
Jonathan Coates
1825f67eee Lazily load models in data generators
Fixes #701 (well, hopefully). Our BlockModelProvider is created when
running other mods' data generators (thought not run), which causes
issues as none of the models are considered as "existing files".
2021-02-13 13:02:24 +00:00
Jonathan Coates
975a994581 Fix missing method usages
Maybe one should do a full gradle build when doing major build c hanges
:D:.
2021-02-13 12:48:59 +00:00
Jonathan Coates
061514549d Bump Gradle/ForgeGradle version
This is definitely going to break the build (it shouldn't, but these
things always do). Anyway...

 - Use the new Java toolchain support, rather than requiring the user to
   install multiple Java versions.
 - Bump versions of several plugins.

We're sadly stuck on Gradle <7 for now, as they drop the old
maven-publish plugin, which drops SCP support.
2021-02-13 12:39:52 +00:00
Jonathan Coates
5e52429c23 Merge pull request #709 from SkyTheCodeMaster/patch-1
Fix `redstone.getBundledInput(side)` returning the output of said side.
2021-02-05 20:54:57 +00:00
SkyTheCodeMaster
396cf15a1f Fix redstone.getBundledInput(side) returning the output of said side. 2021-02-05 14:10:11 -05:00
Jonathan Coates
7514cf7320 Mark as compatible with 1.16.{4,5}
Closes #694
2021-01-24 21:23:29 +00:00
Jonathan Coates
1316d6a3c9 Migrate all examples to use tweaked.cc
Might as well, I've got the server capacity to spare. Hopefully.
2021-01-23 14:58:08 +00:00
Jonathan Coates
e1cbbe3628 Haven't been hoisted by this petard for a while
I really should move this to Gradle. Probably should just write my own
plugin at this point.
2021-01-19 21:33:05 +00:00
Jonathan Coates
6d367e08a3 ./gradlew checkstyleMain
Every time I forget to run this before pushing, I get very sad.
2021-01-19 21:15:18 +00:00
Jonathan Coates
eaa7359c8c Add a whole bunch of tests
Coverage graph goes woosh. Hopefully.

More importantly, all of these are historic regressions, so very much
worth tracking.
2021-01-19 20:02:45 +00:00
SquidDev
657ceda3af Switch back to reobfuscated name in RecordMedia
Fixes #688
2021-01-19 13:43:49 +00:00
JackMacWindows
a934e42219 Finish the rest of the event documentation (#683) 2021-01-19 09:20:52 +00:00
Jonathan Coates
1544749282 Defer sending monitor updates until tick end
We send monitor updates when a player starts watching a chunk. However,
the block/tile data has not been sent when this event is fired, and so
the packet is entirely ignored.

Instead, we now queue a "send this" task, which is then dispatched on
the next tick end.

I have memories of this working on 1.12, so either something changed in
an update or I'm a complete idiot. Both are possible.

Fixes #687
2021-01-18 22:20:48 +00:00
FensieRenaud
763bab80fa Serialise sparse arrays into JSON (#685) 2021-01-18 20:48:33 +00:00
FensieRenaud
417fda3019 Serialise sparse arrays into JSON (#685) 2021-01-18 16:44:39 +00:00
Jonathan Coates
444830cf2d Remove Grgit/jgit usage in build.gradle
The replacement is objectively worse. However, it supports Git
worktrees, which sadly jgit does not.

We really need to rewrite the build script to make it lazy so we're not
executing these commands every time.
2021-01-16 15:41:19 +00:00
252 changed files with 6903 additions and 928 deletions

View File

@@ -16,6 +16,3 @@ indent_size = 2
[*.yml]
indent_size = 2
[*.properties]
insert_final_newline = false

17
.github/matchers/checkstyle.json vendored Normal file
View File

@@ -0,0 +1,17 @@
{
"problemMatcher": [
{
"owner": "checkstyle",
"pattern": [
{
"regexp": "^([a-z]+) ([\\w./-]+):(\\d+):(\\d+): (.*)$",
"severity": 1,
"file": 2,
"line": 3,
"column": 4,
"message": 5
}
]
}
]
}

18
.github/matchers/illuaminate.json vendored Normal file
View File

@@ -0,0 +1,18 @@
{
"problemMatcher": [
{
"owner": "illuaminate",
"severity": "warning",
"pattern": [
{
"regexp": "^([\\w./-]+):\\[(\\d+):(\\d+)\\-(?:\\d+):(?:\\d+)\\]: (.*) \\[([a-z:-]+)\\]$",
"file": 1,
"line": 2,
"column": 3,
"message": 4,
"code": 5
}
]
}
]
}

15
.github/matchers/junit.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
"problemMatcher": [
{
"owner": "junit",
"pattern": [
{
"regexp": "^## ([\\w./-]+):(\\d+): (.*)$",
"file": 1,
"line": 2,
"message": 3
}
]
}
]
}

View File

@@ -23,10 +23,15 @@ jobs:
restore-keys: |
${{ runner.os }}-gradle-
- name: Disable Gradle daemon
run: |
mkdir -p ~/.gradle
echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties
- name: Build with Gradle
run: |
./gradlew assemble --no-daemon || ./gradlew assemble --no-daemon
./gradlew downloadAssets --no-daemon || ./gradlew downloadAssets --no-daemon
./gradlew assemble || ./gradlew assemble
./gradlew downloadAssets || ./gradlew downloadAssets
./gradlew build
- name: Upload Jar
@@ -36,18 +41,21 @@ jobs:
path: build/libs
- name: Upload Coverage
run: bash <(curl -s https://codecov.io/bash)
continue-on-error: true
uses: codecov/codecov-action@v1
- name: Generate Java documentation stubs
run: ./gradlew luaJavadoc --no-daemon
- name: Parse test reports
run: ./tools/parse-reports.py
if: ${{ failure() }}
- name: Lint Lua code
- name: Cache pre-commit
uses: actions/cache@v2
with:
path: ~/.cache/pre-commit
key: ${{ runner.os }}-pre-commit-${{ hashFiles('config/pre-commit/config.yml') }}
restore-keys: |
${{ runner.os }}-pre-commit-
- name: Run linters
run: |
test -d bin || mkdir bin
test -f bin/illuaminate || wget -q -Obin/illuaminate https://squiddev.cc/illuaminate/linux-x86-64/illuaminate
chmod +x bin/illuaminate
bin/illuaminate lint
- name: Check whitespace
run: python3 tools/check-lines.py
pip install pre-commit
pre-commit run --config config/pre-commit/config.yml --show-diff-on-failure --all --color=always

View File

@@ -51,18 +51,10 @@ illuaminate, which spits out our HTML.
For various reasons, getting the environment set up to build documentation can be pretty complex. I'd quite like to
automate this via Docker and/or nix in the future, but this needs to be done manually for now.
First, you will need JDK 9+ (in addition to JDK 8 which is required to build Minecraft itself). Sadly our version of
Gradle doesn't support multiple toolchains, and so you need to install this yourself.
Gradle needs to be told about this JDK via the `JAVA_HOME_11_X64` environment variable or adding `java11Home` to
`~/.gradle/gradle.properties`. On my system this looks like:
```properties
java11Home=/usr/lib/jvm/java-11-openjdk/
```
If you just want to build the documentation stubs for linting, this is enough. However, if you want to build the full
website, you will also need to install a few Node packages by running `npm ci`.
This tooling is only needed if you need to build the whole website. If you just want to generate the Lua stubs, you can
skp this section.
- Install Node/npm and install our Node packages with `npm ci`.
- Install [illuaminate][illuaminate-usage] as described above.
#### Building documentation
Gradle should be your entrypoint to building most documentation. There's two tasks which are of interest:
@@ -73,7 +65,7 @@ Gradle should be your entrypoint to building most documentation. There's two tas
#### Writing documentation
illuaminate's documentation system is not currently documented (somewhat ironic), but is _largely_ the same as
[ldoc][ldoc]. Documentation comments are written in Markdown,
[ldoc][ldoc]. Documentation comments are written in Markdown,
Our markdown engine does _not_ support GitHub flavoured markdown, and so does not support all the features one might
expect (such as tables). It is very much recommended that you build and preview the docs locally first.
@@ -85,18 +77,18 @@ entire test suite (and some additional bits of verification).
Before we get into writing tests, it's worth mentioning the various test suites that CC: Tweaked has:
- "Core" Java (`./src/test/java`): These test core bits of the mod which don't require any Minecraft interaction.
This includes the `@LuaFunction` system, file system code, etc...
These tests are run by `./gradlew test`.
- CraftOS (`./src/test/resources/test-rom/`): These tests are written in Lua, and ensure the Lua environment, libraries
and programs work as expected. These are (generally) written to be able to be run on emulators too, to provide some
sort of compliance test.
These tests are run by the '"Core" Java' test suite, and so are also run with `./gradlew test`.
- In-game (`./src/test/java/dan200/computercraft/ingame/`): These tests are run on an actual Minecraft server, using
[the same system Mojang do][mc-test]. The aim of these is to test in-game behaviour of blocks and peripherals.
These are run by `./gradlew testInGame`.
## CraftOS tests

14
LICENSE
View File

@@ -19,14 +19,14 @@ Mod: The mod code designated by the present license, in source form, binary
form, as obtained standalone, as part of a wider distribution or resulting from
the compilation of the original or modified sources.
Dependency: Code required for the mod to work properly. This includes
Dependency: Code required for the mod to work properly. This includes
dependencies required to compile the code as well as any file or modification
that is explicitly or implicitly required for the mod to be working.
1. Scope
--------
The present license is granted to any user of the mod. As a prerequisite,
The present license is granted to any user of the mod. As a prerequisite,
a user must own a legally acquired copy of Minecraft
2. Liability
@@ -41,13 +41,13 @@ or misuse of this mod fall on the user.
3. Play rights
--------------
The user is allowed to install this mod on a Minecraft client or server and to play
The user is allowed to install this mod on a Minecraft client or server and to play
without restriction.
4. Modification rights
----------------------
The user has the right to decompile the source code, look at either the
The user has the right to decompile the source code, look at either the
decompiled version or the original source code, and to modify it.
5. Distribution of original or modified copy rights
@@ -61,10 +61,10 @@ include:
- patch to its source or binary files
- any copy of a portion of its binary source files
The user is allowed to redistribute this mod partially, in totality, or
The user is allowed to redistribute this mod partially, in totality, or
included in a distribution.
When distributing binary files, the user must provide means to obtain its
When distributing binary files, the user must provide means to obtain its
entire set of sources or modified sources at no cost.
All distributions of this mod must remain licensed under the CCPL.
@@ -92,7 +92,7 @@ must be made available at no cost and remain licensed under the CCPL.
---------------
If you choose to contribute code or assets to be included in this mod, you
agree that, if added to to the main repository at
agree that, if added to to the main repository at
https://github.com/dan200/ComputerCraft, your contributions will be covered by
this license, and that Daniel Ratcliffe will retain the right to re-license the
mod, including your contributions, in part or in whole, under other licenses.

View File

@@ -4,18 +4,18 @@ buildscript {
mavenCentral()
maven {
name = "forge"
url = "https://files.minecraftforge.net/maven"
url = "https://maven.minecraftforge.net"
}
maven {
name = "mixin"
url = "https://dist.creeper.host/Sponge/maven"
name = "Sponge (Mixin)"
url = "https://repo.spongepowered.org/repository/maven-public/"
content { includeGroup "org.spongepowered" }
}
}
dependencies {
classpath 'com.google.code.gson:gson:2.8.1'
classpath 'net.minecraftforge.gradle:ForgeGradle:3.0.190'
classpath 'net.minecraftforge.gradle:ForgeGradle:4.1.9'
classpath 'net.sf.proguard:proguard-gradle:6.1.0beta2'
classpath 'org.ajoberstar.grgit:grgit-gradle:3.0.0'
classpath 'org.spongepowered:mixingradle:0.7-SNAPSHOT'
}
}
@@ -23,24 +23,29 @@ buildscript {
plugins {
id "checkstyle"
id "jacoco"
id "maven-publish"
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"
id "com.matthewprenger.cursegradle" version "1.4.0"
id "com.github.breadmoirai.github-release" version "2.2.12"
id "org.jetbrains.kotlin.jvm" version "1.3.72"
}
apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'org.spongepowered.mixin'
apply plugin: 'org.ajoberstar.grgit'
apply plugin: 'maven-publish'
apply plugin: 'maven'
version = mod_version
group = "org.squiddev"
archivesBaseName = "cc-tweaked-${mc_version}"
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
withSourcesJar()
withJavadocJar()
}
minecraft {
runs {
@@ -124,7 +129,6 @@ repositories {
configurations {
shade
compile.extendsFrom shade
deployerJars
cctJavadoc
}
@@ -138,10 +142,7 @@ dependencies {
runtimeOnly fg.deobf("mezz.jei:jei-1.16.4:7.6.0.58")
compileOnly 'com.google.auto.service:auto-service:1.0-rc7'
annotationProcessor 'com.google.auto.service:auto-service:1.0-rc7'
shade 'org.squiddev:Cobalt:0.5.1-SNAPSHOT'
shade 'org.squiddev:Cobalt:0.5.2-SNAPSHOT'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.0'
@@ -150,10 +151,9 @@ dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72'
testImplementation 'org.jetbrains.kotlin:kotlin-reflect:1.3.72'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.8'
testAnnotationProcessor 'org.spongepowered:mixin:0.8.2:processor'
deployerJars "org.apache.maven.wagon:wagon-ssh:3.0.0"
cctJavadoc 'cc.tweaked:cct-javadoc:1.3.0'
cctJavadoc 'cc.tweaked:cct-javadoc:1.4.0'
}
// Compile tasks
@@ -172,17 +172,14 @@ task luaJavadoc(type: Javadoc) {
options.docletpath = configurations.cctJavadoc.files as List
options.doclet = "cc.tweaked.javadoc.LuaDoclet"
options.noTimestamp = false
// Attempt to run under Java 11 (any Java >= 9 will work though).
if(System.getProperty("java.version").startsWith("1.")
&& (System.getenv("JAVA_HOME_11_X64") != null || project.hasProperty("java11Home"))) {
executable = "${System.getenv("JAVA_HOME_11_X64") ?: project.property("java11Home")}/bin/javadoc"
javadocTool = javaToolchains.javadocToolFor {
languageVersion = JavaLanguageVersion.of(11)
}
}
jar {
dependsOn javadoc
manifest {
attributes(["Specification-Title": "computercraft",
"Specification-Vendor": "SquidDev",
@@ -193,10 +190,6 @@ jar {
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")])
}
from (sourceSets.main.allSource) {
include "dan200/computercraft/api/**/*.java"
}
from configurations.shade.collect { it.isDirectory() ? it : zipTree(it) }
}
@@ -214,7 +207,6 @@ 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
task proguard(type: ProGuardTask, dependsOn: jar) {
@@ -267,16 +259,15 @@ processResources {
def hash = 'none'
Set<String> contributors = []
try {
def grgit = Grgit.open(dir: '.')
hash = grgit.head().id
hash = ["git", "-C", projectDir, "rev-parse", "HEAD"].execute().text.trim()
def blacklist = ['GitHub', 'dan200', 'Daniel Ratcliffe']
grgit.log().each {
if (!blacklist.contains(it.author.name)) contributors.add(it.author.name)
if (!blacklist.contains(it.committer.name)) contributors.add(it.committer.name)
["git", "-C", projectDir, "log", "--format=tformat:%an%n%cn"].execute().text.split('\n').each {
if (!blacklist.contains(it)) contributors.add(it)
}
} catch(Exception ignored) { }
} catch(Exception e) {
e.printStackTrace()
}
inputs.property "commithash", hash
from(sourceSets.main.resources.srcDirs) {
@@ -497,8 +488,8 @@ tasks.register('jacocoTestInGameReport', JacocoReport.class).configure {
it.dependsOn('testInGame')
it.executionData(new File(buildDir, 'jacoco/testInGame.exec'))
it.setSourceDirectories(project.files(sourceSets.main.allJava.srcDirs))
it.setClassDirectories(project.files(new File(buildDir, 'jacocoClassDump/testInGame')))
it.sourceDirectories.from(sourceSets.main.allJava.srcDirs)
it.classDirectories.from(new File(buildDir, 'jacocoClassDump/testInGame'))
it.reports {
xml.enabled true
@@ -560,56 +551,56 @@ curseforge {
relations {
incompatible "computercraft"
}
addGameVersion '1.16.4'
addGameVersion '1.16.5'
}
}
tasks.withType(GenerateModuleMetadata) {
// We can't generate metadata as that includes Forge as a dependency.
enabled = false
}
publishing {
publications {
mavenJava(MavenPublication) {
maven(MavenPublication) {
from components.java
// artifact sourceJar
pom {
name = 'CC: Tweaked'
description = 'CC: Tweaked is a fork of ComputerCraft, adding programmable computers, turtles and more to Minecraft.'
url = 'https://github.com/SquidDev-CC/CC-Tweaked'
scm {
url = 'https://github.com/SquidDev-CC/CC-Tweaked.git'
}
issueManagement {
system = 'github'
url = 'https://github.com/SquidDev-CC/CC-Tweaked/issues'
}
licenses {
license {
name = 'ComputerCraft Public License, Version 1.0'
url = 'https://github.com/SquidDev-CC/CC-Tweaked/blob/mc-1.15.x/LICENSE'
}
}
withXml { asNode().remove(asNode().get("dependencies")) }
}
}
}
}
uploadArchives {
repositories {
if(project.hasProperty('mavenUploadUrl')) {
mavenDeployer {
configuration = configurations.deployerJars
repository(url: project.property('mavenUploadUrl')) {
authentication(
userName: project.property('mavenUploadUser'),
privateKey: project.property('mavenUploadKey'))
}
pom.project {
name 'CC: Tweaked'
packaging 'jar'
description 'CC: Tweaked is a fork of ComputerCraft, adding programmable computers, turtles and more to Minecraft.'
url 'https://github.com/SquidDev-CC/CC-Tweaked'
scm {
url 'https://github.com/SquidDev-CC/CC-Tweaked.git'
}
issueManagement {
system 'github'
url 'https://github.com/SquidDev-CC/CC-Tweaked/issues'
}
licenses {
license {
name 'ComputerCraft Public License, Version 1.0'
url 'https://github.com/SquidDev-CC/CC-Tweaked/blob/master/LICENSE'
distribution 'repo'
}
}
}
pom.whenConfigured { pom ->
pom.dependencies.clear()
if (project.hasProperty("mavenUser")) {
maven {
name = "SquidDev"
url = "https://squiddev.cc/maven"
credentials {
username = project.property("mavenUser") as String
password = project.property("mavenPass") as String
}
}
}
@@ -620,22 +611,27 @@ githubRelease {
token project.hasProperty('githubApiKey') ? project.githubApiKey : ''
owner 'SquidDev-CC'
repo 'CC-Tweaked'
try {
targetCommitish = Grgit.open(dir: '.').branch.current().name
} catch(Exception ignored) { }
targetCommitish.set(project.provider({
try {
return ["git", "-C", projectDir, "rev-parse", "--abbrev-ref", "HEAD"].execute().text.trim()
} catch (Exception e) {
e.printStackTrace()
}
return "master"
}))
tagName "v${mc_version}-${mod_version}"
releaseName "[${mc_version}] ${mod_version}"
body {
body.set(project.provider({
"## " + new File(projectDir, "src/main/resources/data/computercraft/lua/rom/help/whatsnew.txt")
.readLines()
.takeWhile { it != 'Type "help changelog" to see the full version history.' }
.join("\n").trim()
}
}))
prerelease false
}
def uploadTasks = ["uploadArchives", "curseforge", "githubRelease"]
def uploadTasks = ["publish", "curseforge", "githubRelease"]
uploadTasks.forEach { tasks.getByName(it).dependsOn checkRelease }
task uploadAll(dependsOn: uploadTasks) {

View File

@@ -2488,4 +2488,4 @@
</option>
</inspection_tool>
</profile>
</component>
</component>

View File

@@ -58,4 +58,4 @@
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</code_scheme>

View File

@@ -0,0 +1,55 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-merge-conflict
# Quick syntax checkers
- id: check-xml
- id: check-yaml
- id: check-toml
- id: check-json
exclude: "tsconfig\\.json$"
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
rev: 2.3.5
hooks:
- id: editorconfig-checker
args: ['-disable-indentation']
exclude: "^(.*\\.(bat)|LICENSE)$"
- repo: local
hooks:
- id: checkstyle
name: Check Java codestyle
files: ".*\\.java$"
language: system
entry: ./gradlew checkstyleMain checkstyleTest
pass_filenames: false
require_serial: true
- id: license
name: Check Java license headers
files: ".*\\.java$"
language: system
entry: ./gradlew licenseFormat
pass_filenames: false
require_serial: true
- id: illuaminate
name: Check Lua code
files: ".*\\.(lua|java|md)"
language: script
entry: config/pre-commit/illuaminate-lint.sh
pass_filenames: false
require_serial: true
exclude: |
(?x)^(
src/generated|
src/test/resources/test-rom/data/json-parsing/|
src/test/server-files/|
config/idea/
)

View File

@@ -0,0 +1,16 @@
#!/usr/bin/env sh
set -e
test -d bin || mkdir bin
test -f bin/illuaminate || curl -s -obin/illuaminate https://squiddev.cc/illuaminate/linux-x86-64/illuaminate
chmod +x bin/illuaminate
if [ -n ${GITHUB_ACTIONS+x} ]; then
# Register a problem matcher (see https://github.com/actions/toolkit/blob/master/docs/problem-matchers.md)
# for illuaminate.
echo "::add-matcher::.github/matchers/illuaminate.json"
trap 'echo "::remove-matcher owner=illuaminate::"' EXIT
fi
./gradlew luaJavadoc
bin/illuaminate lint

21
doc/events/alarm.md Normal file
View File

@@ -0,0 +1,21 @@
---
module: [kind=event] alarm
see: os.setAlarm To start an alarm.
---
The @{timer} event is fired when an alarm started with @{os.setAlarm} completes.
## Return Values
1. @{string}: The event name.
2. @{number}: The ID of the alarm that finished.
## Example
Starts a timer and then prints its ID:
```lua
local alarmID = os.setAlarm(os.time() + 0.05)
local event, id
repeat
event, id = os.pullEvent("alarm")
until id == alarmID
print("Alarm with ID " .. id .. " was fired")
```

View File

@@ -0,0 +1,18 @@
---
module: [kind=event] computer_command
---
The @{computer_command} event is fired when the `/computercraft queue` command is run for the current computer.
## Return Values
1. @{string}: The event name.
... @{string}: The arguments passed to the command.
## Example
Prints the contents of messages sent:
```lua
while true do
local event = {os.pullEvent("computer_command")}
print("Received message:", table.unpack(event, 2))
end
```

19
doc/events/disk.md Normal file
View File

@@ -0,0 +1,19 @@
---
module: [kind=event] disk
see: disk_eject For the event sent when a disk is removed.
---
The @{disk} event is fired when a disk is inserted into an adjacent or networked disk drive.
## Return Values
1. @{string}: The event name.
2. @{string}: The side of the disk drive that had a disk inserted.
## Example
Prints a message when a disk is inserted:
```lua
while true do
local event, side = os.pullEvent("disk")
print("Inserted a disk on side " .. side)
end
```

19
doc/events/disk_eject.md Normal file
View File

@@ -0,0 +1,19 @@
---
module: [kind=event] disk_eject
see: disk For the event sent when a disk is inserted.
---
The @{disk_eject} event is fired when a disk is removed from an adjacent or networked disk drive.
## Return Values
1. @{string}: The event name.
2. @{string}: The side of the disk drive that had a disk removed.
## Example
Prints a message when a disk is removed:
```lua
while true do
local event, side = os.pullEvent("disk_eject")
print("Removed a disk on side " .. side)
end
```

14
doc/events/http_check.md Normal file
View File

@@ -0,0 +1,14 @@
---
module: [kind=event] http_check
see: http.checkURLAsync To check a URL asynchronously.
---
The @{http_check} event is fired when a URL check finishes.
This event is normally handled inside @{http.checkURL}, but it can still be seen when using @{http.checkURLAsync}.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL requested to be checked.
3. @{boolean}: Whether the check succeeded.
4. @{string|nil}: If the check failed, a reason explaining why the check failed.

View File

@@ -0,0 +1,39 @@
---
module: [kind=event] http_failure
see: http.request To send an HTTP request.
---
The @{http_failure} event is fired when an HTTP request fails.
This event is normally handled inside @{http.get} and @{http.post}, but it can still be seen when using @{http.request}.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the site requested.
3. @{string}: An error describing the failure.
4. @{http.Response|nil}: A response handle if the connection succeeded, but the server's response indicated failure.
## Example
Prints an error why the website cannot be contacted:
```lua
local myURL = "https://does.not.exist.tweaked.cc"
http.request(myURL)
local event, url, err
repeat
event, url, err = os.pullEvent("http_failure")
until url == myURL
print("The URL " .. url .. " could not be reached: " .. err)
```
Prints the contents of a webpage that does not exist:
```lua
local myURL = "https://tweaked.cc/this/does/not/exist"
http.request(myURL)
local event, url, err, handle
repeat
event, url, err, handle = os.pullEvent("http_failure")
until url == myURL
print("The URL " .. url .. " could not be reached: " .. err)
print(handle.getResponseCode())
handle.close()
```

View File

@@ -0,0 +1,27 @@
---
module: [kind=event] http_success
see: http.request To make an HTTP request.
---
The @{http_success} event is fired when an HTTP request returns successfully.
This event is normally handled inside @{http.get} and @{http.post}, but it can still be seen when using @{http.request}.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the site requested.
3. @{http.Response}: The handle for the response text.
## Example
Prints the content of a website (this may fail if the request fails):
```lua
local myURL = "https://tweaked.cc/"
http.request(myURL)
local event, url, handle
repeat
event, url, handle = os.pullEvent("http_success")
until url == myURL
print("Contents of " .. url .. ":")
print(handle.readAll())
handle.close()
```

View File

@@ -11,16 +11,16 @@ If the button pressed represented a printable character, then the @{key} event w
event. If you are consuming text input, use a @{char} event instead!
## Return values
1. [`string`]: The event name.
2. [`number`]: The numerical key value of the key pressed.
3. [`boolean`]: Whether the key event was generated while holding the key (@{true}), rather than pressing it the first time (@{false}).
1. @{string}: The event name.
2. @{number}: The numerical key value of the key pressed.
3. @{boolean}: Whether the key event was generated while holding the key (@{true}), rather than pressing it the first time (@{false}).
## Example
Prints each key when the user presses it, and if the key is being held.
```lua
while true do
local event, key, is_held = os.pullEvent("key")
local event, key, is_held = os.pullEvent("key")
print(("%s held=%s"):format(keys.getName(key), is_held))
end
```

View File

@@ -0,0 +1,22 @@
---
module: [kind=event] modem_message
---
The @{modem_message} event is fired when a message is received on an open channel on any modem.
## Return Values
1. @{string}: The event name.
2. @{string}: The side of the modem that received the message.
3. @{number}: The channel that the message was sent on.
4. @{number}: The reply channel set by the sender.
5. @{any}: The message as sent by the sender.
6. @{number}: The distance between the sender and the receiver, in blocks (decimal).
## Example
Prints a message when one is sent:
```lua
while true do
local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
print(("Message received on side %s on channel %d (reply to %d) from %f blocks away with message %s"):format(side, channel, replyChannel, distance, tostring(message)))
end
```

View File

@@ -0,0 +1,18 @@
---
module: [kind=event] monitor_resize
---
The @{monitor_resize} event is fired when an adjacent or networked monitor's size is changed.
## Return Values
1. @{string}: The event name.
2. @{string}: The side or network ID of the monitor that resized.
## Example
Prints a message when a monitor is resized:
```lua
while true do
local event, side = os.pullEvent("monitor_resize")
print("The monitor on side " .. side .. " was resized.")
end
```

View File

@@ -0,0 +1,20 @@
---
module: [kind=event] monitor_touch
---
The @{monitor_touch} event is fired when an adjacent or networked Advanced Monitor is right-clicked.
## Return Values
1. @{string}: The event name.
2. @{string}: The side or network ID of the monitor that was touched.
3. @{number}: The X coordinate of the touch, in characters.
4. @{number}: The Y coordinate of the touch, in characters.
## Example
Prints a message when a monitor is touched:
```lua
while true do
local event, side, x, y = os.pullEvent("monitor_touch")
print("The monitor on side " .. side .. " was touched at (" .. x .. ", " .. y .. ")")
end
```

View File

@@ -20,5 +20,3 @@ while true do
print(("The mouse button %s was dragged at %d, %d"):format(button, x, y))
end
```

View File

@@ -19,6 +19,3 @@ while true do
print(("The mouse button %s was released at %d, %d"):format(button, x, y))
end
```
[`string`]: string
[`number`]: number

18
doc/events/paste.md Normal file
View File

@@ -0,0 +1,18 @@
---
module: [kind=event] paste
---
The @{paste} event is fired when text is pasted into the computer through Ctrl-V (or ⌘V on Mac).
## Return values
1. @{string}: The event name.
2. @{string} The text that was pasted.
## Example
Prints pasted text:
```lua
while true do
local event, text = os.pullEvent("paste")
print('"' .. text .. '" was pasted')
end
```

19
doc/events/peripheral.md Normal file
View File

@@ -0,0 +1,19 @@
---
module: [kind=event] peripheral
see: peripheral_detach For the event fired when a peripheral is detached.
---
The @{peripheral} event is fired when a peripheral is attached on a side or to a modem.
## Return Values
1. @{string}: The event name.
2. @{string}: The side the peripheral was attached to.
## Example
Prints a message when a peripheral is attached:
```lua
while true do
local event, side = os.pullEvent("peripheral")
print("A peripheral was attached on side " .. side)
end
```

View File

@@ -0,0 +1,19 @@
---
module: [kind=event] peripheral_detach
see: peripheral For the event fired when a peripheral is attached.
---
The @{peripheral_detach} event is fired when a peripheral is detached from a side or from a modem.
## Return Values
1. @{string}: The event name.
2. @{string}: The side the peripheral was detached from.
## Example
Prints a message when a peripheral is detached:
```lua
while true do
local event, side = os.pullEvent("peripheral_detach")
print("A peripheral was detached on side " .. side)
end
```

View File

@@ -0,0 +1,30 @@
---
module: [kind=event] rednet_message
see: modem_message For raw modem messages sent outside of Rednet.
see: rednet.receive To wait for a Rednet message with an optional timeout and protocol filter.
---
The @{rednet_message} event is fired when a message is sent over Rednet.
This event is usually handled by @{rednet.receive}, but it can also be pulled manually.
@{rednet_message} events are sent by @{rednet.run} in the top-level coroutine in response to @{modem_message} events. A @{rednet_message} event is always preceded by a @{modem_message} event. They are generated inside CraftOS rather than being sent by the ComputerCraft machine.
## Return Values
1. @{string}: The event name.
2. @{number}: The ID of the sending computer.
3. @{any}: The message sent.
4. @{string|nil}: The protocol of the message, if provided.
## Example
Prints a message when one is sent:
```lua
while true do
local event, sender, message, protocol = os.pullEvent("rednet_message")
if protocol ~= nil then
print("Received message from " .. sender .. " with protocol " .. protocol .. " and message " .. tostring(message))
else
print("Received message from " .. sender .. " with message " .. tostring(message))
end
end
```

14
doc/events/redstone.md Normal file
View File

@@ -0,0 +1,14 @@
---
module: [kind=event] redstone
---
The @{redstone} event is fired whenever any redstone inputs on the computer change.
## Example
Prints a message when a redstone input changes:
```lua
while true do
os.pullEvent("redstone")
print("A redstone input has changed!")
end
```

View File

@@ -0,0 +1,28 @@
---
module: [kind=event] task_complete
see: commands.execAsync To run a command which fires a task_complete event.
---
The @{task_complete} event is fired when an asynchronous task completes. This is usually handled inside the function call that queued the task; however, functions such as @{commands.execAsync} return immediately so the user can wait for completion.
## Return Values
1. @{string}: The event name.
2. @{number}: The ID of the task that completed.
3. @{boolean}: Whether the command succeeded.
4. @{string}: If the command failed, an error message explaining the failure. (This is not present if the command succeeded.)
...: Any parameters returned from the command.
## Example
Prints the results of an asynchronous command:
```lua
local taskID = commands.execAsync("say Hello")
local event
repeat
event = {os.pullEvent("task_complete")}
until event[2] == taskID
if event[3] == true then
print("Task " .. event[2] .. " succeeded:", table.unpack(event, 4))
else
print("Task " .. event[2] .. " failed: " .. event[4])
end
```

15
doc/events/term_resize.md Normal file
View File

@@ -0,0 +1,15 @@
---
module: [kind=event] term_resize
---
The @{term_resize} event is fired when the main terminal is resized, mainly when a new tab is opened or closed in @{multishell}.
## Example
Prints :
```lua
while true do
os.pullEvent("term_resize")
local w, h = term.getSize()
print("The term was resized to (" .. w .. ", " .. h .. ")")
end
```

25
doc/events/terminate.md Normal file
View File

@@ -0,0 +1,25 @@
---
module: [kind=event] terminate
---
The @{terminate} event is fired when <kbd>Ctrl-T</kbd> is held down.
This event is normally handled by @{os.pullEvent}, and will not be returned. However, @{os.pullEventRaw} will return this event when fired.
@{terminate} will be sent even when a filter is provided to @{os.pullEventRaw}. When using @{os.pullEventRaw} with a filter, make sure to check that the event is not @{terminate}.
## Example
Prints a message when Ctrl-T is held:
```lua
while true do
local event = os.pullEventRaw("terminate")
if event == "terminate" then print("Terminate requested!") end
end
```
Exits when Ctrl-T is held:
```lua
while true do
os.pullEvent()
end
```

21
doc/events/timer.md Normal file
View File

@@ -0,0 +1,21 @@
---
module: [kind=event] timer
see: os.startTimer To start a timer.
---
The @{timer} event is fired when a timer started with @{os.startTimer} completes.
## Return Values
1. @{string}: The event name.
2. @{number}: The ID of the timer that finished.
## Example
Starts a timer and then prints its ID:
```lua
local timerID = os.startTimer(2)
local event, id
repeat
event, id = os.pullEvent("timer")
until id == timerID
print("Timer with ID " .. id .. " was fired")
```

View File

@@ -0,0 +1,14 @@
---
module: [kind=event] turtle_inventory
---
The @{turtle_inventory} event is fired when a turtle's inventory is changed.
## Example
Prints a message when the inventory is changed:
```lua
while true do
os.pullEvent("turtle_inventory")
print("The inventory was changed.")
end
```

View File

@@ -0,0 +1,21 @@
---
module: [kind=event] websocket_closed
---
The @{websocket_closed} event is fired when an open WebSocket connection is closed.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the WebSocket that was closed.
## Example
Prints a message when a WebSocket is closed (this may take a minute):
```lua
local myURL = "wss://example.tweaked.cc/echo"
local ws = http.websocket(myURL)
local event, url
repeat
event, url = os.pullEvent("websocket_closed")
until url == myURL
print("The WebSocket at " .. url .. " was closed.")
```

View File

@@ -0,0 +1,25 @@
---
module: [kind=event] websocket_failure
see: http.websocketAsync To send an HTTP request.
---
The @{websocket_failure} event is fired when a WebSocket connection request fails.
This event is normally handled inside @{http.websocket}, but it can still be seen when using @{http.websocketAsync}.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the site requested.
3. @{string}: An error describing the failure.
## Example
Prints an error why the website cannot be contacted:
```lua
local myURL = "wss://example.tweaked.cc/not-a-websocket"
http.websocketAsync(myURL)
local event, url, err
repeat
event, url, err = os.pullEvent("websocket_failure")
until url == myURL
print("The URL " .. url .. " could not be reached: " .. err)
```

View File

@@ -0,0 +1,26 @@
---
module: [kind=event] websocket_message
---
The @{websocket_message} event is fired when a message is received on an open WebSocket connection.
This event is normally handled by @{http.Websocket.receive}, but it can also be pulled manually.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the WebSocket.
3. @{string}: The contents of the message.
## Example
Prints a message sent by a WebSocket:
```lua
local myURL = "wss://example.tweaked.cc/echo"
local ws = http.websocket(myURL)
ws.send("Hello!")
local event, url, message
repeat
event, url, message = os.pullEvent("websocket_message")
until url == myURL
print("Received message from " .. url .. " with contents " .. message)
ws.close()
```

View File

@@ -0,0 +1,28 @@
---
module: [kind=event] websocket_success
see: http.websocketAsync To open a WebSocket asynchronously.
---
The @{websocket_success} event is fired when a WebSocket connection request returns successfully.
This event is normally handled inside @{http.websocket}, but it can still be seen when using @{http.websocketAsync}.
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the site.
3. @{http.Websocket}: The handle for the WebSocket.
## Example
Prints the content of a website (this may fail if the request fails):
```lua
local myURL = "wss://example.tweaked.cc/echo"
http.websocketAsync(myURL)
local event, url, handle
repeat
event, url, handle = os.pullEvent("websocket_success")
until url == myURL
print("Connected to " .. url)
handle.send("Hello!")
print(handle.receive())
handle.close()
```

View File

@@ -58,10 +58,10 @@ function request(...) end
-- @treturn string A message detailing why the request failed.
-- @treturn Response|nil The failing http response, if available.
--
-- @usage Make a request to [example.computercraft.cc](https://example.computercraft.cc),
-- @usage Make a request to [example.tweaked.cc](https://example.tweaked.cc),
-- and print the returned page.
-- ```lua
-- local request = http.get("https://example.computercraft.cc")
-- local request = http.get("https://example.tweaked.cc")
-- print(request.readAll())
-- -- => HTTP is working!
-- request.close()
@@ -123,7 +123,7 @@ function checkURLAsync(url) end
--
-- @usage
-- ```lua
-- print(http.checkURL("https://example.computercraft.cc/"))
-- print(http.checkURL("https://example.tweaked.cc/"))
-- -- => true
-- print(http.checkURL("http://localhost/"))
-- -- => false Domain not permitted

View File

@@ -1 +1,13 @@
--[[- Craft a recipe based on the turtle's inventory.
The turtle's inventory should set up like a crafting grid. For instance, to
craft sticks, slots 1 and 5 should contain sticks. _All_ other slots should be
empty, including those outside the crafting "grid".
@tparam[opt=64] number limit The maximum number of crafting steps to run.
@throws When limit is less than 1 or greater than 64.
@treturn[1] true If crafting succeeds.
@treturn[2] false If crafting fails.
@treturn string A string describing why crafting failed.
]]
function craft(limit) end

View File

@@ -1,5 +1,5 @@
# Mod properties
mod_version=1.95.2
mod_version=1.96.0
# Minecraft properties (update mods.toml when changing)
mc_version=1.16.4

Binary file not shown.

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

53
gradlew vendored
View File

@@ -1,5 +1,21 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
@@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -66,6 +82,7 @@ esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
@@ -109,10 +126,11 @@ if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
@@ -138,19 +156,19 @@ if $cygwin ; then
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
i=`expr $i + 1`
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
@@ -159,14 +177,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

43
gradlew.bat vendored
View File

@@ -1,3 +1,19 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@@ -13,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -35,7 +54,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@@ -45,28 +64,14 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell

View File

@@ -88,27 +88,16 @@
;; Suppress warnings for currently undocumented modules.
(at
(; Java APIs
/doc/stub/http.lua
/doc/stub/os.lua
/doc/stub/turtle.lua
/doc/stub/global.lua
; Java generated APIs
/build/docs/luaJavadoc/turtle.lua
; Peripherals
/build/docs/luaJavadoc/drive.lua
/build/docs/luaJavadoc/speaker.lua
/build/docs/luaJavadoc/printer.lua
; Generic peripherals
/build/docs/luaJavadoc/fluid_storage.lua
; Lua APIs
(; Lua APIs
/src/main/resources/*/computercraft/lua/rom/apis/io.lua
/src/main/resources/*/computercraft/lua/rom/apis/window.lua)
(linters -doc:undocumented -doc:undocumented-arg -doc:undocumented-return))
;; Suppress warnings for the BIOS using its own deprecated members for now.
(at /src/main/resources/*/computercraft/lua/bios.lua
;; Suppress warnings for various APIs using its own deprecated members.
(at
(/src/main/resources/*/computercraft/lua/bios.lua
/src/main/resources/*/computercraft/lua/rom/apis/turtle/turtle.lua)
(linters -var:deprecated))
(at /src/test/resources/test-rom

View File

@@ -8,7 +8,6 @@ package dan200.computercraft;
import dan200.computercraft.api.turtle.event.TurtleAction;
import dan200.computercraft.core.apis.http.options.Action;
import dan200.computercraft.core.apis.http.options.AddressRule;
import dan200.computercraft.core.asm.GenericSource;
import dan200.computercraft.shared.Config;
import dan200.computercraft.shared.Registry;
import dan200.computercraft.shared.computer.core.ClientComputerRegistry;
@@ -17,7 +16,6 @@ import dan200.computercraft.shared.peripheral.monitor.MonitorRenderer;
import dan200.computercraft.shared.pocket.peripherals.PocketModem;
import dan200.computercraft.shared.pocket.peripherals.PocketSpeaker;
import dan200.computercraft.shared.turtle.upgrades.*;
import dan200.computercraft.shared.util.ServiceUtil;
import net.minecraftforge.fml.common.Mod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -117,6 +115,5 @@ public final class ComputerCraft
{
Config.setup();
Registry.setup();
GenericSource.setup( () -> ServiceUtil.loadServicesForge( GenericSource.class ) );
}
}

View File

@@ -8,6 +8,7 @@ package dan200.computercraft;
import dan200.computercraft.api.ComputerCraftAPI.IComputerCraftAPI;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.ILuaAPIFactory;
import dan200.computercraft.api.media.IMediaProvider;
import dan200.computercraft.api.network.IPacketNetwork;
@@ -18,9 +19,11 @@ import dan200.computercraft.api.pocket.IPocketUpgrade;
import dan200.computercraft.api.redstone.IBundledRedstoneProvider;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.core.apis.ApiFactories;
import dan200.computercraft.core.asm.GenericMethod;
import dan200.computercraft.core.filesystem.FileMount;
import dan200.computercraft.core.filesystem.ResourceMount;
import dan200.computercraft.shared.*;
import dan200.computercraft.shared.peripheral.generic.GenericPeripheralProvider;
import dan200.computercraft.shared.peripheral.modem.wireless.WirelessNetwork;
import dan200.computercraft.shared.util.IDAssigner;
import dan200.computercraft.shared.wired.WiredNode;
@@ -31,6 +34,7 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
@@ -108,6 +112,18 @@ public final class ComputerCraftAPIImpl implements IComputerCraftAPI
Peripherals.register( provider );
}
@Override
public void registerGenericSource( @Nonnull GenericSource source )
{
GenericMethod.register( source );
}
@Override
public void registerGenericCapability( @Nonnull Capability<?> capability )
{
GenericPeripheralProvider.addCapability( capability );
}
@Override
public void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade )
{

View File

@@ -7,6 +7,7 @@ package dan200.computercraft.api;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.api.filesystem.IWritableMount;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.ILuaAPIFactory;
import dan200.computercraft.api.media.IMedia;
import dan200.computercraft.api.media.IMediaProvider;
@@ -23,6 +24,7 @@ import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
@@ -98,7 +100,9 @@ public final class ComputerCraftAPI
* resource folder onto a computer's file system.
*
* The files in this mount will be a combination of files in all mod jar, and data packs that contain
* resources with the same domain and path.
* resources with the same domain and path. For instance, ComputerCraft's resources are stored in
* "/data/computercraft/lua/rom". We construct a mount for that with
* {@code createResourceMount("computercraft", "lua/rom")}.
*
* @param domain The domain under which to look for resources. eg: "mymod".
* @param subPath The subPath under which to look for resources. eg: "lua/myfiles".
@@ -114,7 +118,7 @@ public final class ComputerCraftAPI
}
/**
* Registers a peripheral provider to convert blocks into {@link IPeripheral} implementations.
* rers a peripheral provider to convert blocks into {@link IPeripheral} implementations.
*
* @param provider The peripheral provider to register.
* @see IPeripheral
@@ -125,6 +129,28 @@ public final class ComputerCraftAPI
getInstance().registerPeripheralProvider( provider );
}
/**
* Registers a method source for generic peripherals.
*
* @param source The method source to register.
* @see GenericSource
*/
public static void registerGenericSource( @Nonnull GenericSource source )
{
getInstance().registerGenericSource( source );
}
/**
* Registers a capability that can be used by generic peripherals.
*
* @param capability The capability to register.
* @see GenericSource
*/
public static void registerGenericCapability( @Nonnull Capability<?> capability )
{
getInstance().registerGenericCapability( capability );
}
/**
* Registers a new turtle turtle for use in ComputerCraft. After calling this,
* users should be able to craft Turtles with your new turtle. It is recommended to call
@@ -256,6 +282,10 @@ public final class ComputerCraftAPI
void registerPeripheralProvider( @Nonnull IPeripheralProvider provider );
void registerGenericSource( @Nonnull GenericSource source );
void registerGenericCapability( @Nonnull Capability<?> capability );
void registerTurtleUpgrade( @Nonnull ITurtleUpgrade upgrade );
void registerBundledRedstoneProvider( @Nonnull IBundledRedstoneProvider provider );

View File

@@ -0,0 +1,60 @@
/*
* This file is part of the public ComputerCraft API - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2021. This API may be redistributed unmodified and in full only.
* For help using the API, and posting your mods, visit the forums at computercraft.info.
*/
package dan200.computercraft.api.lua;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.peripheral.IPeripheralProvider;
import dan200.computercraft.core.asm.LuaMethod;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.IItemHandler;
import javax.annotation.Nonnull;
/**
* A generic source of {@link LuaMethod} functions.
*
* Unlike normal objects ({@link IDynamicLuaObject} or {@link IPeripheral}), methods do not target this object but
* instead are defined as {@code static} and accept their target as the first parameter. This allows you to inject
* methods onto objects you do not own, as well as declaring methods for a specific "trait" (for instance, a
* {@link Capability}).
*
* Currently the "generic peripheral" system is incompatible with normal peripherals. Normal {@link IPeripheralProvider}
* or {@link IPeripheral} implementations take priority. Tile entities which use this system are given a peripheral name
* determined by their id, rather than any peripheral provider. This will hopefully change in the future, once a suitable
* design has been established.
*
* For example, the main CC: Tweaked mod defines a generic source for inventories, which works on {@link IItemHandler}s:
*
* <pre>{@code
* public class InventoryMethods implements GenericSource {
* \@LuaFunction( mainThread = true )
* public static int size(IItemHandler inventory) {
* return inventory.getSlots();
* }
*
* // ...
* }
* }</pre>
*
* @see ComputerCraftAPI#registerGenericSource(GenericSource)
* @see ComputerCraftAPI#registerGenericCapability(Capability) New capabilities (those not built into Forge) must be
* explicitly given to the generic peripheral system, as there is no way to enumerate all capabilities.
*/
public interface GenericSource
{
/**
* A unique identifier for this generic source.
*
* This is currently unused, but may be used in the future to allow disabling specific sources. It is recommended
* to return an identifier using your mod's ID.
*
* @return This source's identifier.
*/
@Nonnull
ResourceLocation id();
}

View File

@@ -47,7 +47,10 @@ public class ComputerBorderRenderer
private static final int CORNER_LEFT_X = BORDER;
private static final int CORNER_RIGHT_X = CORNER_LEFT_X + BORDER;
private static final int BORDER_RIGHT_X = 36;
private static final int GAP = 4;
private static final int LIGHT_BORDER_Y = 56;
private static final int LIGHT_CORNER_Y = 80;
public static final int LIGHT_HEIGHT = 8;
private static final float TEX_SCALE = 1 / 256.0f;
@@ -101,15 +104,15 @@ public class ComputerBorderRenderer
public static void render( Matrix4f transform, IVertexBuilder buffer, int x, int y, int z, int width, int height, float r, float g, float b )
{
render( transform, buffer, x, y, z, width, height, 0, r, g, b );
render( transform, buffer, x, y, z, width, height, false, r, g, b );
}
public static void render( Matrix4f transform, IVertexBuilder buffer, int x, int y, int z, int width, int height, int borderHeight, float r, float g, float b )
public static void render( Matrix4f transform, IVertexBuilder buffer, int x, int y, int z, int width, int height, boolean withLight, float r, float g, float b )
{
new ComputerBorderRenderer( transform, buffer, z, r, g, b ).doRender( x, y, width, height, borderHeight );
new ComputerBorderRenderer( transform, buffer, z, r, g, b ).doRender( x, y, width, height, withLight );
}
public void doRender( int x, int y, int width, int height, int bottomHeight )
public void doRender( int x, int y, int width, int height, boolean withLight )
{
int endX = x + width;
int endY = y + height;
@@ -125,28 +128,18 @@ public class ComputerBorderRenderer
// Bottom bar. We allow for drawing a stretched version, which allows for additional elements (such as the
// pocket computer's lights).
if( bottomHeight <= 0 )
if( withLight )
{
renderTexture( x, endY, 0, LIGHT_BORDER_Y, endX - x, BORDER + LIGHT_HEIGHT, BORDER, BORDER + LIGHT_HEIGHT );
renderTexture( x - BORDER, endY, CORNER_LEFT_X, LIGHT_CORNER_Y, BORDER, BORDER + LIGHT_HEIGHT );
renderTexture( endX, endY, CORNER_RIGHT_X, LIGHT_CORNER_Y, BORDER, BORDER + LIGHT_HEIGHT );
}
else
{
renderLine( x, endY, 0, BORDER, endX - x, BORDER );
renderCorner( x - BORDER, endY, CORNER_LEFT_X, CORNER_BOTTOM_Y );
renderCorner( endX, endY, CORNER_RIGHT_X, CORNER_BOTTOM_Y );
}
else
{
// 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( x - BORDER, endY, CORNER_LEFT_X, CORNER_BOTTOM_Y, BORDER, BORDER / 2 );
renderTexture( x, endY, 0, BORDER, width, BORDER / 2, BORDER, BORDER / 2 );
renderTexture( endX, endY, CORNER_RIGHT_X, CORNER_BOTTOM_Y, BORDER, BORDER / 2 );
renderTexture( x - BORDER, endY + BORDER / 2, CORNER_LEFT_X, CORNER_BOTTOM_Y + GAP, BORDER, bottomHeight, BORDER, GAP );
renderTexture( x, endY + BORDER / 2, 0, BORDER + GAP, width, bottomHeight, BORDER, GAP );
renderTexture( endX, endY + BORDER / 2, CORNER_RIGHT_X, CORNER_BOTTOM_Y + GAP, BORDER, bottomHeight, BORDER, GAP );
renderTexture( x - BORDER, endY + bottomHeight + BORDER / 2, CORNER_LEFT_X, CORNER_BOTTOM_Y + BORDER / 2, BORDER, BORDER / 2 );
renderTexture( x, endY + bottomHeight + BORDER / 2, 0, BORDER + BORDER / 2, width, BORDER / 2 );
renderTexture( endX, endY + bottomHeight + BORDER / 2, CORNER_RIGHT_X, CORNER_BOTTOM_Y + BORDER / 2, BORDER, BORDER / 2 );
}
}
private void renderCorner( int x, int y, int u, int v )

View File

@@ -30,8 +30,7 @@ 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.render.ComputerBorderRenderer.BORDER;
import static dan200.computercraft.client.render.ComputerBorderRenderer.MARGIN;
import static dan200.computercraft.client.render.ComputerBorderRenderer.*;
/**
* Emulates map rendering for pocket computers.
@@ -39,8 +38,6 @@ import static dan200.computercraft.client.render.ComputerBorderRenderer.MARGIN;
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID, value = Dist.CLIENT )
public final class ItemPocketRenderer extends ItemMapLikeRenderer
{
private static final int LIGHT_HEIGHT = 8;
private static final ItemPocketRenderer INSTANCE = new ItemPocketRenderer();
private ItemPocketRenderer()
@@ -131,7 +128,7 @@ public final class ItemPocketRenderer extends ItemMapLikeRenderer
BufferBuilder buffer = tessellator.getBuilder();
buffer.begin( GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR_TEX );
ComputerBorderRenderer.render( transform, buffer, 0, 0, 0, width, height, LIGHT_HEIGHT, r, g, b );
ComputerBorderRenderer.render( transform, buffer, 0, 0, 0, width, height, true, r, g, b );
tessellator.end();
}

View File

@@ -14,6 +14,7 @@ import dan200.computercraft.core.apis.http.*;
import dan200.computercraft.core.apis.http.request.HttpRequest;
import dan200.computercraft.core.apis.http.websocket.Websocket;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
@@ -179,7 +180,7 @@ public class HTTPAPI implements ILuaAPI
}
@Nonnull
private static HttpHeaders getHeaders( @Nonnull Map<?, ?> headerTable ) throws LuaException
private HttpHeaders getHeaders( @Nonnull Map<?, ?> headerTable ) throws LuaException
{
HttpHeaders headers = new DefaultHttpHeaders();
for( Map.Entry<?, ?> entry : headerTable.entrySet() )
@@ -197,6 +198,11 @@ public class HTTPAPI implements ILuaAPI
}
}
}
if( !headers.contains( HttpHeaderNames.USER_AGENT ) )
{
headers.set( HttpHeaderNames.USER_AGENT, apiEnvironment.getComputerEnvironment().getUserAgent() );
}
return headers;
}
}

View File

@@ -89,7 +89,7 @@ final class LuaDateTime
formatter.appendValue( ChronoField.HOUR_OF_DAY, 2 );
break;
case 'I':
formatter.appendValue( ChronoField.HOUR_OF_AMPM );
formatter.appendValue( ChronoField.HOUR_OF_AMPM, 2 );
break;
case 'j':
formatter.appendValue( ChronoField.DAY_OF_YEAR, 3 );

View File

@@ -191,7 +191,7 @@ public class RedstoneAPI implements ILuaAPI
@LuaFunction
public final int getBundledInput( ComputerSide side )
{
return environment.getBundledOutput( side );
return environment.getBundledInput( side );
}
/**

View File

@@ -80,10 +80,6 @@ public final class HttpRequestHandler extends SimpleChannelInboundHandler<HttpOb
{
request.headers().set( HttpHeaderNames.ACCEPT_CHARSET, "UTF-8" );
}
if( !request.headers().contains( HttpHeaderNames.USER_AGENT ) )
{
request.headers().set( HttpHeaderNames.USER_AGENT, this.request.environment().getComputerEnvironment().getUserAgent() );
}
request.headers().set( HttpHeaderNames.HOST, uri.getPort() < 0 ? uri.getHost() : uri.getHost() + ":" + uri.getPort() );
request.headers().set( HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE );

View File

@@ -58,10 +58,10 @@ public class HttpResponseHandle implements ObjectSource
* If multiple headers are sent with the same name, they will be combined with a comma.
*
* @return The response's headers.
* @cc.usage Make a request to [example.computercraft.cc](https://example.computercraft.cc), and print the
* @cc.usage Make a request to [example.tweaked.cc](https://example.tweaked.cc), and print the
* returned headers.
* <pre>{@code
* local request = http.get("https://example.computercraft.cc")
* local request = http.get("https://example.tweaked.cc")
* print(textutils.serialize(request.getResponseHeaders()))
* -- => {
* -- [ "Content-Type" ] = "text/plain; charset=utf8",

View File

@@ -11,10 +11,7 @@ import com.google.common.cache.LoadingCache;
import com.google.common.primitives.Primitives;
import com.google.common.reflect.TypeToken;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.IArguments;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.lua.MethodResult;
import dan200.computercraft.api.lua.*;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
@@ -111,7 +108,7 @@ public final class Generator<T>
addMethod( methods, method, annotation, instance );
}
for( GenericSource.GenericMethod method : GenericSource.GenericMethod.all() )
for( GenericMethod method : GenericMethod.all() )
{
if( !method.target.isAssignableFrom( klass ) ) continue;

View File

@@ -0,0 +1,90 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.asm;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.LuaFunction;
import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* A generic method is a method belonging to a {@link GenericSource} with a known target.
*/
public class GenericMethod
{
final Method method;
final LuaFunction annotation;
final Class<?> target;
private static final List<GenericSource> sources = new ArrayList<>();
private static List<GenericMethod> cache;
GenericMethod( Method method, LuaFunction annotation, Class<?> target )
{
this.method = method;
this.annotation = annotation;
this.target = target;
}
/**
* Find all public static methods annotated with {@link LuaFunction} which belong to a {@link GenericSource}.
*
* @return All available generic methods.
*/
static List<GenericMethod> all()
{
if( cache != null ) return cache;
return cache = sources.stream()
.flatMap( x -> Arrays.stream( x.getClass().getDeclaredMethods() ) )
.map( method ->
{
LuaFunction annotation = method.getAnnotation( LuaFunction.class );
if( annotation == null ) return null;
if( !Modifier.isStatic( method.getModifiers() ) )
{
ComputerCraft.log.error( "GenericSource method {}.{} should be static.", method.getDeclaringClass(), method.getName() );
return null;
}
Type[] types = method.getGenericParameterTypes();
if( types.length == 0 )
{
ComputerCraft.log.error( "GenericSource method {}.{} has no parameters.", method.getDeclaringClass(), method.getName() );
return null;
}
Class<?> target = Reflect.getRawType( method, types[0], false );
if( target == null ) return null;
return new GenericMethod( method, annotation, target );
} )
.filter( Objects::nonNull )
.collect( Collectors.toList() );
}
public static synchronized void register( @Nonnull GenericSource source )
{
Objects.requireNonNull( source, "Source cannot be null" );
if( cache != null )
{
ComputerCraft.log.warn( "Registering a generic source {} after cache has been built. This source will be ignored.", cache );
}
sources.add( source );
}
}

View File

@@ -1,120 +0,0 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.core.asm;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.shared.peripheral.generic.GenericPeripheralProvider;
import dan200.computercraft.shared.util.ServiceUtil;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A generic source of {@link LuaMethod} functions. This allows for injecting methods onto objects you do not own.
*
* Unlike conventional Lua objects, the annotated methods should be {@code static}, with their target as the first
* parameter.
*
* This is used by the generic peripheral system ({@link GenericPeripheralProvider}) to provide methods for arbitrary
* tile entities. Eventually this'll be be exposed in the public API. Until it is stabilised, it will remain in this
* package - do not use it in external mods!
*/
public interface GenericSource
{
/**
* A unique identifier for this generic source. This may be used in the future to allow disabling specific sources.
*
* @return This source's identifier.
*/
@Nonnull
ResourceLocation id();
/**
* Register a stream of generic sources.
*
* @param sources The source of generic methods.
* @see ServiceUtil For ways to load this. Sadly {@link java.util.ServiceLoader} is broken under Forge, but we don't
* want to add a hard-dep on Forge within core either.
*/
static void setup( Supplier<Stream<GenericSource>> sources )
{
GenericMethod.sources = sources;
}
/**
* A generic method is a method belonging to a {@link GenericSource} with a known target.
*/
class GenericMethod
{
final Method method;
final LuaFunction annotation;
final Class<?> target;
static Supplier<Stream<GenericSource>> sources;
private static List<GenericMethod> cache;
GenericMethod( Method method, LuaFunction annotation, Class<?> target )
{
this.method = method;
this.annotation = annotation;
this.target = target;
}
/**
* Find all public static methods annotated with {@link LuaFunction} which belong to a {@link GenericSource}.
*
* @return All available generic methods.
*/
static List<GenericMethod> all()
{
if( cache != null ) return cache;
if( sources == null )
{
ComputerCraft.log.warn( "Getting GenericMethods without a provider" );
return cache = Collections.emptyList();
}
return cache = sources.get()
.flatMap( x -> Arrays.stream( x.getClass().getDeclaredMethods() ) )
.map( method ->
{
LuaFunction annotation = method.getAnnotation( LuaFunction.class );
if( annotation == null ) return null;
if( !Modifier.isStatic( method.getModifiers() ) )
{
ComputerCraft.log.error( "GenericSource method {}.{} should be static.", method.getDeclaringClass(), method.getName() );
return null;
}
Type[] types = method.getGenericParameterTypes();
if( types.length == 0 )
{
ComputerCraft.log.error( "GenericSource method {}.{} has no parameters.", method.getDeclaringClass(), method.getName() );
return null;
}
Class<?> target = Reflect.getRawType( method, types[0], false );
if( target == null ) return null;
return new GenericMethod( method, annotation, target );
} )
.filter( Objects::nonNull )
.collect( Collectors.toList() );
}
}
}

View File

@@ -12,6 +12,7 @@ import com.google.common.io.ByteStreams;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.filesystem.IMount;
import dan200.computercraft.core.apis.handles.ArrayByteChannel;
import dan200.computercraft.shared.util.IoUtil;
import net.minecraft.resources.IReloadableResourceManager;
import net.minecraft.resources.IResource;
import net.minecraft.resources.IResourceManager;
@@ -103,9 +104,13 @@ public final class ResourceMount implements IMount
private void load()
{
boolean hasAny = false;
String existingNamespace = null;
FileEntry newRoot = new FileEntry( new ResourceLocation( namespace, subPath ) );
for( ResourceLocation file : manager.listResources( subPath, s -> true ) )
{
existingNamespace = file.getNamespace();
if( !file.getNamespace().equals( namespace ) ) continue;
String localPath = FileSystem.toLocal( file.getPath(), subPath );
@@ -114,6 +119,15 @@ public final class ResourceMount implements IMount
}
root = hasAny ? newRoot : null;
if( !hasAny )
{
ComputerCraft.log.warn( "Cannot find any files under /data/{}/{} for resource mount.", namespace, subPath );
if( existingNamespace != null )
{
ComputerCraft.log.warn( "There are files under /data/{}/{} though. Did you get the wrong namespace?", existingNamespace, subPath );
}
}
}
private FileEntry get( String path )
@@ -231,11 +245,20 @@ public final class ResourceMount implements IMount
byte[] contents = CONTENTS_CACHE.getIfPresent( file );
if( contents != null ) return new ArrayByteChannel( contents );
try( InputStream stream = manager.getResource( file.identifier ).getInputStream() )
try
{
InputStream stream = manager.getResource( file.identifier ).getInputStream();
if( stream.available() > MAX_CACHED_SIZE ) return Channels.newChannel( stream );
contents = ByteStreams.toByteArray( stream );
try
{
contents = ByteStreams.toByteArray( stream );
}
finally
{
IoUtil.closeQuietly( stream );
}
CONTENTS_CACHE.put( file, contents );
return new ArrayByteChannel( contents );
}

View File

@@ -12,46 +12,12 @@ public class TextBuffer
public TextBuffer( char c, int length )
{
text = new char[length];
for( int i = 0; i < length; i++ )
{
text[i] = c;
}
this.fill( c );
}
public TextBuffer( String text )
{
this( text, 1 );
}
public TextBuffer( String text, int repetitions )
{
int textLength = text.length();
this.text = new char[textLength * repetitions];
for( int i = 0; i < repetitions; i++ )
{
for( int j = 0; j < textLength; j++ )
{
this.text[j + i * textLength] = text.charAt( j );
}
}
}
public TextBuffer( TextBuffer text )
{
this( text, 1 );
}
public TextBuffer( TextBuffer text, int repetitions )
{
int textLength = text.length();
this.text = new char[textLength * repetitions];
for( int i = 0; i < repetitions; i++ )
{
for( int j = 0; j < textLength; j++ )
{
this.text[j + i * textLength] = text.charAt( j );
}
}
this.text = text.toCharArray();
}
public int length()
@@ -59,39 +25,16 @@ public class TextBuffer
return text.length;
}
public String read()
{
return read( 0, text.length );
}
public String read( int start )
{
return read( start, text.length );
}
public String read( int start, int end )
{
start = Math.max( start, 0 );
end = Math.min( end, text.length );
int textLength = Math.max( end - start, 0 );
return new String( text, start, textLength );
}
public void write( String text )
{
write( text, 0, text.length() );
write( text, 0 );
}
public void write( String text, int start )
{
write( text, start, start + text.length() );
}
public void write( String text, int start, int end )
{
int pos = start;
start = Math.max( start, 0 );
end = Math.min( end, pos + text.length() );
int end = Math.min( start + text.length(), pos + text.length() );
end = Math.min( end, this.text.length );
for( int i = start; i < end; i++ )
{
@@ -101,23 +44,10 @@ public class TextBuffer
public void write( TextBuffer text )
{
write( text, 0, text.length() );
}
public void write( TextBuffer text, int start )
{
write( text, start, start + text.length() );
}
public void write( TextBuffer text, int start, int end )
{
int pos = start;
start = Math.max( start, 0 );
end = Math.min( end, pos + text.length() );
end = Math.min( end, this.text.length );
for( int i = start; i < end; i++ )
int end = Math.min( text.length(), this.text.length );
for( int i = 0; i < end; i++ )
{
this.text[i] = text.charAt( i - pos );
this.text[i] = text.charAt( i );
}
}
@@ -126,11 +56,6 @@ public class TextBuffer
fill( c, 0, text.length );
}
public void fill( char c, int start )
{
fill( c, start, text.length );
}
public void fill( char c, int start, int end )
{
start = Math.max( start, 0 );
@@ -141,52 +66,6 @@ public class TextBuffer
}
}
public void fill( String text )
{
fill( text, 0, this.text.length );
}
public void fill( String text, int start )
{
fill( text, start, this.text.length );
}
public void fill( String text, int start, int end )
{
int pos = start;
start = Math.max( start, 0 );
end = Math.min( end, this.text.length );
int textLength = text.length();
for( int i = start; i < end; i++ )
{
this.text[i] = text.charAt( (i - pos) % textLength );
}
}
public void fill( TextBuffer text )
{
fill( text, 0, this.text.length );
}
public void fill( TextBuffer text, int start )
{
fill( text, start, this.text.length );
}
public void fill( TextBuffer text, int start, int end )
{
int pos = start;
start = Math.max( start, 0 );
end = Math.min( end, this.text.length );
int textLength = text.length();
for( int i = start; i < end; i++ )
{
this.text[i] = text.charAt( (i - pos) % textLength );
}
}
public char charAt( int i )
{
return text[i];

View File

@@ -22,14 +22,12 @@ import javax.annotation.Nonnull;
public class BlockModelProvider extends BlockStateProvider
{
private final ModelFile monitorBase;
private final ModelFile orientable;
private ModelFile monitorBase;
private ModelFile orientable;
public BlockModelProvider( DataGenerator generator, ExistingFileHelper existingFileHelper )
{
super( generator, ComputerCraft.MOD_ID, existingFileHelper );
monitorBase = models().getExistingFile( new ResourceLocation( ComputerCraft.MOD_ID, "block/monitor_base" ) );
orientable = models().getExistingFile( new ResourceLocation( "block/orientable" ) );
}
@Nonnull
@@ -42,6 +40,9 @@ public class BlockModelProvider extends BlockStateProvider
@Override
protected void registerStatesAndModels()
{
monitorBase = models().getExistingFile( new ResourceLocation( ComputerCraft.MOD_ID, "block/monitor_base" ) );
orientable = models().getExistingFile( new ResourceLocation( "block/orientable" ) );
registerMonitors( Registry.ModBlocks.MONITOR_NORMAL.get() );
registerMonitors( Registry.ModBlocks.MONITOR_ADVANCED.get() );

View File

@@ -246,7 +246,7 @@ public final class Registry
{
// Upgrades
ComputerCraft.TurtleUpgrades.wirelessModemNormal = new TurtleModem( false, new ResourceLocation( ComputerCraft.MOD_ID, "wireless_modem_normal" ) );
TurtleUpgrades.register( ComputerCraft.TurtleUpgrades.wirelessModemNormal );
ComputerCraftAPI.registerTurtleUpgrade( ComputerCraft.TurtleUpgrades.wirelessModemNormal );
ComputerCraft.TurtleUpgrades.wirelessModemAdvanced = new TurtleModem( true, new ResourceLocation( ComputerCraft.MOD_ID, "wireless_modem_advanced" ) );
ComputerCraftAPI.registerTurtleUpgrade( ComputerCraft.TurtleUpgrades.wirelessModemAdvanced );

View File

@@ -79,7 +79,10 @@ public final class ColourableRecipe extends SpecialRecipe
}
if( colourable.isEmpty() ) return ItemStack.EMPTY;
return ((IColouredItem) colourable.getItem()).withColour( colourable, tracker.getColour() );
ItemStack stack = ((IColouredItem) colourable.getItem()).withColour( colourable, tracker.getColour() );
stack.setCount( 1 );
return stack;
}
@Override

View File

@@ -114,10 +114,10 @@ public class JEIComputerCraft implements IModPlugin
*/
private static final ISubtypeInterpreter turtleSubtype = stack -> {
Item item = stack.getItem();
if( !(item instanceof ITurtleItem) ) return "";
if( !(item instanceof ITurtleItem) ) return ISubtypeInterpreter.NONE;
ITurtleItem turtle = (ITurtleItem) item;
StringBuilder name = new StringBuilder();
StringBuilder name = new StringBuilder( "turtle:" );
// Add left and right upgrades to the identifier
ITurtleUpgrade left = turtle.getUpgrade( stack, TurtleSide.LEFT );
@@ -134,9 +134,9 @@ public class JEIComputerCraft implements IModPlugin
*/
private static final ISubtypeInterpreter pocketSubtype = stack -> {
Item item = stack.getItem();
if( !(item instanceof ItemPocketComputer) ) return "";
if( !(item instanceof ItemPocketComputer) ) return ISubtypeInterpreter.NONE;
StringBuilder name = new StringBuilder();
StringBuilder name = new StringBuilder( "pocket:" );
// Add the upgrade to the identifier
IPocketUpgrade upgrade = ItemPocketComputer.getUpgrade( stack );
@@ -150,11 +150,11 @@ public class JEIComputerCraft implements IModPlugin
*/
private static final ISubtypeInterpreter diskSubtype = stack -> {
Item item = stack.getItem();
if( !(item instanceof ItemDisk) ) return "";
if( !(item instanceof ItemDisk) ) return ISubtypeInterpreter.NONE;
ItemDisk disk = (ItemDisk) item;
int colour = disk.getColour( stack );
return colour == -1 ? "" : String.format( "%06x", colour );
return colour == -1 ? ISubtypeInterpreter.NONE : String.format( "%06x", colour );
};
}

View File

@@ -200,7 +200,7 @@ class RecipeResolver implements IRecipeManagerPlugin
for( UpgradeInfo upgrade : upgrades )
{
ItemStack craftingStack = upgrade.stack;
if( !craftingStack.isEmpty() && craftingStack.getItem() == stack.getItem() && upgrade.upgrade.isItemSuitable( stack ) )
if( craftingStack.isEmpty() || craftingStack.getItem() != stack.getItem() || !upgrade.upgrade.isItemSuitable( stack ) )
{
continue;
}
@@ -319,13 +319,6 @@ class RecipeResolver implements IRecipeManagerPlugin
super( ID, null, width, height, input, output );
}
@Nonnull
@Override
public ResourceLocation getId()
{
return null;
}
@Nonnull
@Override
public IRecipeSerializer<?> getSerializer()

View File

@@ -52,7 +52,7 @@ public final class RecordMedia implements IMedia
try
{
return ObfuscationReflectionHelper.getPrivateValue( MusicDiscItem.class, (MusicDiscItem) item, "sound" );
return ObfuscationReflectionHelper.getPrivateValue( MusicDiscItem.class, (MusicDiscItem) item, "field_185076_b" );
}
catch( UnableToAccessFieldException | UnableToFindFieldException e )
{

View File

@@ -15,22 +15,22 @@ import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.common.util.NonNullConsumer;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.items.CapabilityItemHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class GenericPeripheralProvider
{
private static final Capability<?>[] CAPABILITIES = new Capability<?>[] {
CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
CapabilityEnergy.ENERGY,
CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY,
};
private static final ArrayList<Capability<?>> capabilities = new ArrayList<>();
public static synchronized void addCapability( Capability<?> capability )
{
Objects.requireNonNull( capability, "Capability cannot be null" );
if( !capabilities.contains( capability ) ) capabilities.add( capability );
}
@Nullable
public static IPeripheral getPeripheral( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side, NonNullConsumer<LazyOptional<IPeripheral>> invalidate )
@@ -43,7 +43,7 @@ public class GenericPeripheralProvider
List<NamedMethod<PeripheralMethod>> tileMethods = PeripheralMethod.GENERATOR.getMethods( tile.getClass() );
if( !tileMethods.isEmpty() ) addSaturated( saturated, tile, tileMethods );
for( Capability<?> capability : CAPABILITIES )
for( Capability<?> capability : capabilities )
{
LazyOptional<?> wrapper = tile.getCapability( capability );
wrapper.ifPresent( contents -> {

View File

@@ -5,12 +5,11 @@
*/
package dan200.computercraft.shared.peripheral.generic.methods;
import com.google.auto.service.AutoService;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.core.asm.GenericSource;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.versions.forge.ForgeVersion;
import javax.annotation.Nonnull;
@@ -26,14 +25,13 @@ import javax.annotation.Nonnull;
*
* @cc.module energy_storage
*/
@AutoService( GenericSource.class )
public class EnergyMethods implements GenericSource
{
@Nonnull
@Override
public ResourceLocation id()
{
return new ResourceLocation( ForgeVersion.MOD_ID, "energy" );
return new ResourceLocation( ComputerCraft.MOD_ID, "energy" );
}
/**

View File

@@ -5,12 +5,12 @@
*/
package dan200.computercraft.shared.peripheral.generic.methods;
import com.google.auto.service.AutoService;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.core.asm.GenericSource;
import dan200.computercraft.shared.peripheral.generic.data.FluidData;
import net.minecraft.fluid.Fluid;
import net.minecraft.util.ResourceLocation;
@@ -20,7 +20,6 @@ import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.versions.forge.ForgeVersion;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -35,16 +34,28 @@ import static dan200.computercraft.shared.peripheral.generic.methods.ArgumentHel
*
* @cc.module fluid_storage
*/
@AutoService( GenericSource.class )
public class FluidMethods implements GenericSource
{
@Nonnull
@Override
public ResourceLocation id()
{
return new ResourceLocation( ForgeVersion.MOD_ID, "fluid" );
return new ResourceLocation( ComputerCraft.MOD_ID, "fluid" );
}
/**
* Get all "tanks" in this fluid storage.
*
* Each tank either contains some amount of fluid or is empty. Tanks with fluids inside will return some basic
* information about the fluid, including its name and amount.
*
* The returned table is sparse, and so empty tanks will be `nil` - it is recommended to loop over using `pairs`
* rather than `ipairs`.
*
* @param fluids The current fluid handler.
* @return All tanks.
* @cc.treturn { (table|nil)... } All tanks in this fluid storage.
*/
@LuaFunction( mainThread = true )
public static Map<Integer, Map<String, ?>> tanks( IFluidHandler fluids )
{
@@ -59,6 +70,22 @@ public class FluidMethods implements GenericSource
return result;
}
/**
* Move a fluid from one fluid container to another connected one.
*
* This allows you to pull fluid in the current fluid container to another container <em>on the same wired
* network</em>. Both containers must attached to wired modems which are connected via a cable.
*
* @param from Container to move fluid from.
* @param computer The current computer.
* @param toName The name of the peripheral/container to push to. This is the string given to @{peripheral.wrap},
* and displayed by the wired modem.
* @param limit The maximum amount of fluid to move.
* @param fluidName The fluid to move. If not given, an arbitrary fluid will be chosen.
* @return The amount of moved fluid.
* @throws LuaException If the peripheral to transfer to doesn't exist or isn't an fluid container.
* @cc.see peripheral.getName Allows you to get the name of a @{peripheral.wrap|wrapped} peripheral.
*/
@LuaFunction( mainThread = true )
public static int pushFluid(
IFluidHandler from, IComputerAccess computer,
@@ -84,6 +111,22 @@ public class FluidMethods implements GenericSource
: moveFluid( from, new FluidStack( fluid, actualLimit ), to );
}
/**
* Move a fluid from a connected fluid container into this oneone.
*
* This allows you to pull fluid in the current fluid container from another container <em>on the same wired
* network</em>. Both containers must attached to wired modems which are connected via a cable.
*
* @param to Container to move fluid to.
* @param computer The current computer.
* @param fromName The name of the peripheral/container to push to. This is the string given to @{peripheral.wrap},
* and displayed by the wired modem.
* @param limit The maximum amount of fluid to move.
* @param fluidName The fluid to move. If not given, an arbitrary fluid will be chosen.
* @return The amount of moved fluid.
* @throws LuaException If the peripheral to transfer to doesn't exist or isn't an fluid container.
* @cc.see peripheral.getName Allows you to get the name of a @{peripheral.wrap|wrapped} peripheral.
*/
@LuaFunction( mainThread = true )
public static int pullFluid(
IFluidHandler to, IComputerAccess computer,

View File

@@ -5,12 +5,12 @@
*/
package dan200.computercraft.shared.peripheral.generic.methods;
import com.google.auto.service.AutoService;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.lua.GenericSource;
import dan200.computercraft.api.lua.LuaException;
import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.core.asm.GenericSource;
import dan200.computercraft.shared.peripheral.generic.data.ItemData;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
@@ -21,7 +21,6 @@ import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.items.wrapper.InvWrapper;
import net.minecraftforge.versions.forge.ForgeVersion;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -36,14 +35,13 @@ import static dan200.computercraft.shared.peripheral.generic.methods.ArgumentHel
*
* @cc.module inventory
*/
@AutoService( GenericSource.class )
public class InventoryMethods implements GenericSource
{
@Nonnull
@Override
public ResourceLocation id()
{
return new ResourceLocation( ForgeVersion.MOD_ID, "inventory" );
return new ResourceLocation( ComputerCraft.MOD_ID, "inventory" );
}
/**
@@ -63,14 +61,23 @@ public class InventoryMethods implements GenericSource
*
* Each item in the inventory is represented by a table containing some basic information, much like
* {@link dan200.computercraft.shared.turtle.apis.TurtleAPI#getItemDetail} includes. More information can be fetched
* with {@link #getItemDetail}.
* with {@link #getItemDetail}. The table contains the item `name`, the `count` and an a (potentially nil) hash of
* the item's `nbt.` This NBT data doesn't contain anything useful, but allows you to distinguish identical items.
*
* The table is sparse, and so empty slots will be `nil` - it is recommended to loop over using `pairs` rather than
* `ipairs`.
* The returned table is sparse, and so empty slots will be `nil` - it is recommended to loop over using `pairs`
* rather than `ipairs`.
*
* @param inventory The current inventory.
* @return All items in this inventory.
* @cc.treturn { (table|nil)... } All items in this inventory.
* @cc.usage Find an adjacent chest and print all items in it.
*
* <pre>{@code
* local chest = peripheral.find("minecraft:chest")
* for slot, item in pairs(chest.list()) do
* print(("%d x %s in slot %d"):format(item.count, item.name, slot))
* end
* }</pre>
*/
@LuaFunction( mainThread = true )
public static Map<Integer, Map<String, ?>> list( IItemHandler inventory )
@@ -89,11 +96,32 @@ public class InventoryMethods implements GenericSource
/**
* Get detailed information about an item.
*
* The returned information contains the same information as each item in
* {@link #list}, as well as additional details like the display name
* (`displayName`) and item durability (`damage`, `maxDamage`, `durability`).
*
* Some items include more information (such as enchantments) - it is
* recommended to print it out using @{textutils.serialize} or in the Lua
* REPL, to explore what is available.
*
* @param inventory The current inventory.
* @param slot The slot to get information about.
* @return Information about the item in this slot, or {@code nil} if not present.
* @throws LuaException If the slot is out of range.
* @cc.treturn table Information about the item in this slot, or {@code nil} if not present.
* @cc.usage Print some information about the first in a chest.
*
* <pre>{@code
* local chest = peripheral.find("minecraft:chest")
* local item = chest.getItemDetail(1)
* if not item then print("No item") return end
*
* print(("%s (%s)"):format(item.displayName, item.name))
* print(("Count: %d/%d"):format(item.count, item.maxCount))
* if item.damage then
* print(("Damage: %d/%d"):format(item.damage, item.maxDamage))
* end
* }</pre>
*/
@Nullable
@LuaFunction( mainThread = true )
@@ -105,6 +133,33 @@ public class InventoryMethods implements GenericSource
return stack.isEmpty() ? null : ItemData.fill( new HashMap<>(), stack );
}
/**
* Get the maximum number of items which can be stored in this slot.
*
* Typically this will be limited to 64 items. However, some inventories (such as barrels or caches) can store
* hundreds or thousands of items in one slot.
*
* @param inventory Inventory to probe.
* @param slot The slot
* @return The maximum number of items in this slot.
* @throws LuaException If the slot is out of range.
* @cc.usage Count the maximum number of items an adjacent chest can hold.
* <pre>{@code
* local chest = peripheral.find("minecraft:chest")
* local total = 0
* for i = 1, chest.size() do
* total = total + chest.getItemLimit(i)
* end
* print(total)
* }</pre>
*/
@LuaFunction( mainThread = true )
public static int getItemLimit( IItemHandler inventory, int slot ) throws LuaException
{
assertBetween( slot, 1, inventory.getSlots(), "Slot out of range (%s)" );
return inventory.getSlotLimit( slot );
}
/**
* Push items from one inventory to another connected one.
*

View File

@@ -20,6 +20,7 @@ import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.RegistryObject;
import javax.annotation.Nonnull;
@@ -85,9 +86,14 @@ public class BlockMonitor extends BlockGeneric
if( entity instanceof TileMonitor && !world.isClientSide )
{
TileMonitor monitor = (TileMonitor) entity;
monitor.contractNeighbours();
monitor.contract();
monitor.expand();
// Defer the block update if we're being placed by another TE. See #691
if ( livingEntity == null || livingEntity instanceof FakePlayer )
{
monitor.updateNeighborsDeferred();
return;
}
monitor.updateNeighbors();
}
}
}

View File

@@ -9,6 +9,7 @@ import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.network.NetworkHandler;
import dan200.computercraft.shared.network.client.MonitorClientMessage;
import dan200.computercraft.shared.network.client.TerminalState;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
@@ -28,6 +29,7 @@ import java.util.Queue;
public final class MonitorWatcher
{
private static final Queue<TileMonitor> watching = new ArrayDeque<>();
private static final Queue<PlayerUpdate> playerUpdates = new ArrayDeque<>();
private MonitorWatcher()
{
@@ -58,10 +60,8 @@ public final class MonitorWatcher
ServerMonitor serverMonitor = getMonitor( monitor );
if( serverMonitor == null || monitor.enqueued ) continue;
// We use the cached terminal state if available - this is guaranteed to
TerminalState state = monitor.cached;
if( state == null ) state = monitor.cached = serverMonitor.write();
NetworkHandler.sendToPlayer( event.getPlayer(), new MonitorClientMessage( monitor.getBlockPos(), state ) );
// The chunk hasn't been sent to the client yet, so we can't send an update. Do it on tick end.
playerUpdates.add( new PlayerUpdate( event.getPlayer(), monitor ) );
}
}
@@ -70,6 +70,23 @@ public final class MonitorWatcher
{
if( event.phase != TickEvent.Phase.END ) return;
PlayerUpdate playerUpdate;
while( (playerUpdate = playerUpdates.poll()) != null )
{
TileMonitor tile = playerUpdate.monitor;
if( tile.enqueued || tile.isRemoved() ) continue;
ServerMonitor monitor = getMonitor( tile );
if( monitor == null ) continue;
// Some basic sanity checks to the player. It's possible they're no longer within range, but that's harder
// to track efficiently.
ServerPlayerEntity player = playerUpdate.player;
if( !player.isAlive() || player.getLevel() != tile.getLevel() ) continue;
NetworkHandler.sendToPlayer( playerUpdate.player, new MonitorClientMessage( tile.getBlockPos(), getState( tile, monitor ) ) );
}
long limit = ComputerCraft.monitorBandwidth;
boolean obeyLimit = limit > 0;
@@ -90,7 +107,7 @@ public final class MonitorWatcher
continue;
}
TerminalState state = tile.cached = monitor.write();
TerminalState state = getState( tile, monitor );
NetworkHandler.sendToAllTracking( new MonitorClientMessage( pos, state ), chunk );
limit -= state.size();
@@ -101,4 +118,23 @@ public final class MonitorWatcher
{
return !monitor.isRemoved() && monitor.getXIndex() == 0 && monitor.getYIndex() == 0 ? monitor.getCachedServerMonitor() : null;
}
private static TerminalState getState( TileMonitor tile, ServerMonitor monitor )
{
TerminalState state = tile.cached;
if( state == null ) state = tile.cached = monitor.write();
return state;
}
private static final class PlayerUpdate
{
final ServerPlayerEntity player;
final TileMonitor monitor;
private PlayerUpdate( ServerPlayerEntity player, TileMonitor monitor )
{
this.player = player;
this.monitor = monitor;
}
}
}

View File

@@ -55,6 +55,7 @@ public class TileMonitor extends TileGeneric
private LazyOptional<IPeripheral> peripheralCap;
private final Set<IComputerAccess> computers = new HashSet<>();
private boolean needsUpdate = false;
private boolean destroyed = false;
private boolean visiting = false;
@@ -148,6 +149,12 @@ public class TileMonitor extends TileGeneric
@Override
public void blockTick()
{
if ( needsUpdate )
{
needsUpdate = false;
updateNeighbors();
}
if( xIndex != 0 || yIndex != 0 || serverMonitor == null ) return;
serverMonitor.clearChanged();
@@ -526,6 +533,18 @@ public class TileMonitor extends TileGeneric
return true;
}
void updateNeighborsDeferred()
{
needsUpdate = true;
}
void updateNeighbors()
{
contractNeighbours();
contract();
expand();
}
@SuppressWarnings( "StatementWithEmptyBody" )
void expand()
{

View File

@@ -23,6 +23,9 @@ import dan200.computercraft.shared.data.HasComputerIdLootCondition;
import dan200.computercraft.shared.data.PlayerCreativeLootCondition;
import dan200.computercraft.shared.media.items.RecordMedia;
import dan200.computercraft.shared.network.NetworkHandler;
import dan200.computercraft.shared.peripheral.generic.methods.EnergyMethods;
import dan200.computercraft.shared.peripheral.generic.methods.FluidMethods;
import dan200.computercraft.shared.peripheral.generic.methods.InventoryMethods;
import dan200.computercraft.shared.peripheral.modem.wireless.WirelessNetwork;
import dan200.computercraft.shared.util.NullStorage;
import net.minecraft.inventory.container.Container;
@@ -32,15 +35,19 @@ import net.minecraft.loot.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.event.LootTableLoadEvent;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fml.DeferredWorkQueue;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.server.FMLServerStartedEvent;
import net.minecraftforge.fml.event.server.FMLServerStoppedEvent;
import net.minecraftforge.items.CapabilityItemHandler;
import java.util.Arrays;
import java.util.HashSet;
@@ -55,11 +62,15 @@ public final class ComputerCraftProxyCommon
{
NetworkHandler.setup();
net.minecraftforge.fml.DeferredWorkQueue.runLater( () -> {
DeferredWorkQueue.runLater( () -> {
registerProviders();
ArgumentSerializers.register();
registerLoot();
} );
ComputerCraftAPI.registerGenericSource( new InventoryMethods() );
ComputerCraftAPI.registerGenericSource( new FluidMethods() );
ComputerCraftAPI.registerGenericSource( new EnergyMethods() );
}
public static void registerLoot()
@@ -90,6 +101,12 @@ public final class ComputerCraftProxyCommon
// Register capabilities
CapabilityManager.INSTANCE.register( IWiredElement.class, new NullStorage<>(), () -> null );
CapabilityManager.INSTANCE.register( IPeripheral.class, new NullStorage<>(), () -> null );
// Register generic capabilities. This can technically be done off-thread, but we need it to happen
// after Forge's common setup, so this is easiest.
ComputerCraftAPI.registerGenericCapability( CapabilityItemHandler.ITEM_HANDLER_CAPABILITY );
ComputerCraftAPI.registerGenericCapability( CapabilityEnergy.ENERGY );
ComputerCraftAPI.registerGenericCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY );
}
@Mod.EventBusSubscriber( modid = ComputerCraft.MOD_ID )

View File

@@ -16,6 +16,7 @@ import dan200.computercraft.core.apis.IAPIEnvironment;
import dan200.computercraft.core.asm.TaskCallback;
import dan200.computercraft.core.tracking.TrackingField;
import dan200.computercraft.shared.peripheral.generic.data.ItemData;
import dan200.computercraft.shared.peripheral.generic.methods.InventoryMethods;
import dan200.computercraft.shared.turtle.core.*;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
@@ -182,6 +183,10 @@ public class TurtleAPI implements ILuaAPI
/**
* Place a block or item into the world in front of the turtle.
*
* "Placing" an item allows it to interact with blocks and entities in front of the turtle. For instance, buckets
* can pick up and place down fluids, and wheat can be used to breed cows. However, you cannot use {@link #place} to
* perform arbitrary block interactions, such as clicking buttons or flipping levers.
*
* @param args Arguments to place.
* @return The turtle command result.
* @cc.tparam [opt] string text When placing a sign, set its contents to this text.
@@ -202,6 +207,7 @@ public class TurtleAPI implements ILuaAPI
* @cc.tparam [opt] string text When placing a sign, set its contents to this text.
* @cc.treturn boolean Whether the block could be placed.
* @cc.treturn string|nil The reason the block was not placed.
* @see #place For more information about placing items.
*/
@LuaFunction
public final MethodResult placeUp( IArguments args )
@@ -217,6 +223,7 @@ public class TurtleAPI implements ILuaAPI
* @cc.tparam [opt] string text When placing a sign, set its contents to this text.
* @cc.treturn boolean Whether the block could be placed.
* @cc.treturn string|nil The reason the block was not placed.
* @see #place For more information about placing items.
*/
@LuaFunction
public final MethodResult placeDown( IArguments args )
@@ -365,18 +372,36 @@ public class TurtleAPI implements ILuaAPI
return trackCommand( new TurtleDetectCommand( InteractDirection.DOWN ) );
}
/**
* Check if the block in front of the turtle is equal to the item in the currently selected slot.
*
* @return If the block and item are equal.
* @cc.treturn boolean If the block and item are equal.
*/
@LuaFunction
public final MethodResult compare()
{
return trackCommand( new TurtleCompareCommand( InteractDirection.FORWARD ) );
}
/**
* Check if the block above the turtle is equal to the item in the currently selected slot.
*
* @return If the block and item are equal.
* @cc.treturn boolean If the block and item are equal.
*/
@LuaFunction
public final MethodResult compareUp()
{
return trackCommand( new TurtleCompareCommand( InteractDirection.UP ) );
}
/**
* Check if the block below the turtle is equal to the item in the currently selected slot.
*
* @return If the block and item are equal.
* @cc.treturn boolean If the block and item are equal.
*/
@LuaFunction
public final MethodResult compareDown()
{
@@ -472,12 +497,57 @@ public class TurtleAPI implements ILuaAPI
return trackCommand( new TurtleSuckCommand( InteractDirection.DOWN, checkCount( count ) ) );
}
/**
* Get the maximum amount of fuel this turtle currently holds.
*
* @return The fuel level, or "unlimited".
* @cc.treturn [1] number The current amount of fuel a turtle this turtle has.
* @cc.treturn [2] "unlimited" If turtles do not consume fuel when moving.
* @see #getFuelLimit()
* @see #refuel(Optional)
*/
@LuaFunction
public final Object getFuelLevel()
{
return turtle.isFuelNeeded() ? turtle.getFuelLevel() : "unlimited";
}
/**
* Refuel this turtle.
*
* While most actions a turtle can perform (such as digging or placing blocks), moving consumes fuel from the
* turtle's internal buffer. If a turtle has no fuel, it will not move.
*
* {@link #refuel} refuels the turtle, consuming fuel items (such as coal or lava buckets) from the currently
* selected slot and converting them into energy. This finishes once the turtle is fully refuelled or all items have
* been consumed.
*
* @param countA The maximum number of items to consume. One can pass `0` to check if an item is combustable or not.
* @return If this turtle could be refuelled.
* @throws LuaException If the refuel count is out of range.
* @cc.treturn [1] true If the turtle was refuelled.
* @cc.treturn [2] false If the turtle was not refuelled.
* @cc.treturn [2] string The reason the turtle was not refuelled (
* @cc.usage Refuel a turtle from the currently selected slot.
* <pre>{@code
* local level = turtle.getFuelLevel()
* if new_level == "unlimited" then error("Turtle does not need fuel", 0) end
*
* local ok, err = turtle.refuel()
* if ok then
* local new_level = turtle.getFuelLevel()
* print(("Refuelled %d, current level is %d"):format(new_level - level, new_level))
* else
* printError(err)
* end}</pre>
* @cc.usage Check if the current item is a valid fuel source.
* <pre>{@code
* local is_fuel, reason = turtle.refuel(0)
* if not is_fuel then printError(reason) end
* }</pre>
* @see #getFuelLevel()
* @see #getFuelLimit()
*/
@LuaFunction
public final MethodResult refuel( Optional<Integer> countA ) throws LuaException
{
@@ -486,12 +556,30 @@ public class TurtleAPI implements ILuaAPI
return trackCommand( new TurtleRefuelCommand( count ) );
}
/**
* Compare the item in the currently selected slot to the item in another slot.
*
* @param slot The slot to compare to.
* @return If the items are the same.
* @throws LuaException If the slot is out of range.
* @cc.treturn boolean If the two items are equal.
*/
@LuaFunction
public final MethodResult compareTo( int slot ) throws LuaException
{
return trackCommand( new TurtleCompareToCommand( checkSlot( slot ) ) );
}
/**
* Move an item from the selected slot to another one.
*
* @param slotArg The slot to move this item to.
* @param countArg The maximum number of items to move.
* @return If the item was moved or not.
* @throws LuaException If the slot is out of range.
* @throws LuaException If the number of items is out of range.
* @cc.treturn boolean If some items were successfully moved.
*/
@LuaFunction
public final MethodResult transferTo( int slotArg, Optional<Integer> countArg ) throws LuaException
{
@@ -512,18 +600,55 @@ public class TurtleAPI implements ILuaAPI
return turtle.getSelectedSlot() + 1;
}
/**
* Get the maximum amount of fuel this turtle can hold.
*
* By default, normal turtles have a limit of 20,000 and advanced turtles of 100,000.
*
* @return The limit, or "unlimited".
* @cc.treturn [1] number The maximum amount of fuel a turtle can hold.
* @cc.treturn [2] "unlimited" If turtles do not consume fuel when moving.
* @see #getFuelLevel()
* @see #refuel(Optional)
*/
@LuaFunction
public final Object getFuelLimit()
{
return turtle.isFuelNeeded() ? turtle.getFuelLimit() : "unlimited";
}
/**
* Equip (or unequip) an item on the left side of this turtle.
*
* This finds the item in the currently selected slot and attempts to equip it to the left side of the turtle. The
* previous upgrade is removed and placed into the turtle's inventory. If there is no item in the slot, the previous
* upgrade is removed, but no new one is equipped.
*
* @return Whether an item was equiped or not.
* @cc.treturn [1] true If the item was equipped.
* @cc.treturn [2] false If we could not equip the item.
* @cc.treturn [2] string The reason equipping this item failed.
* @see #equipRight()
*/
@LuaFunction
public final MethodResult equipLeft()
{
return trackCommand( new TurtleEquipCommand( TurtleSide.LEFT ) );
}
/**
* Equip (or unequip) an item on the right side of this turtle.
*
* This finds the item in the currently selected slot and attempts to equip it to the right side of the turtle. The
* previous upgrade is removed and placed into the turtle's inventory. If there is no item in the slot, the previous
* upgrade is removed, but no new one is equipped.
*
* @return Whether an item was equiped or not.
* @cc.treturn [1] true If the item was equipped.
* @cc.treturn [2] false If we could not equip the item.
* @cc.treturn [2] string The reason equipping this item failed.
* @see #equipRight()
*/
@LuaFunction
public final MethodResult equipRight()
{
@@ -536,6 +661,18 @@ public class TurtleAPI implements ILuaAPI
* @return The turtle command result.
* @cc.treturn boolean Whether there is a block in front of the turtle.
* @cc.treturn table|string Information about the block in front, or a message explaining that there is no block.
* @cc.usage <pre>{@code
* local has_block, data = turtle.inspect()
* if has_block then
* print(textutils.serialize(data))
* -- {
* -- name = "minecraft:oak_log",
* -- state = { axis = "x" },
* -- tags = { ["minecraft:logs"] = true, ... },
* -- }
* else
* print("No block in front of the turtle")
* end}</pre>
*/
@LuaFunction
public final MethodResult inspect()
@@ -578,6 +715,7 @@ public class TurtleAPI implements ILuaAPI
* more information about the item at the cost of taking longer to run.
* @return The command result.
* @throws LuaException If the slot is out of range.
* @see InventoryMethods#getItemDetail Describes the information returned by a detailed query.
* @cc.treturn nil|table Information about the given slot, or {@code nil} if it is empty.
* @cc.usage Print the current slot, assuming it contains 13 dirt.
*

View File

@@ -15,10 +15,8 @@ import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import java.util.List;
public class TurtleCompareCommand implements ITurtleCommand
@@ -52,19 +50,6 @@ public class TurtleCompareCommand implements ITurtleCommand
Block lookAtBlock = lookAtState.getBlock();
if( !lookAtBlock.isAir( lookAtState, world, newPosition ) )
{
// Try getSilkTouchDrop first
if( !lookAtBlock.hasTileEntity( lookAtState ) )
{
try
{
Method method = ObfuscationReflectionHelper.findMethod( Block.class, "func_180643_i", BlockState.class );
lookAtStack = (ItemStack) method.invoke( lookAtBlock, lookAtState );
}
catch( ReflectiveOperationException | RuntimeException ignored )
{
}
}
// See if the block drops anything with the same ID as itself
// (try 5 times to try and beat random number generators)
for( int i = 0; i < 5 && lookAtStack.isEmpty(); i++ )

View File

@@ -5,9 +5,11 @@
*/
package dan200.computercraft.shared.util;
import net.minecraft.block.BlockState;
import net.minecraft.entity.Entity;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.ISidedInventoryProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
@@ -23,6 +25,7 @@ import net.minecraftforge.items.wrapper.SidedInvWrapper;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class InventoryUtil
{
@@ -41,7 +44,8 @@ public final class InventoryUtil
// Methods for finding inventories:
public static IItemHandler getInventory( World world, BlockPos pos, Direction side )
@Nullable
public static IItemHandler getInventory( @Nonnull World world, @Nonnull BlockPos pos, @Nonnull Direction side )
{
// Look for tile with inventory
TileEntity tileEntity = world.getBlockEntity( pos );
@@ -52,7 +56,7 @@ public final class InventoryUtil
{
return itemHandler.orElseThrow( NullPointerException::new );
}
else if( side != null && tileEntity instanceof ISidedInventory )
else if( tileEntity instanceof ISidedInventory )
{
return new SidedInvWrapper( (ISidedInventory) tileEntity, side );
}
@@ -62,6 +66,13 @@ public final class InventoryUtil
}
}
BlockState block = world.getBlockState( pos );
if( block.getBlock() instanceof ISidedInventoryProvider )
{
ISidedInventory inventory = ((ISidedInventoryProvider) block.getBlock()).getContainer( block, world, pos );
return new SidedInvWrapper( inventory, side );
}
// Look for entity with inventory
Vector3d vecStart = new Vector3d(
pos.getX() + 0.5 + 0.6 * side.getStepX(),

View File

@@ -1,62 +0,0 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.shared.util;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.api.ComputerCraftAPI;
import net.minecraftforge.fml.ModList;
import org.objectweb.asm.Type;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public final class ServiceUtil
{
private static final Type AUTO_SERVICE = Type.getType( "Lcom/google/auto/service/AutoService;" );
private ServiceUtil()
{
}
public static <T> Stream<T> loadServices( Class<T> target )
{
return StreamSupport.stream( ServiceLoader.load( target, ServiceUtil.class.getClassLoader() ).spliterator(), false );
}
public static <T> Stream<T> loadServicesForge( Class<T> target )
{
Type type = Type.getType( target );
ClassLoader loader = ComputerCraftAPI.class.getClassLoader();
return ModList.get().getAllScanData().stream()
.flatMap( x -> x.getAnnotations().stream() )
.filter( x -> x.getAnnotationType().equals( AUTO_SERVICE ) )
.filter( x -> {
Object value = x.getAnnotationData().get( "value" );
return value instanceof List<?> && ((List<?>) value).contains( type );
} )
.flatMap( x -> {
try
{
Class<?> klass = loader.loadClass( x.getClassType().getClassName() );
if( !target.isAssignableFrom( klass ) )
{
ComputerCraft.log.error( "{} is not a subtype of {}", x.getClassType().getClassName(), target.getName() );
return Stream.empty();
}
Class<? extends T> casted = klass.asSubclass( target );
return Stream.of( casted.newInstance() );
}
catch( ReflectiveOperationException e )
{
ComputerCraft.log.error( "Cannot load {}", x.getClassType(), e );
return Stream.empty();
}
} );
}
}

View File

@@ -38,5 +38,21 @@
"upgrade.computercraft.speaker.adjective": "(Alto-Falante)",
"chat.computercraft.wired_modem.peripheral_connected": "Periférico \"%s\" conectado à rede",
"chat.computercraft.wired_modem.peripheral_disconnected": "Periférico \"%s\" desconectado da rede",
"gui.computercraft.tooltip.copy": "Copiar para a área de transferência"
"gui.computercraft.tooltip.copy": "Copiar para a área de transferência",
"commands.computercraft.tp.synopsis": "Teleprota para um computador específico.",
"commands.computercraft.turn_on.done": "Ligou %s/%s computadores",
"commands.computercraft.turn_on.desc": "Liga os computadores em escuta. Você pode especificar o id de instância do computador (ex.: 123), id do computador (ex.: #123) ou o rótulo (ex.: \"@MeuComputador\").",
"commands.computercraft.turn_on.synopsis": "Liga computadores remotamente.",
"commands.computercraft.shutdown.done": "Desliga %s/%s computadores",
"commands.computercraft.shutdown.desc": "Desliga os computadores em escuta ou todos caso não tenha sido especificado. Você pode especificar o id de instância do computador (ex.: 123), id do computador (ex.: #123) ou o rótulo (ex.: \"@MeuComputador\").",
"commands.computercraft.shutdown.synopsis": "Desliga computadores remotamente.",
"commands.computercraft.dump.action": "Ver mais informação sobre este computador",
"commands.computercraft.dump.desc": "Mostra o status de todos os computadores ou uma informação específica sobre um computador. Você pode especificar o id de instância do computador (ex.: 123), id do computador (ex.: #123) ou o rótulo (ex.: \"@MeuComputador\").",
"commands.computercraft.dump.synopsis": "Mostra status de computadores.",
"commands.computercraft.help.no_command": "Comando '%s' não existe",
"commands.computercraft.help.no_children": "%s não tem sub-comandos",
"commands.computercraft.help.desc": "Mostra essa mensagem de ajuda",
"commands.computercraft.help.synopsis": "Providencia ajuda para um comando específico",
"commands.computercraft.desc": "O comando /computercraft providencia várias ferramentas de depuração e administração para controle e interação com computadores.",
"commands.computercraft.synopsis": "Vários comandos para controlar computadores."
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 456 B

After

Width:  |  Height:  |  Size: 398 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 534 B

After

Width:  |  Height:  |  Size: 476 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 475 B

After

Width:  |  Height:  |  Size: 417 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 584 B

After

Width:  |  Height:  |  Size: 526 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 575 B

After

Width:  |  Height:  |  Size: 517 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 503 B

After

Width:  |  Height:  |  Size: 404 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 633 B

After

Width:  |  Height:  |  Size: 534 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 525 B

After

Width:  |  Height:  |  Size: 426 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 641 B

After

Width:  |  Height:  |  Size: 560 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 635 B

After

Width:  |  Height:  |  Size: 554 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 421 B

After

Width:  |  Height:  |  Size: 193 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 501 B

After

Width:  |  Height:  |  Size: 214 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 439 B

After

Width:  |  Height:  |  Size: 199 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 327 B

After

Width:  |  Height:  |  Size: 217 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 290 B

After

Width:  |  Height:  |  Size: 195 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 327 B

After

Width:  |  Height:  |  Size: 218 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 327 B

After

Width:  |  Height:  |  Size: 217 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 290 B

After

Width:  |  Height:  |  Size: 195 B

Some files were not shown because too many files have changed in this diff Show More