This commit is contained in:
2026-10-06 17:59:21 +02:00
parent 9226c1cd87
commit f2d09b8a9c
10 changed files with 220 additions and 24 deletions

View File

@@ -1,5 +1,16 @@
# codecraft # codecraft
Players write Lua in the in-game editor (`J` by default) and run it on the server.
Scripts can place and remove blocks through the `world` table:
```lua
for y = 64, 67 do
world.set_block(10, y, -3, "minecraft:cobblestone")
end
```
The API is documented in [docs/lua-api.md](docs/lua-api.md).
## Setup ## Setup
For setup instructions, please see the [Fabric Documentation page](https://docs.fabricmc.net/develop/getting-started/creating-a-project#setting-up) related to the IDE that you are using. For setup instructions, please see the [Fabric Documentation page](https://docs.fabricmc.net/develop/getting-started/creating-a-project#setting-up) related to the IDE that you are using.

0
gradlew vendored Normal file → Executable file
View File

View File

@@ -2,9 +2,12 @@ package com.aranroig.client;
import com.aranroig.Codecraft; import com.aranroig.Codecraft;
import com.aranroig.client.editor.EditorManager; import com.aranroig.client.editor.EditorManager;
import com.aranroig.payloads.ClientboundProjectFilesPayload;
import com.aranroig.payloads.ClientboundSaveCodePayload;
import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.platform.InputConstants;
import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.client.KeyMapping; import net.minecraft.client.KeyMapping;
import net.minecraft.resources.Identifier; import net.minecraft.resources.Identifier;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
@@ -35,6 +38,12 @@ public class CodecraftClient implements ClientModInitializer {
EditorManager editorOverlay = new EditorManager(); EditorManager editorOverlay = new EditorManager();
ClientPlayNetworking.registerGlobalReceiver(ClientboundProjectFilesPayload.TYPE, (payload, context) ->
editorOverlay.setFiles(payload.files()));
ClientPlayNetworking.registerGlobalReceiver(ClientboundSaveCodePayload.TYPE, (payload, context) ->
editorOverlay.upsertFile(payload.data()));
ClientTickEvents.END_CLIENT_TICK.register(client -> { ClientTickEvents.END_CLIENT_TICK.register(client -> {
while(openEditor.consumeClick()){ while(openEditor.consumeClick()){
if(client.player != null) { if(client.player != null) {

View File

@@ -48,7 +48,7 @@ public class CompletionProvider {
// ── Built-in global tables (as types) ──────────────────────────── // ── Built-in global tables (as types) ────────────────────────────
for (String lib : new String[]{ for (String lib : new String[]{
"string", "table", "math", "io", "os", "coroutine", "string", "table", "math", "io", "os", "coroutine",
"package", "utf8", "debug", "_G", "_VERSION" "package", "utf8", "debug", "_G", "_VERSION", "world"
}) items.add(CompletionItem.type(lib)); }) items.add(CompletionItem.type(lib));
// ── Common snippets ─────────────────────────────────────────────── // ── Common snippets ───────────────────────────────────────────────
@@ -97,6 +97,15 @@ public class CompletionProvider {
items.add(CompletionItem.snippet("print", items.add(CompletionItem.snippet("print",
"print()", "print()",
"print(…)")); "print(…)"));
items.add(CompletionItem.snippet("setblock",
"world.set_block(, , , \"minecraft:stone\")",
"world.set_block(…)"));
items.add(CompletionItem.snippet("removeblock",
"world.remove_block(, , )",
"world.remove_block(…)"));
items.add(CompletionItem.snippet("getblock",
"local block = world.get_block(, , )",
"world.get_block(…)"));
items.add(CompletionItem.snippet("local", items.add(CompletionItem.snippet("local",
"local = ", "local = ",
"local variable")); "local variable"));
@@ -217,6 +226,15 @@ public class CompletionProvider {
}) coLib.add(CompletionItem.method(m[0], m[1])); }) coLib.add(CompletionItem.method(m[0], m[1]));
libs.put("coroutine", coLib); libs.put("coroutine", coLib);
// world.* — block access provided by codecraft itself
List<CompletionItem> worldLib = new ArrayList<>();
for (String[] m : new String[][]{
{"set_block", "set_block(", "world.set_block(x, y, z, \"minecraft:stone\")"},
{"remove_block", "remove_block(", "world.remove_block(x, y, z [,drops])"},
{"get_block", "get_block(", "world.get_block(x, y, z)"},
}) worldLib.add(CompletionItem.method(m[0], m[1]));
libs.put("world", worldLib);
LIBRARY_MEMBERS = Collections.unmodifiableMap(libs); LIBRARY_MEMBERS = Collections.unmodifiableMap(libs);
} }

View File

@@ -43,6 +43,14 @@ public class EditorFileTree extends Widget {
@Override @Override
public boolean handleMouseClicked(MouseButtonEvent event) { public boolean handleMouseClicked(MouseButtonEvent event) {
Font font = editorScreen.getFont();
int index = (int) ((event.y() - getStartY()) / font.lineHeight);
List<EditorFile> files = editorManager.getFiles();
if (index >= 0 && index < files.size()) {
editorManager.openFile(files.get(index));
return true;
}
return false; return false;
} }

View File

@@ -720,8 +720,8 @@ public class EditorFileView extends Widget {
scrollToCursor(); scrollToCursor();
return true; return true;
} }
case 256 -> { // Escape (no popup) case 256 -> { // Escape (no popup) — close the editor
dismissCompletions(); editorScreen.onClose();
return true; return true;
} }
case 32 -> { // Space case 32 -> { // Space
@@ -764,10 +764,43 @@ public class EditorFileView extends Widget {
case 83 -> { // Ctrl+S case 83 -> { // Ctrl+S
saveEditorFile(); saveEditorFile();
} }
case 291 -> { // F1 — open the docs on the word under the cursor
editorManager.openDocsAt(wordUnderCursor());
return true;
}
} }
return false; return false;
} }
/**
* The identifier under or just left of the cursor, extended through a
* {@code .} or {@code :} prefix when there is one: {@code world.set_block},
* {@code set_block}, {@code math} …
*/
private String wordUnderCursor() {
String content = text.toString();
int end = Math.min(cursorPos, content.length());
int start = end;
while (start > 0
&& (Character.isLetterOrDigit(content.charAt(start - 1)) || content.charAt(start - 1) == '_')) {
start--;
}
// Include a "world." / "str:" prefix so qualified calls resolve.
int sep = start - 1;
if (sep >= 0 && (content.charAt(sep) == '.' || content.charAt(sep) == ':')) {
int prefixStart = sep;
while (prefixStart > 0
&& (Character.isLetterOrDigit(content.charAt(prefixStart - 1)) || content.charAt(prefixStart - 1) == '_')) {
prefixStart--;
}
if (prefixStart < sep) {
return content.substring(prefixStart, end);
}
}
return content.substring(start, end);
}
public void setEditorFile(EditorFile currentEditorFile) { public void setEditorFile(EditorFile currentEditorFile) {
this.currentEditorFile = currentEditorFile; this.currentEditorFile = currentEditorFile;
text = new StringBuilder(currentEditorFile.getText()); text = new StringBuilder(currentEditorFile.getText());

View File

@@ -4,6 +4,7 @@ import com.aranroig.SavedProjectData;
import com.aranroig.client.wrapper.Logger; import com.aranroig.client.wrapper.Logger;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.editor.RunInfo; import com.aranroig.editor.RunInfo;
import com.aranroig.payloads.ServerboundRequestProjectPayload;
import com.aranroig.payloads.ServerboundRunCodePayload; import com.aranroig.payloads.ServerboundRunCodePayload;
import com.aranroig.payloads.ServerboundSaveCodePayload; import com.aranroig.payloads.ServerboundSaveCodePayload;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
@@ -21,8 +22,9 @@ public class EditorManager {
EditorFileTree editorFileTree; EditorFileTree editorFileTree;
EditorTopBar editorTopBar; EditorTopBar editorTopBar;
EditorFileView editorFileView; EditorFileView editorFileView;
EditorDocsPanel editorDocsPanel;
List<EditorFile> files; List<EditorFile> files = new ArrayList<>();
public EditorManager() { public EditorManager() {
client = Minecraft.getInstance(); client = Minecraft.getInstance();
@@ -30,6 +32,7 @@ public class EditorManager {
editorFileTree = new EditorFileTree(this); editorFileTree = new EditorFileTree(this);
editorTopBar = new EditorTopBar(this); editorTopBar = new EditorTopBar(this);
editorFileView = new EditorFileView(this); editorFileView = new EditorFileView(this);
editorDocsPanel = new EditorDocsPanel(this);
} }
public List<EditorFile> getFiles() { public List<EditorFile> getFiles() {
@@ -40,6 +43,8 @@ public class EditorManager {
private final int TOP_BAR_HEIGHT = 12; private final int TOP_BAR_HEIGHT = 12;
public void toggleVisible() { public void toggleVisible() {
requestProjectFiles();
TextEditorScreen textEditorScreen = new TextEditorScreen(); TextEditorScreen textEditorScreen = new TextEditorScreen();
// Populate screen with widgets // Populate screen with widgets
@@ -51,23 +56,80 @@ public class EditorManager {
editorTopBar.addToEditorScreen(textEditorScreen); editorTopBar.addToEditorScreen(textEditorScreen);
editorFileView.setSize(FILE_RENDER_WIDTH_SIZE, TOP_BAR_HEIGHT, -1, -1); editorFileView.setSize(FILE_RENDER_WIDTH_SIZE, TOP_BAR_HEIGHT, -1, -1);
editorFileView.setEditorFile(files.getFirst()); if (!files.isEmpty()) {
editorFileView.setEditorFile(files.getFirst());
}
editorFileView.addToEditorScreen(textEditorScreen); editorFileView.addToEditorScreen(textEditorScreen);
/* // Full-screen modal docs layer, above every other widget; hidden until opened.
files = new ArrayList<>(); editorDocsPanel.setSize(0, 0, -1, -1);
editorDocsPanel.setZIndex(2);
editorDocsPanel.addToEditorScreen(textEditorScreen);
// Widgets are reused across opens: make sure a leftover docs modal isn't
// covering the editor, so the text editor really is the focused surface.
editorDocsPanel.close();
// Add example file // Focus the text editor so typing works immediately on open.
EditorFile editorFile = new EditorFile("main.lua", ""); textEditorScreen.selectedWidget = editorFileView;
files.add(editorFile);
*/
// De alguna forma cargar archivos de server
client.setScreenAndShow(textEditorScreen); client.setScreenAndShow(textEditorScreen);
} }
/** Opens the Lua API documentation panel (top bar: Help → Lua API Documentation). */
public void openDocs() {
editorDocsPanel.open();
}
/**
* Opens the documentation panel focused on a function name typed in the
* file view (F1), e.g. {@code "world.set_block"} or just {@code "set_block"}.
*/
public void openDocsAt(String word) {
editorDocsPanel.open(word);
}
/** Asks the server for the current project files; the reply lands in {@link #setFiles(List)}. */
public void requestProjectFiles() {
if (client.player == null) return;
ClientPlayNetworking.send(new ServerboundRequestProjectPayload());
}
/** Called on the client thread when the server sends the full project file list. */
public void setFiles(List<EditorFile> newFiles) {
files = new ArrayList<>(newFiles);
EditorFile current = editorFileView.getCurrentEditorFile();
EditorFile target = current != null ? findFile(current.getName()) : null;
if (target == null && !files.isEmpty()) {
target = files.getFirst();
}
if (target != null) {
editorFileView.setEditorFile(target);
}
}
/** Called on the client thread when another client saved a file on the server. */
public void upsertFile(EditorFile file) {
EditorFile existing = findFile(file.getName());
if (existing == null) {
files.add(file);
} else if (existing != editorFileView.getCurrentEditorFile()) {
// Don't clobber text the user is currently editing.
existing.setText(file.getText());
}
}
public EditorFile findFile(String name) {
for (EditorFile file : files) {
if (file.getName().equals(name)) return file;
}
return null;
}
public void openFile(EditorFile file) {
editorFileView.setEditorFile(file);
}
public void newFile() { public void newFile() {
} }

View File

@@ -35,7 +35,7 @@ public class EditorTopBar extends Widget {
static MenuItem separator() { return new MenuItem("", true); } static MenuItem separator() { return new MenuItem("", true); }
} }
private static final String[] TAB_LABELS = { "File", "Edit", "Run" }; private static final String[] TAB_LABELS = { "File", "Edit", "Run", "Help" };
private static final List<List<MenuItem>> TAB_ITEMS = List.of( private static final List<List<MenuItem>> TAB_ITEMS = List.of(
// File // File
@@ -65,6 +65,10 @@ public class EditorTopBar extends Widget {
MenuItem.item("Stop"), MenuItem.item("Stop"),
MenuItem.separator(), MenuItem.separator(),
MenuItem.item("Build Project") MenuItem.item("Build Project")
),
// Help
List.of(
MenuItem.item("Lua API Documentation")
) )
); );
@@ -236,6 +240,7 @@ public class EditorTopBar extends Widget {
case "Redo" -> editorManager.redo(); case "Redo" -> editorManager.redo();
case "Run Script" -> editorManager.run(); case "Run Script" -> editorManager.run();
case "Stop" -> editorManager.stop(); case "Stop" -> editorManager.stop();
case "Lua API Documentation" -> editorManager.openDocs();
// Add remaining cases as needed // Add remaining cases as needed
default -> System.out.println("[TopBar] Clicked: " + item.label()); default -> System.out.println("[TopBar] Clicked: " + item.label());
} }

View File

@@ -64,7 +64,7 @@ public class LuaHighlighter {
private static final Set<String> LIBRARIES = Set.of( private static final Set<String> LIBRARIES = Set.of(
"string", "table", "math", "io", "os", "string", "table", "math", "io", "os",
"coroutine", "package", "utf8", "debug" "coroutine", "package", "utf8", "debug", "world"
); );
// ── Public types ────────────────────────────────────────────────────── // ── Public types ──────────────────────────────────────────────────────

View File

@@ -1,18 +1,26 @@
package com.aranroig; package com.aranroig;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.payloads.ClientboundProjectFilesPayload;
import com.aranroig.payloads.ClientboundSaveCodePayload;
import com.aranroig.payloads.ServerboundRequestProjectPayload;
import com.aranroig.payloads.ServerboundRunCodePayload; import com.aranroig.payloads.ServerboundRunCodePayload;
import com.aranroig.payloads.ServerboundSaveCodePayload; import com.aranroig.payloads.ServerboundSaveCodePayload;
import com.aranroig.wrapper.ChatLogger;
import com.aranroig.wrapper.WorldApi;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier; import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.world.entity.vehicle.minecart.Minecart; import net.minecraft.server.level.ServerPlayer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.luaj.LuaJ;
import java.util.List; import java.util.List;
@@ -24,8 +32,6 @@ public class Codecraft implements ModInitializer {
// That way, it's clear which mod wrote info, warnings, and errors. // That way, it's clear which mod wrote info, warnings, and errors.
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
private List<EditorFile> editorFiles;
@Override @Override
public void onInitialize() { public void onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state. // This code runs as soon as Minecraft is in a mod-load-ready state.
@@ -35,6 +41,25 @@ public class Codecraft implements ModInitializer {
PayloadTypeRegistry.serverboundPlay().register(ServerboundSaveCodePayload.TYPE, ServerboundSaveCodePayload.CODEC); PayloadTypeRegistry.serverboundPlay().register(ServerboundSaveCodePayload.TYPE, ServerboundSaveCodePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRunCodePayload.TYPE, ServerboundRunCodePayload.CODEC); PayloadTypeRegistry.serverboundPlay().register(ServerboundRunCodePayload.TYPE, ServerboundRunCodePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRequestProjectPayload.TYPE, ServerboundRequestProjectPayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundSaveCodePayload.TYPE, ClientboundSaveCodePayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundProjectFilesPayload.TYPE, ClientboundProjectFilesPayload.CODEC);
ServerPlayNetworking.registerGlobalReceiver(ServerboundRequestProjectPayload.TYPE, (payload, context) -> {
MinecraftServer server = context.player().level().getServer();
if(server == null) return;
SavedProjectData savedData = SavedProjectData.getSavedBlockData(server);
List<EditorFile> files = savedData.getEditorFiles();
// Seed a default entrypoint so the client always has at least one file.
if(files.isEmpty()) {
files.add(new EditorFile("main.lua", ""));
savedData.setEditorFiles(files);
}
ServerPlayNetworking.send(context.player(), new ClientboundProjectFilesPayload(List.copyOf(files)));
});
ServerPlayNetworking.registerGlobalReceiver(ServerboundSaveCodePayload.TYPE, (payload, context) -> { ServerPlayNetworking.registerGlobalReceiver(ServerboundSaveCodePayload.TYPE, (payload, context) -> {
MinecraftServer server = context.player().level().getServer(); MinecraftServer server = context.player().level().getServer();
@@ -57,26 +82,51 @@ public class Codecraft implements ModInitializer {
} }
savedData.setEditorFiles(files); savedData.setEditorFiles(files);
System.out.println("Successfully saved files"); LOGGER.info("Successfully saved file {}", editorFile.getName());
// Push the change to every other client so their editors stay in sync.
for(ServerPlayer player : server.getPlayerList().getPlayers()) {
if(player != context.player()) {
ServerPlayNetworking.send(player, new ClientboundSaveCodePayload(new EditorFile(editorFile.getName(), editorFile.getText())));
}
}
}); });
ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> { ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> {
// HERE
MinecraftServer server = context.player().level().getServer(); MinecraftServer server = context.player().level().getServer();
if(server == null) return; if(server == null) return;
ServerPlayer player = context.player();
SavedProjectData savedData = SavedProjectData.getSavedBlockData(server); SavedProjectData savedData = SavedProjectData.getSavedBlockData(server);
List<EditorFile> files = savedData.getEditorFiles(); List<EditorFile> files = savedData.getEditorFiles();
String entrypoint = payload.data().getEntrypoint(); String entrypoint = payload.data().getEntrypoint();
System.out.println("Want to run the code " + payload.data().getEntrypoint()); LOGGER.info("Running entrypoint {}", entrypoint);
// TODO: Run the entrypoint, might change later EditorFile target = null;
for(EditorFile file : files) { for(EditorFile file : files) {
if(file.getName().equals(entrypoint)) { if(file.getName().equals(entrypoint)) {
System.out.println(file.getText()); target = file;
break;
} }
} }
if(target == null) {
player.sendSystemMessage(Component.literal("§ccodecraft: entrypoint not found: " + entrypoint));
return;
}
Lua lua = new LuaJ();
lua.push(ChatLogger.print(player));
lua.setGlobal("print");
WorldApi.register(lua, player);
try {
lua.run(target.getText());
} catch (Exception e) {
LOGGER.warn("Error running " + entrypoint, e);
player.sendSystemMessage(Component.literal("§ccodecraft error: " + e.getMessage()));
}
}); });
} }