This commit is contained in:
2026-10-06 17:59:26 +02:00
parent f2d09b8a9c
commit 7a115445ab
12 changed files with 1288 additions and 0 deletions

View 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;
}
}

View 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) {
}

View 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
) {
}

View 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();
}
}

View 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) {
}

View 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) {
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View 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;
};
}
}

View 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) };
}
}