Skip to content
Back to search

craftos-mcp

MarketplaceWorks with Claude CodeGitHub

A headless CC:Tweaked emulator for AI agents and tests

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 17 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Akkiruk/craftos-mcp with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Akkiruk/craftos-mcp'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/akkiruk--craftos-mcp/badge.svg)](/listings/akkiruk--craftos-mcp)

HTML

<a href="/listings/akkiruk--craftos-mcp"><img src="/api/listings/akkiruk--craftos-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

You need Node.js 22 or newer.

From npm (Windows and Linux x64)

npx -y craftos-mcp serve                        # the MCP server, for any agent
claude mcp add craftos -- npx -y craftos-mcp serve
npx craftos-mcp test                            # or window, app, run, info: see the command line below

The package holds no engine or ROM. The first command fetches the engine from this repository's release, builds the ROMs from the real CC:Tweaked jars and the GPU fonts, and keeps them in `%LOCALAPPDATA%\craftos-mcp` or `~/.cache/craftos-mcp` (`CRAFTOS_HOME` moves it); that takes a few seconds to a minute, once per version. `serve` answers its client straight away and lets the tools that run computers wait for it. The workspace is the folder you run it in. `craftos-mcp setup --force` does the setup again.

Quick start from a clone

git clone https://github.com/Akkiruk/craftos-mcp
cd craftos-mcp
npm run setup

`npm run setup` installs the packages, builds the tools, builds the ROM from the real CC:Tweaked jar (and Tom's Peripherals' fonts), downloads the prebuilt engine for your OS from the latest release, checks everything and prints the line that connects your agent. Run it again any time: finished steps are skipped. If the release has no engine for your OS it tells you how to build one (below).

Claude Code plugin

One install gives Claude Code the `cc-tweaked-dev` skill and the `craftos` MCP server:

/plugin marketplace add Akkiruk/craftos-mcp
/plugin install craftos-mcp@craftos-mcp

Claude Code keeps a copy of this repository for the plugin, which has no engine or ROM yet, so the first time the server starts it runs the setup above in the background (a few minutes: it downloads the jar and the engine). If `/mcp` shows the server as failed on that first try, wait a minute and reconnect; setup carries on without it. Progress is in `.cache/setup.log` inside the plugin's folder. The plugin asks which mods your pack has (the addon list below), and the server's workspace is the folder you start Claude Code in.

The command line

`craftos-mcp` runs without an agent, so it works in scripts and CI. Run it from your Lua project folder (`--dir` changes that):

craftos-mcp test                         # every *.test.lua below here, ccunit harness; exits 1 on a failure
craftos-mcp test tests/ --addons create --timescale 10
craftos-mcp run clock.lua --monitor top:2x2 --screenshot shot.png   # terminal and monitors as text, PNGs saved
craftos-mcp run sort.lua --world worlds/chests.json --timeout 20 -- --verbose
craftos-mcp info                         # engine, ROM and addons status
craftos-mcp serve                        # the MCP server over stdio

Inside a clone use `npx craftos-mcp ...`, or `node apps/cli/dist/index.js ...`. `craftos-mcp help <command>` lists the options. A `--world` is a JSON file or the name of one in `worlds/`; `--addons` is `all`, `none` or ids separated by commas.

Doing it by hand

1. The engine

Download the prebuilt engine for your OS from the [latest release](../../releases/latest) and unzip it over the repository, or build it yourself:

- **Windows**: Visual Studio 2022 (or its Build Tools) with C++, CMake, Ninja and a [vcpkg](https://vcpkg.io) checkout in `VCPKG_ROOT`. Then `engine\build.cmd`. - **Linux**: a C++17 compiler, CMake, Ninja and vcpkg in `VCPKG_ROOT`. Then `engine/build.sh`.

macOS is not supported yet.

2. The ROM

CC:Tweaked's license does not allow its ROM to be redistributed with this project, so you build it on your own machine. This downloads CC:Tweaked 1.101.3 from Modrinth, checks its hash, and builds `rom/cc-1.101.3`:

node scripts/build-rom.mjs --download

If you already have the jar: `node scripts/build-rom.mjs path/to/cc-tweaked-1.18.2-1.101.3.jar rom/cc-1.101.3`.

The same step downloads Tom's Peripherals 1.18.2-1.2.1 (MIT) and builds the GPU's fonts from it, since they are not

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 12 lines
  1. {
  2. "name": "craftos-mcp",
  3. "description": "A headless CC:Tweaked emulator for AI agents and tests",
  4. "owner": { "name": "craftos-mcp contributors" },
  5. "plugins": [
  6. {
  7. "name": "craftos-mcp",
  8. "source": "./",
  9. "description": "Run, test and screenshot ComputerCraft Lua programs without Minecraft: the cc-tweaked-dev skill and the craftos MCP server."
  10. }
  11. ]
  12. }
README.md · README · 390 lines
  1. # craftos-mcp
  2. > **Minecraft 1.18.2 is complete. 1.20.1 is partly there:** pick it and you get CC:Tweaked 1.121.0's behaviour and
  3. > 1.20.1 turtle data, but the mods' peripherals still behave like their 1.18.2 versions for now. 1.21.1 is next. See
  4. > [Choose your Minecraft version](#choose-your-minecraft-version).
  5. **Let your coding agent test the ComputerCraft code it writes.** AI agents write CC:Tweaked Lua they have never run,
  6. and the bugs turn up on your server. craftos-mcp is a CC:Tweaked emulator the agent drives itself over
  7. [MCP](https://modelcontextprotocol.io): it runs the program, reads the terminal and every monitor, taps buttons,
  8. changes the world around the computer (a player walks up, a chest fills, a train arrives, a reactor heats up, an hour
  9. passes), writes and runs tests, and fixes what broke until it works. All without Minecraft.
  10. ```json
  11. {
  12. "mcpServers": {
  13. "craftos": { "command": "npx", "args": ["-y", "craftos-mcp", "serve"] }
  14. }
  15. }
  16. ```
  17. That one entry works in Claude Code, Cursor, VS Code and any other MCP client; the first start downloads the engine
  18. and builds the ROM by itself. In VS Code, Cursor or Windsurf you can install the
  19. [extension](https://marketplace.visualstudio.com/items?itemName=Rogiedoji.craftos-mcp) instead (also on
  20. [Open VSX](https://open-vsx.org/extension/Rogiedoji/craftos-mcp)): it sets up the server for Copilot, and adds Run in
  21. CraftOS for any `.lua` file and your `*.test.lua` files in the Testing view. The world it simulates is what CC programs depend on: several computers on modems with
  22. real rednet, turtles in a block world, and peripherals from Create, Mekanism, Advanced Peripherals and more.
  23. No agent? The same emulator works for people too:
  24. - **In a window**, like CraftOS-PC: `craftos-mcp window` ([Without an AI agent](#without-an-ai-agent)).
  25. - **In your browser**: `craftos-mcp app` opens computers, monitors and the world side by side.
  26. - **From the command line and CI**: `craftos-mcp test tests/` runs your `*.test.lua` files.
  27. The engine passes 1190 of 1191 of CC:Tweaked's own tests at 1.101.3 (and 1362 of 1363 at 1.121.0), and the ROM is
  28. built from the real CC:Tweaked jar. [How exact is it](docs/accuracy.md) says, area by area, what was measured in game
  29. and what was written from source.
  30. ![A real Claude Code session: it writes a door controller, runs it in craftos-mcp, sees the monitor, finds that a player exactly at the range edge does not open the door, fixes it, and gets its tests passing](docs/media/showcase/agent-demo.gif)
  31. _A real Claude Code session, unscripted: asked for a door controller with tests, it ran its program in the emulator,
  32. caught a monitor that never stopped redrawing and a player at the range edge who could not get in, fixed both, and
  33. finished with its tests passing. Then the same file went onto a computer in real Minecraft and worked there with no code
  34. changes, just a player name added to its whitelist ([the diff](docs/media/showcase/ingame-door-diff.txt),
  35. [the clip](docs/media/showcase/ingame-door.mp4)). The [full transcript](docs/media/showcase/agent-demo-transcript.md)
  36. is next to the [video](docs/media/showcase/agent-demo.mp4)._
  37. Some games built and tested with it are **[playable in your browser](https://rogiedoji.com/craftos)**, no install,
  38. and there's a [highlight reel](docs/media/showcase/sizzle.mp4) of them.
  39. ## What it does
  40. - **Run and test**: run a program in a fresh computer and get the terminal and every monitor back as text, PNGs or
  41. golden snapshots; run `*.test.lua` files with the built-in `ccunit` harness.
  42. - **Interactive sessions**: type, press keys, touch monitors, send events, wait for text. `craftos_ui` reads every
  43. screen as buttons and text runs with colours, so an agent can drive a UI without screenshots.
  44. - **Monitors** at any wall size and text scale, with real touch events.
  45. - **Several computers at once**: wireless, ender and wired modems with real rednet, ranges and wired names.
  46. - **Turtles** in a block world built from vanilla 1.18.2 data: the whole turtle API with its tick timing, digging
  47. with loot-table drops, placing, inventories, refuelling, upgrades and crafting. What a turtle places comes alive:
  48. computers boot, disk drives take floppies, monitors join into walls.
  49. - **CC's generic peripherals**: chests, barrels and any modded block as an inventory, fluid tank and energy store,
  50. with `pushItems`, `pullItems`, `pushFluid` and levels that move over time.
  51. - **Peripherals from other mods**, written from each mod's source and checked against its jar, each one an addon
  52. you switch on only if your pack has it (see [Choose your mods](#choose-your-mods)):
  53. - Advanced Peripherals 0.7.31r: player, energy and environment detectors, chat box, redstone integrator, NBT
  54. storage, AR controller, ME and RS bridges.
  55. - Mekanism 10.2.5: QIO, the Quantum Entangloporter, the boiler and induction matrix; with Mekanism Generators, the
  56. fission reactor, turbine and fusion reactor, running tick by tick (a reactor left alone melts down).
  57. - Create 0.5.1: train stations with schedules and trains on the clock, gauges, speed controllers, sequenced
  58. gearshifts and the display link; Create Crafts & Additions 1.0.0's motor, accumulator, relay and digital adapter.
  59. - Tom's Peripherals 1.2.1: the GPU with its full drawing API, pixel-exact and in screenshots, keyboard, redstone
  60. port and watchdog.
  61. - Bigger Reactors 0.6.0 and Extreme Reactors 2.0.71: reactors and turbines with their real heat, fuel and rotor
  62. physics.
  63. - **Determinism**: seed `math.random`, run the clock faster, or jump it forward so timers fire instantly.
  64. - **Your way in**: a desktop window, a browser app (also the MCP server's live viewer at <http://127.0.0.1:7878>),
  65. a command line, and an in-computer `sim` command to change the world by typing (`sim join Alice`).
  66. ## Games
  67. Three game cabinets and an RPG in plain CC:Tweaked Lua, each with a world file and tests that play real games through
  68. taps on the monitors. They're examples of what you can build and test here, and they use nothing but CC:Tweaked's own
  69. APIs.
  70. | Cabinet | Games | Shows off |
  71. | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
  72. | [Board](workspace/examples/games/board/README.md) | Ultimate Tic-Tac-Toe, Four in a Row, Reversi, Checkers, Dots and Boxes, Mancala, Fleet, Codebreaker; three computer levels | touch monitor walls, two players at one wall |
  73. | [Action](workspace/examples/games/action/README.md) | Snake, Blocks, Bricks, Lander, Mines | fast redraws, real-time touch |
  74. | [Versus](workspace/examples/games/versus/README.md) | Paddle, Trails, Artillery | two computers in one match over rednet |
  75. | [BLIGHTMARE](workspace/examples/games/blightmare/README.md) | a first-person RPG in eleven acts: towns, a world map, turn-based fights, bosses, saves | 2 MB of game packed onto a 1 MB disk |
  76. ![BLIGHTMARE: the opening, a town, a fight and a boss, played by touch](docs/media/showcase/blightmare.gif)
  77. BLIGHTMARE, played by touch ([the whole showcase](docs/media/showcase/blightmare.mp4))
  78. | | |
  79. | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
  80. | ![Blocks: falling pieces steered by taps, lines clearing](docs/media/showcase/action-blocks.gif) | ![Paddle on two computers, each with its own monitor wall, the same match on both](docs/media/showcase/versus-paddle.gif) |
  81. | Blocks, steered by tapping the wall | Paddle across two computers on rednet (3x speed) |
  82. Each cabinet's README says how to open it. The board games, for example:
  83. ```sh
  84. craftos-mcp window workspace/examples/games/board/arcade.world.json --dir workspace --monitor left:6x6 --monitor right:6x6
  85. # then, in the computer: examples/games/board/arcade
  86. ```
  87. `node scripts/make-showcase.mjs` records the videos again from real runs.
  88. ## Examples
  89. [`workspace/examples/`](workspace/examples/README.md) also has complete programs for the mods above, each with a world
  90. and a test that proves it works: a Mekanism reactor controller, a Create train departure board, an energy monitor for
  91. any modded battery, a Tom's Peripherals GPU demo, an Extreme Reactors rod controller, an Advanced Peripherals player
  92. greeter and a rednet chat between two computers. These pictures are rendered from real runs (`node
  93. scripts/make-demo-gif.mjs` makes them again).
  94. ![A Mekanism fission reactor controller on a monitor: the temperature climbs until the program scrams the reactor, then a RESET touch restarts it once it has cooled](docs/media/demo.gif)
  95. _The [reactor controller](workspace/examples/mekanism/reactor.lua) on a simulated Mekanism reactor, with the clock sped
  96. up: it scrams the reactor before it is damaged, and RESET restarts it once it has cooled. The
  97. [test](workspace/examples/mekanism/reactor.test.lua) checks exactly that._
  98. | | |
  99. | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
  100. | ![Create train departure board](docs/media/train-board.png) | ![Tom's Peripherals GPU demo](docs/media/gpu-demo.png) |
  101. | Train departure board: platform, train, status and schedule for each station | GPU demo: a spinning cube, a sine ribbon and ripples where you right-click |
  102. | ![Power monitor for generic energy storage](docs/media/power-monitor.png) | ![Reactor scrammed on a monitor](docs/media/reactor-scram.png) |
  103. | Power monitor: any block with an energy store, with rates and a low-power alarm | The reactor controller after it has scrammed on temperature |
  104. ## Setup
  105. You need Node.js 22 or newer.
  106. ### From npm (Windows and Linux x64)
  107. ```sh
  108. npx -y craftos-mcp serve # the MCP server, for any agent
  109. claude mcp add craftos -- npx -y craftos-mcp serve
  110. npx craftos-mcp test # or window, app, run, info: see the command line below
  111. ```
  112. The package holds no engine or ROM. The first command fetches the engine from this repository's release, builds the
  113. ROMs from the real CC:Tweaked jars and the GPU fonts, and keeps them in `%LOCALAPPDATA%\craftos-mcp` or
  114. `~/.cache/craftos-mcp` (`CRAFTOS_HOME` moves it); that takes a few seconds to a minute, once per version. `serve`
  115. answers its client straight away and lets the tools that run computers wait for it. The workspace is the folder you
  116. run it in. `craftos-mcp setup --force` does the setup again.
  117. ### Quick start from a clone
  118. ```sh
  119. git clone https://github.com/Akkiruk/craftos-mcp
  120. cd craftos-mcp
  121. npm run setup
  122. ```
  123. `npm run setup` installs the packages, builds the tools, builds the ROM from the real CC:Tweaked jar (and Tom's
  124. Peripherals' fonts), downloads the prebuilt engine for your OS from the latest release, checks everything and prints
  125. the line that connects your agent. Run it again any time: finished steps are skipped. If the release has no engine for
  126. your OS it tells you how to build one (below).
  127. ### Claude Code plugin
  128. One install gives Claude Code the `cc-tweaked-dev` skill and the `craftos` MCP server:
  129. ```text
  130. /plugin marketplace add Akkiruk/craftos-mcp
  131. /plugin install craftos-mcp@craftos-mcp
  132. ```
  133. Claude Code keeps a copy of this repository for the plugin, which has no engine or ROM yet, so the first time the
  134. server starts it runs the setup above in the background (a few minutes: it downloads the jar and the engine). If
  135. `/mcp` shows the server as failed on that first try, wait a minute and reconnect; setup carries on without it. Progress
  136. is in `.cache/setup.log` inside the plugin's folder. The plugin asks which mods your pack has (the addon list below),
  137. and the server's workspace is the folder you start Claude Code in.
  138. ### The command line
  139. `craftos-mcp` runs without an agent, so it works in scripts and CI. Run it from your Lua project folder (`--dir`
  140. changes that):
  141. ```sh
  142. craftos-mcp test # every *.test.lua below here, ccunit harness; exits 1 on a failure
  143. craftos-mcp test tests/ --addons create --timescale 10
  144. craftos-mcp run clock.lua --monitor top:2x2 --screenshot shot.png # terminal and monitors as text, PNGs saved
  145. craftos-mcp run sort.lua --world worlds/chests.json --timeout 20 -- --verbose
  146. craftos-mcp info # engine, ROM and addons status
  147. craftos-mcp serve # the MCP server over stdio
  148. ```
  149. Inside a clone use `npx craftos-mcp ...`, or `node apps/cli/dist/index.js ...`. `craftos-mcp help <command>` lists the
  150. options. A `--world` is a JSON file or the name of one in `worlds/`; `--addons` is `all`, `none` or ids separated by
  151. commas.
  152. ### Doing it by hand
  153. #### 1. The engine
  154. Download the prebuilt engine for your OS from the
  155. [latest release](../../releases/latest) and unzip it over the repository, or build it yourself:
  156. - **Windows**: Visual Studio 2022 (or its Build Tools) with C++, CMake, Ninja and a [vcpkg](https://vcpkg.io)
  157. checkout in `VCPKG_ROOT`. Then `engine\build.cmd`.
  158. - **Linux**: a C++17 compiler, CMake, Ninja and vcpkg in `VCPKG_ROOT`. Then `engine/build.sh`.
  159. macOS is not supported yet.
  160. #### 2. The ROM
  161. CC:Tweaked's license does not allow its ROM to be redistributed with this project, so you build it on your own
  162. machine. This downloads CC:Tweaked 1.101.3 from Modrinth, checks its hash, and builds `rom/cc-1.101.3`:
  163. ```sh
  164. node scripts/build-rom.mjs --download
  165. ```
  166. If you already have the jar: `node scripts/build-rom.mjs path/to/cc-tweaked-1.18.2-1.101.3.jar rom/cc-1.101.3`.
  167. The same step downloads Tom's Peripherals 1.18.2-1.2.1 (MIT) and builds the GPU's fonts from it, since they are not
  168. shipped here either (`node scripts/build-toms-fonts.mjs` does it alone).
  169. #### 3. The tools
  170. ```sh
  171. npm install
  172. npm run build
  173. ```
  174. #### 4. Connect your agent
  175. Claude Code:
  176. ```sh
  177. claude mcp add craftos -- node /path/to/craftos-mcp/apps/mcp-server/dist/index.js
  178. ```
  179. VS Code: `.vscode/mcp.json` is already set up for this folder. Other MCP clients: run
  180. `node apps/mcp-server/dist/index.js` over stdio. Then call `craftos_info`; it lists anything that is missing.
  181. Point `CRAFTOS_WORKSPACE` at your own Lua project to work on it in place. Other settings: `CRAFTOS_ENGINE`,
  182. `CRAFTOS_ROM`, `CRAFTOS_RUNTIME_ROOT`, `CRAFTOS_VIEWER_PORT` (`off` turns the viewer off).
  183. ## Without an AI agent
  184. `craftos-mcp window` opens the computer in a desktop window, with the same simulated world an agent gets:
  185. ```sh
  186. craftos-mcp window worlds/generic-storage-demo.json --monitor top:3x2 # from your Lua project folder
  187. craftos-mcp window create-demo --dir path/to/project # a world from worlds/ by name
  188. ```
  189. The computer's files are your folder (`--dir`, default the current one), live: edit in your own editor, then hold
  190. Ctrl+R in the window to reboot. Monitors open as windows of their own and a click is a touch; a world can list them
  191. under `"monitors"`. A world's speakers play real sound. F12 copies a screenshot to the clipboard. Turtle worlds and several computers on
  192. one network do not open in a window yet.
  193. Inside the computer, the `sim` program changes the world, as `craftos_sim_command` does for an agent. It is the
  194. emulator's own: a real CC:Tweaked computer has no `sim`.
  195. ```text
  196. sim join Alice sim leave Alice
  197. sim chat Alice hello sim advance 60 (jump the clock 60 seconds)
  198. sim item chest_0 1 minecraft:diamond 5
  199. sim state (players, peripherals, chat)
  200. sim createTrainArrive station=Create_Station_0 train=Express (any command a mod's simulation knows)
  201. sim help (all of them)
  202. ```
  203. ### In your browser
  204. `craftos-mcp app` starts a local web page and opens it:
  205. ```sh
  206. craftos-mcp app --dir path/to/project # --port 7878 by default; --no-open just prints the address
  207. ```
  208. **New computer** makes one: a normal, advanced, pocket or turtle computer, a world from `worlds/` or your own JSON,
  209. the mods your pack has, monitors and their sizes, and a program to run (or just the shell). Set **Computers** above 1
  210. for a network, each with a modem. Every computer gets a tab. Its terminal takes the keyboard, paste and mouse; the
  211. Ctrl+T, Ctrl+R and Ctrl+S buttons hold the keys for a second as CC needs (your browser keeps Ctrl+T for itself).
  212. Monitors and Tom's Peripherals GPU screens update live, and a click is a touch on that cell or pixel; **UI** outlines
  213. what the screens show as buttons. On the side: the world (players join, leave and chat, the clock jumps, items go
  214. into slots, and the whole sim state as a tree), a box for any sim command with the list of the ones this world knows,
  215. and the computer's files, which you can edit, or copy your project in again, and reboot.
  216. It listens on 127.0.0.1 only. The MCP server's live viewer (<http://127.0.0.1:7878>) is the same page, so you can
  217. watch and help while an agent works.
  218. ## Choose your Minecraft version
  219. | Version | CC:Tweaked | State |
  220. | ------------------ | ---------- | ---------------------------------------------------------------------------------------------------- |
  221. | `1.18.2` (default) | 1.101.3 | Complete: CC itself, turtles, modems and every mod below |
  222. | `1.20.1` | 1.121.0 | CC itself and turtles (1.20.1 block data) as in 1.121.0; the mods still act as their 1.18.2 versions |
  223. | `1.21.1` | 1.121.0 | CC itself as in 1.121.0; turtle data and mods not done yet |
  224. Pick one per world with `"version": "1.20.1"`, for the MCP server with `CRAFTOS_VERSION`, or on the command line with
  225. `--mc 1.20.1`. Each CC:Tweaked version needs its ROM: `node scripts/build-rom.mjs --download 1.20.1`, or
  226. `npm run setup -- --mc all` for every version. A mod that does not exist on the chosen version (Bigger Reactors on
  227. 1.21.1) is refused with a message.
  228. ## Choose your mods
  229. Every mod besides CC:Tweaked is an addon. Switch on only the ones your pack has, so a program cannot come to rely on
  230. a peripheral your server does not have. Set `CRAFTOS_ADDONS` for the MCP server (the `.vscode/mcp.json` here lists
  231. them all: delete the ones you do not use), or give one world its own list with `addons`:
  232. ```json
  233. {
  234. "addons": ["create", "mekanism"],
  235. "peripherals": [{ "name": "station_0", "type": "Create_Station" }]
  236. }
  237. ```
  238. | Id | Mod |
  239. | ---------------------- | ------------------------------------------------ |
  240. | `advanced-peripherals` | Advanced Peripherals 0.7.31r |
  241. | `mekanism` | Mekanism 10.2.5 |
  242. | `mekanism-generators` | Mekanism Generators 10.2.5 (needs `mekanism`) |
  243. | `create` | Create 0.5.1.i |
  244. | `create-additions` | Create Crafts & Additions 1.0.0 (needs `create`) |
  245. | `toms-peripherals` | Tom's Peripherals 1.18.2-1.2.1 |
  246. | `bigger-reactors` | Bigger Reactors 1.18.2-0.6.0-beta.1.4 |
  247. | `extreme-reactors` | Extreme Reactors 1.18.2-2.0.71 |
  248. `"all"` and `"none"` work too. With no setting at all, everything is on. A world that uses a block from an addon that
  249. is off fails before the computer boots and names the addon; `craftos_info` lists what is on.
  250. ## Tools
  251. | Tool | Purpose |
  252. | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
  253. | `craftos_info` | Engine, ROM and workspace status |
  254. | `craftos_write_file`, `craftos_read_file`, `craftos_list_files` | Workspace files (copied to the root of each computer) |
  255. | `craftos_run` | Run a program in a fresh computer: terminal and monitor text, PNGs, golden snapshots |
  256. | `craftos_test` | Run `*.test.lua` files with the `ccunit` harness |
  257. | `craftos_session_create`, `craftos_type`, `craftos_key`, `craftos_touch_monitor`, ... | Interactive computers |
  258. | `craftos_ui`, `craftos_act`, `craftos_settle`, `craftos_expect`, `craftos_script` | Read screens as data, act and wait until the program is done, assert |
  259. | `craftos_network_create`, `craftos_network_update` | Several computers with modems |
  260. | `craftos_sim_command`, `craftos_sim_state` | Change and read the simulated world during a session |
  261. | `craftos_seed`, `craftos_advance`, `craftos_trace`, `craftos_screenshot` | Determinism, the virtual clock, what the program saw, pictures |
  262. For an agent, `.claude/skills/cc-tweaked-dev/SKILL.md` is a short guide to using these well.
  263. ## Your own modpack
  264. The turtle world ships with vanilla Minecraft, Forge and CC:Tweaked data. To give it every block, item, recipe and
  265. loot table in your modpack, generate the data from your own instance:
  266. ```sh
  267. python -I tools/turtledata/extract.py --instance "<your instance>/minecraft"
  268. ```
  269. ## Layout
  270. ```text
  271. engine/ Forked CraftOS-PC 2 (MIT, see engine/UPSTREAM.md)
  272. packages/ rawterm (engine protocol, PNG renderer), runner (runs, tests, sessions, networks, browser app), protocol
  273. apps/ The craftos-mcp command line (window, app, test, run, info, serve) and the MCP server
  274. rom-overlay/ The simulation layered over the CC:Tweaked ROM (peripherals, modems, turtles)
  275. web/ The browser build: the engine as WebAssembly and a player for pages (web/README.md)
  276. scripts/ Setup, ROM builder, CC:Tweaked conformance runner, the video recorder
  277. tools/ Data extraction for turtles
  278. worlds/ Example worlds
  279. docs/ Architecture, security model, peripherals, turtles, conformance
  280. ```
  281. ## Known limits
  282. - Minecraft 1.18.2 is complete; on 1.20.1 and 1.21.1 the mods are still their 1.18.2 versions (see
  283. [Choose your Minecraft version](#choose-your-minecraft-version)). Older versions (1.16.5, 1.12.2) are not supported.
  284. - Only the mods listed above are simulated, and each from its source: where a mechanic is too large to copy (Create's
  285. stress network and track graph, multiblock formation) it is a fixture instead. Each mod's doc ends with what is not
  286. simulated or not confirmed. Pocket computer upgrades and most of Advanced Peripherals' turtle upgrades are not simulated (the geo scanner and chunky turtle are).
  287. - A pattern that never finishes inside one C function (a pathological `string.find`) cannot be aborted by the
  288. engine; the runner's timeout ends the process instead.
  289. - The virtual clock can run faster, but it is not a fully deterministic scheduler.
  290. - Lua runs in a scratch directory per run, but the engine is not sandboxed by the OS. Only run code you trust; see
  291. [docs/security.md](docs/security.md).
  292. ## Credits
  293. The engine is a fork of [CraftOS-PC 2](https://github.com/MCJack123/craftos2) by JackMacWindows (MIT).
  294. [CC:Tweaked](https://tweaked.cc) is by SquidDev and contributors; this project does not include it, and builds its ROM
  295. on your machine from the official jar. Not affiliated with Mojang or Microsoft.
  296. ## License
  297. MIT, see [LICENSE](LICENSE). The engine keeps CraftOS-PC's MIT license ([engine/LICENSE](engine/LICENSE)). See
  298. [NOTICE.md](NOTICE.md) for third-party parts.
packages/runner/src/versions.integration.test.ts · Bundled script · 173 lines · 2 findings marked
  1. import {
  2. existsSync,
  3. mkdirSync,
  4. mkdtempSync,
  5. rmSync,
  6. writeFileSync,
  7. } from "node:fs";
  8. import { tmpdir } from "node:os";
  9. import { join } from "node:path";
  10. import { afterAll, describe, expect, it } from "vitest";
  11. import {
  12. type TestRunResult,
  13. DEFAULT_MC,
  14. type WorldConfig,
  15. checkConfig,
  16. loadConfig,
  17. resolveVersion,
  18. romDirFor,
  19. runTests,
  20. } from "./index.js";
  21. const base = loadConfig();
  22. const scratch = mkdtempSync(join(tmpdir(), "versions-ws-"));
  23. const config = { ...base, workspaceDir: scratch };
  24. const ready = checkConfig(config).length === 0;
  25. // the 1.121.0 ROM: node scripts/build-rom.mjs --download 1.20.1
  26. const newer = existsSync(
  27. join(romDirFor(config, resolveVersion("1.20.1", {})), "bios.lua"),
  28. );
  29. afterAll(() => rmSync(scratch, { recursive: true, force: true }));
  30. async function runLua(
  31. lua: string,
  32. world: WorldConfig | undefined,
  33. name: string,
  34. ): Promise<TestRunResult> {
  35. const file = join(scratch, name);
  36. mkdirSync(join(file, ".."), { recursive: true });
  37. writeFileSync(file, lua);
  38. return runTests(config, { paths: [name], world, timeoutMs: 20000 }, 1);
  39. }
  40. function failures(result: TestRunResult): string[] {
  41. expect(result.files.map((f) => f.status)).toHaveLength(1);
  42. return result.files.flatMap((f) =>
  43. f.status === "passed"
  44. ? []
  45. : [
  46. `${f.status}`,
  47. ...f.tests
  48. .filter((t) => !t.passed)
  49. .map((t) => `${t.name}: ${t.error}`),
  50. ],
  51. );
  52. }
  53. const worldVersionLua = `
  54. local function worldVersion()
  55. local h = fs.open("/results/world.json", "r")
  56. local world = textutils.unserializeJSON(h.readAll())
  57. h.close()
  58. return world.version
  59. end
  60. `;
  61. describe.skipIf(!ready)("the version reaches the engine", () => {
  62. it("1.18.2: CC:Tweaked 1.101.3's _HOST and file handles", async () => {
  63. const result = await runLua(
  64. `${worldVersionLua}
  65. ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft 1.101.3 ", 1, true), _HOST) end)
  66. ccunit.test("world.json", function() ccunit.eq(worldVersion().mc, "1.18.2") ccunit.eq(worldVersion().cc, "1.101.3") end)
  67. ccunit.test("no w+ before 1.109", function() ccunit.raises(function() fs.open("x.txt", "w+") end, "Unsupported mode") end)
  68. ccunit.test("directory read message", function()
  69. local h, err = fs.open("rom", "r") ccunit.eq(h, nil) ccunit.eq(err, "/rom: No such file")
  70. end)
  71. ccunit.test("1.101.3's private addresses", function()
  72. ccunit.eq(http.checkURL("http://10.1.2.3"), false)
  73. ccunit.eq(http.checkURL("http://[::1]"), false)
  74. ccunit.eq(http.checkURL("http://100.100.100.200"), false)
  75. ccunit.eq(http.checkURL("http://100.64.1.1"), true)
  76. ccunit.eq(http.checkURL("http://192.30.255.113"), true)
    • Warning: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 82 on GitHub
  77. end)
  78. ccunit.test("numbers written as Java doubles", function()
  79. local w = fs.open("n.txt", "w") w.write(65) w.close()
  80. local r = fs.open("n.txt", "r") ccunit.eq(r.readAll(), "65.0") r.close()
  81. end)
  82. ccunit.finish()
  83. `,
  84. { version: "1.18.2" },
  85. "default.test.lua",
  86. );
  87. expect(failures(result)).toEqual([]);
  88. });
  89. it(`no version runs the default one (${DEFAULT_MC}, or CRAFTOS_VERSION)`, async () => {
  90. const want = resolveVersion(undefined);
  91. const result = await runLua(
  92. `${worldVersionLua}
  93. ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft ${want.cc} ", 1, true), _HOST) end)
  94. ccunit.test("world.json", function() ccunit.eq(worldVersion().mc, "${want.mc}") end)
  95. ccunit.finish()
  96. `,
  97. undefined,
  98. "no-version.test.lua",
  99. );
  100. expect(failures(result)).toEqual([]);
  101. });
  102. it.skipIf(!newer)(
  103. "1.20.1: CC:Tweaked 1.121.0's _HOST, r+/w+ handles and messages",
  104. async () => {
  105. const result = await runLua(
  106. `${worldVersionLua}
  107. ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft 1.121.0 ", 1, true), _HOST) end)
  108. ccunit.test("world.json", function()
  109. local v = worldVersion() ccunit.eq(v.mc, "1.20.1") ccunit.eq(v.cc, "1.121.0") ccunit.eq(v.loader, "forge")
  110. end)
  111. ccunit.test("w+ reads back what it wrote", function()
  112. local h = fs.open("x.txt", "w+") h.write("hello") h.seek("set", 0) ccunit.eq(h.readAll(), "hello") h.close()
  113. end)
  114. ccunit.test("directory read message", function()
  115. local h, err = fs.open("rom", "r") ccunit.eq(h, nil) ccunit.eq(err, "/rom: Not a file")
  116. end)
  117. ccunit.test("numbers written as Lua prints them", function()
  118. local w = fs.open("n.txt", "w") w.write(65) w.close()
  119. local r = fs.open("n.txt", "r") ccunit.eq(r.readAll(), "65") ccunit.eq(r.readAll(), "") r.close()
  120. end)
  121. ccunit.test("raw bytes in text mode", function()
  122. local w = fs.open("b.txt", "wb") w.write("\\225lo") w.close()
  123. local r = fs.open("b.txt", "r") ccunit.eq(r.readAll(), "\\225lo") r.close()
  124. end)
  125. ccunit.test("queueEvent copies tables", function()
  126. local t = {} os.queueEvent("copy_me", t) local _, u = os.pullEvent("copy_me") ccunit.truthy(u ~= t)
  127. end)
  128. ccunit.test("fs.getDir of ..", function() ccunit.eq(fs.getDir(".."), "../..") end)
  129. ccunit.test("1.121.0's private addresses", function()
  130. ccunit.eq(http.checkURL("http://100.64.1.1"), false)
  131. ccunit.eq(http.checkURL("http://[fc00::1]"), false)
  132. ccunit.eq(http.checkURL("http://192.30.255.113"), true)
    • Warning: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 140 on GitHub
  133. end)
  134. ccunit.finish()
  135. `,
  136. { version: "1.20.1" },
  137. "newer.test.lua",
  138. );
  139. expect(failures(result)).toEqual([]);
  140. },
  141. );
  142. it.skipIf(!newer)("1.21.1 shares the 1.121.0 ROM, on NeoForge", async () => {
  143. const result = await runLua(
  144. `${worldVersionLua}
  145. ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft 1.121.0 ", 1, true), _HOST) end)
  146. ccunit.test("world.json", function() ccunit.eq(worldVersion().mc, "1.21.1") ccunit.eq(worldVersion().loader, "neoforge") end)
  147. ccunit.finish()
  148. `,
  149. { version: "1.21.1" },
  150. "neoforge.test.lua",
  151. );
  152. expect(failures(result)).toEqual([]);
  153. });
  154. it("refuses an addon the version lacks before booting", async () => {
  155. await expect(
  156. runLua(
  157. `ccunit.finish()`,
  158. { version: "1.21.1", addons: ["bigger-reactors"] },
  159. "refused.test.lua",
  160. ),
  161. ).rejects.toThrow(/Bigger Reactors .*no release for Minecraft 1\.21\.1/);
  162. });
  163. });
packages/runner/src/versions.ts · Bundled script · 309 lines · 5 findings marked
  1. /**
  2. * Which Minecraft / CC:Tweaked version a computer behaves as. One engine binary and one runner serve every version:
  3. * the version picks the ROM, the engine's `--cc-version` (every behaviour the engine pinned to 1.101.3 is gated on
  4. * it), the addons' mod versions and the turtle block data.
  5. *
  6. * Which version a world runs, first match wins:
  7. * 1. `world.version`: "1.18.2", "1.20.1", "1.21.1", or { mc, cc?, loader? }.
  8. * 2. The CRAFTOS_VERSION environment variable: the same forms, the object as JSON.
  9. * 3. The newest version in VERSIONS (NEWEST_MC): 1.21.1 (CC:Tweaked 1.121.0) today, the next one once it is added.
  10. *
  11. * Accuracy on 1.20.1 and 1.21.1 rests on CC:Tweaked's source and its own test suite (docs/conformance), not on a
  12. * real game: there is no instance of those versions to compare against.
  13. */
  14. import { join } from "node:path";
  15. import type { RunnerConfig } from "./config.js";
  16. /** A CC:Tweaked jar on Modrinth: build-rom.mjs --download builds the ROM from it after checking the sha512. */
  17. export interface CcJar {
  18. readonly loader: string;
  19. readonly file: string;
  20. readonly url: string;
  21. readonly sha512: string;
  22. }
  23. export interface McVersionInfo {
  24. /** Minecraft version, the id used in `world.version` and CRAFTOS_VERSION. */
  25. readonly mc: string;
  26. /** The CC:Tweaked version computers behave as (the newest for that Minecraft). */
  27. readonly cc: string;
  28. /** Mod loaders it exists for; the first is the default. The ROM is the same for each (byte-identical). */
  29. readonly loaders: readonly string[];
  30. /** The jars build-rom.mjs can download; the first one is used. */
  31. readonly jars: readonly CcJar[];
  32. /** ROM directory under rom/ (scripts/build-rom.mjs writes it). */
  33. readonly romDir: string;
  34. /**
  35. * Turtle block data in the ROM (rom-overlay/rom/ccsim/turtle/data/, made by tools/turtledata/extract.py --mc): 1.18.2
  36. * and 1.20.1 have their own sets; 1.21.1 has none yet, and ccsim falls back to 1.18.2's (turtle/data.lua).
  37. */
  38. readonly blockDataDir: string;
  39. }
  40. /** The CC:Tweaked version the engine behaves as without --cc-version. */
  41. export const ENGINE_DEFAULT_CC = "1.101.3";
  42. const CC_121_DIR = "cc-1.121.0";
  43. export const VERSIONS: readonly McVersionInfo[] = [
  44. {
  45. mc: "1.18.2",
  46. cc: "1.101.3",
  47. loaders: ["forge"],
  48. jars: [
  49. {
  50. loader: "forge",
  51. file: "cc-tweaked-1.18.2-1.101.3.jar",
  52. url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/fmRxKFx2/cc-tweaked-1.18.2-1.101.3.jar",
    • Warning: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 57 on GitHub
  53. sha512:
  54. "dff864e824f111b5901414b633e13ca2ff3685195f1d2992bdf6a3470fb6e1119ba7e995d99575296415fccb00c6cb99939e6a47fdc7983b322f3f65e805a27f",
  55. },
  56. ],
  57. romDir: "cc-1.101.3",
  58. blockDataDir: "/rom/ccsim/turtle/data/",
  59. },
  60. {
  61. mc: "1.20.1",
  62. cc: "1.121.0",
  63. loaders: ["forge", "fabric"],
  64. jars: [
  65. {
  66. loader: "forge",
  67. file: "cc-tweaked-1.20.1-forge-1.121.0.jar",
  68. url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/Qm9iIIEY/cc-tweaked-1.20.1-forge-1.121.0.jar",
    • Warning: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 73 on GitHub
  69. sha512:
  70. "6ebe4c1e8e6165cb97f071a5a54acd942c234ae62d36330369fdae4bf720a93e99b84e833385f0f103e8fb03425ed20c9f9122411f0008e8ac9efa24b719522d",
  71. },
  72. {
  73. loader: "fabric",
  74. file: "cc-tweaked-1.20.1-fabric-1.121.0.jar",
  75. url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/LFj8qZ7a/cc-tweaked-1.20.1-fabric-1.121.0.jar",
    • Warning: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 80 on GitHub
  76. sha512:
  77. "20d29a7f0c239433fe35d4607ccba8b5a65e30f0bfdeba6f0b5a4307c83dc257b3eff4bc25644009f517b062c54d7d3e54ef58ae63db8ac6e43498d73757557a",
  78. },
  79. ],
  80. romDir: CC_121_DIR,
  81. blockDataDir: "/rom/ccsim/turtle/data/1.20.1/",
  82. },
  83. {
  84. mc: "1.21.1",
  85. cc: "1.121.0",
  86. loaders: ["neoforge", "fabric"],
  87. jars: [
  88. {
  89. // Modrinth names the NeoForge build "forge"
  90. loader: "neoforge",
  91. file: "cc-tweaked-1.21.1-forge-1.121.0.jar",
  92. url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/KNdTEfUA/cc-tweaked-1.21.1-forge-1.121.0.jar",
    • Warning: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 97 on GitHub
  93. sha512:
  94. "042f9c2de7f73f83dbe848c79ddab6383ecef5e6c4a9b51f50fdcae70caa4759d4a2cf5d14e8a3ba4d94ce4a79340c4d2fe0c8b33c33a268e21b164021d25ae3",
  95. },
  96. {
  97. loader: "fabric",
  98. file: "cc-tweaked-1.21.1-fabric-1.121.0.jar",
  99. url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/ThbQoK4I/cc-tweaked-1.21.1-fabric-1.121.0.jar",
    • Warning: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 104 on GitHub
  100. sha512:
  101. "7f00c7ed5011d817c8c1405400c1738ddf13971c4a0b7f7a9aa5d98f5e41cc7ac0915c99e36a751e134f009158a1c0078ca354da8395058671d7c40eafc738fd",
  102. },
  103. ],
  104. romDir: CC_121_DIR,
  105. blockDataDir: "/rom/ccsim/turtle/data/1.21.1/",
  106. },
  107. ];
  108. /** What a world (or CRAFTOS_VERSION) may say. */
  109. export type VersionSpec =
  110. | string
  111. | {
  112. /** Minecraft version. */
  113. readonly mc: string;
  114. /** CC:Tweaked version; must be the one this Minecraft version has. */
  115. readonly cc?: string;
  116. /** Mod loader (forge, fabric, neoforge). Default: the version's first. */
  117. readonly loader?: string;
  118. };
  119. /** A version resolved against VERSIONS: what the runner, the engine and ccsim (core.version) get. */
  120. export interface ResolvedVersion {
  121. readonly mc: string;
  122. readonly cc: string;
  123. readonly loader: string;
  124. /** rom/<romDir> */
  125. readonly romDir: string;
  126. readonly blockDataDir: string;
  127. }
  128. const numbers = (mc: string): number[] => mc.split(".").map(Number);
  129. /** The newest Minecraft version there is a ROM for, by its numbers (1.21.1 over 1.20.1 over 1.18.2). */
  130. export const NEWEST_MC: string = VERSIONS.map((v) => v.mc).reduce((a, b) => {
  131. const [x, y] = [numbers(a), numbers(b)];
  132. for (let i = 0; i < Math.max(x.length, y.length); i++)
  133. if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0) ? a : b;
  134. return a;
  135. });
  136. /** The version a world runs with none given: the newest there is (NEWEST_MC), so a new version moves it. */
  137. export const DEFAULT_MC: string = NEWEST_MC;
  138. /** The versions for a help line: "1.18.2 (CC:Tweaked 1.101.3), 1.20.1 or 1.21.1 (CC:Tweaked 1.121.0); default ...". */
  139. export function versionChoices(): string {
  140. const groups: string[] = [];
  141. for (const cc of new Set(VERSIONS.map((v) => v.cc))) {
  142. const mcs = VERSIONS.filter((v) => v.cc === cc).map((v) => v.mc);
  143. groups.push(`${mcs.join(" or ")} (CC:Tweaked ${cc})`);
  144. }
  145. return `${groups.join(", ")}; default ${DEFAULT_MC}`;
  146. }
  147. const BY_MC = new Map(VERSIONS.map((v) => [v.mc, v]));
  148. const KNOWN_CC = [...new Set(VERSIONS.map((v) => v.cc))];
  149. export function versionInfo(mc: string): McVersionInfo | undefined {
  150. return BY_MC.get(mc);
  151. }
  152. function known(): string {
  153. return VERSIONS.map((v) => `${v.mc} (CC:Tweaked ${v.cc})`).join(", ");
  154. }
  155. function parseSpec(spec: VersionSpec, from: string): ResolvedVersion {
  156. let mc: string;
  157. let cc: string | undefined;
  158. let loader: string | undefined;
  159. if (typeof spec === "string") {
  160. const text = spec.trim();
  161. if (text.startsWith("{")) {
  162. let parsed: unknown;
  163. try {
  164. parsed = JSON.parse(text);
  165. } catch (error) {
  166. throw new Error(`${from}: not valid JSON: ${(error as Error).message}`);
  167. }
  168. return parseSpec(parsed as VersionSpec, from);
  169. }
  170. mc = text;
  171. } else if (spec && typeof spec === "object" && typeof spec.mc === "string") {
  172. mc = spec.mc.trim();
  173. if (spec.cc !== undefined) {
  174. if (typeof spec.cc !== "string")
  175. throw new Error(`${from}.cc must be a string like "1.121.0"`);
  176. cc = spec.cc.trim();
  177. }
  178. if (spec.loader !== undefined) {
  179. if (typeof spec.loader !== "string")
  180. throw new Error(`${from}.loader must be a string like "forge"`);
  181. loader = spec.loader.trim().toLowerCase();
  182. }
  183. } else {
  184. throw new Error(
  185. `${from} must be a Minecraft version ("1.20.1") or { mc, cc?, loader? }`,
  186. );
  187. }
  188. const info = BY_MC.get(mc);
  189. if (!info)
  190. throw new Error(
  191. `${from}: unknown Minecraft version ${JSON.stringify(mc)}; known: ${known()}`,
  192. );
  193. if (cc !== undefined && !KNOWN_CC.includes(cc))
  194. throw new Error(
  195. `${from}: unknown CC:Tweaked version ${JSON.stringify(cc)}; known: ${KNOWN_CC.join(", ")}`,
  196. );
  197. if (loader !== undefined && !info.loaders.includes(loader))
  198. throw new Error(
  199. `${from}: CC:Tweaked for Minecraft ${mc} has no ${JSON.stringify(loader)} build; loaders: ${info.loaders.join(", ")}`,
  200. );
  201. const ccVersion = cc ?? info.cc;
  202. return {
  203. mc,
  204. cc: ccVersion,
  205. loader: loader ?? info.loaders[0]!,
  206. // the ROM follows the CC version (one ROM serves every Minecraft on that CC)
  207. romDir:
  208. VERSIONS.find((v) => v.cc === ccVersion && v.mc === mc)?.romDir ??
  209. `cc-${ccVersion}`,
  210. blockDataDir: info.blockDataDir,
  211. };
  212. }
  213. /** The version a world runs as: world.version, else CRAFTOS_VERSION, else DEFAULT_MC. Unknown versions are refused. */
  214. export function resolveVersion(
  215. worldVersion: VersionSpec | undefined,
  216. env: NodeJS.ProcessEnv = process.env,
  217. ): ResolvedVersion {
  218. if (worldVersion !== undefined)
  219. return parseSpec(worldVersion, "world.version");
  220. const envSpec = env["CRAFTOS_VERSION"];
  221. if (envSpec !== undefined && envSpec.trim() !== "")
  222. return parseSpec(envSpec, "CRAFTOS_VERSION");
  223. return parseSpec(DEFAULT_MC, "default");
  224. }
  225. /** Whether this is the version the emulator behaves as with no version given (no engine flag, the default ROM). */
  226. export function isDefaultVersion(version: ResolvedVersion): boolean {
  227. return version.mc === DEFAULT_MC && version.cc === ENGINE_DEFAULT_CC;
  228. }
  229. /**
  230. * The ROM for a version. The default version (DEFAULT_MC) uses config.romDir, as every run did before versions
  231. * existed; other versions use rom/<romDir>. CRAFTOS_ROM (config.romsDir then unset) names one ROM for every version.
  232. */
  233. export function romDirFor(
  234. config: RunnerConfig,
  235. version: ResolvedVersion,
  236. ): string {
  237. if (!config.romsDir || version.romDir === versionInfo(DEFAULT_MC)!.romDir)
  238. return config.romDir;
  239. return join(config.romsDir, version.romDir);
  240. }
  241. /** Engine arguments for a version: none for 1.101.3 (the engine's own default), else --cc-version. */
  242. export function engineVersionArgs(version: ResolvedVersion): string[] {
  243. return version.cc === ENGINE_DEFAULT_CC ? [] : ["--cc-version", version.cc];
  244. }
  245. /** What ccsim reads as core.version (world.json `version`). */
  246. export function versionForSim(version: ResolvedVersion): {
  247. mc: string;
  248. cc: string;
  249. loader: string;
  250. blockData: string;
  251. } {
  252. return {
  253. mc: version.mc,
  254. cc: version.cc,
  255. loader: version.loader,
  256. blockData: version.blockDataDir,
  257. };
  258. }
  259. /** For craftos_info and `craftos-mcp info`: the default version and every version there is. */
  260. export function versionReport(env: NodeJS.ProcessEnv = process.env): {
  261. source: string;
  262. default: { mc: string; cc: string; loader: string } | undefined;
  263. versions: { mc: string; cc: string; loaders: readonly string[] }[];
  264. } {
  265. let current: ResolvedVersion | undefined;
  266. let source: string;
  267. try {
  268. current = resolveVersion(undefined, env);
  269. source =
  270. env["CRAFTOS_VERSION"] !== undefined && env["CRAFTOS_VERSION"] !== ""
  271. ? `CRAFTOS_VERSION=${env["CRAFTOS_VERSION"]}`
  272. : `default: Minecraft ${DEFAULT_MC} (set world.version or CRAFTOS_VERSION for another)`;
  273. } catch (error) {
  274. source = `CRAFTOS_VERSION is invalid: ${(error as Error).message}`;
  275. }
  276. return {
  277. source,
  278. default: current && {
  279. mc: current.mc,
  280. cc: current.cc,
  281. loader: current.loader,
  282. },
  283. versions: VERSIONS.map((v) => ({
  284. mc: v.mc,
  285. cc: v.cc,
  286. loaders: v.loaders,
  287. })),
  288. };
  289. }
scripts/compat/projects/games-media.mjs · Bundled script · 555 lines · 2 findings marked
  1. // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
  2. import { shellInstall, watchAnimation } from "../helpers.mjs";
  3. const RAW = "https://raw.githubusercontent.com";
  4. const SPEAKER = { peripherals: [{ name: "right", type: "speaker" }] };
  5. /**
  6. * The installer most PineStore games share: a progress bar, then "Finished installation! Press any key to close...".
  7. */
  8. async function pineInstall(t, line, timeoutMs = 180000) {
  9. if (!t.booted) await t.boot();
  10. await t.shell(line);
  11. await t.waitFor(/Finished installation!|Press any key/, timeoutMs);
  12. t.noCrash();
  13. await t.key("enter");
  14. await t.waitForPrompt(15000);
  15. }
  16. /** A picture, not a blank or nearly blank screen. */
  17. function expectPicture(t, what, least = 8) {
  18. const variety = t.variety();
  19. if (variety < least)
  20. t.fail(`${what} drew next to nothing (${variety} kinds of cell)`);
  21. }
  22. /** Do something and check the screen is not what it was. */
  23. async function expectReaction(t, what, act, settleMs = 600) {
  24. const before = t.frameHash();
  25. await act();
  26. await t.sleep(settleMs);
  27. t.noCrash();
  28. if (t.frameHash() === before) t.fail(`${what} changed nothing on screen`);
  29. }
  30. /** How many audio buffers a speaker has taken. */
  31. const audioCount = (t, name = "right") =>
  32. t.speaker(name).raw?.audio?.pushed ?? 0;
  33. export default [
  34. {
  35. id: "chess",
  36. name: "Chess",
  37. url: "https://github.com/aTimmYm/Chess",
  38. category: "program",
  39. section: "Games",
  40. // its sha2 library picks CC's `bit` API over bit32 unless _VERSION is "Lua 5.2", and `bit` lacks what it needs
  41. minCC: "1.109.0",
  42. async run(t) {
  43. await t.boot();
  44. await t.shell(
  45. `wget run "${RAW}/aTimmYm/Chess/refs/heads/main/installer.lua"`,
  46. );
  47. await t.waitFor("success", 120000);
  48. await t.waitForPrompt(10000);
  49. t.noCrash();
  50. if (!t.exists("main.lua")) t.fail(`no main.lua installed: ${t.list()}`);
  51. // main.lua starts the graphics-mode version when the terminal has CraftOS-PC's setGraphicsMode, and nothing
  52. // otherwise (its text-mode branch tests a variable that is never set): on CC:Tweaked it returns without a
  53. // word. So the check starts the text-mode game the way that branch would have.
  54. await t.shell("main");
  55. await t.waitForPrompt(10000);
  56. t.noCrash();
  57. t.put(
  58. "textmode.lua",
  59. `package.path = package.path .. ";/Data/?;/Data/?.lua;/Data/?/init.lua"\nos.run(_ENV, "TM.lua")\n`,
  60. );
  61. await t.shell("clear");
  62. await t.shell("textmode");
  63. await t.sleep(5000);
  64. await t.shot("menu");
  65. t.noCrash();
  66. if (/> ?$/.test(t.text().trimEnd()))
  67. t.fail(`TM.lua ended at once:\n${t.text()}`);
  68. expectPicture(t, "the main menu", 6);
  69. t.expect("Local Game");
  70. await expectReaction(
  71. t,
  72. "starting a local game",
  73. () => t.clickText("Local Game"),
  74. 2500,
  75. );
  76. await t.shot("board");
  77. // a first move: the pawn in front of the king, two squares up (wherever the board is, clicking two cells in
  78. // its middle column must not break anything)
  79. const { width, height } = {
  80. width: t.lines()[0].length,
  81. height: t.lines().length,
  82. };
  83. await t.click(Math.floor(width / 2), height - 4);
  84. await t.click(Math.floor(width / 2), height - 8);
  85. await t.sleep(1000);
  86. await t.shot("moved");
  87. t.noCrash();
  88. },
  89. },
  90. {
  91. id: "ccdoom",
  92. name: "CCDoom",
  93. url: "https://github.com/Xella37/CCDoom",
  94. category: "program",
  95. section: "Games",
  96. async run(t) {
  97. await pineInstall(t, "pastebin run xLC8mABU");
  98. await t.shell("Doom");
  99. await t.sleep(3000);
  100. await t.shot("menu");
  101. t.noCrash();
  102. expectPicture(t, "the title screen");
  103. // Play, then "Normal Mode"
  104. await t.key("enter");
  105. await t.waitFor("Normal Mode", 15000);
  106. await t.shot("modes");
  107. await t.key("enter");
  108. await t.waitFor(/^(?![\s\S]*Normal Mode)/, 30000);
  109. await t.sleep(4000);
  110. await t.shot("level");
  111. t.noCrash();
  112. expectPicture(t, "the level", 12);
  113. await expectReaction(t, "walking and turning", async () => {
  114. await t.hold("w", 700);
  115. await t.hold("right", 500);
  116. });
  117. await expectReaction(
  118. t,
  119. "shooting and walking on",
  120. async () => {
  121. await t.key("space");
  122. await t.hold("s", 600);
  123. },
  124. 800,
  125. );
  126. await t.shot("played");
  127. },
  128. },
  129. {
  130. id: "watermelon-game",
  131. name: "Watermelon Game 3D",
  132. url: "https://github.com/Xella37/Watermelon-Game-3D",
  133. category: "program",
  134. section: "Games",
  135. async run(t) {
  136. await t.boot();
  137. await t.shell("wget run https://pinestore.cc/d/psi/32");
  138. await t.sleep(4000);
  139. await t.shot("installer");
  140. for (let i = 0; i < 60 && !/> ?$/.test(t.text().trimEnd()); i++) {
  141. if (t.has(/[Pp]ress any key|key to/)) await t.key("enter");
  142. await t.sleep(2000);
  143. }
  144. await t.waitForPrompt(10000);
  145. t.noCrash();
  146. await t.shell("WatermelonGame");
  147. await t.waitFor("Press enter to continue", 15000);
  148. await t.shot("controls");
  149. await t.key("enter");
  150. await t.sleep(3000);
  151. await t.shot("game");
  152. t.noCrash();
  153. expectPicture(t, "the game");
  154. await expectReaction(t, "moving and dropping a fruit", async () => {
  155. await t.hold("left", 400);
  156. await t.key("space");
  157. await t.sleep(1500);
  158. await t.hold("right", 600);
  159. await t.key("space");
  160. });
  161. await t.shot("dropped");
  162. },
  163. },
  164. {
  165. id: "tetracraft",
  166. name: "Tetracraft",
  167. url: "https://pastebin.com/2jmN835i",
    • Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
    • Warning: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 173 on GitHub
  168. category: "program",
  169. section: "Games",
  170. async run(t) {
  171. await shellInstall(t, "pastebin get 2jmN835i tetracraft");
  172. t.hash("tetracraft");
  173. await t.shell("tetracraft");
  174. await t.sleep(2500);
  175. await t.shot("start");
  176. t.noCrash();
  177. expectPicture(t, "the game", 4);
  178. await expectReaction(t, "moving a piece", async () => {
  179. await t.key("left");
  180. await t.key("left");
  181. await t.key("up");
  182. await t.hold("down", 600);
  183. });
  184. await t.shot("played");
  185. await watchAnimation(t, 3000, 2);
  186. },
  187. },
  188. {
  189. id: "cc-minecraft",
  190. name: "CC:Minecraft",
  191. url: "https://github.com/Xella37/CC-Minecraft",
  192. category: "program",
  193. section: "Games",
  194. async run(t) {
  195. await pineInstall(t, "pastebin run hgm142Pj");
  196. await t.shell("Minecraft");
  197. await t.waitFor("Singleplayer", 20000);
  198. await t.shot("menu");
  199. await t.clickText("Singleplayer");
  200. await t.sleep(1500);
  201. await t.shot("worlds");
  202. await t.clickText("New World");
  203. await t.waitFor("World Creation");
  204. const name = t.find("Name:");
  205. await t.click(name.x + 12, name.y);
  206. await t.type("compat");
  207. await t.shot("creation");
  208. await t.clickText("Create World");
  209. // generating the world takes a while
  210. await t.waitFor(/^(?![\s\S]*World Creation)/, 60000);
  211. await t.sleep(6000);
  212. await t.shot("start");
  213. t.noCrash();
  214. expectPicture(t, "the world", 10);
  215. await expectReaction(t, "walking and looking around", async () => {
  216. await t.hold("w", 800);
  217. await t.hold("left", 600);
  218. });
  219. await t.shot("walked");
  220. // break the block in front, pick another and place it
  221. await t.click(26, 10, 1);
  222. await t.key("two");
  223. await t.click(26, 10, 2);
  224. await t.sleep(500);
  225. await t.shot("built");
  226. t.noCrash();
  227. },
  228. },
  229. {
  230. id: "rubiks-cube",
  231. name: "CC Rubik's Cube",
  232. url: "https://github.com/MichielP1807/CC-Rubiks-Cube",
  233. category: "program",
  234. section: "Games",
  235. async run(t) {
  236. await pineInstall(t, "pastebin run A5wTQs2B");
  237. await t.shell("Cube");
  238. await t.sleep(3000);
  239. await t.shot("cube");
  240. t.noCrash();
  241. expectPicture(t, "the cube");
  242. await expectReaction(t, "turning the cube", () => t.hold("left", 600));
  243. await expectReaction(t, "turning a face", async () => {
  244. await t.key("e");
  245. await t.key("space");
  246. });
  247. await t.shot("turned");
  248. },
  249. },
  250. {
  251. id: "the-button",
  252. name: "The Button",
  253. url: "https://github.com/MichielP1807/CC-Bored-Button",
  254. category: "program",
  255. section: "Games",
  256. async run(t) {
  257. await pineInstall(
  258. t,
  259. `wget run ${RAW}/MichielP1807/CC-Bored-Button/main/installer.lua`,
  260. );
  261. await t.shell("Button");
  262. await t.sleep(3000);
  263. await t.shot("button");
  264. t.noCrash();
  265. expectPicture(t, "the button");
  266. await expectReaction(t, "pressing the button", async () => {
  267. await t.click(26, 10);
  268. await t.click(26, 10);
  269. });
  270. await t.shot("pressed");
  271. },
  272. },
  273. {
  274. id: "samurai-salad",
  275. name: "Samurai Salad",
  276. url: "https://github.com/MichielP1807/CC-Samurai-Salad",
  277. category: "program",
  278. section: "Games",
  279. async run(t) {
  280. await pineInstall(t, "pastebin run Sxfk57tP");
  281. await t.shell("SamuraiSalad");
  282. await t.sleep(3000);
  283. await t.shot("start");
  284. t.noCrash();
  285. expectPicture(t, "the game");
  286. // slicing is dragging the mouse across the fruit
  287. await t.drag(10, 14, 40, 5);
  288. await t.drag(40, 14, 10, 5);
  289. await watchAnimation(t, 2500, 3);
  290. await t.shot("sliced");
  291. },
  292. },
  293. {
  294. id: "spamtons-jump",
  295. name: "Spamton's Jump",
  296. url: "https://github.com/simadude/obsi2-pinejam25-game",
  297. category: "program",
  298. section: "Games",
  299. // its installer fetches the sprites as text: before CC:Tweaked 1.109 a text handle decodes UTF-8 and they
  300. // arrive damaged ("Unknown character (?) ... Make sure your image is valid")
  301. minCC: "1.109.0",
  302. world: SPEAKER,
  303. async run(t) {
  304. await t.boot();
  305. await t.shell(
  306. `wget run ${RAW}/simadude/obsi2-pinejam25-game/refs/heads/main/installer.lua`,
  307. );
  308. await t.sleep(5000);
  309. await t.shot("installer");
  310. for (let i = 0; i < 60 && !/> ?$/.test(t.text().trimEnd()); i++) {
  311. if (t.has("Continue")) await t.clickText("Continue");
  312. await t.sleep(2000);
  313. }
  314. await t.waitForPrompt(10000);
  315. t.noCrash();
  316. await t.shot("installed");
  317. await t.shell("main");
  318. await t.sleep(3000);
  319. await t.shot("title");
  320. t.noCrash();
  321. expectPicture(t, "the title screen", 4);
  322. await t.key("enter");
  323. await t.key("space");
  324. await t.sleep(1500);
  325. await expectReaction(t, "running and jumping", async () => {
  326. await t.hold("right", 600);
  327. await t.key("space");
  328. await t.key("up");
  329. });
  330. await t.shot("played");
  331. },
  332. },
  333. {
  334. id: "mine-clicker",
  335. name: "Mine Clicker",
  336. url: "https://github.com/Sparkwave2/mine-clicker",
  337. category: "program",
  338. section: "Games",
  339. world: SPEAKER,
  340. async run(t) {
  341. await shellInstall(t, "pastebin get hgw016VY mineclicker.lua");
  342. t.hash("mineclicker.lua");
  343. await t.shell("mineclicker");
  344. await t.sleep(2500);
  345. await t.shot("start");
  346. t.noCrash();
  347. expectPicture(t, "the game", 4);
  348. await expectReaction(t, "clicking the block", async () => {
  349. for (let i = 0; i < 6; i++) await t.click(12, 9, 1, 80);
  350. });
  351. await t.shot("clicked");
  352. },
  353. },
  354. {
  355. id: "crazy-cargo-crusade",
  356. name: "Crazy Cargo Crusade",
  357. url: "https://github.com/SammyForReal/CrazyCargoCrusade",
  358. category: "program",
  359. section: "Games",
  360. async run(t) {
  361. await shellInstall(
  362. t,
  363. "wget https://github.com/SammyForReal/CrazyCargoCrusade/releases/download/0.1.0/ccc.lua",
  364. );
  365. t.hash("ccc.lua");
  366. await t.shell("ccc");
  367. await t.sleep(4000);
  368. await t.shot("start");
  369. t.noCrash();
  370. expectPicture(t, "the game", 4);
  371. await t.key("enter");
  372. await t.sleep(1500);
  373. await expectReaction(t, "driving", async () => {
  374. await t.hold("w", 800);
  375. await t.hold("a", 400);
  376. });
  377. await t.shot("driving");
  378. },
  379. },
  380. {
  381. id: "pumpkin-carver",
  382. name: "Pumpkin Carver",
  383. url: "https://github.com/Xella37/Pumpkin-Carver",
  384. category: "program",
  385. section: "Games",
  386. async run(t) {
  387. await t.boot();
  388. await t.shell("wget run https://pinestore.cc/d/psi/118");
  389. await t.sleep(4000);
  390. for (let i = 0; i < 60 && !/> ?$/.test(t.text().trimEnd()); i++) {
  391. if (t.has(/[Pp]ress any key|key to/)) await t.key("enter");
  392. await t.sleep(2000);
  393. }
  394. await t.waitForPrompt(10000);
  395. t.noCrash();
  396. await t.shell("pumpkincarver");
  397. // its own instructions end with "Press any key to continue..."
  398. await t.waitFor("Press any key to continue", 15000);
  399. await t.shot("instructions");
  400. await t.key("enter");
  401. await t.sleep(3000);
  402. await t.shot("pumpkin");
  403. t.noCrash();
  404. expectPicture(t, "the pumpkin");
  405. await expectReaction(t, "carving", () => t.drag(22, 8, 30, 12));
  406. await t.shot("carved");
  407. },
  408. },
  409. {
  410. id: "meowsynth",
  411. name: "MeowSynthCC",
  412. url: "https://github.com/MichielP1807/MeowSynthCC",
  413. category: "program",
  414. section: "Audio and video players",
  415. world: SPEAKER,
  416. async run(t) {
  417. await pineInstall(
  418. t,
  419. `wget run ${RAW}/MichielP1807/MeowSynthCC/main/installer.lua`,
  420. );
  421. await t.shell("meow");
  422. await t.sleep(3000);
  423. await t.shot("synth");
  424. t.noCrash();
  425. expectPicture(t, "the synth");
  426. const before = audioCount(t);
  427. // the keyboard row plays notes
  428. for (let round = 0; round < 5 && audioCount(t) <= before; round++) {
  429. for (const key of ["a", "s", "d", "f"]) await t.hold(key, 250);
  430. await t.sleep(1000);
  431. }
  432. await t.shot("played");
  433. t.noCrash();
  434. if (audioCount(t) <= before)
  435. t.fail(
  436. `playing four notes sent the speaker no audio: ${JSON.stringify(t.speaker("right").raw).slice(0, 300)}`,
  437. );
  438. },
  439. },
  440. {
  441. id: "herobrine",
  442. name: "Herobrine",
  443. url: "https://github.com/MCJack123/Herobrine",
  444. category: "program",
  445. section: "Demoscene and proof of concept",
  446. // the release is one file with its data as raw bytes in a string: before CC:Tweaked 1.109 a program is read as
  447. // UTF-8 text and those bytes do not survive
  448. minCC: "1.109.0",
  449. world: SPEAKER,
  450. timeoutS: 420,
  451. async run(t) {
  452. await shellInstall(
  453. t,
  454. "wget https://github.com/MCJack123/Herobrine/releases/download/1.0.1/herobrine.lua herobrine.lua",
  455. 120000,
  456. );
  457. t.hash("herobrine.lua");
  458. await t.shell("herobrine");
  459. await t.sleep(8000);
  460. await t.shot("start");
  461. t.noCrash();
  462. // the demo is timed to its soundtrack: sample it for a minute and a half
  463. let frames = 0;
  464. for (let i = 0; i < 9; i++) {
  465. frames += await watchAnimation(t, 10000, 1);
  466. await t.shot(`at-${(i + 1) * 10 + 8}s`);
  467. if (/> ?$/.test(t.text().trimEnd())) break;
  468. }
  469. t.note(`${frames} different frames seen, ${audioCount(t)} audio buffers`);
  470. if (frames < 40) t.fail(`only ${frames} different frames in the demo`);
  471. if (audioCount(t) < 10)
  472. t.fail(`the soundtrack sent the speaker ${audioCount(t)} buffers`);
  473. },
  474. },
  475. {
  476. id: "4th-dimension",
  477. name: "4th Dimension",
  478. url: "https://github.com/MCJack123/4thDimension",
  479. category: "program",
  480. section: "Demoscene and proof of concept",
  481. // Its music is mixed in Lua while it plays. At the 8 times slowdown the other checks use, one mixing pass runs
  482. // past CC's 7 seconds without yielding; at 4 times it plays, late. It runs here at the engine's own speed, and
  483. // notes.mjs says so: which of these a real computer is on this workload has not been measured.
  484. world: { ...SPEAKER, cobaltSpeed: false },
  485. timeoutS: 420,
  486. async run(t) {
  487. const repo = t.clone("https://github.com/MCJack123/4thDimension");
  488. t.install(repo, ".");
  489. await t.boot();
  490. await t.shell("player");
  491. await t.sleep(8000);
  492. await t.shot("start");
  493. t.noCrash();
  494. let frames = 0;
  495. for (let i = 0; i < 9; i++) {
  496. frames += await watchAnimation(t, 10000, 1);
  497. await t.shot(`at-${(i + 1) * 10 + 8}s`);
  498. if (/> ?$/.test(t.text().trimEnd())) break;
  499. }
  500. t.note(`${frames} different frames seen, ${audioCount(t)} audio buffers`);
  501. if (frames < 40) t.fail(`only ${frames} different frames in the demo`);
  502. if (audioCount(t) < 10)
  503. t.fail(`the soundtrack sent the speaker ${audioCount(t)} buffers`);
  504. },
  505. },
  506. {
  507. id: "jane-demo",
  508. name: "Jane Demo",
  509. url: "https://github.com/piguman3/PineJam2026Demo",
  510. category: "program",
  511. section: "Demoscene and proof of concept",
  512. world: SPEAKER,
  513. async run(t) {
  514. const repo = t.clone("https://github.com/piguman3/PineJam2026Demo");
  515. for (const file of [
  516. "demo.lua",
  517. "Pine3D.lua",
  518. "betterblittle.lua",
  519. "anim.bin",
  520. "janecut.dfpwm",
  521. ])
  522. t.install(`${repo}/${file}`, file);
  523. await t.boot();
  524. const started = Date.now();
  525. await t.shell("demo");
  526. await t.sleep(3000);
  527. await t.shot("start");
  528. t.noCrash();
  529. let frames = 0;
  530. for (let i = 0; i < 4; i++) {
  531. frames += await watchAnimation(t, 8000, 1);
  532. await t.shot(`at-${(i + 1) * 8 + 3}s`);
  533. if (/> ?$/.test(t.text().trimEnd())) break;
  534. }
  535. // "a really tiny 38 second demo": it ends on its own
  536. await t.waitForPrompt(30000);
  537. const seconds = (Date.now() - started) / 1000;
  538. t.note(
  539. `${frames} different frames seen, ${audioCount(t)} audio buffers, ended after ${seconds.toFixed(0)} s`,
  540. );
  541. t.noCrash();
  542. if (frames < 30) t.fail(`only ${frames} different frames in the demo`);
  543. if (audioCount(t) < 10)
  544. t.fail(`the soundtrack sent the speaker ${audioCount(t)} buffers`);
  545. if (seconds < 30 || seconds > 60)
  546. t.fail(`a 38 second demo took ${seconds.toFixed(0)} s`);
  547. },
  548. },
  549. ];
scripts/compat/projects/libraries-other.mjs · Bundled script · 494 lines · 2 findings marked
  1. // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
  2. import { shellInstall } from "../helpers.mjs";
  3. const RAW = "https://raw.githubusercontent.com";
  4. const GIST = "https://gist.githubusercontent.com";
  5. const chest = (n, items = {}) => ({
  6. name: `minecraft:chest_${n}`,
  7. type: "minecraft:chest",
  8. size: 27,
  9. items,
  10. });
  11. /** Chests behind wired modems on one cable, and the computer's own wired modem on it, as a storage room has. */
  12. const storageRoom = (...chests) => ({
  13. world: {
  14. peripherals: [
  15. { name: "back", type: "modem", kind: "wired", network: "storage" },
  16. ],
  17. },
  18. wired: [{ id: "storage", peripherals: chests }],
  19. });
  20. export default [
  21. {
  22. id: "ecnet2",
  23. name: "ECNet2",
  24. url: "https://github.com/migeyel/ecnet",
  25. category: "library",
  26. section: "Networking",
  27. computers: [
  28. {
  29. name: "server",
  30. world: {
  31. peripherals: [{ name: "top", type: "modem" }],
  32. position: { x: 0, y: 64, z: 0 },
  33. },
  34. },
  35. {
  36. name: "client",
  37. world: {
  38. peripherals: [{ name: "top", type: "modem" }],
  39. position: { x: 5, y: 64, z: 0 },
  40. },
  41. },
  42. ],
  43. async run(t) {
  44. const client = t.computer("client");
  45. const ecnet = t.clone("https://github.com/migeyel/ecnet", "ecnet");
  46. const crypto = t.clone(
  47. "https://github.com/migeyel/ccryptolib",
  48. "ccryptolib",
  49. );
  50. for (const c of [t, client]) {
  51. c.install(`${ecnet}/ecnet2`, "ecnet2");
  52. c.install(`${crypto}/ccryptolib`, "ccryptolib");
  53. }
  54. // its own ping example: the server as it is, the client with the server's real address in place of the
  55. // author's
  56. t.install(`${ecnet}/examples/ping/server.lua`, "server.lua");
  57. t.put(
  58. "address.lua",
  59. `local ecnet2 = require "ecnet2"
  60. require "ccryptolib.random".initWithTiming()
  61. local h = fs.open("address.txt", "w") h.write(ecnet2.Identity("/.ecnet2").address) h.close()
  62. `,
  63. );
  64. await t.boot();
  65. await t.shell("address");
  66. await t.waitForFile("address.txt", 30000);
  67. await t.waitForPrompt();
  68. t.noCrash();
  69. const address = t.read("address.txt");
  70. if (!/^[A-Za-z0-9_-]{43}=$/.test(address))
  71. t.fail(`the identity's address is ${address}`);
  72. const { readFileSync } = await import("node:fs");
  73. const source = readFileSync(
  74. `${ecnet}/examples/ping/client.lua`,
  75. "utf8",
  76. ).replace(
  77. /local server = "[^"]*"/,
  78. `local server = ${JSON.stringify(address)}`,
  79. );
  80. client.put("client.lua", source);
  81. await t.shell("server");
  82. await t.sleep(1500);
  83. t.noCrash();
  84. await client.shell("client");
  85. await client.waitFor("ping v1.0", 20000);
  86. await client.shell("hello over ecnet");
  87. await t.waitFor(/got\s+hello over ecnet\s+on channel/, 15000);
  88. await client.waitFor(/hello over ecnet\s*\n\s*hello over ecnet/, 15000);
  89. await t.shot("ping");
  90. await client.shot("ping");
  91. // "from 5 blocks away": the modem's distance, through the encrypted tunnel
  92. t.expect(/from\s+5\s+blocks\s+away/);
  93. t.noCrash();
  94. client.noCrash();
  95. },
  96. },
  97. {
  98. id: "taskmaster",
  99. name: "Taskmaster",
  100. url: "https://gist.github.com/MCJack123/1678fb2c240052f1480b07e9053d4537",
  101. category: "library",
  102. section: "Threads / multitasking",
  103. async run(t) {
  104. await shellInstall(
  105. t,
  106. `wget ${GIST}/MCJack123/1678fb2c240052f1480b07e9053d4537/raw taskmaster.lua`,
  107. );
  108. t.hash("taskmaster.lua");
  109. const out = await t.lua(`
  110. local taskmaster = require("taskmaster")
  111. local order = {}
  112. -- three tasks in parallel, as its first example
  113. taskmaster(
  114. function() sleep(0.3) order[#order + 1] = "slow" end,
  115. function() sleep(0.1) order[#order + 1] = "fast" end,
  116. function() order[#order + 1] = "now" end
  117. ):waitForAll()
  118. result(table.concat(order, ","))
  119. -- event listeners and a timer in one loop, stopped from inside
  120. local loop = taskmaster()
  121. local seen = {}
  122. loop:eventListener("ping", function(ev, n) seen[#seen + 1] = "ping" .. n end)
  123. loop:addTimer(0.1, function() os.queueEvent("ping", #seen + 1) if #seen >= 3 then loop:stop() end end)
  124. loop:run()
  125. result(table.concat(seen, ","))
  126. -- waitForAny returns when the first finishes
  127. local started = os.epoch("utc")
  128. taskmaster(function() sleep(0.2) end, function() sleep(5) end):waitForAny()
  129. result(os.epoch("utc") - started < 1500)
  130. `);
  131. if (out[0] !== "now,fast,slow") t.fail(`task order was ${out[0]}`);
  132. if (!out[1].startsWith("ping1,ping2,ping3"))
  133. t.fail(`listeners saw ${out[1]}`);
  134. if (out[2] !== "true") t.fail("waitForAny waited for the slow task");
  135. },
  136. },
  137. {
  138. id: "redrun",
  139. name: "RedRun",
  140. url: "https://gist.github.com/MCJack123/473475f07b980d57dd2bd818026c97e8",
  141. category: "library",
  142. section: "Threads / multitasking",
  143. async run(t) {
  144. await shellInstall(
  145. t,
  146. `wget ${GIST}/MCJack123/473475f07b980d57dd2bd818026c97e8/raw redrun.lua`,
  147. );
  148. t.hash("redrun.lua");
  149. // RedRun hooks the coroutine rednet.run lives in (through getfenv), so its tasks outlive the program that
  150. // started them: this one keeps answering events from the shell prompt
  151. const out = await t.lua(`
  152. local redrun = require("redrun")
  153. local id = redrun.start(function()
  154. while true do
  155. local _, text = os.pullEvent("compat_note")
  156. local h = fs.open("heard.txt", "a") h.writeLine(text) h.close()
  157. end
  158. end, "listener")
  159. result(type(id), redrun.getid("listener") == id)
  160. os.queueEvent("compat_note", "first")
  161. sleep(0.2)
  162. result(type(redrun.getstate(id)))
  163. `);
  164. if (out[0] !== "number\ttrue") t.fail(`start gave ${out[0]}`);
  165. if (out[1] !== "table") t.fail(`the task's state is a ${out[1]}`);
  166. await t.waitForPrompt();
  167. t.event("compat_note", "second");
  168. await t.sleep(500);
  169. const heard = t.read("heard.txt").trim().split(/\r?\n/).join(",");
  170. if (heard !== "first,second")
  171. t.fail(
  172. `the background task heard "${heard}", not first and then second (after its program ended)`,
  173. );
  174. const killed = await t.lua(`
  175. local redrun = require("redrun")
  176. local id = redrun.getid("listener")
  177. redrun.kill(id)
  178. os.queueEvent("compat_note", "third")
  179. sleep(0.2)
  180. result(redrun.getstate(id))
  181. `);
  182. if (killed[0] !== "nil") t.fail(`after kill its state is ${killed[0]}`);
  183. if (t.read("heard.txt").includes("third"))
  184. t.fail("the killed task still ran");
  185. },
  186. },
  187. {
  188. id: "fatboychummy-thread",
  189. name: "Thread (Fatboychummy libraries)",
  190. url: "https://github.com/Fatboychummy-CC/Libraries/blob/main/thread.lua",
  191. category: "library",
  192. section: "Threads / multitasking",
  193. async run(t) {
  194. const repo = t.clone("https://github.com/Fatboychummy-CC/Libraries");
  195. t.install(repo, "lib");
  196. await t.boot();
  197. const out = await t.lua(`
  198. package.path = package.path .. ";/lib/?.lua"
  199. local thread = require("thread")
  200. local order = {}
  201. thread.new(function() sleep(0.2) order[#order + 1] = "b" end)
  202. thread.new(function() order[#order + 1] = "a" end):after(function() order[#order + 1] = "after-a" end)
  203. thread.new(function() sleep(0.05) error("boom") end):on_error(function() order[#order + 1] = "caught" end)
  204. thread.new(function() sleep(0.5) thread.stop() end)
  205. thread.run()
  206. result(table.concat(order, ","))
  207. `);
  208. for (const want of ["a", "after-a", "caught", "b"])
  209. if (!out[0].split(",").includes(want))
  210. t.fail(`the threads ran as ${out[0]}; ${want} is missing`);
  211. },
  212. },
  213. {
  214. id: "aes",
  215. name: "AES library",
  216. url: "https://gist.github.com/afonya2/489c3306a7d85f8f9512df321d904dbb",
  217. category: "library",
  218. section: "Encryption",
  219. async run(t) {
  220. await shellInstall(
  221. t,
  222. `wget ${GIST}/afonya2/489c3306a7d85f8f9512df321d904dbb/raw aes.lua`,
  223. );
  224. t.hash("aes.lua");
  225. // FIPS-197 appendix C.1: AES-128 of 00112233445566778899aabbccddeeff under 000102030405060708090a0b0c0d0e0f
  226. const out = await t.lua(
  227. `
  228. local aes = require("aes")
  229. local function bytes(hex) local t = {} for b in hex:gmatch("%x%x") do t[#t + 1] = tonumber(b, 16) end return t end
  230. local function hex(t) local s = {} for i = 1, #t do s[i] = ("%02x"):format(t[i]) end return table.concat(s) end
  231. local key = bytes("000102030405060708090a0b0c0d0e0f")
  232. local plain = bytes("00112233445566778899aabbccddeeff")
  233. local cipher = aes.Encrypt(plain, key)
  234. result(hex(cipher))
  235. result(hex(aes.Decrypt(cipher, key)))
  236. local iv = bytes("0f0e0d0c0b0a09080706050403020100")
  237. local text = aes.StringToTable("the quick brown fox jumps over the lazy dog")
  238. local back = aes.DecryptCBC(aes.EncryptCBC(text, key, iv), key, iv)
  239. result(aes.TableToString(back))
  240. `,
  241. 60000,
  242. );
  243. if (!out[0].startsWith("69c4e0d86a7b0430d8cdb78070b4c55a"))
  244. t.fail(`AES-128 of the FIPS-197 vector gave ${out[0]}`);
  245. if (!out[1].startsWith("00112233445566778899aabbccddeeff"))
  246. t.fail(`decrypting gave ${out[1]}`);
  247. if (!out[2].startsWith("the quick brown fox jumps over the lazy dog"))
  248. t.fail(`CBC round trip gave ${out[2]}`);
  249. },
  250. },
  251. {
  252. id: "sha256",
  253. name: "SHA256 / HMAC / PBKDF2 (Anavrins)",
  254. url: "https://pastebin.com/6UV4qfNF",
    • Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
    • Warning: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 257 on GitHub
  255. category: "library",
  256. section: "Encryption",
  257. async run(t) {
  258. await shellInstall(t, "pastebin get 6UV4qfNF sha256.lua");
  259. t.hash("sha256.lua");
  260. const out = await t.lua(
  261. `
  262. local sha = require("sha256")
  263. result(sha.digest("abc"):toHex())
  264. result(sha.digest(""):toHex())
  265. result(sha.digest(("a"):rep(1000)):toHex())
  266. -- RFC 4231 test case 2
  267. result(sha.hmac("what do ya want for nothing?", "Jefe"):toHex())
  268. -- RFC 7914 section 11: PBKDF2-HMAC-SHA256, "passwd" / "salt", 1 iteration, 64 bytes
  269. result(sha.pbkdf2("passwd", "salt", 1, 64):toHex())
  270. `,
  271. 60000,
  272. );
  273. const want = [
  274. "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
  275. "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
  276. "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
  277. "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
  278. "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783",
  279. ];
  280. want.forEach((hash, i) => {
  281. if (out[i] !== hash) t.fail(`vector ${i + 1} gave ${out[i]}`);
  282. });
  283. },
  284. },
  285. {
  286. id: "hopper",
  287. name: "hopper.lua",
  288. url: "https://github.com/umnikos/hopper.lua",
  289. category: "library",
  290. section: "Peripheral management",
  291. ...storageRoom(
  292. chest(0, {
  293. 1: { name: "minecraft:cobblestone", count: 64 },
  294. 2: { name: "minecraft:cobblestone", count: 10 },
  295. 3: { name: "minecraft:iron_ingot", count: 32 },
  296. 5: { name: "minecraft:diamond", count: 3 },
  297. }),
  298. chest(1),
  299. chest(2),
  300. ),
  301. async run(t) {
  302. await shellInstall(t, `wget ${RAW}/umnikos/hopper.lua/main/hopper.lua`);
  303. t.hash("hopper.lua");
  304. // everything but the diamonds from chest 0 to chest 1, once
  305. await t.shell("hopper -once *chest_0 *chest_1 -not *:diamond");
  306. await t.waitForPrompt(30000);
  307. await t.shot("moved");
  308. t.noCrash();
  309. const count = `
  310. local function count(name)
  311. local total = {}
  312. for _, item in pairs(peripheral.call(name, "list")) do total[item.name] = (total[item.name] or 0) + item.count end
  313. local keys = {} for k in pairs(total) do keys[#keys + 1] = k end table.sort(keys)
  314. for i, k in ipairs(keys) do keys[i] = k:gsub("minecraft:", "") .. "=" .. total[k] end
  315. return table.concat(keys, " ")
  316. end`;
  317. let out = await t.lua(
  318. `${count}\nresult(count("minecraft:chest_0")) result(count("minecraft:chest_1"))`,
  319. );
  320. if (out[0] !== "diamond=3")
  321. t.fail(`chest 0 should keep only its diamonds, it holds: ${out[0]}`);
  322. if (out[1] !== "cobblestone=74 iron_ingot=32")
  323. t.fail(`chest 1 holds: ${out[1]}`);
  324. // as a library: require it and move a limited amount
  325. out = await t.lua(
  326. `${count}
  327. local hopper = require("hopper")
  328. hopper("*chest_1 *chest_2 *:iron_ingot -transfer-limit 20 -once")
  329. result(count("minecraft:chest_1")) result(count("minecraft:chest_2"))`,
  330. );
  331. if (out[1] !== "iron_ingot=20")
  332. t.fail(
  333. `a 20 item limit moved: ${out[1]} (chest 1 left with ${out[0]})`,
  334. );
  335. if (out[0] !== "cobblestone=74 iron_ingot=12")
  336. t.fail(`chest 1 holds: ${out[0]}`);
  337. },
  338. },
  339. {
  340. id: "oil",
  341. name: "Open Inventory Library",
  342. url: "https://github.com/afonya2/CC-OpenInvLib",
  343. category: "library",
  344. section: "Peripheral management",
  345. ...storageRoom(
  346. chest(0, {
  347. 1: { name: "minecraft:cobblestone", count: 64 },
  348. 2: { name: "minecraft:oak_log", count: 16 },
  349. }),
  350. chest(1),
  351. chest(2),
  352. ),
  353. async run(t) {
  354. await shellInstall(
  355. t,
  356. `wget ${RAW}/afonya2/CC-OpenInvLib/refs/heads/main/openinvlib.lua oil.lua`,
  357. );
  358. t.hash("oil.lua");
  359. const out = await t.lua(
  360. `
  361. shell.run("oil.lua")
  362. local oil = openInvLib
  363. result(type(oil))
  364. oil.scanPeripherals()
  365. local id = assert(oil.createStorage("main", { "minecraft:chest_0", "minecraft:chest_1" }))
  366. local storage = oil.getStorage(id)
  367. result(storage.getName(), storage.getSize())
  368. local part = storage.getPartition(assert(storage.createPartition("all", 1, storage.getSize())))
  369. oil.scanStorages()
  370. result(part.getItemCount("minecraft:cobblestone"), part.getItemCount("minecraft:oak_log"))
  371. `,
  372. 60000,
  373. );
  374. await t.shot("oil");
  375. if (out[0] !== "table") t.fail("oil.lua left no openInvLib global");
  376. if (out[1] !== "main\t54")
  377. t.fail(`the storage of two chests is ${out[1]}`);
  378. if (out[2] !== "64\t16") t.fail(`the partition counts ${out[2]}`);
  379. },
  380. },
  381. {
  382. id: "desyncc",
  383. name: "DesynCC",
  384. url: "https://github.com/afonya2/DesynCC",
  385. category: "library",
  386. section: "Other libraries",
  387. async run(t) {
  388. await t.boot();
  389. await t.shell(
  390. `wget run ${RAW}/afonya2/DesynCC/refs/heads/main/installer.lua test`,
  391. );
  392. await t.waitFor("[y/n]", 30000);
  393. await t.shell("y");
  394. await t.waitForPrompt(60000);
  395. t.noCrash();
  396. await t.shot("installed");
  397. const out = await t.lua(`
  398. local desyncc = require("desyncc.main")
  399. local sys = desyncc:new()
  400. local order = {}
  401. local function main()
  402. local slow = sys:async(function() sleep(0.3) return "slow" end)
  403. local fast = sys:async(function() sleep(0.1) return "fast" end)
  404. local a, b = slow(), fast()
  405. order[#order + 1] = b.status()
  406. order[#order + 1] = b.await()
  407. order[#order + 1] = a.await()
  408. end
  409. -- start() ends by raising "Main task died" once main returns: that is how the library stops
  410. local ok, err = pcall(function() sys:start(main) end)
  411. assert(not ok and tostring(err):find("Main task died"), err)
  412. result(table.concat(order, ","))
  413. `);
  414. if (!out[0].endsWith("suspended,fast,slow"))
  415. t.fail(`async/await gave ${out[0]}`);
  416. // one of its own tests, which says what it should print: nil, "Before the function is awaited", suspended,
  417. // then five seconds later "Hello, world!", "a b", "After the function is awaited" and "a b" again
  418. await t.shell("clear");
  419. const started = Date.now();
  420. await t.shell("desyncc/test/asyncAwait.lua");
  421. await t.waitFor("Main task died", 15000);
  422. const waited = Date.now() - started;
  423. await t.waitForPrompt(10000);
  424. await t.shot("test");
  425. t.expect(
  426. /nil\s+Before the function is awaited\s+suspended\s+Hello,\s+world!\s+a\s+b\s+After the function is awaited\s+(resolved\s+)?a\s+b/,
  427. );
  428. if (waited < 4000 || waited > 8000)
  429. t.fail(`the awaited sleep(5) took ${waited} ms`);
  430. },
  431. },
  432. {
  433. id: "telem",
  434. name: "Telem",
  435. url: "https://github.com/cyberbit/telem",
  436. category: "library",
  437. section: "Other libraries",
  438. // its installer fetches the compressed modules as text and writes them with a text handle, which only keeps
  439. // bytes as they are from CC:Tweaked 1.109 on
  440. minCC: "1.109.0",
  441. ...storageRoom(
  442. chest(0, {
  443. 1: { name: "minecraft:cobblestone", count: 64 },
  444. 2: { name: "minecraft:cobblestone", count: 36 },
  445. 3: { name: "minecraft:iron_ingot", count: 32 },
  446. }),
  447. ),
  448. async run(t) {
  449. await t.boot();
  450. await t.shell("wget run https://pinestore.cc/d/14");
  451. // the installer is a mouse-driven wizard: pick the compact release, then Finish
  452. await t.waitFor("Telem Installer", 30000);
  453. await t.shot("installer");
  454. await t.waitFor("Release (compact)", 30000);
  455. await t.key("enter");
  456. await t.waitFor("Press Enter", 30000);
  457. await t.key("enter");
  458. await t.waitFor("Complete", 90000);
  459. await t.shot("installed");
  460. await t.key("enter");
  461. await t.waitForPrompt(30000);
  462. t.noCrash();
  463. if (!t.exists("telem.lua"))
  464. t.fail(`the installer left no telem.lua: ${t.list()}`);
  465. t.hash("telem.lua");
  466. const out = await t.lua(`
  467. local telem = require("telem")
  468. local seen = {}
  469. local backplane = telem.backplane()
  470. :addInput("hello", telem.input.helloWorld(123))
  471. :addInput("chest", telem.input.itemStorage("minecraft:chest_0"))
  472. :addInput("mine", telem.input.custom(function() return { answer = 42 } end))
  473. :addOutput("collect", telem.output.custom(function(collection)
  474. for _, metric in ipairs(collection.metrics) do seen[metric.name] = metric.value end
  475. end))
  476. backplane:cycle()
  477. local names = {} for k, v in pairs(seen) do names[#names + 1] = k .. "=" .. v end table.sort(names)
  478. result(table.concat(names, " "))
  479. `);
  480. await t.shot("metrics");
  481. for (const want of [
  482. "hello_world=123",
  483. "answer=42",
  484. "storage:minecraft:cobblestone=100",
  485. "storage:minecraft:iron_ingot=32",
  486. ])
  487. if (!out[0].includes(want))
  488. t.fail(`the backplane collected "${out[0]}", without ${want}`);
  489. },
  490. },
  491. ];
scripts/compat/projects/libraries-ui.mjs · Bundled script · 499 lines · 2 findings marked
  1. // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
  2. import { shellInstall, watchAnimation } from "../helpers.mjs";
  3. const RAW = "https://raw.githubusercontent.com";
  4. /** A Lua line that writes `value` to `file`, for demos that report what happened. */
  5. const NOTE = `local function note(file, value) local h = fs.open(file, "w") h.write(tostring(value)) h.close() end`;
  6. export default [
  7. {
  8. id: "basalt",
  9. name: "Basalt",
  10. url: "https://github.com/Pyroxenium/Basalt",
  11. category: "library",
  12. section: "UI frameworks",
  13. monitors: [{ name: "top", blocksWide: 3, blocksHigh: 2 }],
  14. async run(t) {
  15. await shellInstall(
  16. t,
  17. `wget run ${RAW}/Pyroxenium/Basalt/master/docs/install.lua release latest.lua`,
  18. );
  19. if (!t.exists("basalt.lua")) t.fail("the installer left no basalt.lua");
  20. t.hash("basalt.lua");
  21. t.put(
  22. "demo.lua",
  23. `${NOTE}
  24. local basalt = require("basalt")
  25. local main = basalt.createFrame()
  26. local label = main:addLabel():setText("Hello Basalt"):setPosition(2, 2)
  27. local button = main:addButton():setText("Press"):setPosition(2, 4):setSize(12, 3)
  28. button:onClick(function() label:setText("Clicked!") note("clicked.txt", "yes") end)
  29. local input = main:addInput():setPosition(2, 8):setSize(20, 1)
  30. input:onChange(function(self) note("typed.txt", self:getValue()) end)
  31. local list = main:addList():setPosition(26, 2):setSize(14, 6)
  32. for i = 1, 10 do list:addItem("Item " .. i) end
  33. list:onChange(function(self) note("picked.txt", self:getItem(self:getItemIndex()).text) end)
  34. local mon = basalt.addMonitor():setMonitor("top")
  35. mon:addButton():setText("Touch"):setPosition(2, 2):setSize(10, 3):onClick(function(self)
  36. self:setText("Touched") note("touched.txt", "yes")
  37. end)
  38. basalt.autoUpdate()
  39. `,
  40. );
  41. await t.shell("demo");
  42. await t.waitFor("Hello Basalt");
  43. await t.waitFor("Touch", 5000, "top");
  44. await t.shot("start");
  45. await t.click(5, 5);
  46. await t.waitFor("Clicked!");
  47. await t.click(4, 8);
  48. await t.type("hello");
  49. await t.waitFor("hello");
  50. await t.click(28, 4);
  51. await t.touch("top", 4, 3);
  52. await t.waitFor("Touched", 5000, "top");
  53. await t.shot("used");
  54. t.noCrash();
  55. if (t.read("typed.txt") !== "hello")
  56. t.fail(`the input holds "${t.read("typed.txt")}", not hello`);
  57. if (t.read("picked.txt") !== "Item 3")
  58. t.fail(`the list picked "${t.read("picked.txt")}", not Item 3`);
  59. },
  60. },
  61. {
  62. id: "basalt2",
  63. name: "Basalt 2",
  64. url: "https://github.com/Pyroxenium/Basalt2",
  65. category: "library",
  66. section: "UI frameworks",
  67. async run(t) {
  68. await shellInstall(
  69. t,
  70. `wget run ${RAW}/Pyroxenium/Basalt2/main/install.lua -f`,
  71. );
  72. if (!t.exists("basalt.lua")) t.fail("the installer left no basalt.lua");
  73. t.hash("basalt.lua");
  74. t.put(
  75. "demo.lua",
  76. `${NOTE}
  77. local basalt = require("basalt")
  78. local main = basalt.getMainFrame()
  79. local label = main:addLabel({ x = 2, y = 2, text = "Hello Basalt2" })
  80. main:addButton({ x = 2, y = 4, width = 12, height = 3, text = "Press" }):onClick(function()
  81. label:setText("Clicked!") note("clicked.txt", "yes")
  82. end)
  83. local input = main:addInput({ x = 2, y = 8, width = 20 })
  84. input:onChange("text", function(self, value) note("typed.txt", value) end)
  85. basalt.run()
  86. `,
  87. );
  88. await t.shell("demo");
  89. await t.waitFor("Hello Basalt2");
  90. await t.shot("start");
  91. await t.click(5, 5);
  92. await t.waitFor("Clicked!");
  93. await t.click(4, 8);
  94. await t.type("hello");
  95. await t.waitFor("hello");
  96. await t.shot("used");
  97. t.noCrash();
  98. if (t.read("typed.txt") !== "hello")
  99. t.fail(`the input holds "${t.read("typed.txt")}", not hello`);
  100. // its own examples
  101. await t.terminate();
  102. await t.shell("clear");
  103. for (const example of ["graphs", "TabControl"]) {
  104. await t.shell(
  105. `wget ${RAW}/Pyroxenium/Basalt2/main/examples/${example}.lua ${example}.lua`,
  106. 1500,
  107. );
  108. await t.waitForPrompt();
  109. await t.shell(example);
  110. await t.settle(700, 8000);
  111. await t.shot(example);
  112. t.noCrash();
  113. if (t.variety() < 4) t.fail(`${example} drew next to nothing`);
  114. await t.click(10, 2);
  115. await t.click(20, 8);
  116. t.noCrash();
  117. await t.terminate();
  118. await t.shell("clear");
  119. }
  120. },
  121. },
  122. {
  123. id: "pixelui",
  124. name: "PixelUI",
  125. url: "https://github.com/Shlomo1412/PixelUI",
  126. category: "library",
  127. section: "UI frameworks",
  128. // written with goto, which CC:Tweaked has from 1.109 (Lua 5.2)
  129. minCC: "1.109.0",
  130. async run(t) {
  131. await shellInstall(t, `wget ${RAW}/Shlomo1412/PixelUI/main/pixelui.lua`);
  132. await shellInstall(t, `wget ${RAW}/Shlomo1412/PixelUI/main/demo.lua`);
  133. t.hash("pixelui.lua");
  134. await t.shell("demo");
  135. await t.settle(700, 10000);
  136. await t.shot("demo");
  137. t.noCrash();
  138. if (t.variety() < 6) t.fail("the demo drew next to nothing");
  139. const before = t.frameHash();
  140. await t.click(10, 5);
  141. await t.click(25, 8);
  142. await t.key("tab");
  143. await t.type("abc");
  144. await t.settle(400, 3000);
  145. await t.shot("used");
  146. t.noCrash();
  147. if (t.frameHash() === before)
  148. t.fail("clicking and typing changed nothing on screen");
  149. },
  150. },
  151. {
  152. id: "primeui",
  153. name: "PrimeUI",
  154. url: "https://github.com/MCJack123/PrimeUI",
  155. category: "library",
  156. section: "UI frameworks",
  157. async run(t) {
  158. const repo = t.clone("https://github.com/MCJack123/PrimeUI");
  159. t.install(repo, "primeui");
  160. await t.boot();
  161. await t.shell("cd primeui");
  162. await t.shell("test");
  163. // its test program walks through every component, one page at a time
  164. await t.waitFor("Sample Text");
  165. await t.waitFor("Next");
  166. await t.shot("scrollbox");
  167. await t.scroll(10, 10, 1);
  168. await t.key("enter");
  169. await t.waitFor("Item 1");
  170. await t.shot("checkboxes");
  171. await t.key("space");
  172. await t.key("down");
  173. await t.key("space");
  174. await t.key("enter");
  175. await t.settle(500, 5000);
  176. await t.shot("page3");
  177. t.noCrash();
  178. for (let page = 0; page < 8 && !/> ?$/.test(t.text().trimEnd()); page++) {
  179. await t.type("x");
  180. await t.key("enter");
  181. await t.settle(500, 4000);
  182. t.noCrash();
  183. }
  184. await t.shot("end");
  185. },
  186. },
  187. {
  188. id: "tamperer",
  189. name: "Tamperer 2.0",
  190. url: "https://github.com/Fatboychummy-CC/Tamperer",
  191. category: "library",
  192. section: "UI frameworks",
  193. async run(t) {
  194. await t.boot();
  195. await t.shell(
  196. `wget run ${RAW}/Fatboychummy-CC/Tamperer/refs/heads/better/installer.lua lib no_ccryptolib`,
  197. );
  198. await t.waitFor("(y/n)", 30000);
  199. await t.shell("y");
  200. await t.waitFor("What version", 30000);
  201. await t.shell("no_ccryptolib");
  202. await t.waitForPrompt(60000);
  203. t.noCrash();
  204. await t.shot("installed");
  205. if (!t.exists("lib/tamperer.lua") && !t.exists("lib/tamperer/init.lua"))
  206. t.fail(`the installer left no tamperer in lib: ${t.list("lib")}`);
  207. await t.shell("clear");
  208. t.put(
  209. "demo.lua",
  210. `${NOTE}
  211. package.path = package.path .. ";lib/?.lua;lib/?/init.lua"
  212. local tamperer = require("tamperer")
  213. local menu = tamperer.new({ title = "Main Menu", description = "A menu of ours" })
  214. menu:add_number("volume", "Volume", "Volume of the music", 50, 0, 100)
  215. menu:add_boolean("fullscreen", "Fullscreen", "Enable fullscreen mode", false)
  216. menu:set_on_change(function(m, selection)
  217. note("changed.txt", selection.i_label .. "=" .. tostring(selection.value))
  218. end)
  219. menu:run()
  220. `,
  221. );
  222. await t.shell("demo");
  223. await t.waitFor("Main Menu");
  224. await t.waitFor("Fullscreen");
  225. await t.shot("menu");
  226. await t.key("down");
  227. await t.key("enter");
  228. await t.settle(400, 3000);
  229. await t.shot("toggled");
  230. t.noCrash();
  231. if (!t.exists("changed.txt"))
  232. t.fail("toggling Fullscreen never reached the change callback");
  233. if (t.read("changed.txt") !== "fullscreen=true")
  234. t.fail(`the callback saw ${t.read("changed.txt")}`);
  235. },
  236. },
  237. {
  238. id: "obsi2",
  239. name: "Obsi 2",
  240. url: "https://github.com/simadude/obsi2",
  241. category: "library",
  242. section: "2D game development",
  243. async run(t) {
  244. const repo = t.clone("https://github.com/simadude/obsi2");
  245. t.install(repo, "obsi2");
  246. t.put(
  247. "main.lua",
  248. `local obsi = require("obsi2")
  249. local x, frames = 1, 0
  250. function obsi.update(dt)
  251. if obsi.keyboard.isDown("right") then x = x + 40 * dt end
  252. frames = frames + 1
  253. if frames % 5 == 0 then
  254. local h = fs.open("state.txt", "w") h.write(math.floor(x) .. " " .. frames) h.close()
  255. end
  256. end
  257. function obsi.draw()
  258. obsi.graphics.setBackgroundColor(colors.blue)
  259. obsi.graphics.setForegroundColor(colors.yellow)
  260. obsi.graphics.rectangle("fill", math.floor(x), 5, 6, 4)
  261. obsi.graphics.write("obsi " .. frames, 2, 1)
  262. end
  263. obsi.init()
  264. `,
  265. );
  266. await t.boot();
  267. await t.shell("main");
  268. await t.waitFor(/obsi \d+/);
  269. await watchAnimation(t, 1500, 5);
  270. await t.shot("start");
  271. const before = Number(t.read("state.txt").split(" ")[0]);
  272. await t.hold("right", 1000);
  273. await t.sleep(300);
  274. await t.shot("moved");
  275. const after = Number(t.read("state.txt").split(" ")[0]);
  276. if (!(after > before + 10))
  277. t.fail(`holding right moved the box from ${before} to ${after}`);
  278. t.noCrash();
  279. },
  280. },
  281. {
  282. id: "pine3d",
  283. name: "Pine3D",
  284. url: "https://github.com/Xella37/Pine3D",
  285. category: "library",
  286. section: "3D renderers",
  287. async run(t) {
  288. const repo = t.clone("https://github.com/Xella37/Pine3D");
  289. t.install(repo, ".");
  290. await t.boot();
  291. await t.shell("Mountains");
  292. await t.sleep(2500);
  293. t.noCrash();
  294. await t.shot("mountains");
  295. if (t.variety() < 10) t.fail("the mountains scene drew next to nothing");
  296. const before = t.frameHash();
  297. await t.hold("w", 800);
  298. await t.hold("left", 600);
  299. await t.shot("flown");
  300. t.noCrash();
  301. if (t.frameHash() === before)
  302. t.fail("flying with W and the arrow keys did not change the view");
  303. },
  304. },
  305. {
  306. id: "c3d",
  307. name: "C3D",
  308. url: "https://github.com/9551-Dev/libC3D-dev",
  309. category: "library",
  310. section: "3D renderers",
  311. async run(t) {
  312. await shellInstall(
  313. t,
  314. `wget run ${RAW}/9551-Dev/C3D/master/installer.lua`,
  315. 180000,
  316. );
  317. if (!t.exists("c3d.lua")) t.fail("the installer left no c3d.lua");
  318. // the spinning cube of its documentation (c3d.madefor.cc, "texturing"), without the texture
  319. t.put(
  320. "cube/main.lua",
  321. `local cube = c3d.geometry.cube_simple()
  322. local frames = 0
  323. function c3d.load()
  324. cube = cube:push():reposition(0, 0, 1)
  325. end
  326. function c3d.update()
  327. frames = frames + 1
  328. cube:set_rotation(0, 1, 0, os.epoch("utc") / 10)
  329. if frames % 5 == 0 then
  330. local h = fs.open("frames.txt", "w") h.write(tostring(frames)) h.close()
  331. end
  332. end
  333. `,
  334. );
  335. await t.shell("c3d cube");
  336. await t.sleep(2000);
  337. t.noCrash();
  338. await watchAnimation(t, 2000, 4);
  339. await t.shot("cube");
  340. if (!(Number(t.read("frames.txt")) > 10))
  341. t.fail("the update callback barely ran");
  342. },
  343. },
  344. {
  345. id: "pixelbox",
  346. name: "Pixelbox Lite",
  347. url: "https://github.com/9551-Dev/pixelbox_lite",
  348. category: "library",
  349. section: "Teletext renderers",
  350. async run(t) {
  351. await shellInstall(
  352. t,
  353. `wget ${RAW}/9551-Dev/pixelbox_lite/master/pixelbox_lite.lua`,
  354. );
  355. t.hash("pixelbox_lite.lua");
  356. // the two programs in its examples folder
  357. for (const example of ["first", "chladni"]) {
  358. await shellInstall(
  359. t,
  360. `wget ${RAW}/9551-Dev/pixelbox_lite/master/examples/${example}.lua`,
  361. );
  362. }
  363. await t.shell("clear");
  364. await t.shell("first");
  365. await t.sleep(500);
  366. await t.shot("first");
  367. t.noCrash();
  368. // first.lua: a blue column at pixel x 5 and a yellow one at 7, rows 5 to 7, joined by one blue pixel. Pixels are
  369. // 2x3 to a cell, so that is cells (3,2) to (4,3), drawn with teletext characters in those two colours. The
  370. // render leaves the cursor on the last line, so the shell's next prompt scrolls it all up a line.
  371. const drawn = [t.cell(3, 1), t.cell(4, 1), t.cell(3, 2), t.cell(4, 2)];
  372. const colours = new Set(drawn.flatMap((c) => [c.fg, c.bg]));
  373. if (!drawn.every((c) => c.code >= 128 && c.code < 160))
  374. t.fail(`expected teletext characters, got ${JSON.stringify(drawn)}`);
  375. if (!colours.has(11) || !colours.has(4))
  376. t.fail(`expected blue and yellow, got ${JSON.stringify(drawn)}`);
  377. await t.shell("clear");
  378. await t.shell("chladni");
  379. await t.sleep(1500);
  380. await t.shot("chladni");
  381. t.noCrash();
  382. if (t.variety() < 8) t.fail("the Chladni figure drew next to nothing");
  383. },
  384. },
  385. {
  386. id: "shrekbox",
  387. name: "Shrekbox",
  388. url: "https://codeberg.org/ShreksHellraiser/shrekbox",
  389. category: "library",
  390. section: "Teletext renderers",
  391. async run(t) {
  392. const repo = t.clone("https://codeberg.org/ShreksHellraiser/shrekbox");
  393. // the demos folder reaches the two libraries through symbolic links, which a computer has none of: a player
  394. // puts the libraries and a demo side by side
  395. for (const file of ["shrekbox.lua", "shrekdraw.lua"])
  396. t.install(`${repo}/${file}`, file);
  397. for (const demo of ["snow", "lines", "pipes"])
  398. t.install(`${repo}/demos/${demo}.lua`, `${demo}.lua`);
  399. await t.boot();
  400. for (const demo of ["snow", "pipes"]) {
  401. await t.shell(demo);
  402. await t.sleep(1200);
  403. t.noCrash();
  404. const frames = await watchAnimation(t, 1500, 3);
  405. t.note(`${demo}: ${frames} frames in 1.5 s`);
  406. await t.shot(demo);
  407. await t.terminate();
  408. await t.shell("clear");
  409. }
  410. // lines.lua is a drawing program: drag the mouse and the three layers each get a line
  411. await t.shell("lines");
  412. await t.waitFor("Draw!");
  413. const empty = t.variety();
  414. await t.drag(5, 3, 40, 14);
  415. await t.shot("lines");
  416. t.noCrash();
  417. if (t.variety() <= empty + 2)
  418. t.fail("dragging the mouse across the screen drew no line");
  419. },
  420. },
  421. {
  422. id: "morefonts",
  423. name: "More Fonts",
  424. url: "https://github.com/MichielP1807/more-fonts",
  425. category: "library",
  426. section: "Fonts",
  427. async run(t) {
  428. await t.boot();
  429. await t.shell(
  430. `wget run ${RAW}/MichielP1807/more-fonts/main/installer.lua`,
  431. );
  432. await t.waitFor("Finished installation!", 60000);
  433. await t.shot("installer");
  434. await t.key("enter");
  435. await t.waitForPrompt();
  436. if (!t.exists("morefonts.lua"))
  437. t.fail("the installer left no morefonts.lua");
  438. t.hash("morefonts.lua");
  439. await t.shell("fontbrowser");
  440. // on its first run it downloads every font and sleeps a second (which drops keys); it draws nothing until the
  441. // first event after that, so the download list stays up until a key is pressed
  442. await t.waitFor("Downloading", 30000);
  443. await t.settle(2500, 120000);
  444. await t.key("left");
  445. await t.waitFor(/^(?![\s\S]*Downloading)/, 20000);
  446. await t.shot("browser");
  447. t.noCrash();
  448. const first = t.frameHash();
  449. await t.key("right");
  450. await t.settle(600, 8000);
  451. await t.shot("next-font");
  452. t.noCrash();
  453. if (t.frameHash() === first)
  454. t.fail("the right arrow did not show another font");
  455. if (t.variety() < 6) t.fail("the font browser drew next to nothing");
  456. },
  457. },
  458. {
  459. id: "bigfont",
  460. name: "Bigfont",
  461. url: "https://pastebin.com/3LfWxRWh",
    • Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
    • Warning: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 464 on GitHub
  462. category: "library",
  463. section: "Fonts",
  464. monitors: [{ name: "top", blocksWide: 4, blocksHigh: 2, textScale: 0.5 }],
  465. async run(t) {
  466. await shellInstall(t, "pastebin get 3LfWxRWh bigfont");
  467. t.hash("bigfont");
  468. t.put(
  469. "demo.lua",
  470. `local bigfont = require("bigfont")
  471. term.clear() term.setCursorPos(1, 1)
  472. bigfont.bigPrint("Big")
  473. bigfont.hugePrint("Huge")
  474. local mon = peripheral.wrap("top")
  475. mon.clear()
  476. bigfont.writeOn(mon, 1, "MONITOR", 2, 2)
  477. print("done")
  478. `,
  479. );
  480. await t.shell("demo");
  481. await t.waitFor("done");
  482. await t.shot("fonts");
  483. t.noCrash();
  484. // big text is drawn with the teletext characters 128 to 159, three rows a line
  485. const teletext = (monitor) =>
  486. t
  487. .lines(monitor)
  488. .join("")
  489. .split("")
  490. .filter((c) => c.charCodeAt(0) >= 128 && c.charCodeAt(0) < 160)
  491. .length;
  492. if (teletext() < 20) t.fail("the terminal shows no big letters");
  493. if (teletext("top") < 10) t.fail("the monitor shows no big letters");
  494. },
  495. },
  496. ];
scripts/compat/projects/programs.mjs · Bundled script · 461 lines · 2 findings marked
  1. // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
  2. import { shellInstall } from "../helpers.mjs";
  3. const RAW = "https://raw.githubusercontent.com";
  4. /** A short DFPWM clip that is public on GitHub (the Jane demo's soundtrack), for the players that take a URL. */
  5. const DFPWM_URL = `${RAW}/piguman3/PineJam2026Demo/main/janecut.dfpwm`;
  6. const chest = (n, items = {}) => ({
  7. name: `minecraft:chest_${n}`,
  8. type: "minecraft:chest",
  9. size: 27,
  10. items,
  11. });
  12. /** Wait until a speaker has been given audio, and say how much. */
  13. async function expectAudio(t, speaker, timeoutMs = 30000) {
  14. const end = Date.now() + timeoutMs;
  15. for (;;) {
  16. const played = t
  17. .speaker(speaker)
  18. .sounds.filter((s) => s.kind === "audio" && s.accepted !== false);
  19. if (played.length >= 3) return played;
  20. if (Date.now() > end)
  21. t.fail(
  22. `speaker ${speaker} got ${played.length} audio buffers in ${timeoutMs} ms: ${JSON.stringify(t.speaker(speaker).raw).slice(0, 300)}`,
  23. );
  24. await t.sleep(250);
  25. }
  26. }
  27. export default [
  28. {
  29. id: "cc-misc",
  30. name: "MISC (Modular Item Storage and Crafting)",
  31. url: "https://github.com/Storehaus/CC-MISC",
  32. category: "program",
  33. section: "Storage, turtles and peripherals",
  34. world: {
  35. peripherals: [
  36. { name: "back", type: "modem", kind: "wired", network: "storage" },
  37. ],
  38. },
  39. wired: [
  40. {
  41. id: "storage",
  42. peripherals: [
  43. chest(0, {
  44. 1: { name: "minecraft:cobblestone", count: 64 },
  45. 2: { name: "minecraft:cobblestone", count: 36 },
  46. 3: { name: "minecraft:iron_ingot", count: 32 },
  47. }),
  48. chest(1, { 5: { name: "minecraft:oak_log", count: 16 } }),
  49. chest(2),
  50. chest(3),
  51. ],
  52. },
  53. ],
  54. async run(t) {
  55. await t.boot();
  56. await t.shell(`wget run ${RAW}/Storehaus/CC-MISC/master/installer.lua`);
  57. await t.waitFor("MISC INSTALLER", 30000);
  58. await t.shot("installer");
  59. // server, then the base install (storage and its modules)
  60. await t.type("s");
  61. await t.waitFor("Base");
  62. await t.shot("server-options");
  63. await t.type("b");
  64. await t.waitForPrompt(120000);
  65. t.noCrash();
  66. await t.shot("installed");
  67. if (!t.exists("startup.lua") || !t.exists("modules"))
  68. t.fail(`the installer left no startup.lua and modules: ${t.list()}`);
  69. // it runs from startup.lua: restart the computer, as the installer says
  70. await t.shell("reboot");
  71. await t.rebooted();
  72. // first start: it asks for what its config lacks, the modem the chests are behind
  73. await t.waitFor("Please input a string:", 20000);
  74. await t.shot("config");
  75. await t.shell("back");
  76. await t.sleep(6000);
  77. await t.shot("running");
  78. t.noCrash();
  79. },
  80. },
  81. {
  82. id: "github-downloader",
  83. name: "Github Downloader",
  84. url: "https://pinestore.cc/projects/157/github-downloader-on-cc",
  85. category: "program",
  86. section: "Utility",
  87. async run(t) {
  88. await shellInstall(t, "pastebin get jP9CNvYS githubdw");
  89. t.hash("githubdw");
  90. await t.shell("githubdw");
  91. await t.waitFor("Paste repository URL");
  92. await t.shot("start");
  93. // the address is pasted, as the screen asks
  94. t.event("paste", "https://github.com/9551-Dev/pixelbox_lite");
  95. await t.waitFor("pixelbox_lite");
  96. await t.key("enter");
  97. await t.waitFor(/files downloaded/, 120000);
  98. await t.shot("done");
  99. t.expect("All files downloaded successfully!");
  100. t.noCrash();
  101. if (t.size("pixelbox_lite.lua") < 1000)
  102. t.fail(`pixelbox_lite.lua was not downloaded: ${t.list()}`);
  103. if (!t.exists("examples/first.lua"))
  104. t.fail("the examples folder was not downloaded");
  105. await t.clickText("Continue");
  106. await t.waitFor("Paste repository URL");
  107. },
  108. },
  109. {
  110. id: "consult",
  111. name: "CONSULT",
  112. url: "https://github.com/SammyForReal/CONSULT",
  113. category: "program",
  114. section: "Code editors",
  115. async run(t) {
  116. await shellInstall(
  117. t,
  118. "wget https://github.com/1Turtle/consult/releases/latest/download/cosu.lua",
  119. );
  120. t.hash("cosu.lua");
  121. await t.shell("cosu hello.lua");
  122. await t.waitFor("hello.lua");
  123. await t.waitFor("Ln 1, Col 1");
  124. await t.shot("empty");
  125. await t.type('print("hello from consult")');
  126. await t.key("enter");
  127. await t.type("local x = 1 + 2");
  128. await t.waitFor("Ln 2, Col 16");
  129. await t.shot("typed");
  130. await t.combo("leftCtrl", "s");
  131. await t.sleep(800);
  132. await t.shot("saved");
  133. t.noCrash();
  134. if (!t.exists("hello.lua")) t.fail("Ctrl+S did not write hello.lua");
  135. const saved = t.read("hello.lua").replace(/\r/g, "").trimEnd();
  136. if (saved !== 'print("hello from consult")\nlocal x = 1 + 2')
  137. t.fail(`hello.lua holds:\n${saved}`);
  138. // F5 runs the file
  139. await t.key("f5");
  140. await t.waitFor("hello from consult", 10000);
  141. await t.shot("ran");
  142. },
  143. },
  144. {
  145. id: "quark",
  146. name: "Quark",
  147. url: "https://github.com/aTimmYm/Quark",
  148. category: "program",
  149. section: "Code editors",
  150. minCC: "1.109.0", // goto
  151. async run(t) {
  152. await t.boot();
  153. await t.shell(
  154. `wget run "${RAW}/aTimmYm/Quark/refs/heads/main/installer_updater/installer.lua"`,
  155. );
  156. await t.waitFor("Enter the path", 30000);
  157. await t.shell("/");
  158. await t.waitForPrompt(180000);
  159. t.noCrash();
  160. await t.shot("installed");
  161. if (!t.exists("Quark/main.lua"))
  162. t.fail(`the installer left no Quark/main.lua: ${t.list()}`);
  163. t.put("notes.lua", 'print("one")\n');
  164. await t.shell("clear");
  165. await t.shell("Quark/main.lua");
  166. await t.waitFor("New File", 20000);
  167. await t.shot("welcome");
  168. t.noCrash();
  169. t.expect("Open Project");
  170. await t.clickText("New File");
  171. await t.settle(600, 8000);
  172. await t.shot("new-file");
  173. await t.type('print("typed in quark")');
  174. await t.settle(500, 5000);
  175. await t.shot("typed");
  176. t.noCrash();
  177. t.expect('print("typed in quark")');
  178. },
  179. },
  180. {
  181. id: "shrekword",
  182. name: "ShrekWord",
  183. url: "https://github.com/ShrekshelleraiserCC/shrekword",
  184. category: "program",
  185. section: "Code editors",
  186. async run(t) {
  187. await shellInstall(
  188. t,
  189. "wget https://github.com/ShrekshelleraiserCC/shrekword/releases/latest/download/sword.lua",
  190. );
  191. t.hash("sword.lua");
  192. await t.shell("sword");
  193. await t.waitFor("Check for updates on startup?");
  194. await t.shell("n");
  195. await t.waitFor("File");
  196. await t.waitFor(/Page 1\/1/);
  197. await t.shot("empty");
  198. await t.type("Dear reader, this was typed in ShrekWord.");
  199. await t.waitFor("ShrekWord.");
  200. await t.shot("typed");
  201. t.noCrash();
  202. // File > Save As
  203. await t.clickText("File");
  204. await t.waitFor("Save As");
  205. await t.shot("file-menu");
  206. await t.clickText("Save As");
  207. await t.settle(400, 3000);
  208. await t.shot("save-as");
  209. await t.type("letter.sdoc");
  210. await t.key("enter");
  211. await t.settle(400, 3000);
  212. await t.shot("saved");
  213. t.noCrash();
  214. if (!t.exists("letter.sdoc"))
  215. t.fail(`Save As wrote no letter.sdoc: ${t.list()}`);
  216. if (!t.read("letter.sdoc").includes("this was typed in ShrekWord"))
  217. t.fail("the saved document does not hold the text");
  218. // Ctrl+Q quits
  219. await t.combo("leftCtrl", "q");
  220. await t.waitForPrompt(10000);
  221. },
  222. },
  223. {
  224. id: "spritemog",
  225. name: "SpriteMog 1.2",
  226. url: "https://pastebin.com/iHpQhwvy",
    • Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
    • Warning: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 230 on GitHub
  227. category: "program",
  228. section: "Code editors",
  229. async run(t) {
  230. await shellInstall(t, "pastebin get iHpQhwvy spritemog");
  231. t.hash("spritemog");
  232. await t.shell("spritemog");
  233. await t.waitFor("-SELECT PALETTE-");
  234. await t.shot("palettes");
  235. await t.clickText("default");
  236. await t.waitFor("-SELECT SPRITE-");
  237. await t.clickText("newSprite");
  238. await t.settle(600, 8000);
  239. await t.shot("editor");
  240. t.noCrash();
  241. const before = t.frameHash();
  242. await t.drag(20, 8, 30, 12);
  243. await t.settle(400, 4000);
  244. await t.shot("drawn");
  245. t.noCrash();
  246. if (t.frameHash() === before)
  247. t.fail("drawing with the mouse changed nothing");
  248. },
  249. },
  250. {
  251. id: "pixelcode",
  252. name: "PixelCode",
  253. url: "https://github.com/Shlomo1412/PixelUI/blob/main/code_editor_app.lua",
  254. category: "program",
  255. section: "Code editors",
  256. minCC: "1.109.0",
  257. async run(t) {
  258. await shellInstall(t, `wget ${RAW}/Shlomo1412/PixelUI/main/pixelui.lua`);
  259. await shellInstall(
  260. t,
  261. `wget ${RAW}/Shlomo1412/PixelUI/main/code_editor_app.lua`,
  262. );
  263. await t.shell("code_editor_app");
  264. await t.waitFor("Press Alt to open toolbar");
  265. await t.shot("start");
  266. await t.click(20, 4);
  267. await t.type("local answer = 42");
  268. await t.settle(400, 3000);
  269. await t.shot("typed");
  270. t.noCrash();
  271. t.expect("local answer = 42");
  272. // F1 is its help; Alt opens the toolbar
  273. await t.key("leftAlt");
  274. await t.settle(400, 3000);
  275. await t.shot("toolbar");
  276. t.noCrash();
  277. },
  278. },
  279. {
  280. id: "craft-web",
  281. name: "Craft-Web",
  282. url: "https://github.com/Elemnto56/Craft-Web",
  283. category: "program",
  284. section: "Web, internet and communication",
  285. minCC: "1.109.0",
  286. async run(t) {
  287. await shellInstall(
  288. t,
  289. `wget ${RAW}/Elemnto56/Craft-Web/refs/heads/main/craft-installer.lua`,
  290. );
  291. await t.shell("craft-installer");
  292. await t.waitFor("(y/n)", 30000);
  293. await t.shell("y");
  294. await t.waitFor("Done! Goodbye.", 30000);
  295. await t.waitForPrompt();
  296. await t.shell("clear");
  297. await t.shell("craft-web");
  298. await t.waitFor("Welcome to Craft-Web!", 15000);
  299. await t.shot("home");
  300. t.noCrash();
  301. t.expect("Address Bar");
  302. await t.clickText("Exit");
  303. await t.waitForPrompt(10000);
  304. },
  305. },
  306. {
  307. id: "musicify",
  308. name: "Musicify",
  309. url: "https://github.com/knijn/musicify",
  310. category: "program",
  311. section: "Audio and video players",
  312. world: { peripherals: [{ name: "right", type: "speaker" }] },
  313. async run(t) {
  314. await t.boot();
  315. await t.shell(`wget run ${RAW}/knijn/musicify/main/install.lua`);
  316. await t.waitFor("anything else to continue", 30000);
  317. await t.shell("y");
  318. await t.waitForPrompt(60000);
  319. t.noCrash();
  320. await t.shot("installed");
  321. await t.shell("clear");
  322. await t.shell("musicify list");
  323. await t.waitFor(/1 \| /, 30000);
  324. await t.shot("list");
  325. // S and W scroll the list, Q leaves it (by raising "Closed list")
  326. const first = t.text();
  327. await t.hold("s", 400);
  328. if (t.text() === first) t.fail("S did not scroll the song list");
  329. await t.key("q");
  330. await t.waitFor("Closed list", 10000);
  331. // the q of that key press lands on the shell's line, as it does at a real keyboard
  332. await t.key("backspace");
  333. await t.shell("clear");
  334. await t.shell("musicify play 1");
  335. const played = await expectAudio(t, "right", 60000);
  336. await t.shot("playing");
  337. t.noCrash();
  338. t.note(
  339. `speaker got ${played.length} buffers, ${played[0].samples} samples each`,
  340. );
  341. },
  342. },
  343. {
  344. id: "quartz",
  345. name: "Quartz Audio Player",
  346. url: "https://github.com/Ale32bit/Quartz",
  347. category: "program",
  348. section: "Audio and video players",
  349. // "insert a disk containing a .dfpwm": two speakers for its stereo, and a drive with a floppy in it
  350. world: {
  351. peripherals: [
  352. { name: "left", type: "speaker" },
  353. { name: "right", type: "speaker" },
  354. { name: "top", type: "drive", disk: 0 },
  355. ],
  356. },
  357. async run(t) {
  358. await shellInstall(
  359. t,
  360. "wget run https://raw.github.com/Ale32bit/Quartz/main/download.lua",
  361. 60000,
  362. );
  363. // record a song onto the floppy: the first 100 kB of a clip, since a floppy holds 125 kB
  364. const recorded = await t.lua(`
  365. local h = assert(http.get(${JSON.stringify(DFPWM_URL)}, nil, true))
  366. local data = h.read(100000)
  367. h.close()
  368. local f = fs.open("disk/song.dfpwm", "wb")
  369. f.write(data)
  370. f.close()
  371. result(#data, fs.getSize("disk/song.dfpwm"))`);
  372. if (recorded[0] !== "100000\t100000")
  373. t.fail(`the song on the disk is ${recorded[0]} bytes`);
  374. await t.shell("clear");
  375. await t.shell("player");
  376. await t.waitFor("Ready", 15000);
  377. await t.shot("log");
  378. t.noCrash();
  379. t.expect(/Speaker configuration:\s+stereo/);
  380. // F1 leaves the log for the player; space plays
  381. await t.key("f1");
  382. await t.settle(500, 5000);
  383. await t.shot("player");
  384. await t.key("space");
  385. await t.sleep(4000);
  386. await t.shot("playing");
  387. t.noCrash();
  388. const left = t.speaker("left").raw?.audio?.pushed ?? 0;
  389. const right = t.speaker("right").raw?.audio?.pushed ?? 0;
  390. if (left < 1 || right < 1)
  391. t.fail(`the speakers got ${left} and ${right} audio buffers`);
  392. t.note(`left ${left}, right ${right} audio buffers in 4 s`);
  393. },
  394. },
  395. {
  396. id: "pocketbox",
  397. name: "Pocketbox",
  398. url: "https://github.com/windclan/pocketbox",
  399. category: "program",
  400. section: "Audio and video players",
  401. world: { peripherals: [{ name: "right", type: "speaker" }] },
  402. async run(t) {
  403. await shellInstall(
  404. t,
  405. `wget ${RAW}/windclan/pocketbox/main/pocketboxv4.lua pocketbox.lua`,
  406. );
  407. t.hash("pocketbox.lua");
  408. t.put(
  409. "autoplay.pb",
  410. `[url]\npath:${DFPWM_URL}\ntitle:Jane\nartist:piguman3\n`,
  411. );
  412. await t.shell("clear");
  413. await t.shell("pocketbox");
  414. const played = await expectAudio(t, "right", 60000);
  415. await t.shot("playing");
  416. t.noCrash();
  417. t.note(`speaker got ${played.length} buffers`);
  418. t.expect(/Jane/);
  419. },
  420. },
  421. {
  422. id: "ccmaps",
  423. name: "CCMaps",
  424. url: "https://pinestore.cc/projects/66/ccmaps",
  425. category: "program",
  426. section: "Demoscene and proof of concept",
  427. async run(t) {
  428. await shellInstall(
  429. t,
  430. "wget run https://gist.githubusercontent.com/cyberbit/993372d662918aeb4973701ac7122987/raw/ccmaps_install.lua",
  431. 60000,
  432. );
  433. await t.shell("ccmaps");
  434. // it fetches its map data, then draws coastlines with teletext characters: wait for those
  435. const drawn = () =>
  436. t
  437. .lines()
  438. .join("")
  439. .split("")
  440. .filter((c) => c.charCodeAt(0) > 128 && c.charCodeAt(0) < 160).length;
  441. for (let i = 0; i < 180 && drawn() < 20; i++) await t.sleep(500);
  442. await t.settle(1500, 30000);
  443. await t.shot("map");
  444. t.noCrash();
  445. if (drawn() < 20) t.fail("no map was drawn");
  446. const before = t.frameHash();
  447. // drag the map, then zoom
  448. await t.drag(30, 10, 15, 6);
  449. await t.scroll(25, 9, -1);
  450. await t.settle(1500, 30000);
  451. await t.shot("moved");
  452. t.noCrash();
  453. if (t.frameHash() === before)
  454. t.fail("dragging and zooming left the map as it was");
  455. },
  456. },
  457. ];
tools/turtledata/extract.py · Bundled script · 847 lines · 1 finding marked
  1. """Pull the block and item data a turtle needs out of the real game jars.
  2. Reads the Minecraft client jar, Forge, and every mod jar in the pack, and writes compact Lua tables, one file per
  3. namespace plus the combined _recipes.lua, _cooking.lua and _tag_members.lua, to rom-overlay/rom/ccsim/turtle/data/
  4. (1.18.2) or rom-overlay/rom/ccsim/turtle/data/<mc>/ (any other Minecraft version), or --out:
  5. names.lua id -> English display name (assets/<ns>/lang/en_us.json)
  6. blocks.lua every block id, with its state properties and their values (assets/<ns>/blockstates)
  7. items.lua every item id (item models, lang keys, loot table outputs, recipe outputs)
  8. loot.lua block loot tables (data/<ns>/loot_tables/blocks), kept as JSON-shaped Lua tables
  9. block_tags.lua block id -> its tags, fully resolved (nested #tags and "replace" honoured)
  10. item_tags.lua item id -> its tags
  11. recipes.lua crafting_shaped / crafting_shapeless recipes, for turtle.craft
  12. The pack's CraftTweaker and KubeJS scripts change some recipes at runtime; those changes are not in the jars
  13. (docs/conformance/emulator-vs-real-deviations.md).
  14. Two data sets:
  15. pack (default) vanilla + Forge + every jar in <instance>/mods. Mod data is All Rights Reserved: private repo only.
  16. --vanilla vanilla + Forge + the CC:Tweaked jar only, safe to publish. Use with --out so it does not
  17. overwrite the pack set.
  18. Minecraft versions (--mc, the MC table below):
  19. 1.18.2 (default) Forge 40.2.21 and CC:Tweaked 1.101.3, from the launcher's libraries and the pack instance. The block
  20. report comes from the client jar run on the launcher's libraries.
  21. 1.20.1 Forge 47.4.28 and CC:Tweaked 1.121.0 (forge). Vanilla only (there is no 1.20.1 pack instance), so
  22. --vanilla is implied unless --instance is given. The jars are read from --jars; --download fetches
  23. them there first: the client and server jars from Mojang's version manifest (sha1 checked), Forge's
  24. universal jar from its maven and CC:Tweaked from Modrinth (both hash checked). The block report
  25. comes from the server jar's bundler, so no launcher libraries are needed.
  26. Usage:
  27. python -I tools/turtledata/extract.py # pack set into rom-overlay/rom/ccsim/turtle/data
  28. python -I tools/turtledata/extract.py --vanilla --out .public-data/turtle-data
  29. python -I tools/turtledata/extract.py --mc 1.20.1 --jars <scratch dir> --download
  30. python -I tools/turtledata/extract.py --mc 1.20.1 --jars <scratch dir> --out .public-data/turtle-data/1.20.1
  31. Options (each also has an environment variable; the flag wins):
  32. --mc VERSION Minecraft version, 1.18.2 or 1.20.1 (TURTLEDATA_MC; default 1.18.2)
  33. --jars DIR a folder holding the version's jars under their own names (TURTLEDATA_JARS; looked in before
  34. --libraries and the instance); --download fills it
  35. --download fetch the jars --jars lacks (1.20.1 only)
  36. --out DIR output directory; every *.lua in it is deleted first (default rom-overlay/rom/ccsim/turtle/data,
  37. or its <mc>/ folder)
  38. --instance DIR the instance's minecraft dir, holding mods/ (TURTLEDATA_INSTANCE)
  39. --libraries DIR launcher libraries dir (TURTLEDATA_LIBRARIES; default %APPDATA%\\PrismLauncher\\libraries)
  40. --client-jar JAR minecraft-<mc>-client.jar (TURTLEDATA_CLIENT_JAR; default in --jars, then under --libraries)
  41. --server-jar JAR minecraft-<mc>-server.jar, 1.20.1 only (TURTLEDATA_SERVER_JAR; default in --jars)
  42. --forge-jar JAR forge-<mc>-<forge>-universal.jar, or the -client jar (TURTLEDATA_FORGE_JAR; default in --jars,
  43. then under --libraries, universal first)
  44. --cc-jar JAR the version's CC:Tweaked jar, --vanilla only (TURTLEDATA_CC_JAR; default in --jars, then
  45. <instance>/mods/)
  46. Java on PATH is needed for the vanilla block report (blocks.json). On 1.18.2 it runs on the client jar plus every jar
  47. under --libraries except Forge, LWJGL and the launcher's own; on 1.20.1 on the server jar alone.
  48. Data formats: 1.20.1 keeps 1.18.2's folders (loot_tables, recipes, tags/blocks, tags/items) and JSON shapes; its
  49. recipes add "category" and "show_notification", which are ignored, and its smithing recipes (smithing_transform,
  50. smithing_trim) are not crafting recipes, so they are skipped like 1.18.2's smithing. 1.21 renames the folders to the
  51. singular and gives recipe results components: the MC table's "folders" is where that goes.
  52. """
  53. import argparse
  54. import hashlib
  55. import json
  56. import os
  57. import re
  58. import sys
  59. import zipfile
  60. from collections import defaultdict
  61. HERE = os.path.dirname(os.path.abspath(__file__))
  62. REPO = os.path.dirname(os.path.dirname(HERE))
  63. DEFAULT_OUT = os.path.join(REPO, "rom-overlay", "rom", "ccsim", "turtle", "data")
  64. PRISM = os.path.join(os.environ.get("APPDATA", ""), "PrismLauncher")
  65. DEFAULT_LIBS = os.path.join(PRISM, "libraries")
  66. DEFAULT_INSTANCE = "" # no default: pass --instance (or --cc-jar with --vanilla)
  67. # Data folder names under data/<ns>/: 1.18.2 to 1.20.6 (1.21 makes them singular)
  68. PLURAL = {"loot": "loot_tables", "recipes": "recipes", "block_tags": "blocks", "item_tags": "items"}
  69. # Per Minecraft version: Forge, the CC:Tweaked jar (packages/runner/src/versions.ts has the same pins), the data
  70. # folder layout, how the block report is made, where the set goes, and whether the owner has a pack for it.
  71. MC = {
  72. "1.18.2": {
  73. "forge": "1.18.2-40.2.21",
  74. "cc_jar": "cc-tweaked-1.18.2-1.101.3.jar",
  75. "folders": PLURAL,
  76. "reports": "classpath",
  77. "out": DEFAULT_OUT,
  78. "pack": True,
  79. },
  80. "1.20.1": {
  81. "forge": "1.20.1-47.4.28",
  82. "cc_jar": "cc-tweaked-1.20.1-forge-1.121.0.jar",
  83. "folders": PLURAL,
  84. "reports": "server",
  85. "out": os.path.join(DEFAULT_OUT, "1.20.1"),
  86. "pack": False,
  87. # CC:Tweaked's own blocks are not in the vanilla server the map colours are read from: ModRegistry.Blocks
  88. # (MapColor.STONE 0x707070, GOLD 0xFAEE4D, WOOD 0x8F7748; the command computer and the cable's item have
  89. # none of their own: NONE, and Block.byItem(wired_modem) is the cable)
  90. "map_colours": {
  91. "computercraft:computer_normal": 0x707070, "computercraft:computer_advanced": 0xFAEE4D,
  92. "computercraft:computer_command": 0,
  93. "computercraft:turtle_normal": 0x707070, "computercraft:turtle_advanced": 0xFAEE4D,
  94. "computercraft:speaker": 0x707070, "computercraft:disk_drive": 0x707070, "computercraft:printer": 0x707070,
  95. "computercraft:monitor_normal": 0x707070, "computercraft:monitor_advanced": 0xFAEE4D,
  96. "computercraft:wireless_modem_normal": 0x707070, "computercraft:wireless_modem_advanced": 0xFAEE4D,
  97. "computercraft:wired_modem_full": 0x707070, "computercraft:cable": 0x707070,
  98. "computercraft:lectern": 0x8F7748, "computercraft:redstone_relay": 0x707070,
  99. },
  100. "downloads": {
  101. "forge": ("https://maven.minecraftforge.net/net/minecraftforge/forge/1.20.1-47.4.28/"
  102. "forge-1.20.1-47.4.28-universal.jar", "sha1", "1c2208dc1db2a61ddb6d5dcbe8eae4fd44629e9d"),
  103. "cc": ("https://cdn.modrinth.com/data/gu7yAYhd/versions/Qm9iIIEY/cc-tweaked-1.20.1-forge-1.121.0.jar",
    • Warning: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 117 on GitHub
  104. "sha512", "6ebe4c1e8e6165cb97f071a5a54acd942c234ae62d36330369fdae4bf720a93e99b84e833385f0f103e8fb"
  105. "03425ed20c9f9122411f0008e8ac9efa24b719522d"),
  106. },
  107. },
  108. }
  109. MANIFEST = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
  110. FORGE_VERSION = MC["1.18.2"]["forge"]
  111. CC_JAR = MC["1.18.2"]["cc_jar"]
  112. ID = re.compile(r"^[a-z0-9_.-]+:[a-z0-9_./-]+$")
  113. def fail(message):
  114. sys.exit("extract.py: " + message)
  115. def parse_args(argv):
  116. p = argparse.ArgumentParser(description="Regenerate the turtle block/item/tag/recipe/loot data from the game jars.")
  117. p.add_argument("--mc", default=os.environ.get("TURTLEDATA_MC") or "1.18.2", choices=sorted(MC),
  118. help="Minecraft version (env TURTLEDATA_MC; default 1.18.2)")
  119. p.add_argument("--vanilla", action="store_true",
  120. help="only vanilla, Forge and CC:Tweaked (the publishable set); no other mod jars")
  121. p.add_argument("--out", default=None, help="output directory (default rom-overlay/rom/ccsim/turtle/data[/<mc>])")
  122. p.add_argument("--jars", default=os.environ.get("TURTLEDATA_JARS"),
  123. help="folder holding the version's jars under their own names (env TURTLEDATA_JARS)")
  124. p.add_argument("--download", action="store_true", help="fetch the jars --jars lacks (1.20.1 only)")
  125. p.add_argument("--instance", default=os.environ.get("TURTLEDATA_INSTANCE"),
  126. help="instance minecraft dir holding mods/ (env TURTLEDATA_INSTANCE)")
  127. p.add_argument("--libraries", default=os.environ.get("TURTLEDATA_LIBRARIES") or DEFAULT_LIBS,
  128. help="launcher libraries dir (env TURTLEDATA_LIBRARIES)")
  129. p.add_argument("--client-jar", default=os.environ.get("TURTLEDATA_CLIENT_JAR"),
  130. help="minecraft client jar (env TURTLEDATA_CLIENT_JAR)")
  131. p.add_argument("--server-jar", default=os.environ.get("TURTLEDATA_SERVER_JAR"),
  132. help="minecraft server jar, 1.20.1 only (env TURTLEDATA_SERVER_JAR)")
  133. p.add_argument("--forge-jar", default=os.environ.get("TURTLEDATA_FORGE_JAR"),
  134. help="Forge universal or client jar (env TURTLEDATA_FORGE_JAR)")
  135. p.add_argument("--cc-jar", default=os.environ.get("TURTLEDATA_CC_JAR"),
  136. help="CC:Tweaked jar for --vanilla (env TURTLEDATA_CC_JAR)")
  137. args = p.parse_args(argv)
  138. info = MC[args.mc]
  139. args.info = info
  140. forge_version, cc_name = info["forge"], info["cc_jar"]
  141. if args.out is None:
  142. args.out = info["out"]
  143. if not info["pack"] and not args.instance and not args.vanilla:
  144. print("no " + args.mc + " pack instance: making the vanilla set (--vanilla)")
  145. args.vanilla = True
  146. if not args.instance:
  147. args.instance = DEFAULT_INSTANCE
  148. if args.download:
  149. if not args.jars:
  150. fail("--download needs --jars (the folder to download into)")
  151. download(args.mc, args.jars)
  152. def in_jars(name):
  153. path = os.path.join(args.jars, name) if args.jars else None
  154. return path if path and os.path.isfile(path) else None
  155. client_name = "minecraft-" + args.mc + "-client.jar"
  156. if not args.client_jar:
  157. args.client_jar = in_jars(client_name)
  158. if info["reports"] == "classpath" or not args.client_jar:
  159. if not os.path.isdir(args.libraries):
  160. fail("libraries dir not found: " + args.libraries + " (pass --libraries or set TURTLEDATA_LIBRARIES)")
  161. if not args.client_jar:
  162. args.client_jar = os.path.join(args.libraries, "com", "mojang", "minecraft", args.mc, client_name)
  163. if not os.path.isfile(args.client_jar):
  164. fail("Minecraft client jar not found: " + args.client_jar + " (pass --client-jar or set TURTLEDATA_CLIENT_JAR"
  165. + (", or --jars with --download)" if info.get("downloads") else ")"))
  166. if info["reports"] == "server":
  167. args.server_jar = args.server_jar or in_jars("minecraft-" + args.mc + "-server.jar")
  168. if not args.server_jar or not os.path.isfile(args.server_jar):
  169. fail("Minecraft " + args.mc + " server jar not found (pass --server-jar, or --jars with --download)")
  170. name = "minecraft-" + args.mc + "-server-mappings.txt"
  171. args.mappings = in_jars(name) or os.path.join(os.path.dirname(os.path.abspath(args.server_jar)), name)
  172. if not args.forge_jar:
  173. for name in ("forge-" + forge_version + "-universal.jar", "forge-" + forge_version + "-client.jar"):
  174. if in_jars(name):
  175. args.forge_jar = in_jars(name)
  176. break
  177. if not args.forge_jar:
  178. forge_dir = os.path.join(args.libraries, "net", "minecraftforge", "forge", forge_version)
  179. for name in ("forge-" + forge_version + "-universal.jar", "forge-" + forge_version + "-client.jar"):
  180. if os.path.isfile(os.path.join(forge_dir, name)):
  181. args.forge_jar = os.path.join(forge_dir, name)
  182. break
  183. else:
  184. fail("Forge " + forge_version + " universal/client jar not found in " + forge_dir +
  185. " (pass --forge-jar or set TURTLEDATA_FORGE_JAR)")
  186. elif not os.path.isfile(args.forge_jar):
  187. fail("Forge jar not found: " + args.forge_jar + " (pass --forge-jar or set TURTLEDATA_FORGE_JAR)")
  188. mods = os.path.join(args.instance, "mods")
  189. if args.vanilla:
  190. if not args.cc_jar:
  191. args.cc_jar = in_jars(cc_name)
  192. if not args.cc_jar:
  193. if not os.path.isdir(mods):
  194. fail("no mods dir at " + mods + " to find " + cc_name +
  195. " in (pass --cc-jar / TURTLEDATA_CC_JAR, or --instance / TURTLEDATA_INSTANCE)")
  196. args.cc_jar = os.path.join(mods, cc_name)
  197. if not os.path.isfile(args.cc_jar):
  198. fail("CC:Tweaked jar not found: " + args.cc_jar + " (pass --cc-jar or set TURTLEDATA_CC_JAR)")
  199. elif not os.path.isdir(mods):
  200. fail("no mods dir at " + mods + " (pass --instance or set TURTLEDATA_INSTANCE to the instance's minecraft dir)")
  201. return args
  202. def jars(args):
  203. found = [args.client_jar, args.forge_jar]
  204. if args.vanilla:
  205. found.append(args.cc_jar)
  206. return found
  207. mods = os.path.join(args.instance, "mods")
  208. for name in sorted(os.listdir(mods)):
  209. if name.endswith(".jar"):
  210. found.append(os.path.join(mods, name))
  211. return found
  212. def fetch(url):
  213. import urllib.request
  214. req = urllib.request.Request(url, headers={"User-Agent": "turtledata-extract"})
  215. with urllib.request.urlopen(req, timeout=300) as r:
  216. return r.read()
  217. def download(mc, folder):
  218. """Fetch the client and server jars (Mojang's version manifest, sha1 checked), Forge and CC:Tweaked (pinned
  219. hashes) into folder, skipping the ones already there with the right hash. The jars are only read as data."""
  220. info = MC[mc]
  221. if not info.get("downloads"):
  222. fail("--download is not set up for " + mc + ": pass the jars")
  223. os.makedirs(folder, exist_ok=True)
  224. def get(name, url, algo, digest):
  225. path = os.path.join(folder, name)
  226. if os.path.isfile(path):
  227. with open(path, "rb") as f:
  228. if hashlib.new(algo, f.read()).hexdigest() == digest:
  229. return
  230. print("downloading " + url)
  231. body = fetch(url)
  232. if hashlib.new(algo, body).hexdigest() != digest:
  233. fail(name + ": " + algo + " mismatch from " + url)
  234. with open(path, "wb") as f:
  235. f.write(body)
  236. manifest = json.loads(fetch(MANIFEST))
  237. entry = next((v for v in manifest.get("versions", []) if v.get("id") == mc), None)
  238. if not entry:
  239. fail("Minecraft " + mc + " is not in Mojang's version manifest")
  240. version = json.loads(fetch(entry["url"]))
  241. for side in ("client", "server"):
  242. d = version["downloads"][side]
  243. get("minecraft-" + mc + "-" + side + ".jar", d["url"], "sha1", d["sha1"])
  244. # Mojang's own name mappings, only to find the game's map colours and compostables by name (server_extras)
  245. d = version["downloads"]["server_mappings"]
  246. get("minecraft-" + mc + "-server-mappings.txt", d["url"], "sha1", d["sha1"])
  247. url, algo, digest = info["downloads"]["forge"]
  248. get("forge-" + info["forge"] + "-universal.jar", url, algo, digest)
  249. url, algo, digest = info["downloads"]["cc"]
  250. get(info["cc_jar"], url, algo, digest)
  251. def server_reports(server_jar, mappings=None):
  252. """The block report from the server jar's bundler (1.18 and later ship the data generator there with its
  253. libraries): java -DbundlerMainClass=net.minecraft.data.Main -jar server.jar --reports. With Mojang's mappings, also
  254. what only the game's code knows (server_extras): (blocks, registries, extras)."""
  255. import shutil
  256. import subprocess
  257. import tempfile
  258. java = shutil.which("java")
  259. if not java:
  260. print("java not found: block properties come from blockstate files only")
  261. return None, None, None
  262. out = tempfile.mkdtemp(prefix="mcreports-")
  263. try:
  264. subprocess.run([java, "-DbundlerMainClass=net.minecraft.data.Main", "-jar", os.path.abspath(server_jar),
  265. "--reports", "--output", os.path.join(out, "generated")],
  266. cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
  267. with open(os.path.join(out, "generated", "reports", "blocks.json"), encoding="utf-8") as f:
  268. blocks = json.load(f)
  269. with open(os.path.join(out, "generated", "reports", "registries.json"), encoding="utf-8") as f:
  270. registries = json.load(f)
  271. extras = None
  272. if mappings and os.path.isfile(mappings):
  273. try:
  274. extras = server_extras(java, out, mappings)
  275. except Exception as e:
  276. print("map colours and compostables not read (" + str(e) + ")")
  277. elif mappings is not None:
  278. print("no server mappings (" + str(mappings) + "): no map colours or compostables; --download fetches them")
  279. return blocks, registries, extras
  280. except Exception as e:
  281. print("data generator failed (" + str(e) + "): block properties come from blockstate files only")
  282. return None, None, None
  283. finally:
  284. shutil.rmtree(out, ignore_errors=True)
  285. # Read by server_extras through reflection: every block state's map colour (BlockStateBase.getMapColor on an empty
  286. # level at 0,0,0, as CC:Tweaked 1.121.0's DetailHelpers.fillMapColour asks for an item's block) and ComposterBlock's
  287. # COMPOSTABLES. The @names@ are filled from Mojang's mappings, since the jar's own names are obfuscated.
  288. EXTRAS_JAVA = r"""
  289. import java.lang.reflect.*;
  290. import java.util.*;
  291. import java.io.*;
  292. public class TurtleDataExtras {
  293. static Method m(Class<?> c, String name, Class<?>... p) throws Exception {
  294. for (Class<?> k = c; k != null; k = k.getSuperclass()) {
  295. try { Method x = k.getDeclaredMethod(name, p); x.setAccessible(true); return x; } catch (NoSuchMethodException e) {}
  296. }
  297. throw new NoSuchMethodException(c + "." + name);
  298. }
  299. static Object f(Class<?> c, String name, Object o) throws Exception {
  300. Field x = c.getDeclaredField(name); x.setAccessible(true); return x.get(o);
  301. }
  302. static String q(String s) { return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; }
  303. public static void main(String[] a) throws Exception {
  304. m(Class.forName("@SC@"), "@SC_detect@").invoke(null);
  305. m(Class.forName("@BS@"), "@BS_boot@").invoke(null);
  306. Class<?> bir = Class.forName("@BIR@");
  307. Object blocks = f(bir, "@BIR_BLOCK@", null), items = f(bir, "@BIR_ITEM@", null);
  308. Method getKey = m(Class.forName("@REG@"), "@REG_getKey@", Object.class);
  309. Class<?> bp = Class.forName("@BP@"), mc = Class.forName("@MC@");
  310. Method stateDef = m(Class.forName("@BLK@"), "@BLK_states@");
  311. Method possible = m(Class.forName("@SD@"), "@SD_states@");
  312. Method mapColor = m(Class.forName("@BSB@"), "@BSB_map@", Class.forName("@BG@"), bp);
  313. Object level = f(Class.forName("@EBG@"), "@EBG_I@", null), zero = f(bp, "@BP_ZERO@", null);
  314. StringBuilder out = new StringBuilder("{\"mapColours\":{");
  315. String sep = "";
  316. for (Object block : (Iterable<?>) blocks) {
  317. out.append(sep).append(q(getKey.invoke(blocks, block).toString())).append(":{");
  318. sep = ",";
  319. String sep2 = "";
  320. for (Object st : (List<?>) possible.invoke(stateDef.invoke(block))) {
  321. int col = (int) f(mc, "@MC_col@", mapColor.invoke(st, level, zero));
  322. String s = st.toString();
  323. int i = s.indexOf('[');
  324. out.append(sep2).append(q(i < 0 ? "" : s.substring(i + 1, s.length() - 1))).append(':').append(col);
  325. sep2 = ",";
  326. }
  327. out.append('}');
  328. }
  329. out.append("},\"compostables\":{");
  330. Method asItem = m(Class.forName("@IL@"), "@IL_as@");
  331. sep = "";
  332. for (Map.Entry<?, ?> e : ((Map<?, ?>) f(Class.forName("@CB@"), "@CB_C@", null)).entrySet()) {
  333. out.append(sep).append(q(getKey.invoke(items, asItem.invoke(e.getKey())).toString())).append(':')
  334. .append(Float.floatToIntBits(((Number) e.getValue()).floatValue()));
  335. sep = ",";
  336. }
  337. out.append("}}");
  338. try (Writer w = new OutputStreamWriter(new FileOutputStream(a[0]), "UTF-8")) { w.write(out.toString()); }
  339. }
  340. }
  341. """
  342. def obf_names(mappings):
  343. """The obfuscated names EXTRAS_JAVA needs, from Mojang's ProGuard-format mappings."""
  344. classes, members, cur = {}, {}, None
  345. with open(mappings, encoding="utf-8") as f:
  346. for line in f:
  347. line = line.rstrip("\n")
  348. if not line or line.startswith("#"):
  349. continue
  350. if not line.startswith(" "):
  351. m = re.match(r"(\S+) -> (\S+):", line)
  352. cur = m.group(1)
  353. classes[cur], members[cur] = m.group(2), []
  354. else:
  355. members[cur].append(line.strip())
  356. def method(c, name, params=""):
  357. for line in members[c]:
  358. m = re.match(r"(?:\d+:\d+:)?\S+ (\S+)\(([^)]*)\)(?::\d+:\d+)? -> (\S+)", line)
  359. if m and m.group(1) == name and m.group(2) == params:
  360. return m.group(3)
  361. raise KeyError(c + "." + name)
  362. def field(c, name):
  363. for line in members[c]:
  364. m = re.match(r"\S+ (\S+) -> (\S+)$", line)
  365. if m and m.group(1) == name:
  366. return m.group(2)
  367. raise KeyError(c + "." + name)
  368. p = "net.minecraft."
  369. reg, blk, sd = p + "core.registries.BuiltInRegistries", p + "world.level.block.Block", \
  370. p + "world.level.block.state.StateDefinition"
  371. bsb = p + "world.level.block.state.BlockBehaviour$BlockStateBase"
  372. return {
  373. "SC": classes[p + "SharedConstants"], "SC_detect": method(p + "SharedConstants", "tryDetectVersion"),
  374. "BS": classes[p + "server.Bootstrap"], "BS_boot": method(p + "server.Bootstrap", "bootStrap"),
  375. "BIR": classes[reg], "BIR_BLOCK": field(reg, "BLOCK"), "BIR_ITEM": field(reg, "ITEM"),
  376. "REG": classes[p + "core.Registry"], "REG_getKey": method(p + "core.Registry", "getKey", "java.lang.Object"),
  377. "BLK": classes[blk], "BLK_states": method(blk, "getStateDefinition"),
  378. "SD": classes[sd], "SD_states": method(sd, "getPossibleStates"),
  379. "BSB": classes[bsb],
  380. "BSB_map": method(bsb, "getMapColor", "net.minecraft.world.level.BlockGetter,net.minecraft.core.BlockPos"),
  381. "BG": classes[p + "world.level.BlockGetter"],
  382. "BP": classes[p + "core.BlockPos"], "BP_ZERO": field(p + "core.BlockPos", "ZERO"),
  383. "MC": classes[p + "world.level.material.MapColor"], "MC_col": field(p + "world.level.material.MapColor", "col"),
  384. "EBG": classes[p + "world.level.EmptyBlockGetter"], "EBG_I": field(p + "world.level.EmptyBlockGetter", "INSTANCE"),
  385. "CB": classes[p + "world.level.block.ComposterBlock"],
  386. "CB_C": field(p + "world.level.block.ComposterBlock", "COMPOSTABLES"),
  387. "IL": classes[p + "world.level.ItemLike"], "IL_as": method(p + "world.level.ItemLike", "asItem"),
  388. }
  389. def server_extras(java, run_dir, mappings):
  390. """Run EXTRAS_JAVA on the server the bundler unpacked into run_dir: {"mapColours": {id: {stateKey: rgb}},
  391. "compostables": {id: chance}}. The chance is the game's float, kept exact."""
  392. import struct
  393. import subprocess
  394. src = EXTRAS_JAVA
  395. names = obf_names(mappings)
  396. for key in sorted(names, key=len, reverse=True):
  397. src = src.replace("@" + key + "@", names[key])
  398. java_file = os.path.join(run_dir, "TurtleDataExtras.java")
  399. with open(java_file, "w", encoding="utf-8") as f:
  400. f.write(src)
  401. cp = []
  402. for root, _, files in os.walk(os.path.join(run_dir, "versions")):
  403. cp += [os.path.join(root, f) for f in files if f.endswith(".jar")]
  404. for root, _, files in os.walk(os.path.join(run_dir, "libraries")):
  405. cp += [os.path.join(root, f) for f in sorted(files) if f.endswith(".jar")]
  406. result = os.path.join(run_dir, "extras.json")
  407. subprocess.run([java, "-cp", os.pathsep.join(cp), java_file, result], cwd=run_dir, check=True,
  408. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
  409. with open(result, encoding="utf-8") as f:
  410. extras = json.load(f)
  411. extras["compostables"] = {k: struct.unpack(">f", struct.pack(">i", v))[0]
  412. for k, v in extras["compostables"].items()}
  413. return extras
  414. def map_colour_entry(states):
  415. """One block's map colours, compact: the colour when every state shares it, else {by, default, values} where
  416. `by` are the fewest state properties that decide it and values maps their values ("x" or "head,true") to it."""
  417. colours = set(states.values())
  418. if len(colours) == 1:
  419. return colours.pop()
  420. parsed = []
  421. for key, col in states.items():
  422. props = dict(pair.split("=", 1) for pair in key.split(",")) if key else {}
  423. parsed.append((props, col))
  424. names = sorted(parsed[0][0])
  425. from itertools import combinations
  426. for size in range(1, len(names) + 1):
  427. for by in combinations(names, size):
  428. values, ok = {}, True
  429. for props, col in parsed:
  430. k = ",".join(props[n] for n in by)
  431. if values.setdefault(k, col) != col:
  432. ok = False
  433. break
  434. if ok:
  435. default = max(colours, key=lambda c: sum(1 for _, x in parsed if x == c))
  436. return {"by": list(by), "default": default,
  437. "values": {k: v for k, v in sorted(values.items()) if v != default}}
  438. return None
  439. def vanilla_reports(client_jar, libs):
  440. """Run Minecraft's own data generator (net.minecraft.data.Main --reports) from the client jar: blocks.json has every
  441. vanilla block's real properties and default state, registries.json every item. None when Java is missing."""
  442. import shutil
  443. import subprocess
  444. import tempfile
  445. java = shutil.which("java")
  446. if not java:
  447. print("java not found: block properties come from blockstate files only")
  448. return None, None
  449. skip = re.compile(r"forge|minecraftforge|[\\/]com[\\/]mojang[\\/]minecraft[\\/]|lwjgl|fmlloader|cpw|modlauncher|natives")
  450. cp = [client_jar]
  451. for root, _, files in os.walk(libs):
  452. for f in files:
  453. path = os.path.join(root, f)
  454. if f.endswith(".jar") and not skip.search(path):
  455. cp.append(path)
  456. out = tempfile.mkdtemp(prefix="mcreports-")
  457. try:
  458. subprocess.run([java, "-cp", os.pathsep.join(cp), "net.minecraft.data.Main", "--reports", "--output", out],
  459. cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
  460. with open(os.path.join(out, "reports", "blocks.json"), encoding="utf-8") as f:
  461. blocks = json.load(f)
  462. with open(os.path.join(out, "reports", "registries.json"), encoding="utf-8") as f:
  463. registries = json.load(f)
  464. return blocks, registries
  465. except Exception as e:
  466. print("data generator failed (" + str(e) + "): block properties come from blockstate files only")
  467. return None, None
  468. finally:
  469. shutil.rmtree(out, ignore_errors=True)
  470. def load_json(data):
  471. try:
  472. text = data.decode("utf-8-sig")
  473. # some mods ship JSON with comments or trailing commas
  474. text = re.sub(r"^\s*//.*$", "", text, flags=re.M)
  475. text = re.sub(r",(\s*[}\]])", r"\1", text)
  476. return json.loads(text)
  477. except Exception:
  478. return None
  479. def main():
  480. args = parse_args(sys.argv[1:])
  481. out_dir = os.path.abspath(args.out)
  482. names = {}
  483. blocks = {} # id -> {prop: [values]}
  484. items = set()
  485. loot = {}
  486. tag_files = {"blocks": defaultdict(list), "items": defaultdict(list)} # tag -> [json, ...] in load order
  487. recipes = {}
  488. cooking = {}
  489. folders = args.info["folders"]
  490. tag_groups = {folders["block_tags"]: "blocks", folders["item_tags"]: "items"}
  491. for jar in jars(args):
  492. try:
  493. z = zipfile.ZipFile(jar)
  494. except Exception:
  495. continue
  496. for entry in z.namelist():
  497. if not entry.endswith(".json"):
  498. continue
  499. parts = entry.split("/")
  500. if len(parts) < 4:
  501. continue
  502. root, ns, kind = parts[0], parts[1], parts[2]
  503. rest = "/".join(parts[3:])[:-5]
  504. if root == "assets" and kind == "lang" and rest == "en_us":
  505. data = load_json(z.read(entry))
  506. if isinstance(data, dict):
  507. for key, value in data.items():
  508. m = re.match(r"^(block|item)\.([a-z0-9_.-]+)\.([a-z0-9_./-]+)$", key)
  509. if m and isinstance(value, str):
  510. ident = m.group(2) + ":" + m.group(3)
  511. # an item name wins over the block name only when there is no block name
  512. if m.group(1) == "block" or ident not in names:
  513. names[ident] = value
  514. if m.group(1) == "item":
  515. items.add(ident)
  516. elif root == "assets" and kind == "blockstates" and "/" not in rest:
  517. data = load_json(z.read(entry))
  518. ident = ns + ":" + rest
  519. props = defaultdict(set)
  520. if isinstance(data, dict):
  521. keys = []
  522. if isinstance(data.get("variants"), dict):
  523. keys = list(data["variants"].keys())
  524. for key in keys:
  525. for pair in key.split(","):
  526. if "=" in pair:
  527. k, v = pair.split("=", 1)
  528. props[k].add(v)
  529. for part in data.get("multipart", []) or []:
  530. when = part.get("when") if isinstance(part, dict) else None
  531. conds = []
  532. if isinstance(when, dict):
  533. if "OR" in when and isinstance(when["OR"], list):
  534. conds = [c for c in when["OR"] if isinstance(c, dict)]
  535. else:
  536. conds = [when]
  537. for c in conds:
  538. for k, v in c.items():
  539. for one in str(v).split("|"):
  540. props[k].add(one)
  541. blocks[ident] = {k: sorted(v) for k, v in props.items()}
  542. elif root == "assets" and kind == "models" and rest.startswith("item/") and "/" not in rest[5:]:
  543. items.add(ns + ":" + rest[5:])
  544. elif root == "data" and kind == folders["loot"] and rest.startswith("blocks/"):
  545. data = load_json(z.read(entry))
  546. if isinstance(data, dict):
  547. loot[ns + ":" + rest[7:]] = data
  548. elif root == "data" and kind == "tags" and rest.split("/", 1)[0] in tag_groups and "/" in rest:
  549. group, path = rest.split("/", 1)
  550. data = load_json(z.read(entry))
  551. if isinstance(data, dict):
  552. tag_files[tag_groups[group]][ns + ":" + path].append(data)
  553. elif root == "data" and kind == folders["recipes"]:
  554. data = load_json(z.read(entry))
  555. if isinstance(data, dict):
  556. recipe = crafting_recipe(data)
  557. if recipe:
  558. recipes[ns + ":" + rest] = recipe
  559. cook = cooking_recipe(data)
  560. if cook:
  561. cooking[ns + ":" + rest] = cook
  562. # Vanilla: the real properties and default states, and the real item registry, over the model-file guesses
  563. defaults = {}
  564. extras = None
  565. if args.info["reports"] == "server":
  566. report, registries, extras = server_reports(args.server_jar, args.mappings)
  567. else:
  568. report, registries = vanilla_reports(args.client_jar, args.libraries)
  569. if report:
  570. for ident, info in report.items():
  571. blocks[ident] = {k: list(v) for k, v in (info.get("properties") or {}).items()}
  572. for st in info.get("states", []):
  573. if st.get("default"):
  574. defaults[ident] = st.get("properties") or {}
  575. if registries:
  576. vanilla_items = set((registries.get("minecraft:item") or {}).get("entries", {}).keys())
  577. items = {i for i in items if not i.startswith("minecraft:")} | vanilla_items
  578. for data in loot.values():
  579. for out in loot_outputs(data):
  580. if not out.startswith("minecraft:") or not registries:
  581. items.add(out)
  582. for recipe in recipes.values():
  583. items.add(recipe["result"]["item"])
  584. # a block with an item model is also an item; a block alone (fire, water) is not
  585. items = {i for i in items if ID.match(i)}
  586. block_tags = resolve_tags(tag_files["blocks"])
  587. item_tags = resolve_tags(tag_files["items"])
  588. # One file per namespace, so a turtle that only meets vanilla blocks loads only minecraft.lua
  589. sections = {
  590. "names": names,
  591. "blocks": blocks,
  592. "defaults": defaults,
  593. "items": {i: True for i in items},
  594. "loot": loot,
  595. "blockTags": invert(block_tags),
  596. "itemTags": invert(item_tags),
  597. }
  598. # Map colours (CC:Tweaked 1.121.0's item and block details have them): only from the server's code, so only
  599. # where server_extras ran; a set without them keeps exactly the sections it always had
  600. if extras:
  601. colours = {ident: map_colour_entry(states) for ident, states in extras["mapColours"].items()}
  602. colours.update(args.info.get("map_colours", {}))
  603. sections["mapColours"] = {k: v for k, v in colours.items() if v is not None}
  604. by_ns = defaultdict(lambda: {k: {} for k in sections})
  605. for section, table in sections.items():
  606. for ident, value in table.items():
  607. by_ns[ident.split(":", 1)[0]][section][ident] = value
  608. if os.path.isdir(out_dir):
  609. for old in os.listdir(out_dir):
  610. if old.endswith(".lua"):
  611. os.remove(os.path.join(out_dir, old))
  612. os.makedirs(out_dir, exist_ok=True)
  613. for ns, data in by_ns.items():
  614. write_sections(os.path.join(out_dir, ns + ".lua"), data)
  615. write_sections(os.path.join(out_dir, "_recipes.lua"), {"recipes": recipes})
  616. write_sections(os.path.join(out_dir, "_cooking.lua"), {"cooking": cooking})
  617. # Tag members, for recipe ingredients given as a tag
  618. write_sections(os.path.join(out_dir, "_tag_members.lua"), {"items": {t: sorted(m) for t, m in item_tags.items()}})
  619. if extras:
  620. # ComposterBlock.COMPOSTABLES: item id -> the chance one item raises the level
  621. write_sections(os.path.join(out_dir, "_compostables.lua"), {"compostables": extras["compostables"]})
  622. print("Minecraft " + args.mc + " " + ("vanilla" if args.vanilla else "pack") + " set -> " + out_dir)
  623. print(f"{len(blocks)} blocks, {len(items)} items, {len(names)} names, {len(loot)} loot tables, "
  624. f"{len(block_tags)} block tags, {len(item_tags)} item tags, {len(recipes)} crafting recipes")
  625. def crafting_recipe(data):
  626. """A shaped or shapeless crafting recipe, unwrapped from forge:conditional; None for anything else."""
  627. if data.get("type") == "forge:conditional" and isinstance(data.get("recipes"), list) and data["recipes"]:
  628. first = data["recipes"][0]
  629. data = first.get("recipe") if isinstance(first, dict) else None
  630. if not isinstance(data, dict):
  631. return None
  632. kind = data.get("type")
  633. result = data.get("result")
  634. if isinstance(result, str):
  635. result = {"item": result}
  636. if not isinstance(result, dict) or not isinstance(result.get("item"), str):
  637. return None
  638. out = {"item": result["item"], "count": int(result.get("count", 1))}
  639. if isinstance(result.get("nbt"), (dict, str)):
  640. out["nbt"] = result["nbt"] if isinstance(result["nbt"], str) else json.dumps(result["nbt"])
  641. if kind == "minecraft:crafting_shaped":
  642. pattern = data.get("pattern")
  643. key = data.get("key")
  644. if not isinstance(pattern, list) or not isinstance(key, dict):
  645. return None
  646. return {"type": "shaped", "pattern": pattern, "key": {k: ingredient(v) for k, v in key.items()}, "result": out}
  647. if kind == "minecraft:crafting_shapeless":
  648. ings = data.get("ingredients")
  649. if not isinstance(ings, list):
  650. return None
  651. return {"type": "shapeless", "ingredients": [ingredient(v) for v in ings], "result": out}
  652. return None
  653. def cooking_recipe(data):
  654. """A smelting, blasting, smoking or campfire cooking recipe: {type, ingredient, result, time}; None for anything else."""
  655. kind = data.get("type")
  656. short = {"minecraft:smelting": "smelting", "minecraft:blasting": "blasting", "minecraft:smoking": "smoking",
  657. "minecraft:campfire_cooking": "campfire_cooking"}.get(kind)
  658. result = data.get("result")
  659. if isinstance(result, dict):
  660. result = result.get("item")
  661. if not short or not isinstance(result, str) or "ingredient" not in data:
  662. return None
  663. default = {"smelting": 200, "blasting": 100, "smoking": 100, "campfire_cooking": 600}[short]
  664. return {"type": short, "ingredient": ingredient(data["ingredient"]), "result": result,
  665. "time": int(data.get("cookingtime", default))}
  666. def ingredient(value):
  667. """An ingredient as a list of alternatives, each {"item": id} or {"tag": id}."""
  668. alts = value if isinstance(value, list) else [value]
  669. out = []
  670. for alt in alts:
  671. if isinstance(alt, dict):
  672. if isinstance(alt.get("item"), str):
  673. out.append({"item": alt["item"]})
  674. elif isinstance(alt.get("tag"), str):
  675. out.append({"tag": alt["tag"]})
  676. return out
  677. def loot_outputs(node):
  678. if isinstance(node, dict):
  679. if node.get("type") == "minecraft:item" and isinstance(node.get("name"), str):
  680. yield node["name"]
  681. for v in node.values():
  682. yield from loot_outputs(v)
  683. elif isinstance(node, list):
  684. for v in node:
  685. yield from loot_outputs(v)
  686. def resolve_tags(files):
  687. raw = {}
  688. for tag, datas in files.items():
  689. values = []
  690. for data in datas:
  691. if data.get("replace") is True:
  692. values = []
  693. for v in data.get("values", []) or []:
  694. if isinstance(v, dict):
  695. v = v.get("id")
  696. if isinstance(v, str):
  697. values.append(v)
  698. raw[tag] = values
  699. resolved = {}
  700. def members(tag, seen):
  701. if tag in resolved:
  702. return resolved[tag]
  703. if tag in seen:
  704. return set()
  705. seen.add(tag)
  706. out = set()
  707. for v in raw.get(tag, []):
  708. if v.startswith("#"):
  709. out |= members(v[1:], seen)
  710. elif ID.match(v):
  711. out.add(v)
  712. resolved[tag] = out
  713. return out
  714. for tag in raw:
  715. members(tag, set())
  716. return resolved
  717. def invert(tags):
  718. by_id = defaultdict(list)
  719. for tag, ids in tags.items():
  720. for ident in ids:
  721. by_id[ident].append(tag)
  722. return {k: sorted(v) for k, v in sorted(by_id.items())}
  723. def lua(value, out):
  724. if value is None:
  725. out.append("nil")
  726. elif value is True:
  727. out.append("true")
  728. elif value is False:
  729. out.append("false")
  730. elif isinstance(value, (int, float)):
  731. out.append(repr(value) if isinstance(value, float) else str(value))
  732. elif isinstance(value, str):
  733. out.append(json.dumps(value, ensure_ascii=False))
  734. elif isinstance(value, list):
  735. out.append("{")
  736. for v in value:
  737. lua(v, out)
  738. out.append(",")
  739. out.append("}")
  740. elif isinstance(value, dict):
  741. out.append("{")
  742. for k, v in value.items():
  743. if isinstance(k, str) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", k) and k not in LUA_KEYWORDS:
  744. out.append(k + "=")
  745. else:
  746. out.append("[" + json.dumps(str(k), ensure_ascii=False) + "]=")
  747. lua(v, out)
  748. out.append(",")
  749. out.append("}")
  750. else:
  751. out.append(json.dumps(str(value)))
  752. LUA_KEYWORDS = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
  753. "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"}
  754. def write_sections(path, sections):
  755. # one entry per line, so a diff of a regenerated file stays readable
  756. lines = ["-- generated by tools/turtledata/extract.py from the game jars; do not edit", "return {"]
  757. for section in sorted(sections):
  758. lines.append(section + "={")
  759. value = sections[section]
  760. for k in sorted(value):
  761. out = []
  762. lua(value[k], out)
  763. lines.append("[" + json.dumps(k, ensure_ascii=False) + "]=" + "".join(out) + ",")
  764. lines.append("},")
  765. lines.append("}")
  766. with open(path, "w", encoding="utf-8", newline="\n") as f:
  767. f.write("\n".join(lines) + "\n")
  768. if __name__ == "__main__":
  769. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.