wackasm-opencomputers
Typed Rust bindings to every OpenComputers component, for WASI programs running on the WebAssembly (wackasm) architecture.
Full documentation, including how to get programs onto a computer: https://decduck.github.io/wackasm/.
use Duration;
use *;
Build with cargo build --release --target wasm32-wasip1, keeping the stack
small (RUSTFLAGS="-C link-arg=-zstack-size=65536"), copy the .wasm to
/bin/ on a disk, and run it from the wackasm shell. crates/wackasm-oc-programs
has a worked example (demo).
What's in it
components: one struct per component type, one method per callback: 52 component types and 375 methods.Gpu,Screen,Filesystem,Eeprom,Internet,Modem,Tunnel,Redstone,Robot,Drone,InventoryController,Transposer,Geolyzer,Hologram,Printer3d,Data,Database,Debug, the Adapter's vanilla blocks (Furnace,NoteBlock,Beacon, ...) and the rest. Each method's docs are OpenComputers' own, plus the Lua signature and whether it is a direct call. Find components withGpu::first(),Gpu::all()orGpu::at(address).component:list,methods, untypedinvoke, andProxyfor components the wrappers don't know (other mods').signal:pull,pull_filtered,push, and a typedSignalfor the standard events (keys, touch, clipboard, component added and removed, redstone, modem messages, motion, ...). Anything else arrives asSignal::Other.computer: address, uptime, memory, beep, shutdown and reboot, crash, logging to the server, andfiles_disk()(the diskstd::fsuses).internet: HTTP(S) through an internet card,internet::get(url)orinternet::Request::new(url)withmethod,header,body, thensend(). That returns aResponsewithstatus(),message()andheaders(), and the body asstd::io::Read.internet::TcpStream::connect(host, port)isRead + Write, withtry_readfor polling. Dropping either closes and releases it. Reads come in 2 KiB chunks, one per tick.draw: aCanvasframebuffer with text, half-block pixels (two per cell), braille dots (2x4 per cell), lines, rectangles, circles and plots.present()sends only the cells that changed, merged into as few GPU calls as possible, optionally double-buffered through GPU video memory.process: running other programs, likestd::process.Command::new("cat").arg("notes.txt"), withenv,envs,env_remove,env_clear,current_diranddisk, thenstatus()(this program's stdin and stdout),output()(captured), orspawn()for aChildyou drive event by event (next_event,write_stdin,close_stdin,kill,wait,wait_with_output). Programs are found onPATH(default/bin) asNAME.wasmorNAME, on this program's disk, then the boot disk, then the others. Children inherit the environment, the disk and the current directory. One child at a time, and stderr is merged into stdout.- Working directory:
std::env::current_dir/set_current_dirand relativestd::fspaths work. A program starts in the directory it was run from because the crate changes intoPWDbeforemain. That happens whenever the program links the crate, which can take ause wackasm_opencomputers as _;. In a build without LTO, callprocess::enter_working_dir()at the top ofmainto be sure. task(the optionalasyncfeature): a single-threaded executor (task::run,spawn,join,join_all,sleep,timeout,signal), an_asynctwin of every component method,component::invoke_async, and async internet (get_async,send_async,read_async,connect_async, ...). Calls are queued with the architecture and the program keeps running until their results come back, so one program can wait on several calls, timers and signals at once. Enable it withfeatures = ["async"]; everything else works without it.Side,Colorandkeys: the codes robots, redstone and keyboards use.
Files are easiest through std::fs, which the architecture maps onto a disk.
Type mapping
Generated from each callback's documented signature (function(x:number, y:number, value:string[, vertical:boolean]):boolean):
| Lua | parameter | optional parameter | return |
|---|---|---|---|
number |
impl Into<Number> (ints, f64, Side, Color) |
Option<Number> |
Number |
string |
impl AsRef<[u8]> (&str, bytes, Address) |
Option<&str> |
OcString (bytes; .as_str(), Display) |
boolean |
bool |
Option<bool> |
bool |
userdata |
Handle |
Option<Handle> |
Handle |
table, unions |
impl Into<Value> |
Option<Value> |
Value |
data... |
&[Value] |
||
X or nil |
Option<X> |
||
a, b |
(A, B) |
Optional parameters are concrete types, so None needs no annotation.
Trailing omitted ones are dropped, so the component applies its own defaults.
A reply of nil, "reason" becomes Err(Error::Failed(reason)) unless the
return type is optional. Some boolean methods report false, "reason"; those
return Ok(false), and the reason is in the raw reply from
Component::invoke.
Number is an integer or a float, as OpenComputers sent it: integers stay
exact, and Number::as_i64, as_f64 and friends convert either way.
Regenerating
The wrappers come from OpenComputers itself: tools/extract_callbacks.py
reads the @Callback annotations and component names out of the mod jar
into tools/callbacks.json, and tools/gen_components.py turns that into
src/components.rs.
python tools/extract_callbacks.py <OpenComputers-MC1.12.2-1.7.5.221.jar> tools/callbacks.json
python tools/gen_components.py tools/callbacks.json src/components.rs
The jar is in Gradle's cache after building mc-mod (look for
OpenComputers-MC1.12.2-*.jar under ~/.gradle/caches/modules-2).
Caveats
- Signatures come from OpenComputers' doc strings. Where a doc says
numberfor something that is really an integer code, the wrapper takesimpl Into<Number>, which accepts both. - Methods that only some tiers or variants have (data card tier 3, wireless
modem strength, ...) are on the one struct, and fail with
Error::NoSuchMethodon parts that lack them. - Calls cost what they cost in Lua: direct calls draw on the per-tick budget, and indirect ones wait for the next tick.