This commit is contained in:
@@ -26,6 +26,7 @@ import com.aranroig.payloads.ServerboundSaveCodePayload;
|
||||
import com.aranroig.payloads.ServerboundShellInputPayload;
|
||||
import com.aranroig.payloads.ServerboundShellResizePayload;
|
||||
import com.aranroig.payloads.ServerboundSpawnShellPayload;
|
||||
import com.aranroig.project.ProjectStore;
|
||||
import com.aranroig.shell.ShellManager;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
|
||||
@@ -34,7 +35,6 @@ import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -83,6 +83,12 @@ public class Codecraft implements ModInitializer {
|
||||
// currently running script happens per event.
|
||||
ScriptRuntimeManager.install();
|
||||
|
||||
// The project now lives as plain .lua files under config/codecraft:
|
||||
// move a world's scripts out of its saved data the first time a
|
||||
// server starts, and drain the queued keystroke writes to disk before
|
||||
// it stops.
|
||||
ProjectStore.install();
|
||||
|
||||
// Drop players from their live editing sessions when they leave, and
|
||||
// throw the cached documents away when the world stops.
|
||||
DocumentManager.install();
|
||||
@@ -92,17 +98,15 @@ public class Codecraft implements ModInitializer {
|
||||
ShellManager.install();
|
||||
|
||||
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();
|
||||
// Read fresh from disk every time the editor opens: scripts edited
|
||||
// with an external editor in the meantime are in here too.
|
||||
List<EditorFile> files = ProjectStore.loadAll();
|
||||
|
||||
// Seed a default entrypoint so the client always has at least one file.
|
||||
// Names carry no extension: the sidebar shows them as they are.
|
||||
if(files.isEmpty()) {
|
||||
files.add(new EditorFile(ProjectPath.ENTRYPOINT, ""));
|
||||
savedData.setEditorFiles(files);
|
||||
ProjectStore.write(ProjectPath.ENTRYPOINT, "");
|
||||
files = List.of(new EditorFile(ProjectPath.ENTRYPOINT, ""));
|
||||
}
|
||||
|
||||
ServerPlayNetworking.send(context.player(), new ClientboundProjectFilesPayload(List.copyOf(files)));
|
||||
@@ -160,24 +164,18 @@ public class Codecraft implements ModInitializer {
|
||||
ShellManager.close(context.player()));
|
||||
|
||||
ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> {
|
||||
MinecraftServer server = context.player().level().getServer();
|
||||
if(server == null) return;
|
||||
|
||||
ServerPlayer player = context.player();
|
||||
|
||||
SavedProjectData savedData = SavedProjectData.getSavedBlockData(server);
|
||||
List<EditorFile> files = savedData.getEditorFiles();
|
||||
|
||||
String entrypoint = payload.data().getEntrypoint();
|
||||
LOGGER.info("Running entrypoint {}", entrypoint);
|
||||
|
||||
EditorFile target = findByName(files, entrypoint);
|
||||
if(target == null) {
|
||||
String code = ProjectStore.read(entrypoint);
|
||||
if(code == null) {
|
||||
// Worlds seeded while names still carried the extension.
|
||||
target = findByName(files, entrypoint + ProjectPath.LEGACY_EXTENSION);
|
||||
code = ProjectStore.read(entrypoint + ProjectPath.LEGACY_EXTENSION);
|
||||
}
|
||||
|
||||
if(target == null) {
|
||||
if(code == null) {
|
||||
player.sendSystemMessage(Component.literal("§ccodecraft: entrypoint not found: " + entrypoint));
|
||||
return;
|
||||
}
|
||||
@@ -187,7 +185,7 @@ public class Codecraft implements ModInitializer {
|
||||
// events on a brand-new Lua state.
|
||||
ScriptRuntime runtime = ScriptRuntimeManager.startRun(player);
|
||||
try {
|
||||
runtime.run(target.getText());
|
||||
runtime.run(code);
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Error running " + entrypoint, e);
|
||||
player.sendSystemMessage(Component.literal("§ccodecraft error: " + e.getMessage()));
|
||||
@@ -195,14 +193,6 @@ public class Codecraft implements ModInitializer {
|
||||
});
|
||||
}
|
||||
|
||||
/** The project's file called {@code name}, or null when the project has none. */
|
||||
private static EditorFile findByName(List<EditorFile> files, String name) {
|
||||
for(EditorFile file : files) {
|
||||
if(file.getName().equals(name)) return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Identifier id(String path) {
|
||||
return Identifier.fromNamespaceAndPath(MOD_ID, path);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,15 @@ import net.minecraft.world.level.saveddata.SavedDataType;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The project files as they were stored before: baked into the world's saved
|
||||
* data, where no editor outside the game could reach them.
|
||||
*
|
||||
* <p>Superseded by {@link com.aranroig.project.ProjectStore}, which keeps the
|
||||
* project as plain files under {@code config/codecraft}. This class is kept
|
||||
* only so a world updated from the old storage gets its scripts migrated
|
||||
* there once; nothing reads or writes it any more besides that migration.</p>
|
||||
*/
|
||||
public class SavedProjectData extends SavedData {
|
||||
private List<EditorFile> editorFiles;
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.aranroig.collab;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.SavedProjectData;
|
||||
import com.aranroig.editor.Edit;
|
||||
import com.aranroig.editor.EditorFile;
|
||||
import com.aranroig.editor.EditorPresence;
|
||||
import com.aranroig.project.ProjectStore;
|
||||
import com.aranroig.payloads.ClientboundDocumentEditPayload;
|
||||
import com.aranroig.payloads.ClientboundDocumentStatePayload;
|
||||
import com.aranroig.payloads.ClientboundEditAckPayload;
|
||||
@@ -51,7 +51,10 @@ import java.util.UUID;
|
||||
* <h2>Threading</h2>
|
||||
*
|
||||
* <p>All of this runs on the server thread: payload handlers and the connection
|
||||
* events below are dispatched there, so the maps need no locking.</p>
|
||||
* events below are dispatched there, so the maps need no locking. Nothing here
|
||||
* touches the disk either: what the documents hold is written out by
|
||||
* {@link com.aranroig.project.ProjectStore}, which keeps the server thread off
|
||||
* the filesystem.</p>
|
||||
*/
|
||||
public final class DocumentManager {
|
||||
|
||||
@@ -112,7 +115,7 @@ public final class DocumentManager {
|
||||
session.anchor = -1;
|
||||
}
|
||||
|
||||
Document document = document(server, file);
|
||||
Document document = document(file);
|
||||
ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version));
|
||||
|
||||
broadcastPresence(server, file);
|
||||
@@ -141,7 +144,7 @@ public final class DocumentManager {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null) return;
|
||||
|
||||
Document document = document(server, file);
|
||||
Document document = document(file);
|
||||
|
||||
// Never take the client's word for who wrote an edit: rebasing skips
|
||||
// the sender's own edits, so a spoofed author would apply one twice.
|
||||
@@ -162,7 +165,7 @@ public final class DocumentManager {
|
||||
}
|
||||
|
||||
document.apply(applied);
|
||||
boolean brandNew = persist(server, file, document.text);
|
||||
boolean brandNew = ProjectStore.scheduleWrite(file, document.text);
|
||||
|
||||
ServerPlayNetworking.send(player,
|
||||
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
|
||||
@@ -184,7 +187,7 @@ public final class DocumentManager {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null) return;
|
||||
|
||||
Document document = document(server, file);
|
||||
Document document = document(file);
|
||||
String current = document.text;
|
||||
|
||||
if (current.equals(text)) {
|
||||
@@ -192,7 +195,7 @@ public final class DocumentManager {
|
||||
// has to exist on disk (a brand-new file is saved before it has
|
||||
// any edits flowing), and confirm the version they are on so they
|
||||
// can check their copy against it.
|
||||
persist(server, file, current);
|
||||
ProjectStore.write(file, current);
|
||||
ServerPlayNetworking.send(player,
|
||||
new ClientboundEditAckPayload(file, document.version, current.hashCode(), current.length()));
|
||||
} else {
|
||||
@@ -204,7 +207,7 @@ public final class DocumentManager {
|
||||
// A whole-file save states what the file should contain, so it is
|
||||
// applied to the server's current text instead of being rebased.
|
||||
document.apply(edit);
|
||||
persist(server, file, document.text);
|
||||
ProjectStore.write(file, document.text);
|
||||
|
||||
ServerPlayNetworking.send(player,
|
||||
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
|
||||
@@ -219,30 +222,16 @@ public final class DocumentManager {
|
||||
|
||||
/**
|
||||
* Moves {@code oldName} to {@code newName} everywhere the server knows it:
|
||||
* in the saved project, in the cached document and in the sessions of
|
||||
* everyone editing it — and the other editors' file lists are told. A name
|
||||
* the project already holds is refused.
|
||||
* on disk and in the write queue, in the cached document and in the
|
||||
* sessions of everyone editing it — and the other editors' file lists are
|
||||
* told. A name the project already holds is refused.
|
||||
*/
|
||||
public static void renameFile(ServerPlayer player, String oldName, String newName) {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null || oldName.equals(newName)) return;
|
||||
|
||||
SavedProjectData data = SavedProjectData.getSavedBlockData(server);
|
||||
List<EditorFile> files = data.getEditorFiles();
|
||||
|
||||
for (EditorFile editorFile : files) {
|
||||
if (editorFile.getName().equals(newName)) return; // the name is taken
|
||||
}
|
||||
|
||||
boolean onDisk = false;
|
||||
for (EditorFile editorFile : files) {
|
||||
if (editorFile.getName().equals(oldName)) {
|
||||
editorFile.setName(newName);
|
||||
onDisk = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (onDisk) data.markDirty();
|
||||
if (ProjectStore.exists(newName)) return; // the name is taken
|
||||
ProjectStore.rename(oldName, newName);
|
||||
|
||||
// The live document keeps its version history under the new name, so
|
||||
// the editors of the file can carry on without refetching anything.
|
||||
@@ -282,44 +271,16 @@ public final class DocumentManager {
|
||||
|
||||
// ── Internals ─────────────────────────────────────────────────────────
|
||||
|
||||
private static Document document(MinecraftServer server, String file) {
|
||||
private static Document document(String file) {
|
||||
Document document = DOCUMENTS.get(file);
|
||||
if (document == null) {
|
||||
String text = "";
|
||||
for (EditorFile editorFile : SavedProjectData.getSavedBlockData(server).getEditorFiles()) {
|
||||
if (editorFile.getName().equals(file)) {
|
||||
text = editorFile.getText();
|
||||
break;
|
||||
}
|
||||
}
|
||||
document = new Document(text);
|
||||
String text = ProjectStore.read(file);
|
||||
document = new Document(text == null ? "" : text);
|
||||
DOCUMENTS.put(file, document);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the live text back into the project's saved data, saying whether
|
||||
* that meant the project gained the file. The write itself is throttled by
|
||||
* {@code SavedData}, so marking it dirty per keystroke is cheap and means a
|
||||
* crash loses at most a second of typing.
|
||||
*/
|
||||
private static boolean persist(MinecraftServer server, String file, String text) {
|
||||
SavedProjectData data = SavedProjectData.getSavedBlockData(server);
|
||||
List<EditorFile> files = data.getEditorFiles();
|
||||
|
||||
for (EditorFile editorFile : files) {
|
||||
if (editorFile.getName().equals(file)) {
|
||||
editorFile.setText(text);
|
||||
data.markDirty();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
files.add(new EditorFile(file, text));
|
||||
data.setEditorFiles(files);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells every editor but {@code author} that the project holds {@code file}
|
||||
* with {@code text}. It is how one player's new file turns into a row in the
|
||||
|
||||
@@ -19,8 +19,9 @@ import java.util.List;
|
||||
* {@code src/main/resources/data/codecraft/docs/lua-api.json} and is loaded from
|
||||
* the mod resources on first access, so documentation can be edited (and, once
|
||||
* packed, overridden) without touching Java. It describes the functions
|
||||
* registered by the wrappers in {@code com.aranroig.wrapper} (currently
|
||||
* {@code world} and the {@code print} helper) and by
|
||||
* registered by the wrappers in {@code com.aranroig.wrapper} (including
|
||||
* {@code world}, {@code entities}, {@code scoreboard}, {@code hud}, {@code items},
|
||||
* {@code run} and the {@code print} helper) and by
|
||||
* {@link com.aranroig.listeners.EventsApi} ({@code events}). The client editor
|
||||
* reads it to render the browsable documentation panel, so it is the single
|
||||
* source of truth shown to players.</p>
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package com.aranroig.listeners;
|
||||
|
||||
import com.aranroig.wrapper.ChatLogger;
|
||||
import com.aranroig.wrapper.ServerCommandApi;
|
||||
import com.aranroig.wrapper.WorldApi;
|
||||
import com.aranroig.wrapper.EntityApi;
|
||||
import com.aranroig.wrapper.HudApi;
|
||||
import com.aranroig.wrapper.ItemApi;
|
||||
import com.aranroig.wrapper.ScoreboardApi;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
|
||||
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
|
||||
@@ -90,8 +95,8 @@ public final class ScriptRuntimeManager {
|
||||
* run}. Any listeners the player registered previously are dropped.
|
||||
*
|
||||
* @param player the player who pressed <em>Run Script</em>
|
||||
* @return the fresh runtime with {@code print}, {@code world} and
|
||||
* {@code events} already registered on its Lua state
|
||||
* @return the fresh runtime with the Minecraft API tables, {@code run},
|
||||
* {@code print} and {@code events} already registered
|
||||
*/
|
||||
public static ScriptRuntime startRun(ServerPlayer player) {
|
||||
stop(player);
|
||||
@@ -105,7 +110,12 @@ public final class ScriptRuntimeManager {
|
||||
ScriptRuntime runtime = new ScriptRuntime(lua, player);
|
||||
lua.push(ChatLogger.print(player));
|
||||
lua.setGlobal("print");
|
||||
ServerCommandApi.register(lua, player);
|
||||
WorldApi.register(lua, player);
|
||||
EntityApi.register(lua, player);
|
||||
ScoreboardApi.register(lua, player);
|
||||
HudApi.register(lua, player);
|
||||
ItemApi.register(lua, player);
|
||||
EventsApi.register(lua, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
388
src/main/java/com/aranroig/project/ProjectStore.java
Normal file
388
src/main/java/com/aranroig/project/ProjectStore.java
Normal file
@@ -0,0 +1,388 @@
|
||||
package com.aranroig.project;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.SavedProjectData;
|
||||
import com.aranroig.editor.EditorFile;
|
||||
import com.aranroig.editor.ProjectPath;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The project as physical files on the server's machine: the file called
|
||||
* {@code lib/gui/theme} lives at {@code config/codecraft/lib/gui/theme.lua},
|
||||
* folders and all, so scripts can be edited, versioned and copied with
|
||||
* whatever tools live outside the game. Names on disk keep the {@code .lua}
|
||||
* extension even though the project's own names dropped it — an editor
|
||||
* outside the game should know what it is looking at.
|
||||
*
|
||||
* <h2>Writing</h2>
|
||||
*
|
||||
* <p>An explicit save writes through at once; keystrokes do not wait for the
|
||||
* disk — they land in a pending map that a daemon thread drains a beat after
|
||||
* the typing settles, so a crash loses at most that much typing and the
|
||||
* server thread never blocks on a file. Everything still in the queue is
|
||||
* written before the server stops.</p>
|
||||
*
|
||||
* <p>Reading happens fresh from disk every time the editor is opened, so a
|
||||
* script changed with an external editor between sessions is picked up too.
|
||||
* (A file open in the editor keeps the game's copy as its authority, as
|
||||
* always — external edits to a document somebody is typing in are the live
|
||||
* editing protocol's problem, not this class's.)</p>
|
||||
*
|
||||
* <h2>Threading</h2>
|
||||
*
|
||||
* <p>Callers are on the server thread. The pending map is guarded by its own
|
||||
* lock and every actual disk operation by {@link #DISK_LOCK}, which lets the
|
||||
* writer thread and a synchronous save or flush disagree only about ordering,
|
||||
* never about the same file at the same time.</p>
|
||||
*/
|
||||
public final class ProjectStore {
|
||||
|
||||
/** Scripts keep this on disk; project names carry it only when they picked one up before files dropped it. */
|
||||
private static final String EXTENSION = ProjectPath.LEGACY_EXTENSION;
|
||||
|
||||
/** How long after the last keystroke the queued writes hit the disk. */
|
||||
private static final long WRITE_DELAY_MS = 1_000;
|
||||
|
||||
/** Guards the disk itself: no two writers touch the same file at once. */
|
||||
private static final Object DISK_LOCK = new Object();
|
||||
|
||||
/** Text changed but not written yet; the newest text per file wins. */
|
||||
private static final Map<String, String> PENDING = new HashMap<>();
|
||||
private static boolean flushScheduled = false;
|
||||
|
||||
/** Single daemon writer: the server thread never waits for the disk. */
|
||||
private static final ScheduledExecutorService IO = Executors.newSingleThreadScheduledExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable, "codecraft-project-writer");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
private ProjectStore() {
|
||||
}
|
||||
|
||||
/** The folder the project lives at: {@code config/codecraft}. */
|
||||
public static Path root() {
|
||||
return FabricLoader.getInstance().getConfigDir().resolve(Codecraft.MOD_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves old worlds' projects out of their saved data into the config
|
||||
* folder when a server starts, and writes everything still queued to disk
|
||||
* before it stops. Call once from {@link com.aranroig.Codecraft#onInitialize()}.
|
||||
*/
|
||||
public static void install() {
|
||||
ServerLifecycleEvents.SERVER_STARTED.register(ProjectStore::migrateWorldData);
|
||||
ServerLifecycleEvents.SERVER_STOPPING.register(server -> flushNow());
|
||||
}
|
||||
|
||||
// ── Reading ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Every script of the project, read fresh from disk: whatever was edited
|
||||
* with an external editor since the last time the editor was opened is in
|
||||
* here too. Typing that has not reached the disk yet wins over the older
|
||||
* copy the file holds there, and a file that is nothing but typing — saved
|
||||
* by a keystroke and not flushed yet — counts as one. Folders exist while
|
||||
* something is in them: a file is what makes the project, not a directory.
|
||||
*/
|
||||
public static List<EditorFile> loadAll() {
|
||||
Map<String, String> texts = new LinkedHashMap<>();
|
||||
|
||||
Path root = root();
|
||||
if (Files.isDirectory(root)) {
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
List<Path> paths = walk
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(p -> p.getFileName().toString().endsWith(EXTENSION))
|
||||
.sorted()
|
||||
.toList();
|
||||
for (Path path : paths) {
|
||||
String text = readFromDisk(path);
|
||||
if (text == null) continue; // unreadable: skip rather than lose the rest
|
||||
texts.put(nameOf(path), text);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Codecraft.LOGGER.warn("Could not list the project files in {}", root, e);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (PENDING) {
|
||||
texts.putAll(PENDING);
|
||||
}
|
||||
|
||||
List<EditorFile> files = new ArrayList<>(texts.size());
|
||||
for (Map.Entry<String, String> entry : texts.entrySet()) {
|
||||
files.add(new EditorFile(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of the file called {@code name}: what was typed and not written
|
||||
* yet if there is such a thing, what the disk holds otherwise. Null when
|
||||
* the project has no such file.
|
||||
*/
|
||||
public static String read(String name) {
|
||||
synchronized (PENDING) {
|
||||
String pending = PENDING.get(name);
|
||||
if (pending != null) return pending;
|
||||
}
|
||||
Path path = pathOf(name);
|
||||
if (path == null || !Files.isRegularFile(path)) return null;
|
||||
return readFromDisk(path);
|
||||
}
|
||||
|
||||
/** Whether the project holds a file called {@code name}, written or not. */
|
||||
public static boolean exists(String name) {
|
||||
synchronized (PENDING) {
|
||||
if (PENDING.containsKey(name)) return true;
|
||||
}
|
||||
Path path = pathOf(name);
|
||||
return path != null && Files.isRegularFile(path);
|
||||
}
|
||||
|
||||
// ── Writing ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Writes the file right now, saying whether that meant the project gained
|
||||
* it. For explicit saves and files that must exist the moment they are
|
||||
* spoken of; typing goes through {@link #scheduleWrite} instead.
|
||||
*/
|
||||
public static boolean write(String name, String text) {
|
||||
return writeNow(name, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records {@code text} for the disk to pick up soon, saying whether that
|
||||
* meant the project gained the file. One keystroke's worth goes through
|
||||
* here instead of {@link #write}: the writer thread catches up
|
||||
* {@value #WRITE_DELAY_MS} after the typing settles, so a burst of keys
|
||||
* becomes one file write and the server thread never waits on the disk.
|
||||
*/
|
||||
public static boolean scheduleWrite(String name, String text) {
|
||||
Path target = pathOf(name);
|
||||
if (target == null) {
|
||||
Codecraft.LOGGER.warn("Refusing to store a project file called {}", name);
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean brandNew;
|
||||
boolean schedule;
|
||||
synchronized (PENDING) {
|
||||
brandNew = !PENDING.containsKey(name) && !Files.exists(target);
|
||||
PENDING.put(name, text);
|
||||
schedule = !flushScheduled;
|
||||
flushScheduled = true;
|
||||
}
|
||||
|
||||
if (schedule) {
|
||||
IO.schedule(ProjectStore::flushPending, WRITE_DELAY_MS, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
return brandNew;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves {@code oldName} to {@code newName} on disk and in the write queue,
|
||||
* so a renamed file carries its latest text to its new name. A name the
|
||||
* project already holds is not moved onto; callers refuse it first.
|
||||
*/
|
||||
public static void rename(String oldName, String newName) {
|
||||
Path from = pathOf(oldName);
|
||||
Path to = pathOf(newName);
|
||||
if (from == null || to == null) return;
|
||||
|
||||
// Whatever is queued belongs to the file, not to its name: get it onto
|
||||
// disk at the old path before the file changes hands.
|
||||
String pending;
|
||||
synchronized (PENDING) {
|
||||
pending = PENDING.remove(oldName);
|
||||
}
|
||||
if (pending != null) writeNow(oldName, pending);
|
||||
|
||||
synchronized (DISK_LOCK) {
|
||||
if (!Files.exists(from)) return; // nothing to move
|
||||
try {
|
||||
Path parent = to.getParent();
|
||||
if (parent != null) Files.createDirectories(parent);
|
||||
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
|
||||
pruneEmptyParents(from.getParent());
|
||||
} catch (IOException e) {
|
||||
Codecraft.LOGGER.warn("Could not rename project file {} to {}", oldName, newName, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Internals ─────────────────────────────────────────────────────────
|
||||
|
||||
/** Writes everything still queued: called before the server stops. */
|
||||
private static void flushNow() {
|
||||
flushPending();
|
||||
}
|
||||
|
||||
private static void flushPending() {
|
||||
Map<String, String> batch;
|
||||
synchronized (PENDING) {
|
||||
flushScheduled = false;
|
||||
if (PENDING.isEmpty()) return;
|
||||
batch = Map.copyOf(PENDING);
|
||||
PENDING.clear();
|
||||
}
|
||||
for (Map.Entry<String, String> entry : batch.entrySet()) {
|
||||
writeNow(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes through a temporary file and moves it into place: an editor watching the folder never reads half a script. */
|
||||
private static boolean writeNow(String name, String text) {
|
||||
Path target = pathOf(name);
|
||||
if (target == null) {
|
||||
Codecraft.LOGGER.warn("Refusing to store a project file called {}", name);
|
||||
return false;
|
||||
}
|
||||
|
||||
synchronized (DISK_LOCK) {
|
||||
boolean brandNew = !Files.exists(target);
|
||||
try {
|
||||
Path parent = target.getParent();
|
||||
if (parent != null) Files.createDirectories(parent);
|
||||
|
||||
Path temp = target.resolveSibling(target.getFileName() + ".tmp");
|
||||
Files.writeString(temp, text, StandardCharsets.UTF_8);
|
||||
try {
|
||||
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
return brandNew;
|
||||
} catch (IOException e) {
|
||||
Codecraft.LOGGER.warn("Could not write project file {}", name, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String readFromDisk(Path path) {
|
||||
try {
|
||||
String text = Files.readString(path, StandardCharsets.UTF_8);
|
||||
// Editors outside the game may write \r\n; the one in it speaks \n.
|
||||
if (text.indexOf('\r') >= 0) text = text.replace("\r\n", "\n").replace('\r', '\n');
|
||||
return text;
|
||||
} catch (IOException e) {
|
||||
Codecraft.LOGGER.warn("Could not read project file {}", path, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The file {@code name} lives at under the project root, or null when it
|
||||
* is not a name the store will touch. Names arrive over the network, so
|
||||
* one that climbs out of the config folder through {@code ..} is refused
|
||||
* here rather than after it has overwritten something outside it.
|
||||
*/
|
||||
private static Path pathOf(String name) {
|
||||
if (name == null || name.isEmpty()) return null;
|
||||
|
||||
Path path = root();
|
||||
int from = 0;
|
||||
while (from < name.length()) {
|
||||
int separator = name.indexOf(ProjectPath.SEPARATOR, from);
|
||||
String segment = separator < 0 ? name.substring(from) : name.substring(from, separator);
|
||||
if (!isSafeSegment(segment)) return null;
|
||||
try {
|
||||
path = path.resolve(segment);
|
||||
} catch (InvalidPathException e) {
|
||||
return null;
|
||||
}
|
||||
from = separator < 0 ? name.length() : separator + 1;
|
||||
}
|
||||
|
||||
String fileName = path.getFileName().toString();
|
||||
return fileName.endsWith(EXTENSION) ? path : path.resolveSibling(fileName + EXTENSION);
|
||||
}
|
||||
|
||||
private static boolean isSafeSegment(String segment) {
|
||||
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) return false;
|
||||
for (int i = 0; i < segment.length(); i++) {
|
||||
char c = segment.charAt(i);
|
||||
if (c == '\0' || c == '\\') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The project's name for a file under the root: the path to it, with no extension. */
|
||||
private static String nameOf(Path path) {
|
||||
String relative = root().relativize(path).toString().replace(File.separatorChar, ProjectPath.SEPARATOR);
|
||||
return relative.endsWith(EXTENSION)
|
||||
? relative.substring(0, relative.length() - EXTENSION.length())
|
||||
: relative;
|
||||
}
|
||||
|
||||
/** Removes the folders a rename left empty: in this project a folder exists while something is in it. */
|
||||
private static void pruneEmptyParents(Path folder) {
|
||||
Path root = root();
|
||||
try {
|
||||
Path current = folder;
|
||||
while (current != null && current.startsWith(root) && !current.equals(root)) {
|
||||
try (Stream<Path> children = Files.list(current)) {
|
||||
if (children.findAny().isPresent()) break;
|
||||
}
|
||||
Path parent = current.getParent();
|
||||
Files.deleteIfExists(current);
|
||||
current = parent;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// An empty folder that outlives the rename is a cosmetic problem.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The project is one per server now, not one per world save, so a world
|
||||
* whose scripts still live in its saved data gets them moved into the
|
||||
* config folder the first time it starts after the update — unless the
|
||||
* folder already holds a project, which wins. The world keeps its copy
|
||||
* untouched: what is left behind is a backup.
|
||||
*/
|
||||
private static void migrateWorldData(MinecraftServer server) {
|
||||
if (hasScripts()) return;
|
||||
|
||||
List<EditorFile> files = SavedProjectData.getSavedBlockData(server).getEditorFiles();
|
||||
if (files.isEmpty()) return;
|
||||
|
||||
int moved = 0;
|
||||
for (EditorFile file : files) {
|
||||
if (write(file.getName(), file.getText())) moved++;
|
||||
}
|
||||
Codecraft.LOGGER.info("Migrated {} project file{} from world data to {}",
|
||||
moved, moved == 1 ? "" : "s", root());
|
||||
}
|
||||
|
||||
private static boolean hasScripts() {
|
||||
Path root = root();
|
||||
if (!Files.isDirectory(root)) return false;
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.anyMatch(p -> Files.isRegularFile(p) && p.getFileName().toString().endsWith(EXTENSION));
|
||||
} catch (IOException e) {
|
||||
return true; // cannot tell: leave the world's copy alone
|
||||
}
|
||||
}
|
||||
}
|
||||
155
src/main/java/com/aranroig/wrapper/EntityApi.java
Normal file
155
src/main/java/com/aranroig/wrapper/EntityApi.java
Normal file
@@ -0,0 +1,155 @@
|
||||
package com.aranroig.wrapper;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySpawnReason;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Entity queries and basic operations available to a running Lua script. */
|
||||
public final class EntityApi {
|
||||
private EntityApi() {
|
||||
}
|
||||
|
||||
public static void register(Lua lua, ServerPlayer owner) {
|
||||
lua.newTable();
|
||||
int table = lua.getTop();
|
||||
lua.push((L, args) -> nearby(L, owner, args)); lua.setField(table, "nearby");
|
||||
lua.push((L, args) -> spawn(L, owner, args)); lua.setField(table, "spawn");
|
||||
lua.push((L, args) -> get(L, owner, args)); lua.setField(table, "get");
|
||||
lua.push((L, args) -> teleport(L, owner, args)); lua.setField(table, "teleport");
|
||||
lua.push((L, args) -> remove(L, owner, args)); lua.setField(table, "remove");
|
||||
lua.push((L, args) -> setName(L, owner, args)); lua.setField(table, "set_name");
|
||||
lua.push((L, args) -> setHealth(L, owner, args)); lua.setField(table, "set_health");
|
||||
lua.setGlobal("entities");
|
||||
}
|
||||
|
||||
private static LuaValue[] nearby(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
double radius = args.length > 0 && args[0].type() == Lua.LuaType.NUMBER ? args[0].toNumber() : 16.0;
|
||||
if (!Double.isFinite(radius) || radius < 0 || radius > 128) return fail(lua, "radius must be between 0 and 128");
|
||||
String filter = args.length > 1 && args[1].type() == Lua.LuaType.STRING ? normalizeId(args[1].toString()) : null;
|
||||
if (args.length > 1 && filter == null) return fail(lua, "entity type must be a valid id");
|
||||
if (filter != null && !BuiltInRegistries.ENTITY_TYPE.containsKey(Identifier.parse(filter))) return fail(lua, "unknown entity type");
|
||||
|
||||
double r = radius;
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (Entity entity : owner.level().getEntities(owner, owner.getBoundingBox().inflate(r), candidate ->
|
||||
candidate.distanceToSqr(owner) <= r * r
|
||||
&& (filter == null || BuiltInRegistries.ENTITY_TYPE.getKey(candidate.getType()).toString().equals(filter)))) {
|
||||
ids.add(entity.getUUID().toString());
|
||||
}
|
||||
return new LuaValue[]{LuaTables.array(lua, ids)};
|
||||
}
|
||||
|
||||
private static LuaValue[] spawn(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 4 || args[0].type() != Lua.LuaType.STRING) {
|
||||
return fail(lua, "usage: entities.spawn(type, x, y, z)");
|
||||
}
|
||||
Identifier id = identifier(args[0].toString());
|
||||
Double x = decimal(args[1]), y = decimal(args[2]), z = decimal(args[3]);
|
||||
if (id == null || !BuiltInRegistries.ENTITY_TYPE.containsKey(id)) return fail(lua, "unknown entity type");
|
||||
if (x == null || y == null || z == null) return fail(lua, "x, y and z must be numbers");
|
||||
if (Math.abs(x) > 30_000_000 || Math.abs(z) > 30_000_000 || y < owner.level().getMinY() || y >= owner.level().getMaxY()) {
|
||||
return fail(lua, "position is outside the world bounds");
|
||||
}
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getOptional(id).orElse(null);
|
||||
if (type == null) return fail(lua, "unknown entity type");
|
||||
if (!type.canSummon()) return fail(lua, "that entity type cannot be summoned");
|
||||
Entity entity = type.create(owner.level(), EntitySpawnReason.COMMAND);
|
||||
if (entity == null || entity instanceof ServerPlayer) return fail(lua, "could not create that entity");
|
||||
entity.setPos(x, y, z);
|
||||
entity.setYRot(owner.getYRot());
|
||||
if (!owner.level().addFreshEntity(entity)) return fail(lua, "the entity could not be added to the world");
|
||||
return new LuaValue[]{lua.from(entity.getUUID().toString())};
|
||||
}
|
||||
|
||||
private static LuaValue[] get(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
Entity entity = entity(owner, args);
|
||||
if (entity == null) return new LuaValue[]{lua.fromNull(), lua.from("entity not found")};
|
||||
return new LuaValue[]{lua.from(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()).toString()),
|
||||
lua.from(entity.getX()), lua.from(entity.getY()), lua.from(entity.getZ()),
|
||||
lua.from(entity.getName().getString())};
|
||||
}
|
||||
|
||||
private static LuaValue[] teleport(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 4) return fail(lua, "usage: entities.teleport(uuid, x, y, z)");
|
||||
Entity entity = entity(owner, args);
|
||||
if (entity == null) return fail(lua, "entity not found");
|
||||
Double x = decimal(args[1]), y = decimal(args[2]), z = decimal(args[3]);
|
||||
if (x == null || y == null || z == null) return fail(lua, "x, y and z must be numbers");
|
||||
if (Math.abs(x) > 30_000_000 || Math.abs(z) > 30_000_000 || y < entity.level().getMinY() || y >= entity.level().getMaxY()) {
|
||||
return fail(lua, "position is outside the world bounds");
|
||||
}
|
||||
entity.teleportTo(x, y, z);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] remove(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
Entity entity = entity(owner, args);
|
||||
if (entity == null) return fail(lua, "entity not found");
|
||||
if (entity instanceof ServerPlayer) return fail(lua, "players cannot be removed");
|
||||
entity.discard();
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] setName(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 2 || args[1].type() != Lua.LuaType.STRING) return fail(lua, "usage: entities.set_name(uuid, name)");
|
||||
Entity entity = entity(owner, args);
|
||||
if (entity == null) return fail(lua, "entity not found");
|
||||
entity.setCustomName(Component.literal(args[1].toString()));
|
||||
entity.setCustomNameVisible(true);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] setHealth(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 2) return fail(lua, "usage: entities.set_health(uuid, health)");
|
||||
Entity entity = entity(owner, args);
|
||||
if (!(entity instanceof LivingEntity living)) return fail(lua, "living entity not found");
|
||||
Double health = decimal(args[1]);
|
||||
if (health == null || health < 0 || health > living.getMaxHealth()) return fail(lua, "health must be between 0 and max health");
|
||||
living.setHealth(health.floatValue());
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static Entity entity(ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length == 0 || args[0].type() != Lua.LuaType.STRING) return null;
|
||||
try {
|
||||
UUID uuid = UUID.fromString(args[0].toString());
|
||||
for (ServerLevel level : owner.level().getServer().getAllLevels()) {
|
||||
Entity entity = level.getEntityInAnyDimension(uuid);
|
||||
if (entity != null) return entity;
|
||||
}
|
||||
return null;
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Identifier identifier(String input) {
|
||||
return Identifier.tryParse(input.indexOf(':') < 0 ? "minecraft:" + input : input);
|
||||
}
|
||||
|
||||
private static String normalizeId(String input) {
|
||||
Identifier id = identifier(input);
|
||||
return id == null ? null : id.toString();
|
||||
}
|
||||
|
||||
private static Double decimal(LuaValue value) {
|
||||
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
|
||||
double number = value.toNumber();
|
||||
return Double.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
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)}; }
|
||||
}
|
||||
141
src/main/java/com/aranroig/wrapper/HudApi.java
Normal file
141
src/main/java/com/aranroig/wrapper/HudApi.java
Normal file
@@ -0,0 +1,141 @@
|
||||
package com.aranroig.wrapper;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.bossevents.CustomBossEvent;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
|
||||
/** Title, action-bar and boss-bar feedback for online players. */
|
||||
public final class HudApi {
|
||||
private HudApi() {
|
||||
}
|
||||
|
||||
public static void register(Lua lua, ServerPlayer owner) {
|
||||
lua.newTable();
|
||||
int table = lua.getTop();
|
||||
lua.push((L, args) -> text(L, owner, args, "title")); lua.setField(table, "title");
|
||||
lua.push((L, args) -> text(L, owner, args, "subtitle")); lua.setField(table, "subtitle");
|
||||
lua.push((L, args) -> text(L, owner, args, "action_bar")); lua.setField(table, "action_bar");
|
||||
lua.push((L, args) -> times(L, owner, args)); lua.setField(table, "title_times");
|
||||
lua.push((L, args) -> clear(L, owner, args)); lua.setField(table, "clear_titles");
|
||||
lua.push((L, args) -> bossbar(L, owner, args, "add")); lua.setField(table, "bossbar_add");
|
||||
lua.push((L, args) -> bossbar(L, owner, args, "remove")); lua.setField(table, "bossbar_remove");
|
||||
lua.push((L, args) -> bossbar(L, owner, args, "value")); lua.setField(table, "bossbar_value");
|
||||
lua.push((L, args) -> bossbar(L, owner, args, "max")); lua.setField(table, "bossbar_max");
|
||||
lua.push((L, args) -> bossbar(L, owner, args, "visible")); lua.setField(table, "bossbar_visible");
|
||||
lua.setGlobal("hud");
|
||||
}
|
||||
|
||||
private static LuaValue[] text(Lua lua, ServerPlayer owner, LuaValue[] args, String kind) {
|
||||
if (args.length < 1 || args[0].type() != Lua.LuaType.STRING) return fail(lua, "usage: hud." + kind + "(text [, player])");
|
||||
ServerPlayer target = player(owner, args, 1);
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
Component text = Component.literal(args[0].toString());
|
||||
switch (kind) {
|
||||
case "title" -> target.connection.send(new ClientboundSetTitleTextPacket(text));
|
||||
case "subtitle" -> target.connection.send(new ClientboundSetSubtitleTextPacket(text));
|
||||
case "action_bar" -> target.connection.send(new ClientboundSetActionBarTextPacket(text));
|
||||
}
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] times(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 3) return fail(lua, "usage: hud.title_times(fade_in, stay, fade_out [, player])");
|
||||
Integer fadeIn = integer(args[0]), stay = integer(args[1]), fadeOut = integer(args[2]);
|
||||
if (fadeIn == null || stay == null || fadeOut == null || fadeIn < 0 || stay < 0 || fadeOut < 0) {
|
||||
return fail(lua, "title times must be non-negative whole numbers of ticks");
|
||||
}
|
||||
ServerPlayer target = player(owner, args, 3);
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
target.connection.send(new ClientboundSetTitlesAnimationPacket(fadeIn, stay, fadeOut));
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] clear(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length > 0 && args[0].type() != Lua.LuaType.NIL && args[0].type() != Lua.LuaType.BOOLEAN) return fail(lua, "reset must be true or false");
|
||||
boolean reset = args.length > 0 && args[0].type() == Lua.LuaType.BOOLEAN && args[0].toBoolean();
|
||||
ServerPlayer target = player(owner, args, 1);
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
target.connection.send(new ClientboundClearTitlesPacket(reset));
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] bossbar(Lua lua, ServerPlayer owner, LuaValue[] args, String operation) {
|
||||
String usage = switch (operation) {
|
||||
case "add" -> "hud.bossbar_add(id, name [, max [, player]])";
|
||||
case "remove" -> "hud.bossbar_remove(id)";
|
||||
case "value", "max" -> "hud.bossbar_" + operation + "(id, value)";
|
||||
default -> "hud.bossbar_visible(id, visible [, player])";
|
||||
};
|
||||
if (args.length < (operation.equals("remove") ? 1 : 2) || args[0].type() != Lua.LuaType.STRING) return fail(lua, "usage: " + usage);
|
||||
Identifier id = Identifier.tryParse(args[0].toString().indexOf(':') < 0 ? "codecraft:" + args[0] : args[0].toString());
|
||||
if (id == null) return fail(lua, "boss bar id must be a valid resource id");
|
||||
var bossbars = owner.level().getServer().getCustomBossEvents();
|
||||
CustomBossEvent event = bossbars.get(id);
|
||||
switch (operation) {
|
||||
case "add" -> {
|
||||
if (args[1].type() != Lua.LuaType.STRING) return fail(lua, "boss bar name must be a string");
|
||||
if (args.length > 2 && args[2].type() != Lua.LuaType.NIL && args[2].type() != Lua.LuaType.NUMBER) return fail(lua, "max must be a number");
|
||||
int max = args.length > 2 && args[2].type() != Lua.LuaType.NIL ? safeInteger(args[2]) : 100;
|
||||
if (max < 1 || max > 1_000_000) return fail(lua, "boss bar max must be between 1 and 1000000");
|
||||
if (event != null) return fail(lua, "boss bar already exists");
|
||||
ServerPlayer target = player(owner, args, 3);
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
event = bossbars.create(owner.getRandom(), id, Component.literal(args[1].toString()));
|
||||
event.setMax(max);
|
||||
event.addPlayer(target);
|
||||
return success(lua);
|
||||
}
|
||||
case "remove" -> {
|
||||
if (event == null) return fail(lua, "boss bar not found");
|
||||
bossbars.remove(event);
|
||||
return success(lua);
|
||||
}
|
||||
case "value", "max" -> {
|
||||
if (event == null) return fail(lua, "boss bar not found");
|
||||
int value = safeInteger(args[1]);
|
||||
if (value < 0 || value > 1_000_000) return fail(lua, "boss bar value must be between 0 and 1000000");
|
||||
if (operation.equals("value")) {
|
||||
if (value > event.max()) return fail(lua, "boss bar value cannot exceed its max");
|
||||
event.setValue(value);
|
||||
} else {
|
||||
if (value < 1) return fail(lua, "boss bar max must be at least 1");
|
||||
event.setMax(value);
|
||||
if (event.value() > value) event.setValue(value);
|
||||
}
|
||||
return success(lua);
|
||||
}
|
||||
case "visible" -> {
|
||||
if (args[1].type() != Lua.LuaType.BOOLEAN) return fail(lua, "visible must be true or false");
|
||||
if (event == null) return fail(lua, "boss bar not found");
|
||||
ServerPlayer target = player(owner, args, 2);
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
if (args[1].toBoolean()) event.addPlayer(target); else event.removePlayer(target);
|
||||
return success(lua);
|
||||
}
|
||||
default -> { return fail(lua, "unknown boss bar operation"); }
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer integer(LuaValue value) {
|
||||
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
|
||||
long number = value.toInteger();
|
||||
return number < Integer.MIN_VALUE || number > Integer.MAX_VALUE ? null : (int) number;
|
||||
}
|
||||
private static ServerPlayer player(ServerPlayer owner, LuaValue[] args, int index) {
|
||||
if (args.length <= index || args[index].type() == Lua.LuaType.NIL) return owner;
|
||||
if (args[index].type() != Lua.LuaType.STRING) return null;
|
||||
return owner.level().getServer().getPlayerList().getPlayerByName(args[index].toString());
|
||||
}
|
||||
private static int safeInteger(LuaValue value) { Integer n = integer(value); return n == null ? -1 : n; }
|
||||
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)}; }
|
||||
}
|
||||
133
src/main/java/com/aranroig/wrapper/ItemApi.java
Normal file
133
src/main/java/com/aranroig/wrapper/ItemApi.java
Normal file
@@ -0,0 +1,133 @@
|
||||
package com.aranroig.wrapper;
|
||||
|
||||
import net.minecraft.core.NonNullList;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
/** Item registry and online player inventory helpers. */
|
||||
public final class ItemApi {
|
||||
private ItemApi() {
|
||||
}
|
||||
|
||||
public static void register(Lua lua, ServerPlayer owner) {
|
||||
lua.newTable();
|
||||
int table = lua.getTop();
|
||||
lua.push((L, args) -> give(L, owner, args)); lua.setField(table, "give");
|
||||
lua.push((L, args) -> count(L, owner, args)); lua.setField(table, "count");
|
||||
lua.push((L, args) -> clear(L, owner, args)); lua.setField(table, "clear");
|
||||
lua.push((L, args) -> getSlot(L, owner, args)); lua.setField(table, "get_slot");
|
||||
lua.push((L, args) -> setSlot(L, owner, args)); lua.setField(table, "set_slot");
|
||||
lua.setGlobal("items");
|
||||
}
|
||||
|
||||
private static LuaValue[] give(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 2 || !string(args[0])) return fail(lua, "usage: items.give(item, count [, player])");
|
||||
Item item = item(args[0].toString());
|
||||
Integer count = integer(args[1]);
|
||||
ServerPlayer target = player(owner, args, 2);
|
||||
if (item == null) return fail(lua, "unknown item id");
|
||||
if (count == null || count < 1 || count > 2304) return fail(lua, "count must be between 1 and 2304");
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
ItemStack stack = new ItemStack(item, count);
|
||||
target.getInventory().add(stack);
|
||||
if (!stack.isEmpty()) target.drop(stack, false);
|
||||
target.containerMenu.broadcastChanges();
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] count(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: items.count(item [, player])");
|
||||
Item item = item(args[0].toString());
|
||||
ServerPlayer target = player(owner, args, 1);
|
||||
if (item == null) return fail(lua, "unknown item id");
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
int total = 0;
|
||||
Inventory inventory = target.getInventory();
|
||||
for (ItemStack stack : inventory.getNonEquipmentItems()) {
|
||||
if (!stack.isEmpty() && stack.getItem() == item) total += stack.getCount();
|
||||
}
|
||||
return new LuaValue[]{lua.from((long) total)};
|
||||
}
|
||||
|
||||
private static LuaValue[] clear(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: items.clear(item [, player])");
|
||||
Item item = item(args[0].toString());
|
||||
ServerPlayer target = player(owner, args, 1);
|
||||
if (item == null) return fail(lua, "unknown item id");
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
int removed = 0;
|
||||
Inventory inventory = target.getInventory();
|
||||
for (ItemStack stack : inventory.getNonEquipmentItems()) {
|
||||
if (!stack.isEmpty() && stack.getItem() == item) {
|
||||
removed += stack.getCount();
|
||||
stack.setCount(0);
|
||||
}
|
||||
}
|
||||
inventory.setChanged();
|
||||
target.containerMenu.broadcastChanges();
|
||||
return new LuaValue[]{lua.from(true), lua.from((long) removed)};
|
||||
}
|
||||
|
||||
private static LuaValue[] getSlot(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 1) return fail(lua, "usage: items.get_slot(slot [, player])");
|
||||
Integer slot = integer(args[0]);
|
||||
ServerPlayer target = player(owner, args, 1);
|
||||
if (slot == null || slot < 0 || slot >= 36) return fail(lua, "slot must be between 0 and 35");
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
ItemStack stack = target.getInventory().getNonEquipmentItems().get(slot);
|
||||
if (stack.isEmpty()) return new LuaValue[]{lua.fromNull()};
|
||||
return new LuaValue[]{lua.from(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString()), lua.from((long) stack.getCount())};
|
||||
}
|
||||
|
||||
private static LuaValue[] setSlot(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 3 || !string(args[1])) return fail(lua, "usage: items.set_slot(slot, item, count [, player])");
|
||||
Integer slot = integer(args[0]), count = integer(args[2]);
|
||||
ServerPlayer target = player(owner, args, 3);
|
||||
if (slot == null || slot < 0 || slot >= 36) return fail(lua, "slot must be between 0 and 35");
|
||||
if (count == null || count < 0 || count > 99) return fail(lua, "count must be between 0 and 99");
|
||||
if (target == null) return fail(lua, "player is not online");
|
||||
Inventory inventory = target.getInventory();
|
||||
NonNullList<ItemStack> slots = inventory.getNonEquipmentItems();
|
||||
if (count == 0) {
|
||||
slots.set(slot, ItemStack.EMPTY);
|
||||
} else {
|
||||
Item item = item(args[1].toString());
|
||||
if (item == null) return fail(lua, "unknown item id");
|
||||
if (count > item.getDefaultMaxStackSize()) {
|
||||
return fail(lua, "count exceeds this item's stack size");
|
||||
}
|
||||
slots.set(slot, new ItemStack(item, count));
|
||||
}
|
||||
inventory.setChanged();
|
||||
target.containerMenu.broadcastChanges();
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static ServerPlayer player(ServerPlayer owner, LuaValue[] args, int index) {
|
||||
if (args.length <= index || args[index].type() == Lua.LuaType.NIL) return owner;
|
||||
if (!string(args[index])) return null;
|
||||
return owner.level().getServer().getPlayerList().getPlayerByName(args[index].toString());
|
||||
}
|
||||
|
||||
private static Item item(String input) {
|
||||
Identifier id = Identifier.tryParse(input.indexOf(':') < 0 ? "minecraft:" + input : input);
|
||||
Item item = id == null ? null : BuiltInRegistries.ITEM.getOptional(id).orElse(null);
|
||||
return item == Items.AIR ? null : item;
|
||||
}
|
||||
|
||||
private static Integer integer(LuaValue value) {
|
||||
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
|
||||
long number = value.toInteger();
|
||||
return number < Integer.MIN_VALUE || number > Integer.MAX_VALUE ? null : (int) number;
|
||||
}
|
||||
private static boolean string(LuaValue value) { return value != null && value.type() == Lua.LuaType.STRING; }
|
||||
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)}; }
|
||||
}
|
||||
23
src/main/java/com/aranroig/wrapper/LuaTables.java
Normal file
23
src/main/java/com/aranroig/wrapper/LuaTables.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.aranroig.wrapper;
|
||||
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaTableValue;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/** Small helpers for returning ordinary Lua tables from Java callbacks. */
|
||||
final class LuaTables {
|
||||
private LuaTables() {
|
||||
}
|
||||
|
||||
static LuaValue array(Lua lua, Collection<?> values) {
|
||||
lua.newTable();
|
||||
LuaTableValue table = new LuaTableValue(lua, Lua.LuaType.TABLE);
|
||||
int index = 1;
|
||||
for (Object value : values) {
|
||||
table.set(index++, value);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
124
src/main/java/com/aranroig/wrapper/ScoreboardApi.java
Normal file
124
src/main/java/com/aranroig/wrapper/ScoreboardApi.java
Normal file
@@ -0,0 +1,124 @@
|
||||
package com.aranroig.wrapper;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.scores.DisplaySlot;
|
||||
import net.minecraft.world.scores.Objective;
|
||||
import net.minecraft.world.scores.ScoreHolder;
|
||||
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
|
||||
import net.minecraft.world.scores.criteria.ObjectiveCriteria.RenderType;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Objective and score operations for the server scoreboard. */
|
||||
public final class ScoreboardApi {
|
||||
private static final Pattern OBJECTIVE_NAME = Pattern.compile("[A-Za-z0-9_.+-]{1,16}");
|
||||
|
||||
private ScoreboardApi() {
|
||||
}
|
||||
|
||||
public static void register(Lua lua, ServerPlayer owner) {
|
||||
lua.newTable();
|
||||
int table = lua.getTop();
|
||||
lua.push((L, args) -> create(L, owner, args)); lua.setField(table, "create_objective");
|
||||
lua.push((L, args) -> remove(L, owner, args)); lua.setField(table, "remove_objective");
|
||||
lua.push((L, args) -> set(L, owner, args, false)); lua.setField(table, "set");
|
||||
lua.push((L, args) -> set(L, owner, args, true)); lua.setField(table, "add");
|
||||
lua.push((L, args) -> get(L, owner, args)); lua.setField(table, "get");
|
||||
lua.push((L, args) -> reset(L, owner, args)); lua.setField(table, "reset");
|
||||
lua.push((L, args) -> display(L, owner, args)); lua.setField(table, "display");
|
||||
lua.setGlobal("scoreboard");
|
||||
}
|
||||
|
||||
private static LuaValue[] create(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: scoreboard.create_objective(name [, criterion [, display_name]])");
|
||||
String name = args[0].toString();
|
||||
if (!OBJECTIVE_NAME.matcher(name).matches()) return fail(lua, "objective name must be 1 to 16 letters, numbers, dots, underscores, pluses or hyphens");
|
||||
var scoreboard = owner.level().getServer().getScoreboard();
|
||||
if (scoreboard.getObjective(name) != null) return fail(lua, "objective already exists");
|
||||
if (args.length > 1 && !string(args[1])) return fail(lua, "criterion must be a string");
|
||||
if (args.length > 2 && !string(args[2])) return fail(lua, "display name must be a string");
|
||||
String criterionName = args.length > 1 && string(args[1]) ? args[1].toString() : "dummy";
|
||||
ObjectiveCriteria criteria = ObjectiveCriteria.byName(criterionName).orElse(null);
|
||||
if (criteria == null) return fail(lua, "unknown scoreboard criterion");
|
||||
String display = args.length > 2 && string(args[2]) ? args[2].toString() : name;
|
||||
scoreboard.addObjective(name, criteria, Component.literal(display), criteria.getDefaultRenderType(), false, null);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] remove(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
Objective objective = objective(owner, args);
|
||||
if (objective == null) return fail(lua, "objective not found");
|
||||
owner.level().getServer().getScoreboard().removeObjective(objective);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] set(Lua lua, ServerPlayer owner, LuaValue[] args, boolean add) {
|
||||
if (args.length < 3 || !string(args[0]) || !string(args[1])) return fail(lua, "usage: scoreboard." + (add ? "add" : "set") + "(player, objective, value)");
|
||||
Integer value = integer(args[2]);
|
||||
if (value == null) return fail(lua, "score must be an integer");
|
||||
Objective objective = owner.level().getServer().getScoreboard().getObjective(args[1].toString());
|
||||
if (objective == null) return fail(lua, "objective not found");
|
||||
var score = owner.level().getServer().getScoreboard().getOrCreatePlayerScore(ScoreHolder.forNameOnly(args[0].toString()), objective);
|
||||
if (add) score.add(value); else score.set(value);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] get(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 2 || !string(args[0]) || !string(args[1])) return fail(lua, "usage: scoreboard.get(player, objective)");
|
||||
Objective objective = owner.level().getServer().getScoreboard().getObjective(args[1].toString());
|
||||
if (objective == null) return new LuaValue[]{lua.fromNull(), lua.from("objective not found")};
|
||||
var score = owner.level().getServer().getScoreboard().getPlayerScoreInfo(ScoreHolder.forNameOnly(args[0].toString()), objective);
|
||||
return score == null ? new LuaValue[]{lua.fromNull()} : new LuaValue[]{lua.from((long) score.value())};
|
||||
}
|
||||
|
||||
private static LuaValue[] reset(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: scoreboard.reset(player [, objective])");
|
||||
var scoreboard = owner.level().getServer().getScoreboard();
|
||||
ScoreHolder player = ScoreHolder.forNameOnly(args[0].toString());
|
||||
if (args.length < 2 || args[1].type() == Lua.LuaType.NIL) {
|
||||
scoreboard.resetAllPlayerScores(player);
|
||||
return success(lua);
|
||||
}
|
||||
if (!string(args[1])) return fail(lua, "objective must be a string");
|
||||
Objective objective = scoreboard.getObjective(args[1].toString());
|
||||
if (objective == null) return fail(lua, "objective not found");
|
||||
scoreboard.resetSinglePlayerScore(player, objective);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] display(Lua lua, ServerPlayer owner, LuaValue[] args) {
|
||||
if (args.length < 2 || !string(args[0]) || !string(args[1])) return fail(lua, "usage: scoreboard.display(objective, slot)");
|
||||
Objective objective = owner.level().getServer().getScoreboard().getObjective(args[0].toString());
|
||||
if (objective == null) return fail(lua, "objective not found");
|
||||
DisplaySlot slot = slot(args[1].toString());
|
||||
if (slot == null) return fail(lua, "slot must be list, sidebar, or below_name");
|
||||
owner.level().getServer().getScoreboard().setDisplayObjective(slot, objective);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static Objective objective(ServerPlayer owner, LuaValue[] args) {
|
||||
return args.length > 0 && string(args[0]) ? owner.level().getServer().getScoreboard().getObjective(args[0].toString()) : null;
|
||||
}
|
||||
|
||||
private static DisplaySlot slot(String raw) {
|
||||
return switch (raw.toLowerCase(Locale.ROOT)) {
|
||||
case "list" -> DisplaySlot.LIST;
|
||||
case "sidebar" -> DisplaySlot.SIDEBAR;
|
||||
case "below_name" -> DisplaySlot.BELOW_NAME;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean string(LuaValue value) { return value != null && value.type() == Lua.LuaType.STRING; }
|
||||
private static Integer integer(LuaValue value) {
|
||||
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
|
||||
long n = value.toInteger();
|
||||
return n < Integer.MIN_VALUE || n > Integer.MAX_VALUE ? null : (int) n;
|
||||
}
|
||||
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)}; }
|
||||
}
|
||||
46
src/main/java/com/aranroig/wrapper/ServerCommandApi.java
Normal file
46
src/main/java/com/aranroig/wrapper/ServerCommandApi.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package com.aranroig.wrapper;
|
||||
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
/**
|
||||
* Registers the server command helper exposed to Lua scripts.
|
||||
* Commands use the server source (without a player or position), including its
|
||||
* full command permissions.
|
||||
*/
|
||||
public final class ServerCommandApi {
|
||||
|
||||
private ServerCommandApi() {
|
||||
}
|
||||
|
||||
/** Registers the global {@code run(command)} function. */
|
||||
public static void register(Lua lua, ServerPlayer player) {
|
||||
lua.push((L, args) -> execute(L, player, args));
|
||||
lua.setGlobal("run");
|
||||
}
|
||||
|
||||
private static LuaValue[] execute(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
if (args.length < 1 || args[0].type() != Lua.LuaType.STRING) {
|
||||
return fail(lua, "usage: run(\"command\")");
|
||||
}
|
||||
|
||||
String command = args[0].toString().trim();
|
||||
if (command.isEmpty()) {
|
||||
return fail(lua, "command cannot be empty");
|
||||
}
|
||||
|
||||
runCommand(player, command);
|
||||
return new LuaValue[]{ lua.from(true) };
|
||||
}
|
||||
|
||||
/** Executes a command from the server source for wrapper APIs that need a vanilla command. */
|
||||
static void runCommand(ServerPlayer player, String command) {
|
||||
var server = player.level().getServer();
|
||||
server.getCommands().performPrefixedCommand(server.createCommandSourceStack(), command);
|
||||
}
|
||||
|
||||
private static LuaValue[] fail(Lua lua, String reason) {
|
||||
return new LuaValue[]{ lua.from(false), lua.from(reason) };
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,10 @@ import net.minecraft.world.level.block.state.BlockState;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* The {@code world} table given to user scripts: placing, removing and reading blocks.
|
||||
* The {@code world} table given to user scripts: block access and basic world state.
|
||||
*
|
||||
* <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
|
||||
@@ -50,6 +52,27 @@ public class WorldApi {
|
||||
lua.push((L, args) -> getBlock(L, player, args));
|
||||
lua.setField(world, "get_block");
|
||||
|
||||
lua.push((L, args) -> getDimension(L, player, args));
|
||||
lua.setField(world, "get_dimension");
|
||||
|
||||
lua.push((L, args) -> getTime(L, player, args));
|
||||
lua.setField(world, "get_time");
|
||||
|
||||
lua.push((L, args) -> setTime(L, player, args));
|
||||
lua.setField(world, "set_time");
|
||||
|
||||
lua.push((L, args) -> getWeather(L, player, args));
|
||||
lua.setField(world, "get_weather");
|
||||
|
||||
lua.push((L, args) -> setWeather(L, player, args));
|
||||
lua.setField(world, "set_weather");
|
||||
|
||||
lua.push((L, args) -> getBiome(L, player, args));
|
||||
lua.setField(world, "get_biome");
|
||||
|
||||
lua.push((L, args) -> players(L, player, args));
|
||||
lua.setField(world, "players");
|
||||
|
||||
lua.setGlobal("world");
|
||||
}
|
||||
|
||||
@@ -161,6 +184,59 @@ public class WorldApi {
|
||||
return new LuaValue[]{ lua.from(BlockStateParser.serialize(level.getBlockState(pos))) };
|
||||
}
|
||||
|
||||
private static LuaValue[] getDimension(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
return new LuaValue[]{lua.from(player.level().dimension().identifier().toString())};
|
||||
}
|
||||
|
||||
private static LuaValue[] getTime(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
return new LuaValue[]{lua.from(player.level().getOverworldClockTime())};
|
||||
}
|
||||
|
||||
private static LuaValue[] setTime(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
long ticks = args.length > 0 ? longNumber(args[0]) : -1;
|
||||
if (ticks < 0 || ticks > Integer.MAX_VALUE) {
|
||||
return fail(lua, "ticks must be between 0 and 2147483647");
|
||||
}
|
||||
ServerCommandApi.runCommand(player, "time set " + ticks);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] getWeather(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
String weather = player.level().isThundering() ? "thunder" : player.level().isRaining() ? "rain" : "clear";
|
||||
return new LuaValue[]{lua.from(weather)};
|
||||
}
|
||||
|
||||
private static LuaValue[] setWeather(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
if (args.length < 1 || args[0].type() != Lua.LuaType.STRING) {
|
||||
return fail(lua, "usage: world.set_weather(\"clear\" | \"rain\" | \"thunder\" [, duration])");
|
||||
}
|
||||
String weather = args[0].toString();
|
||||
if (!weather.equals("clear") && !weather.equals("rain") && !weather.equals("thunder")) {
|
||||
return fail(lua, "weather must be clear, rain or thunder");
|
||||
}
|
||||
long duration = args.length > 1 ? longNumber(args[1]) : 6000L;
|
||||
if (duration < 1 || duration > 1_000_000_000L) return fail(lua, "duration must be between 1 and 1000000000 ticks");
|
||||
ServerCommandApi.runCommand(player, "weather " + weather + " " + duration);
|
||||
return success(lua);
|
||||
}
|
||||
|
||||
private static LuaValue[] getBiome(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
if (args.length < 3) return missing(lua, "usage: world.get_biome(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);
|
||||
String biome = level.getBiome(pos).unwrapKey().map(key -> key.identifier().toString()).orElse("unknown");
|
||||
return new LuaValue[]{lua.from(biome)};
|
||||
}
|
||||
|
||||
private static LuaValue[] players(Lua lua, ServerPlayer player, LuaValue[] args) {
|
||||
ArrayList<String> names = new ArrayList<>();
|
||||
player.level().getServer().getPlayerList().getPlayers().forEach(serverPlayer -> names.add(serverPlayer.getScoreboardName()));
|
||||
return new LuaValue[]{LuaTables.array(lua, names)};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads {@code x}, {@code y} and {@code z} from the first three arguments.
|
||||
*
|
||||
@@ -188,6 +264,12 @@ public class WorldApi {
|
||||
}
|
||||
}
|
||||
|
||||
private static long longNumber(LuaValue value) {
|
||||
if (value == null || value.type() != Lua.LuaType.NUMBER) return -1;
|
||||
long n = value.toInteger();
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Precondition shared by the three functions.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user