Thingo
This commit is contained in:
46
AGENTS.md
Normal file
46
AGENTS.md
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
Codecraft is a Fabric mod (mod id `codecraft`, group `com.aranroig`) that lets players write and run Lua code from an in-game code editor. The Lua runtime is [luajava](https://iroiro.party/luajava/) (`party.iroiro.luajava:luajava` + `luaj`, pure-Java LuaJ, no native libs).
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- `./gradlew build` — compile and build the mod jar (output in `build/libs/`). This is the only verification available; there are no tests.
|
||||||
|
- `./gradlew runClient` — launch the dev client with the mod loaded.
|
||||||
|
- `./gradlew runDatagen` — regenerate data (lang files) into `src/main/generated/`.
|
||||||
|
- Requires JDK 25. CI (`.github/workflows/build.yml`) builds on ubuntu-24.04 with JDK 25 (Microsoft distribution).
|
||||||
|
|
||||||
|
## Versions
|
||||||
|
|
||||||
|
All versions live in `gradle.properties` (check https://fabricmc.net/develop): Minecraft `26.2`, loader `0.19.3`, loom `1.17-SNAPSHOT`, Fabric API `0.153.0+26.2`. Java release/target is 25. Mod version comes from `mod_version` and is expanded into `fabric.mod.json` at build time — never hardcode the version there.
|
||||||
|
|
||||||
|
## Source layout
|
||||||
|
|
||||||
|
Loom uses `splitEnvironmentSourceSets()`:
|
||||||
|
|
||||||
|
- `src/main/java` — common/server code. Entrypoint `com.aranroig.Codecraft` (registers payloads, handles them server-side). Lua execution belongs here eventually.
|
||||||
|
- `src/client/java` — client-only code. Entrypoints `com.aranroig.client.CodecraftClient` (keybind, default `J`, toggles the editor) and `com.aranroig.client.CodecraftDataGenerator` (datagen).
|
||||||
|
- `src/main/resources` — `fabric.mod.json`, mixins config, assets.
|
||||||
|
- `src/main/generated` — datagen output (e.g. `assets/codecraft/lang/en_us.json`). Do not hand-edit; add translations in `CodecraftEnglishLangProvider` and run `runDatagen`.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Flow: client editor → custom payloads → server → persisted project.
|
||||||
|
|
||||||
|
- **Networking** (`com.aranroig.payloads`): one record per message implementing `CustomPacketPayload` with a static `TYPE` and `StreamCodec`. Serverbound payloads must be registered in `Codecraft.onInitialize()` via `PayloadTypeRegistry.serverboundPlay().register(...)`, and received with `ServerPlayNetworking.registerGlobalReceiver(...)`.
|
||||||
|
- **Persistence** (`SavedProjectData`): a `SavedData` stored in the overworld (`saved_project_data`). Holds the list of `EditorFile`s that make up the user's project.
|
||||||
|
- **Editor UI** (`com.aranroig.client.editor`): a custom immediate-mode-ish GUI system, not vanilla widgets. `EditorScreen` routes key/mouse input to `Widget`s by hit-testing (`inside()`) and z-index. `EditorManager` owns the widgets and editor actions (save/run/etc.); `EditorFileTree`, `EditorTopBar`, `EditorFileView` are the three panels. `EditorFileView` is the actual text editor; `LuaHighlighter` tokenizes lines into colored `Span`s and `CompletionProvider` handles autocomplete.
|
||||||
|
- **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload` with the entrypoint name; the server handler in `Codecraft.java` is a TODO (currently just prints). Example of embedding: `Lua l = new LuaJ(); l.register("print", Logger.print()); l.run(code);` — `com.aranroig.client.wrapper.Logger` adapts a `LuaFunction` to print into the player chat. Decide carefully whether Lua runs client- or server-side; server-side is the apparent direction.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Use `Codecraft.id(path)` / `Identifier.fromNamespaceAndPath(MOD_ID, path)` for all ids, and the `Codecraft.LOGGER` (slf4j) instead of `System.out.println` for new logging.
|
||||||
|
- Data classes that cross both persistence and network layers (see `EditorFile`) carry both a Mojang `Codec` and a `StreamCodec`; `RunInfo` currently only has a stream codec.
|
||||||
|
- Records are used for payloads/simple data; match the style of the file you're editing (entrypoint classes from the Fabric template use tabs, editor code uses 4 spaces).
|
||||||
|
- Translation keys follow `key.codecraft.*` / `key.category.codecraft.*`.
|
||||||
|
- Mixin configs: `codecraft.mixins.json` (common, package `com.aranroig.mixin`) and `codecraft.client.mixins.json` (client). `ExampleMixin` / `ExampleClientMixin` are template leftovers.
|
||||||
|
|
||||||
|
## Status / gotchas
|
||||||
|
|
||||||
|
- Work in progress: `EditorManager.newFile/undo/redo/stop` are empty stubs, server-side code execution is unimplemented, `com.aranroig.editor.Project` is a stub that is meant to replace the raw `List<EditorFile>` usage, and `EditorManager.files` is never populated (loading files from the server is an open TODO; `toggleVisible()` will NPE on `files.getFirst()`).
|
||||||
|
- Some TODOs/comments are written in Spanish/Catalan; leave them unless resolving them.
|
||||||
|
- Minecraft 26.2 uses the newer class/mapping names (`Identifier`, `GuiGraphicsExtractor`, `MouseButtonEvent`, `Component`, etc.) — don't rename them back to older MCP/Yarn-era names.
|
||||||
194
docs/lua-api.md
Normal file
194
docs/lua-api.md
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
# Lua scripting
|
||||||
|
|
||||||
|
Scripts are written in the in-game editor (`J` by default, rebindable under
|
||||||
|
*Options → Controls* → *Codecraft*) and run **on the server**. The top bar's
|
||||||
|
**Run Script** executes `main.lua`, which is the entrypoint.
|
||||||
|
|
||||||
|
This same documentation is browsable in-game from the editor:
|
||||||
|
**Help → Lua API Documentation**, or press **F1** on a function while editing.
|
||||||
|
|
||||||
|
Because a script runs on the server thread from start to finish, everything it does
|
||||||
|
happens at once and the game waits for it to finish. Loops that place millions of
|
||||||
|
blocks will freeze the server, so keep them reasonable.
|
||||||
|
|
||||||
|
```lua
|
||||||
|
print("hello, player!")
|
||||||
|
```
|
||||||
|
|
||||||
|
## print(...)
|
||||||
|
|
||||||
|
Writes to the chat of the player who ran the script, tab-separated, like Minecraft
|
||||||
|
commands do.
|
||||||
|
|
||||||
|
```lua
|
||||||
|
print("blocks placed:", 12)
|
||||||
|
```
|
||||||
|
|
||||||
|
Whole numbers go through the Lua wrapper and are printed as `12.0`. To print them
|
||||||
|
without the decimal, concatenate them into a string:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
print("blocks placed: " .. 12) -- -> blocks placed: 12
|
||||||
|
```
|
||||||
|
|
||||||
|
## Blocks
|
||||||
|
|
||||||
|
Coordinates are **absolute world coordinates** — never relative to the player — in the
|
||||||
|
dimension the running player stands in. Press `F3` to read your own coordinates, then
|
||||||
|
use them in the script.
|
||||||
|
|
||||||
|
| Function | Returns |
|
||||||
|
| --------------------------------------- | --------------------------------------------------- |
|
||||||
|
| `world.set_block(x, y, z, block)` | `true`, or `false` and a reason |
|
||||||
|
| `world.remove_block(x, y, z[, drops])` | `true`, or `false` and a reason |
|
||||||
|
| `world.get_block(x, y, z)` | block id string, or `nil` and a reason |
|
||||||
|
|
||||||
|
### world.set_block(x, y, z, block)
|
||||||
|
|
||||||
|
Places a block and updates neighbours and clients, like `/setblock` does. `block` is a
|
||||||
|
block id, with or without the `minecraft:` namespace, and may carry block states:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
world.set_block(10, 64, -3, "minecraft:stone")
|
||||||
|
world.set_block(10, 65, -3, "gold_block") -- namespace optional
|
||||||
|
world.set_block(10, 66, -3, "minecraft:oak_stairs[facing=north]")
|
||||||
|
world.set_block(11, 66, -3, "minecraft:wall_torch[facing=south]") -- needs a wall behind it
|
||||||
|
```
|
||||||
|
|
||||||
|
The block is placed even if something is in the way. Blocks that cannot survive where
|
||||||
|
they are put (a torch without a wall, a flower without ground) drop themselves again,
|
||||||
|
and the call reports it as a failure.
|
||||||
|
|
||||||
|
Replacing a block that holds items, such as a chest, drops the contents like
|
||||||
|
`/setblock` does.
|
||||||
|
|
||||||
|
### world.remove_block(x, y, z[, drops])
|
||||||
|
|
||||||
|
Removes the block. Without `drops` the block just vanishes, silently and without items.
|
||||||
|
With `true` it breaks the way a player breaking it would: items, sound and particles.
|
||||||
|
|
||||||
|
```lua
|
||||||
|
world.remove_block(10, 64, -3) -- vanish
|
||||||
|
world.remove_block(10, 65, -3, true) -- break it, dropping items
|
||||||
|
```
|
||||||
|
|
||||||
|
### world.get_block(x, y, z)
|
||||||
|
|
||||||
|
Returns the block id at that position, including its block states, so the result can be
|
||||||
|
handed straight back to `world.set_block`:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
print(world.get_block(10, 64, -3)) -- -> minecraft:grass_block[snowy=false]
|
||||||
|
```
|
||||||
|
|
||||||
|
Air is `"minecraft:air"`, a string, and every string is *true* in Lua — compare
|
||||||
|
against the id rather than testing the value:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local block = world.get_block(10, 64, -3)
|
||||||
|
if block ~= "minecraft:air" then
|
||||||
|
print("something is there: " .. block)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
A pillar four blocks tall:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
for y = 64, 67 do
|
||||||
|
world.set_block(10, y, -3, "minecraft:cobblestone")
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
A 7×7 platform:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
for x = -3, 3 do
|
||||||
|
for z = -3, 3 do
|
||||||
|
world.set_block(10 + x, 64, -3 + z, "minecraft:stone_bricks")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
A room with walls, a floor and an empty inside, i.e. hollowing out a box:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local x, y, z = 10, 64, -3 -- corner of the room
|
||||||
|
local width, height, depth = 7, 4, 7
|
||||||
|
|
||||||
|
for dx = 0, width - 1 do
|
||||||
|
for dy = 0, height - 1 do
|
||||||
|
for dz = 0, depth - 1 do
|
||||||
|
local shell = dx == 0 or dx == width - 1
|
||||||
|
or dy == 0 or dy == height - 1
|
||||||
|
or dz == 0 or dz == depth - 1
|
||||||
|
local px, py, pz = x + dx, y + dy, z + dz
|
||||||
|
if shell then
|
||||||
|
world.set_block(px, py, pz, "minecraft:stone_bricks")
|
||||||
|
else
|
||||||
|
world.remove_block(px, py, pz)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
Copy the block type of one place to another:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local block = world.get_block(10, 64, -3)
|
||||||
|
if block then
|
||||||
|
world.set_block(20, 70, 5, block)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
Clear an area of everything that is not air (leaves, grass, and so on):
|
||||||
|
|
||||||
|
```lua
|
||||||
|
for x = 0, 15 do
|
||||||
|
for y = 60, 80 do
|
||||||
|
for z = 0, 15 do
|
||||||
|
if world.get_block(x, y, z) ~= "minecraft:air" then
|
||||||
|
world.remove_block(x, y, z)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
## Checking whether a call worked
|
||||||
|
|
||||||
|
Every block function returns a reason as its second value, which is worth printing
|
||||||
|
while a script misbehaves:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local ok, reason = world.set_block(10, 64, -3, "minecraft:stone")
|
||||||
|
if not ok then
|
||||||
|
print("could not place the block: " .. reason)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
| Reason | What it means |
|
||||||
|
| ------------------------------------------ | ------------------------------------------------------------------------- |
|
||||||
|
| `usage: world.set_block(...)` | too few arguments |
|
||||||
|
| `x, y and z must be numbers` | a coordinate is missing, `nil`, or a string like `"10"` |
|
||||||
|
| `block must be a string, e.g. "minecraft:stone"` | the block was given as a number or table rather than a string |
|
||||||
|
| `'X' is not a block` | unknown block id, a misspelled state, or a tag such as `#minecraft:logs` |
|
||||||
|
| `y must be between -64 and 319, not 400` | outside the world's build height |
|
||||||
|
| `the chunk at x, z is not loaded` | too far away from any player, and not force-loaded |
|
||||||
|
| `'X' does not fit at x, y, z` | the block was placed and removed itself again (no support block) |
|
||||||
|
| `there is nothing to remove at x, y, z` | the target block is already air |
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
- No reach or permission checks: a script can change any block in a **loaded** chunk of
|
||||||
|
the running player's dimension. Keep an eye on what you run.
|
||||||
|
- Only loaded chunks can be read or edited — those around players, or force-loaded.
|
||||||
|
- Block entity data is not exposed: a placed chest is empty, and a sign has no text.
|
||||||
|
- Only `main.lua` is executed. Code in the other project files is not loaded, so
|
||||||
|
`require` does not find them yet.
|
||||||
|
- The Lua runtime is LuaJ (Lua 5.1) with only the base library loaded: `tostring`,
|
||||||
|
`tonumber`, `type`, `pcall`, `pairs`, `ipairs`, `assert`, `error` are available, but
|
||||||
|
the `string`, `math`, `table` and `coroutine` libraries are not, so `math.floor(2.7)`
|
||||||
|
fails with *attempt to index a nil value*.
|
||||||
548
src/client/java/com/aranroig/client/editor/EditorDocsPanel.java
Normal file
548
src/client/java/com/aranroig/client/editor/EditorDocsPanel.java
Normal file
@@ -0,0 +1,548 @@
|
|||||||
|
package com.aranroig.client.editor;
|
||||||
|
|
||||||
|
import com.aranroig.docs.ExampleDoc;
|
||||||
|
import com.aranroig.docs.FunctionDoc;
|
||||||
|
import com.aranroig.docs.LuaApiDocs;
|
||||||
|
import com.aranroig.docs.Topic;
|
||||||
|
import com.aranroig.client.editor.LuaHighlighter.Span;
|
||||||
|
import net.minecraft.client.gui.Font;
|
||||||
|
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||||
|
import net.minecraft.client.input.CharacterEvent;
|
||||||
|
import net.minecraft.client.input.KeyEvent;
|
||||||
|
import net.minecraft.client.input.MouseButtonEvent;
|
||||||
|
import org.jspecify.annotations.NonNull;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Modal documentation browser for the Lua functions this mod adds.
|
||||||
|
*
|
||||||
|
* <p>Covers the whole editor screen (z-index 2, set in {@link EditorManager})
|
||||||
|
* while visible: a dimmed backdrop, a scrollable list of topics/functions on
|
||||||
|
* the left and the rendered documentation of the selection on the right.</p>
|
||||||
|
*
|
||||||
|
* <p>Opened through {@link #open()} / {@link #open(String)} — the top bar's
|
||||||
|
* <em>Help → Lua API Documentation</em> menu and <em>F1</em> in the file view.
|
||||||
|
* Closed with Escape, the ✕ button or a click outside the panel. While open it
|
||||||
|
* keeps itself in {@code EditorScreen.selectedWidget} so keyboard and scroll
|
||||||
|
* events arrive here.</p>
|
||||||
|
*/
|
||||||
|
public class EditorDocsPanel extends Widget {
|
||||||
|
|
||||||
|
private boolean visible = false;
|
||||||
|
|
||||||
|
private Font font;
|
||||||
|
/** Mouse position of the last frame, used to route scrolling to the right column. */
|
||||||
|
private int mouseX, mouseY;
|
||||||
|
|
||||||
|
// ── Model ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** One row of the left list: a topic header or a function underneath one. */
|
||||||
|
private record Row(boolean isFunction, int topic, int function, String label) {}
|
||||||
|
|
||||||
|
private final List<Topic> topics = LuaApiDocs.topics();
|
||||||
|
private final List<Row> rows = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Index into {@link #rows} of the current selection. */
|
||||||
|
private int selectedRow = 0;
|
||||||
|
|
||||||
|
private int listScroll = 0;
|
||||||
|
private int detailScroll = 0;
|
||||||
|
/** Height of the rendered detail page, measured while drawing, for clamping. */
|
||||||
|
private int detailContentHeight = 0;
|
||||||
|
|
||||||
|
private final LuaHighlighter highlighter = new LuaHighlighter();
|
||||||
|
|
||||||
|
// ── Colors (same palette as the rest of the editor) ───────────────────
|
||||||
|
|
||||||
|
private static final int COLOR_OVERLAY = 0xB0000000;
|
||||||
|
private static final int COLOR_PANEL_BG = 0xFF1E1E1E;
|
||||||
|
private static final int COLOR_BORDER = 0xFF666666;
|
||||||
|
private static final int COLOR_TITLE_BG = 0xFF252525;
|
||||||
|
private static final int COLOR_TITLE = 0xFFFFFFFF;
|
||||||
|
private static final int COLOR_HINT = 0xFF555577;
|
||||||
|
private static final int COLOR_TEXT = 0xFFD4D4D4;
|
||||||
|
private static final int COLOR_DIM = 0xFF888888;
|
||||||
|
private static final int COLOR_TOPIC = 0xFF4EC9B0;
|
||||||
|
private static final int COLOR_SIGNATURE = 0xFFDCDCAA;
|
||||||
|
private static final int COLOR_PARAM_NAME = 0xFF9CDCFE;
|
||||||
|
private static final int COLOR_SECTION = 0xFF569CD6;
|
||||||
|
private static final int COLOR_ROW_SELECTED = 0xFF383868;
|
||||||
|
private static final int COLOR_ROW_HOVER = 0xFF2A2A3A;
|
||||||
|
private static final int COLOR_LIST_BG = 0xFF1A1A1A;
|
||||||
|
private static final int COLOR_CODE_BG = 0xFF252525;
|
||||||
|
|
||||||
|
// ── Layout ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static final int MARGIN = 16;
|
||||||
|
private static final int LIST_WIDTH = 170;
|
||||||
|
private static final int PAD = 6;
|
||||||
|
private static final int ROW_PAD = 2;
|
||||||
|
private static final int FUNC_INDENT = 10;
|
||||||
|
private static final int SCROLL_SPEED = 3;
|
||||||
|
|
||||||
|
public EditorDocsPanel(EditorManager editorManager) {
|
||||||
|
super(editorManager);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
for (int t = 0; t < topics.size(); t++) {
|
||||||
|
rows.add(new Row(false, t, -1, topics.get(t).title()));
|
||||||
|
List<FunctionDoc> functions = topics.get(t).functions();
|
||||||
|
for (int f = 0; f < functions.size(); f++) {
|
||||||
|
rows.add(new Row(true, t, f, functions.get(f).name()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Open / close ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Opens the panel, keeping the previous selection. */
|
||||||
|
public void open() {
|
||||||
|
open(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the panel and selects the function whose name matches {@code word}
|
||||||
|
* (fully qualified like {@code world.set_block}, or just the last segment
|
||||||
|
* like {@code set_block}). A {@code null} or unmatched word keeps the
|
||||||
|
* current selection.
|
||||||
|
*/
|
||||||
|
public void open(String word) {
|
||||||
|
if (word != null && !word.isEmpty()) {
|
||||||
|
selectByName(word);
|
||||||
|
} else if (selectedRow < 0 || selectedRow >= rows.size()) {
|
||||||
|
selectedRow = 0;
|
||||||
|
}
|
||||||
|
visible = true;
|
||||||
|
scrollSelectionIntoView();
|
||||||
|
if (editorScreen != null) {
|
||||||
|
editorScreen.selectedWidget = this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void close() {
|
||||||
|
visible = false;
|
||||||
|
if (editorScreen != null && editorScreen.selectedWidget == this) {
|
||||||
|
editorScreen.selectedWidget = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isOpen() {
|
||||||
|
return visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void selectByName(String word) {
|
||||||
|
// Exact match first, then the unqualified last segment.
|
||||||
|
for (int i = 0; i < rows.size(); i++) {
|
||||||
|
Row row = rows.get(i);
|
||||||
|
if (row.isFunction() && row.label().equalsIgnoreCase(word)) {
|
||||||
|
selectRow(i);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < rows.size(); i++) {
|
||||||
|
Row row = rows.get(i);
|
||||||
|
if (row.isFunction()
|
||||||
|
&& row.label().toLowerCase().endsWith("." + word.toLowerCase())) {
|
||||||
|
selectRow(i);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void selectRow(int index) {
|
||||||
|
selectedRow = index;
|
||||||
|
detailScroll = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void scrollSelectionIntoView() {
|
||||||
|
int rowH = rowHeight();
|
||||||
|
int top = rowHeight() * selectedRow - listScroll;
|
||||||
|
int viewH = listAreaBottom() - listTop();
|
||||||
|
if (top < 0) {
|
||||||
|
listScroll = rowHeight() * selectedRow;
|
||||||
|
} else if (top + rowH > viewH) {
|
||||||
|
listScroll = rowHeight() * selectedRow + rowH - viewH;
|
||||||
|
}
|
||||||
|
clampListScroll();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Geometry helpers ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private int lineHeight() { return font != null ? font.lineHeight : 10; }
|
||||||
|
private int rowHeight() { return lineHeight() + ROW_PAD; }
|
||||||
|
private int titleHeight(){ return lineHeight() + PAD * 2 - 2; }
|
||||||
|
|
||||||
|
private int panelX1() { return getStartX() + MARGIN; }
|
||||||
|
private int panelY1() { return getStartY() + MARGIN; }
|
||||||
|
private int panelX2() { return getEndX() - MARGIN; }
|
||||||
|
private int panelY2() { return getEndY() - MARGIN; }
|
||||||
|
|
||||||
|
private int listX2() { return panelX1() + LIST_WIDTH; }
|
||||||
|
private int listTop() { return panelY1() + titleHeight(); }
|
||||||
|
private int listAreaBottom() { return panelY2(); }
|
||||||
|
private int detailX() { return listX2() + PAD + 1; }
|
||||||
|
private int detailTop() { return listTop() + PAD; }
|
||||||
|
|
||||||
|
private int maxListScroll() {
|
||||||
|
return Math.max(0, rows.size() * rowHeight() - (listAreaBottom() - listTop()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void clampListScroll() {
|
||||||
|
listScroll = Math.max(0, Math.min(listScroll, maxListScroll()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean insideCloseButton(int mx, int my) {
|
||||||
|
int buttonSize = titleHeight();
|
||||||
|
return mx >= panelX2() - buttonSize && mx < panelX2()
|
||||||
|
&& my >= panelY1() && my < panelY1() + buttonSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
private FunctionDoc selectedFunction() {
|
||||||
|
Row row = rows.get(selectedRow);
|
||||||
|
return row.isFunction() ? topics.get(row.topic()).functions().get(row.function()) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Widget overrides ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean inside(double x, double y) {
|
||||||
|
return visible && super.inside(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
|
||||||
|
if (!visible) return;
|
||||||
|
font = editorScreen.getFont();
|
||||||
|
this.mouseX = mouseX;
|
||||||
|
this.mouseY = mouseY;
|
||||||
|
|
||||||
|
clampListScroll();
|
||||||
|
detailScroll = Math.max(0, Math.min(detailScroll,
|
||||||
|
Math.max(0, detailContentHeight - (panelY2() - listTop() - PAD * 2))));
|
||||||
|
|
||||||
|
// Backdrop + panel
|
||||||
|
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_OVERLAY);
|
||||||
|
graphics.fill(panelX1(), panelY1(), panelX2(), panelY2(), COLOR_PANEL_BG);
|
||||||
|
graphics.fill(panelX1(), panelY1(), panelX2(), panelY1() + 1, COLOR_BORDER); // top
|
||||||
|
graphics.fill(panelX1(), panelY2() - 1, panelX2(), panelY2(), COLOR_BORDER); // bottom
|
||||||
|
graphics.fill(panelX1(), panelY1(), panelX1() + 1, panelY2(), COLOR_BORDER); // left
|
||||||
|
graphics.fill(panelX2() - 1, panelY1(), panelX2(), panelY2(), COLOR_BORDER); // right
|
||||||
|
|
||||||
|
drawTitleBar(graphics);
|
||||||
|
drawList(graphics, mouseX, mouseY);
|
||||||
|
graphics.fill(listX2() - 1, listTop(), listX2(), panelY2() - 1, COLOR_BORDER);
|
||||||
|
drawDetail(graphics);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawTitleBar(@NonNull GuiGraphicsExtractor graphics) {
|
||||||
|
int titleH = titleHeight();
|
||||||
|
graphics.fill(panelX1() + 1, panelY1(), panelX2() - 1, panelY1() + titleH, COLOR_TITLE_BG);
|
||||||
|
|
||||||
|
graphics.text(font, "Lua API documentation",
|
||||||
|
panelX1() + PAD, panelY1() + (titleH - lineHeight()) / 2, COLOR_TITLE, false);
|
||||||
|
|
||||||
|
// Close button
|
||||||
|
int buttonSize = titleH;
|
||||||
|
int bx = panelX2() - buttonSize;
|
||||||
|
boolean hovered = mouseX >= bx && mouseX < panelX2() && mouseY >= panelY1() && mouseY < panelY1() + titleH;
|
||||||
|
if (hovered) {
|
||||||
|
graphics.fill(bx, panelY1(), panelX2() - 1, panelY1() + titleH, COLOR_ROW_HOVER);
|
||||||
|
}
|
||||||
|
graphics.text(font, "X",
|
||||||
|
bx + (buttonSize - font.width("X")) / 2,
|
||||||
|
panelY1() + (titleH - lineHeight()) / 2, COLOR_TITLE, false);
|
||||||
|
|
||||||
|
// Hint, right-aligned before the button
|
||||||
|
String hint = "F1 in the editor opens docs on the word under the cursor";
|
||||||
|
int hintX = bx - 8 - font.width(hint);
|
||||||
|
if (hintX > panelX1() + font.width("Lua API documentation") + 12) {
|
||||||
|
graphics.text(font, hint, hintX, panelY1() + (titleH - lineHeight()) / 2, COLOR_HINT, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawList(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) {
|
||||||
|
graphics.enableScissor(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1);
|
||||||
|
graphics.fill(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1, COLOR_LIST_BG);
|
||||||
|
|
||||||
|
int rowH = rowHeight();
|
||||||
|
for (int i = 0; i < rows.size(); i++) {
|
||||||
|
Row row = rows.get(i);
|
||||||
|
int y = listTop() + i * rowH - listScroll;
|
||||||
|
if (y + rowH < listTop() || y > panelY2()) continue;
|
||||||
|
|
||||||
|
boolean selected = i == selectedRow;
|
||||||
|
boolean hovered = mouseX >= panelX1() && mouseX < listX2()
|
||||||
|
&& mouseY >= y && mouseY < y + rowH;
|
||||||
|
if (selected) {
|
||||||
|
graphics.fill(panelX1() + 1, y, listX2() - 1, y + rowH, COLOR_ROW_SELECTED);
|
||||||
|
} else if (hovered) {
|
||||||
|
graphics.fill(panelX1() + 1, y, listX2() - 1, y + rowH, COLOR_ROW_HOVER);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (row.isFunction()) {
|
||||||
|
graphics.text(font, row.label(), panelX1() + PAD + FUNC_INDENT,
|
||||||
|
y + ROW_PAD / 2, COLOR_TEXT, false);
|
||||||
|
} else {
|
||||||
|
graphics.text(font, row.label(), panelX1() + PAD,
|
||||||
|
y + ROW_PAD / 2, COLOR_TOPIC, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
graphics.disableScissor();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Detail page ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private void drawDetail(@NonNull GuiGraphicsExtractor graphics) {
|
||||||
|
int x = detailX();
|
||||||
|
int maxWidth = panelX2() - PAD - x;
|
||||||
|
int y = detailTop() - detailScroll;
|
||||||
|
|
||||||
|
graphics.enableScissor(listX2(), listTop(), panelX2() - 1, panelY2() - 1);
|
||||||
|
|
||||||
|
FunctionDoc function = selectedFunction();
|
||||||
|
if (function == null) {
|
||||||
|
Topic topic = topics.get(rows.get(selectedRow).topic());
|
||||||
|
y = drawSection(graphics, topic.title(), x, y);
|
||||||
|
y = drawWrapped(graphics, topic.blurb(), x, maxWidth, y, COLOR_TEXT);
|
||||||
|
y += lineHeight();
|
||||||
|
y = drawSection(graphics, "Functions", x, y);
|
||||||
|
for (FunctionDoc f : topic.functions()) {
|
||||||
|
y = drawLine(graphics, f.signature(), x, maxWidth, y, COLOR_SIGNATURE);
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
y = drawLine(graphics, function.signature(), x, maxWidth, y, COLOR_SIGNATURE);
|
||||||
|
y += lineHeight();
|
||||||
|
|
||||||
|
y = drawSection(graphics, "Description", x, y);
|
||||||
|
y = drawWrapped(graphics, function.summary(), x, maxWidth, y, COLOR_TEXT);
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
|
||||||
|
if (!function.params().isEmpty()) {
|
||||||
|
y = drawSection(graphics, "Parameters", x, y);
|
||||||
|
for (var param : function.params()) {
|
||||||
|
String suffix = param.optional() ? " (optional)" : "";
|
||||||
|
drawRun(graphics, x, y,
|
||||||
|
param.name(), COLOR_PARAM_NAME,
|
||||||
|
" · " + param.type() + suffix, COLOR_DIM);
|
||||||
|
y += lineHeight();
|
||||||
|
y = drawWrapped(graphics, param.description(), x + FUNC_INDENT,
|
||||||
|
maxWidth - FUNC_INDENT, y, COLOR_TEXT);
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
}
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (function.returns() != null && !function.returns().isEmpty()) {
|
||||||
|
y = drawSection(graphics, "Returns", x, y);
|
||||||
|
y = drawWrapped(graphics, function.returns(), x, maxWidth, y, COLOR_TEXT);
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!function.notes().isEmpty()) {
|
||||||
|
y = drawSection(graphics, "Notes", x, y);
|
||||||
|
for (String note : function.notes()) {
|
||||||
|
String bullet = "• ";
|
||||||
|
drawRun(graphics, x, y, bullet, COLOR_DIM, null, COLOR_TEXT);
|
||||||
|
int bulletW = font.width(bullet);
|
||||||
|
List<String> lines = wrap(note, maxWidth - bulletW);
|
||||||
|
for (String line : lines) {
|
||||||
|
graphics.text(font, line, x + bulletW, y, COLOR_TEXT, false);
|
||||||
|
y += lineHeight();
|
||||||
|
}
|
||||||
|
// The last line already advanced a full line; add an extra gap so
|
||||||
|
// consecutive bullets are clearly separated (previously they
|
||||||
|
// started only half a line below the previous and crowded together).
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
}
|
||||||
|
y -= lineHeight() / 2; // drop the gap left after the final bullet
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ExampleDoc example : function.examples()) {
|
||||||
|
y = drawSection(graphics,
|
||||||
|
example.title().isEmpty() ? "Example" : "Example — " + example.title(),
|
||||||
|
x, y);
|
||||||
|
y = drawCodeBlock(graphics, example.code(), x, maxWidth, y);
|
||||||
|
y += lineHeight() / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
graphics.disableScissor();
|
||||||
|
detailContentHeight = y + detailScroll - detailTop();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Section header; returns the y below it. */
|
||||||
|
private int drawSection(@NonNull GuiGraphicsExtractor graphics, String title, int x, int y) {
|
||||||
|
graphics.text(font, title, x, y, COLOR_SECTION, true);
|
||||||
|
return y + lineHeight() + lineHeight() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One wrapped plain line, clipped to {@code maxWidth}; returns the y below it. */
|
||||||
|
private int drawLine(@NonNull GuiGraphicsExtractor graphics, String text, int x, int maxWidth, int y, int color) {
|
||||||
|
for (String line : wrap(text, maxWidth)) {
|
||||||
|
graphics.text(font, line, x, y, color, false);
|
||||||
|
y += lineHeight();
|
||||||
|
}
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One line made of up to two coloured runs. */
|
||||||
|
private int drawRun(@NonNull GuiGraphicsExtractor graphics, int x, int y,
|
||||||
|
String first, int firstColor, String second, int secondColor) {
|
||||||
|
graphics.text(font, first, x, y, firstColor, false);
|
||||||
|
if (second != null) {
|
||||||
|
graphics.text(font, second, x + font.width(first), y, secondColor, false);
|
||||||
|
}
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int drawWrapped(@NonNull GuiGraphicsExtractor graphics, String text,
|
||||||
|
int x, int maxWidth, int y, int color) {
|
||||||
|
if (text == null || text.isEmpty()) return y;
|
||||||
|
for (String paragraph : text.split("\n")) {
|
||||||
|
for (String line : wrap(paragraph, maxWidth)) {
|
||||||
|
graphics.text(font, line, x, y, color, false);
|
||||||
|
y += lineHeight();
|
||||||
|
}
|
||||||
|
y += lineHeight() / 2; // breathing room between paragraphs
|
||||||
|
}
|
||||||
|
return y - lineHeight() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fenced, syntax-highlighted Lua snippet on a dark background. */
|
||||||
|
private int drawCodeBlock(@NonNull GuiGraphicsExtractor graphics, String code,
|
||||||
|
int x, int maxWidth, int y) {
|
||||||
|
String[] lines = code.split("\n", -1);
|
||||||
|
int blockTop = y;
|
||||||
|
int blockH = lines.length * lineHeight() + PAD * 2;
|
||||||
|
|
||||||
|
graphics.fill(x, blockTop, Math.min(x + maxWidth, panelX2() - PAD), blockTop + blockH, COLOR_CODE_BG);
|
||||||
|
|
||||||
|
boolean inMultiline = false;
|
||||||
|
int textY = blockTop + PAD;
|
||||||
|
for (String line : lines) {
|
||||||
|
int textX = x + PAD;
|
||||||
|
LuaHighlighter.LineTokens tokens = highlighter.tokenizeLine(line, inMultiline);
|
||||||
|
for (Span span : tokens.spans()) {
|
||||||
|
graphics.text(font, span.text(), textX, textY, span.color(), true);
|
||||||
|
textX += font.width(span.text());
|
||||||
|
}
|
||||||
|
if (tokens.spans().isEmpty()) {
|
||||||
|
graphics.text(font, line, textX, textY, COLOR_TEXT, true);
|
||||||
|
}
|
||||||
|
inMultiline = tokens.continuesMultilineString();
|
||||||
|
textY += lineHeight();
|
||||||
|
}
|
||||||
|
return blockTop + blockH + lineHeight() / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Input handling ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean handleMouseClicked(MouseButtonEvent event) {
|
||||||
|
if (!visible) return false;
|
||||||
|
int mx = (int) event.x();
|
||||||
|
int my = (int) event.y();
|
||||||
|
|
||||||
|
if (event.button() != 0) return true;
|
||||||
|
|
||||||
|
// Click outside the panel → dismiss.
|
||||||
|
if (mx < panelX1() || mx >= panelX2() || my < panelY1() || my >= panelY2()) {
|
||||||
|
close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (insideCloseButton(mx, my)) {
|
||||||
|
close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Left list: select the clicked row.
|
||||||
|
if (mx < listX2() && my >= listTop()) {
|
||||||
|
int index = (my - listTop() + listScroll) / rowHeight();
|
||||||
|
if (index >= 0 && index < rows.size()) {
|
||||||
|
selectRow(index);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anything else inside the panel is consumed (scrolling happens per-column).
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean handleKeyPressed(KeyEvent event) {
|
||||||
|
if (!visible) return false;
|
||||||
|
switch (event.key()) {
|
||||||
|
case 256 -> { // Escape — close the docs, not the editor
|
||||||
|
close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case 264 -> { // Down
|
||||||
|
selectRow(Math.min(selectedRow + 1, rows.size() - 1));
|
||||||
|
scrollSelectionIntoView();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
case 265 -> { // Up
|
||||||
|
selectRow(Math.max(selectedRow - 1, 0));
|
||||||
|
scrollSelectionIntoView();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true; // swallow the rest while the modal is open
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean handleCharTyped(CharacterEvent event) {
|
||||||
|
return visible; // swallow typing while the modal is open
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean handleMouseDragged(MouseButtonEvent event) {
|
||||||
|
return visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean handleMouseReleased(MouseButtonEvent event) {
|
||||||
|
return visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean handleMouseScrolled(double scrollY) {
|
||||||
|
if (!visible || font == null) return false;
|
||||||
|
int amount = (int) (scrollY * SCROLL_SPEED * font.lineHeight);
|
||||||
|
if (mouseX >= panelX1() && mouseX < listX2()) {
|
||||||
|
listScroll = Math.max(0, Math.min(listScroll - amount, maxListScroll()));
|
||||||
|
} else {
|
||||||
|
detailScroll = Math.max(0, detailScroll - amount);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Text helpers ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Greedy word wrap on spaces; long words are left to the scissor. */
|
||||||
|
private List<String> wrap(String text, int maxWidth) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
if (text == null || text.isEmpty()) {
|
||||||
|
lines.add("");
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
StringBuilder current = new StringBuilder();
|
||||||
|
for (String word : text.split(" ")) {
|
||||||
|
String candidate = current.isEmpty() ? word : current + " " + word;
|
||||||
|
if (!current.isEmpty() && font.width(candidate) > maxWidth) {
|
||||||
|
lines.add(current.toString());
|
||||||
|
current.setLength(0);
|
||||||
|
current.append(word);
|
||||||
|
} else {
|
||||||
|
if (!current.isEmpty()) current.append(' ');
|
||||||
|
current.append(word);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.add(current.toString());
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/main/java/com/aranroig/docs/ExampleDoc.java
Normal file
10
src/main/java/com/aranroig/docs/ExampleDoc.java
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package com.aranroig.docs;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A titled Lua snippet shown in the in-game documentation.
|
||||||
|
*
|
||||||
|
* @param title one-line caption, may be empty
|
||||||
|
* @param code the snippet, lines separated by {@code \n}
|
||||||
|
*/
|
||||||
|
public record ExampleDoc(String title, String code) {
|
||||||
|
}
|
||||||
25
src/main/java/com/aranroig/docs/FunctionDoc.java
Normal file
25
src/main/java/com/aranroig/docs/FunctionDoc.java
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package com.aranroig.docs;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single documented Lua function.
|
||||||
|
*
|
||||||
|
* @param name full dotted name, e.g. {@code "world.set_block"}
|
||||||
|
* @param signature the call as the player would read it, e.g. {@code world.set_block(x, y, z, block)}
|
||||||
|
* @param summary one or two sentences on what it does; {@code \n} separates paragraphs
|
||||||
|
* @param params positional parameters (empty for variadic helpers)
|
||||||
|
* @param returns what the call evaluates to
|
||||||
|
* @param notes gotchas, failure reasons, tips — each entry is one bullet
|
||||||
|
* @param examples runnable snippets
|
||||||
|
*/
|
||||||
|
public record FunctionDoc(
|
||||||
|
String name,
|
||||||
|
String signature,
|
||||||
|
String summary,
|
||||||
|
List<ParamDoc> params,
|
||||||
|
String returns,
|
||||||
|
List<String> notes,
|
||||||
|
List<ExampleDoc> examples
|
||||||
|
) {
|
||||||
|
}
|
||||||
142
src/main/java/com/aranroig/docs/LuaApiDocs.java
Normal file
142
src/main/java/com/aranroig/docs/LuaApiDocs.java
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
package com.aranroig.docs;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The in-game reference for every Lua global this mod exposes to user scripts.
|
||||||
|
*
|
||||||
|
* <p>This is a hand-written catalog describing the functions registered by the
|
||||||
|
* wrappers in {@code com.aranroig.wrapper} (currently {@code world} from
|
||||||
|
* {@link com.aranroig.wrapper.WorldApi} and the {@code print} helper). The
|
||||||
|
* client editor reads it to render the browsable documentation panel, so it is
|
||||||
|
* the single source of truth shown to players.</p>
|
||||||
|
*
|
||||||
|
* <p>Keep it in sync with the wrapper implementations and {@code docs/lua-api.md}.</p>
|
||||||
|
*/
|
||||||
|
public final class LuaApiDocs {
|
||||||
|
|
||||||
|
private LuaApiDocs() {
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── world.* — block access ────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static final FunctionDoc SET_BLOCK = new FunctionDoc(
|
||||||
|
"world.set_block",
|
||||||
|
"world.set_block(x, y, z, block)",
|
||||||
|
"Places a block and updates neighbours and clients, like /setblock does.",
|
||||||
|
List.of(
|
||||||
|
new ParamDoc("x", "number", false, "Absolute world x coordinate (F3 to read your own)."),
|
||||||
|
new ParamDoc("y", "number", false, "Absolute world y coordinate."),
|
||||||
|
new ParamDoc("z", "number", false, "Absolute world z coordinate."),
|
||||||
|
new ParamDoc("block", "string", false,
|
||||||
|
"Block id, with or without the minecraft: namespace, optionally with block states.")
|
||||||
|
),
|
||||||
|
"true on success, or false followed by a reason string.",
|
||||||
|
List.of(
|
||||||
|
"Coordinates are absolute, never relative to the player.",
|
||||||
|
"A block that cannot survive where it is put (a torch without a wall, a flower without ground) drops itself again and the call reports failure.",
|
||||||
|
"Replacing a block that holds items, such as a chest, drops its contents."
|
||||||
|
),
|
||||||
|
List.of(
|
||||||
|
new ExampleDoc("Namespace is optional; states are allowed",
|
||||||
|
"world.set_block(10, 64, -3, \"minecraft:stone\")\n"
|
||||||
|
+ "world.set_block(10, 65, -3, \"gold_block\")\n"
|
||||||
|
+ "world.set_block(10, 66, -3, \"minecraft:oak_stairs[facing=north]\")"),
|
||||||
|
new ExampleDoc("Check whether it worked",
|
||||||
|
"local ok, reason = world.set_block(10, 64, -3, \"minecraft:stone\")\n"
|
||||||
|
+ "if not ok then\n"
|
||||||
|
+ " print(\"could not place the block: \" .. reason)\n"
|
||||||
|
+ "end")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final FunctionDoc REMOVE_BLOCK = new FunctionDoc(
|
||||||
|
"world.remove_block",
|
||||||
|
"world.remove_block(x, y, z [, drops])",
|
||||||
|
"Removes the block at the given position.",
|
||||||
|
List.of(
|
||||||
|
new ParamDoc("x", "number", false, "Absolute world x coordinate."),
|
||||||
|
new ParamDoc("y", "number", false, "Absolute world y coordinate."),
|
||||||
|
new ParamDoc("z", "number", false, "Absolute world z coordinate."),
|
||||||
|
new ParamDoc("drops", "boolean", true,
|
||||||
|
"Pass true to break the block the way a player would (items, sound, particles).")
|
||||||
|
),
|
||||||
|
"true on success, or false followed by a reason string.",
|
||||||
|
List.of(
|
||||||
|
"Without drops the block just vanishes, silently and without items.",
|
||||||
|
"Fails with \"there is nothing to remove\" if the target is already air."
|
||||||
|
),
|
||||||
|
List.of(
|
||||||
|
new ExampleDoc("Vanish versus break",
|
||||||
|
"world.remove_block(10, 64, -3) -- vanish\n"
|
||||||
|
+ "world.remove_block(10, 65, -3, true) -- break it, dropping items")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final FunctionDoc GET_BLOCK = new FunctionDoc(
|
||||||
|
"world.get_block",
|
||||||
|
"world.get_block(x, y, z)",
|
||||||
|
"Returns the block id at that position, including its block states.",
|
||||||
|
List.of(
|
||||||
|
new ParamDoc("x", "number", false, "Absolute world x coordinate."),
|
||||||
|
new ParamDoc("y", "number", false, "Absolute world y coordinate."),
|
||||||
|
new ParamDoc("z", "number", false, "Absolute world z coordinate.")
|
||||||
|
),
|
||||||
|
"The block id string (ready to hand to set_block), or nil followed by a reason string.",
|
||||||
|
List.of(
|
||||||
|
"Air is the string \"minecraft:air\", and every string is truthy in Lua — compare against the id rather than testing the value.",
|
||||||
|
"The result carries block states, e.g. minecraft:grass_block[snowy=false]."
|
||||||
|
),
|
||||||
|
List.of(
|
||||||
|
new ExampleDoc("Compare against the id, not the value",
|
||||||
|
"local block = world.get_block(10, 64, -3)\n"
|
||||||
|
+ "if block ~= \"minecraft:air\" then\n"
|
||||||
|
+ " print(\"something is there: \" .. block)\n"
|
||||||
|
+ "end"),
|
||||||
|
new ExampleDoc("Copy one place to another",
|
||||||
|
"local block = world.get_block(10, 64, -3)\n"
|
||||||
|
+ "if block then\n"
|
||||||
|
+ " world.set_block(20, 70, 5, block)\n"
|
||||||
|
+ "end")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── print — chat output ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static final FunctionDoc PRINT = new FunctionDoc(
|
||||||
|
"print",
|
||||||
|
"print(...)",
|
||||||
|
"Writes to the chat of the player who ran the script, tab-separated.",
|
||||||
|
List.of(),
|
||||||
|
"nothing",
|
||||||
|
List.of(
|
||||||
|
"Whole numbers go through the Lua wrapper and are printed as 12.0; concatenate them into a string to drop the decimal.",
|
||||||
|
"Runs on the server, so output appears in the running player's chat."
|
||||||
|
),
|
||||||
|
List.of(
|
||||||
|
new ExampleDoc("Print to chat",
|
||||||
|
"print(\"blocks placed:\", 12)"),
|
||||||
|
new ExampleDoc("Drop the trailing .0",
|
||||||
|
"print(\"blocks placed: \" .. 12) -- -> blocks placed: 12")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── The full table ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static final List<Topic> TOPICS = List.of(
|
||||||
|
new Topic("world", "Read and write blocks in the running player's dimension.",
|
||||||
|
List.of(SET_BLOCK, REMOVE_BLOCK, GET_BLOCK)),
|
||||||
|
new Topic("print", "Send text to the chat of the player running the script.",
|
||||||
|
List.of(PRINT))
|
||||||
|
);
|
||||||
|
|
||||||
|
/** All documented topics, in display order. */
|
||||||
|
public static List<Topic> topics() {
|
||||||
|
return TOPICS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flattened list of every documented function, across all topics. */
|
||||||
|
public static List<FunctionDoc> functions() {
|
||||||
|
return TOPICS.stream().flatMap(t -> t.functions().stream()).toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/main/java/com/aranroig/docs/ParamDoc.java
Normal file
12
src/main/java/com/aranroig/docs/ParamDoc.java
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package com.aranroig.docs;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One parameter of a documented Lua function.
|
||||||
|
*
|
||||||
|
* @param name parameter name as written in the signature, e.g. {@code "block"}
|
||||||
|
* @param type short type name shown to the user, e.g. {@code "string"} or {@code "number"}
|
||||||
|
* @param optional whether the parameter may be omitted
|
||||||
|
* @param description what the parameter means
|
||||||
|
*/
|
||||||
|
public record ParamDoc(String name, String type, boolean optional, String description) {
|
||||||
|
}
|
||||||
14
src/main/java/com/aranroig/docs/Topic.java
Normal file
14
src/main/java/com/aranroig/docs/Topic.java
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package com.aranroig.docs;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Top-level grouping shown in the left-hand list of the in-game docs panel,
|
||||||
|
* e.g. the {@code world} table or the {@code print} helper.
|
||||||
|
*
|
||||||
|
* @param title short header, usually the Lua table name
|
||||||
|
* @param blurb one or two sentences describing the group; {@code \n} separates paragraphs
|
||||||
|
* @param functions the functions this topic documents
|
||||||
|
*/
|
||||||
|
public record Topic(String title, String blurb, List<FunctionDoc> functions) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.aranroig.payloads;
|
||||||
|
|
||||||
|
import com.aranroig.Codecraft;
|
||||||
|
import com.aranroig.editor.EditorFile;
|
||||||
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
|
import net.minecraft.network.codec.ByteBufCodecs;
|
||||||
|
import net.minecraft.network.codec.StreamCodec;
|
||||||
|
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record ClientboundProjectFilesPayload(List<EditorFile> files) implements CustomPacketPayload {
|
||||||
|
|
||||||
|
public static final Identifier PROJECT_FILES_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "project_files");
|
||||||
|
|
||||||
|
public static final CustomPacketPayload.Type<ClientboundProjectFilesPayload> TYPE = new CustomPacketPayload.Type<>(PROJECT_FILES_PAYLOAD_ID);
|
||||||
|
|
||||||
|
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundProjectFilesPayload> CODEC =
|
||||||
|
StreamCodec.composite(
|
||||||
|
EditorFile.STREAM_CODEC.apply(ByteBufCodecs.list()),
|
||||||
|
ClientboundProjectFilesPayload::files,
|
||||||
|
ClientboundProjectFilesPayload::new
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Type<? extends CustomPacketPayload> type() {
|
||||||
|
return TYPE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.aranroig.payloads;
|
||||||
|
|
||||||
|
import com.aranroig.Codecraft;
|
||||||
|
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||||
|
import net.minecraft.network.codec.StreamCodec;
|
||||||
|
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
|
||||||
|
public record ServerboundRequestProjectPayload() implements CustomPacketPayload {
|
||||||
|
|
||||||
|
public static final Identifier REQUEST_PROJECT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "request_project");
|
||||||
|
|
||||||
|
public static final CustomPacketPayload.Type<ServerboundRequestProjectPayload> TYPE = new CustomPacketPayload.Type<>(REQUEST_PROJECT_PAYLOAD_ID);
|
||||||
|
|
||||||
|
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundRequestProjectPayload> CODEC =
|
||||||
|
StreamCodec.unit(new ServerboundRequestProjectPayload());
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Type<? extends CustomPacketPayload> type() {
|
||||||
|
return TYPE;
|
||||||
|
}
|
||||||
|
}
|
||||||
22
src/main/java/com/aranroig/wrapper/ChatLogger.java
Normal file
22
src/main/java/com/aranroig/wrapper/ChatLogger.java
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package com.aranroig.wrapper;
|
||||||
|
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import party.iroiro.luajava.value.LuaFunction;
|
||||||
|
|
||||||
|
public class ChatLogger {
|
||||||
|
public static LuaFunction print(ServerPlayer player) {
|
||||||
|
return (lua, args) -> {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 0; i < args.length; i++) {
|
||||||
|
if (i > 0) sb.append('\t');
|
||||||
|
sb.append(args[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
player.sendSystemMessage(Component.literal(sb.toString()));
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
223
src/main/java/com/aranroig/wrapper/WorldApi.java
Normal file
223
src/main/java/com/aranroig/wrapper/WorldApi.java
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
package com.aranroig.wrapper;
|
||||||
|
|
||||||
|
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||||
|
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||||
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.world.level.block.Block;
|
||||||
|
import net.minecraft.world.level.block.Blocks;
|
||||||
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
|
import party.iroiro.luajava.Lua;
|
||||||
|
import party.iroiro.luajava.value.LuaValue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@code world} table given to user scripts: placing, removing and reading blocks.
|
||||||
|
*
|
||||||
|
* <p>Coordinates are absolute world coordinates in the dimension the executing player
|
||||||
|
* stands in. They are not limited by the player's reach, so a script can edit any block
|
||||||
|
* of a loaded chunk.</p>
|
||||||
|
*
|
||||||
|
* <p>Failures are reported the Lua way: a function returns {@code false} (or {@code nil}
|
||||||
|
* for {@code world.get_block}) followed by a short reason, so callers can write
|
||||||
|
* {@code if not world.set_block(...) then ... end}.</p>
|
||||||
|
*
|
||||||
|
* <p>Registered from {@link com.aranroig.Codecraft} on the server thread, which is the
|
||||||
|
* only thread allowed to touch the world.</p>
|
||||||
|
*/
|
||||||
|
public class WorldApi {
|
||||||
|
|
||||||
|
/** Update flags for {@link net.minecraft.world.level.Level#setBlock}: neighbours and clients. */
|
||||||
|
private static final int UPDATE_FLAGS = Block.UPDATE_ALL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers the global {@code world} table.
|
||||||
|
*
|
||||||
|
* @param lua state to register the table on
|
||||||
|
* @param player the player the edits belong to, which also selects the dimension
|
||||||
|
*/
|
||||||
|
public static void register(Lua lua, ServerPlayer player) {
|
||||||
|
lua.newTable();
|
||||||
|
int world = lua.getTop();
|
||||||
|
|
||||||
|
lua.push((L, args) -> setBlock(L, player, args));
|
||||||
|
lua.setField(world, "set_block");
|
||||||
|
|
||||||
|
lua.push((L, args) -> removeBlock(L, player, args));
|
||||||
|
lua.setField(world, "remove_block");
|
||||||
|
|
||||||
|
lua.push((L, args) -> getBlock(L, player, args));
|
||||||
|
lua.setField(world, "get_block");
|
||||||
|
|
||||||
|
lua.setGlobal("world");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code world.set_block(x, y, z, block)}
|
||||||
|
*
|
||||||
|
* <p>{@code block} is a block id such as {@code "minecraft:stone"}, optionally with
|
||||||
|
* block states: {@code "minecraft:oak_stairs[facing=north]"}. Tags are not allowed.</p>
|
||||||
|
*/
|
||||||
|
private static LuaValue[] setBlock(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||||
|
if (args.length < 4) {
|
||||||
|
return fail(lua, "usage: world.set_block(x, y, z, \"minecraft:stone\")");
|
||||||
|
}
|
||||||
|
|
||||||
|
BlockPos pos = position(args);
|
||||||
|
if (pos == null) {
|
||||||
|
return fail(lua, "x, y and z must be numbers");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args[3].type() != Lua.LuaType.STRING) {
|
||||||
|
return fail(lua, "block must be a string, e.g. \"minecraft:stone\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
String description = args[3].toString();
|
||||||
|
BlockState state;
|
||||||
|
try {
|
||||||
|
state = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, description, false).blockState();
|
||||||
|
} catch (CommandSyntaxException e) {
|
||||||
|
return fail(lua, "'" + description + "' is not a block");
|
||||||
|
}
|
||||||
|
|
||||||
|
ServerLevel level = player.level();
|
||||||
|
String problem = blockProblem(level, pos);
|
||||||
|
if (problem != null) {
|
||||||
|
return fail(lua, problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
level.setBlock(pos, state, UPDATE_FLAGS);
|
||||||
|
|
||||||
|
// Read the block back instead of trusting the result of setBlock: a block that
|
||||||
|
// cannot stay where it was put (a torch in mid-air) removes itself again.
|
||||||
|
if (level.getBlockState(pos).getBlock() != state.getBlock()) {
|
||||||
|
return fail(lua, "'" + description + "' does not fit at " + describe(pos));
|
||||||
|
}
|
||||||
|
return success(lua);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code world.remove_block(x, y, z [, drops])}
|
||||||
|
*
|
||||||
|
* <p>The block vanishes without drops unless {@code drops} is given as {@code true},
|
||||||
|
* in which case it breaks as if a player had broken it.</p>
|
||||||
|
*/
|
||||||
|
private static LuaValue[] removeBlock(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||||
|
if (args.length < 3) {
|
||||||
|
return fail(lua, "usage: world.remove_block(x, y, z [, drops])");
|
||||||
|
}
|
||||||
|
|
||||||
|
BlockPos pos = position(args);
|
||||||
|
if (pos == null) {
|
||||||
|
return fail(lua, "x, y and z must be numbers");
|
||||||
|
}
|
||||||
|
|
||||||
|
ServerLevel level = player.level();
|
||||||
|
String problem = blockProblem(level, pos);
|
||||||
|
if (problem != null) {
|
||||||
|
return fail(lua, problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (level.getBlockState(pos).isAir()) {
|
||||||
|
return fail(lua, "there is nothing to remove at " + describe(pos));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args.length > 3 && args[3].toBoolean()) {
|
||||||
|
return level.destroyBlock(pos, true, player, UPDATE_FLAGS)
|
||||||
|
? success(lua)
|
||||||
|
: fail(lua, "could not remove the block at " + describe(pos));
|
||||||
|
}
|
||||||
|
|
||||||
|
level.setBlock(pos, Blocks.AIR.defaultBlockState(), UPDATE_FLAGS);
|
||||||
|
if (!level.getBlockState(pos).isAir()) {
|
||||||
|
return fail(lua, "could not remove the block at " + describe(pos));
|
||||||
|
}
|
||||||
|
return success(lua);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code world.get_block(x, y, z)}
|
||||||
|
*
|
||||||
|
* <p>Returns the block id with its block states, e.g. {@code "minecraft:air"} or
|
||||||
|
* {@code "minecraft:oak_stairs[facing=north]"}, ready to be given to set_block.</p>
|
||||||
|
*/
|
||||||
|
private static LuaValue[] getBlock(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||||
|
if (args.length < 3) {
|
||||||
|
return missing(lua, "usage: world.get_block(x, y, z)");
|
||||||
|
}
|
||||||
|
|
||||||
|
BlockPos pos = position(args);
|
||||||
|
if (pos == null) {
|
||||||
|
return missing(lua, "x, y and z must be numbers");
|
||||||
|
}
|
||||||
|
|
||||||
|
ServerLevel level = player.level();
|
||||||
|
String problem = blockProblem(level, pos);
|
||||||
|
if (problem != null) {
|
||||||
|
return missing(lua, problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LuaValue[]{ lua.from(BlockStateParser.serialize(level.getBlockState(pos))) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads {@code x}, {@code y} and {@code z} from the first three arguments.
|
||||||
|
*
|
||||||
|
* @return the position, or {@code null} when one of them is not a number
|
||||||
|
*/
|
||||||
|
private static BlockPos position(LuaValue[] args) {
|
||||||
|
Integer x = number(args[0]);
|
||||||
|
Integer y = number(args[1]);
|
||||||
|
Integer z = number(args[2]);
|
||||||
|
if (x == null || y == null || z == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new BlockPos(x, y, z);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads a Lua number as an int, or {@code null} for anything else. */
|
||||||
|
private static Integer number(LuaValue value) {
|
||||||
|
if (value == null || value.type() != Lua.LuaType.NUMBER) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return (int) value.toInteger();
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Precondition shared by the three functions.
|
||||||
|
*
|
||||||
|
* @return why the block cannot be touched, or {@code null} when it can
|
||||||
|
*/
|
||||||
|
private static String blockProblem(ServerLevel level, BlockPos pos) {
|
||||||
|
if (level.isOutsideBuildHeight(pos)) {
|
||||||
|
return "y must be between " + level.getMinY() + " and " + level.getMaxY()
|
||||||
|
+ ", not " + pos.getY();
|
||||||
|
}
|
||||||
|
if (!level.isLoaded(pos)) {
|
||||||
|
return "the chunk at " + pos.getX() + ", " + pos.getZ() + " is not loaded";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String describe(BlockPos pos) {
|
||||||
|
return pos.getX() + ", " + pos.getY() + ", " + pos.getZ();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaValue[] success(Lua lua) {
|
||||||
|
return new LuaValue[]{ lua.from(true) };
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LuaValue[] fail(Lua lua, String reason) {
|
||||||
|
return new LuaValue[]{ lua.from(false), lua.from(reason) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Failure for {@code world.get_block}, which gives {@code nil} rather than {@code false}. */
|
||||||
|
private static LuaValue[] missing(Lua lua, String reason) {
|
||||||
|
return new LuaValue[]{ lua.fromNull(), lua.from(reason) };
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user