leejunyoung5819mc-paper-plugin-test-mcp-26.3

공개

마인크래프트 26.3 Paper 서버의 플러그인 테스트를 하려는 AI 에이전트를 위한 MCP 도구

794줄28 KB
1package dev.mctester.bridge;
2
3import com.google.gson.JsonArray;
4import com.google.gson.JsonElement;
5import com.google.gson.JsonObject;
6import com.mojang.blaze3d.platform.NativeImage;
7import com.mojang.blaze3d.platform.Window;
8import dev.mctester.bridge.mixin.AbstractContainerScreenAccessor;
9import dev.mctester.bridge.mixin.KeyMappingAccessor;
10import net.minecraft.client.KeyMapping;
11import net.minecraft.client.Minecraft;
12import net.minecraft.client.Screenshot;
13import net.minecraft.client.gui.components.AbstractWidget;
14import net.minecraft.client.gui.components.EditBox;
15import net.minecraft.client.gui.components.events.ContainerEventHandler;
16import net.minecraft.client.gui.components.events.GuiEventListener;
17import net.minecraft.client.gui.screens.ConnectScreen;
18import net.minecraft.client.gui.screens.Screen;
19import net.minecraft.client.gui.screens.TitleScreen;
20import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
21import net.minecraft.client.input.KeyEvent;
22import net.minecraft.client.input.MouseButtonInfo;
23import net.minecraft.client.multiplayer.ClientLevel;
24import net.minecraft.client.multiplayer.ServerData;
25import net.minecraft.client.multiplayer.resolver.ServerAddress;
26import net.minecraft.client.player.LocalPlayer;
27import net.minecraft.core.BlockPos;
28import net.minecraft.core.component.DataComponents;
29import net.minecraft.core.registries.BuiltInRegistries;
30import net.minecraft.network.chat.Component;
31import net.minecraft.world.entity.Entity;
32import net.minecraft.world.entity.LivingEntity;
33import net.minecraft.world.entity.player.Inventory;
34import net.minecraft.world.inventory.AbstractContainerMenu;
35import net.minecraft.world.inventory.ContainerInput;
36import net.minecraft.world.inventory.Slot;
37import net.minecraft.world.item.Item;
38import net.minecraft.world.item.ItemStack;
39import net.minecraft.world.item.TooltipFlag;
40import net.minecraft.world.item.component.ItemLore;
41import net.minecraft.world.phys.AABB;
42import net.minecraft.world.phys.BlockHitResult;
43import net.minecraft.world.phys.EntityHitResult;
44import net.minecraft.world.phys.HitResult;
45import net.minecraft.world.phys.Vec3;
46
47import java.io.File;
48import java.util.ArrayList;
49import java.util.List;
50import java.util.Locale;
51import java.util.concurrent.CompletableFuture;
52import java.util.concurrent.TimeUnit;
53import java.util.function.Supplier;
54
55/**
56 * All bridge operations. Anything touching game state runs on the client thread via {@link #onClient}.
57 * Input is injected through the same handlers SDLEventHandler calls (MouseHandler.onButton,
58 * KeyboardHandler.keyPress/textInput) or through KeyMapping clicks, so the client behaves as if
59 * a human pressed the button; container clicks go through MultiPlayerGameMode.handleContainerInput,
60 * which is what AbstractContainerScreen itself calls and sends the same packet.
61 */
62final class Actions {
63 private Actions() {}
64
65 // ------------------------------------------------------------------ helpers
66
67 static JsonObject ok() {
68 JsonObject o = new JsonObject();
69 o.addProperty("ok", true);
70 return o;
71 }
72
73 static JsonObject err(String msg) {
74 JsonObject o = new JsonObject();
75 o.addProperty("ok", false);
76 o.addProperty("error", msg);
77 return o;
78 }
79
80 private static Minecraft mc() {
81 return Minecraft.getInstance();
82 }
83
84 static <T> T onClient(Supplier<T> s) {
85 return await(onClientAsync(s), 10_000);
86 }
87
88 static <T> CompletableFuture<T> onClientAsync(Supplier<T> s) {
89 CompletableFuture<T> f = new CompletableFuture<>();
90 mc().execute(() -> {
91 try {
92 f.complete(s.get());
93 } catch (Throwable t) {
94 f.completeExceptionally(t);
95 }
96 });
97 return f;
98 }
99
100 static <T> T await(CompletableFuture<T> f, long ms) {
101 try {
102 return f.get(ms, TimeUnit.MILLISECONDS);
103 } catch (java.util.concurrent.ExecutionException e) {
104 Throwable c = e.getCause();
105 if (c instanceof RuntimeException re) throw re;
106 throw new RuntimeException(c);
107 } catch (java.util.concurrent.TimeoutException e) {
108 throw new BridgeException("timed out after " + ms + "ms waiting for the client thread");
109 } catch (InterruptedException e) {
110 Thread.currentThread().interrupt();
111 throw new RuntimeException(e);
112 }
113 }
114
115 private static LocalPlayer player() {
116 LocalPlayer p = mc().player;
117 if (p == null) throw new BridgeException("not in a world (player is null); connect first");
118 return p;
119 }
120
121 private static String str(JsonObject in, String k, String def) {
122 JsonElement e = in.get(k);
123 return e == null || e.isJsonNull() ? def : e.getAsString();
124 }
125
126 private static int i(JsonObject in, String k, int def) {
127 JsonElement e = in.get(k);
128 return e == null || e.isJsonNull() ? def : (int) Double.parseDouble(e.getAsString());
129 }
130
131 private static double d(JsonObject in, String k, double def) {
132 JsonElement e = in.get(k);
133 return e == null || e.isJsonNull() ? def : Double.parseDouble(e.getAsString());
134 }
135
136 private static boolean b(JsonObject in, String k, boolean def) {
137 JsonElement e = in.get(k);
138 return e == null || e.isJsonNull() ? def : Boolean.parseBoolean(e.getAsString());
139 }
140
141 private static String id(Item item) {
142 return BuiltInRegistries.ITEM.getKey(item).toString();
143 }
144
145 static JsonElement item(ItemStack s) {
146 if (s == null || s.isEmpty()) return com.google.gson.JsonNull.INSTANCE;
147 JsonObject o = new JsonObject();
148 o.addProperty("id", id(s.getItem()));
149 o.addProperty("count", s.getCount());
150 o.addProperty("name", s.getHoverName().getString());
151 ItemLore lore = s.get(DataComponents.LORE);
152 JsonArray l = new JsonArray();
153 if (lore != null) for (Component c : lore.lines()) l.add(c.getString());
154 o.add("lore", l);
155 if (s.isDamageableItem()) {
156 o.addProperty("damage", s.getDamageValue());
157 o.addProperty("maxDamage", s.getMaxDamage());
158 }
159 if (s.isEnchanted()) o.addProperty("enchanted", true);
160 try {
161 Minecraft m = mc();
162 JsonArray tip = new JsonArray();
163 for (Component c : s.getTooltipLines(Item.TooltipContext.of(m.level), m.player, TooltipFlag.NORMAL)) tip.add(c.getString());
164 o.add("tooltip", tip);
165 } catch (Throwable t) {
166 o.addProperty("tooltipError", t.toString());
167 }
168 return o;
169 }
170
171 private static JsonObject vec(Vec3 v) {
172 JsonObject o = new JsonObject();
173 o.addProperty("x", round(v.x));
174 o.addProperty("y", round(v.y));
175 o.addProperty("z", round(v.z));
176 return o;
177 }
178
179 private static double round(double v) {
180 return Math.round(v * 100.0) / 100.0;
181 }
182
183 // ------------------------------------------------------------------ read state
184
185 static JsonObject health(JsonObject in) {
186 return onClient(() -> {
187 JsonObject o = ok();
188 Minecraft m = mc();
189 o.addProperty("inWorld", m.player != null);
190 o.addProperty("player", m.getUser().getName());
191 o.addProperty("tick", Ticks.now());
192 Screen s = m.gui.screen();
193 o.addProperty("screen", s == null ? null : s.getClass().getSimpleName());
194 return o;
195 });
196 }
197
198 static JsonObject state(JsonObject in) {
199 return onClient(() -> {
200 Minecraft m = mc();
201 JsonObject o = ok();
202 o.addProperty("user", m.getUser().getName());
203 o.addProperty("inWorld", m.player != null);
204 ServerData sd = m.getCurrentServer();
205 if (sd != null) o.addProperty("server", sd.ip);
206 o.addProperty("fps", m.getFps());
207 Screen s = m.gui.screen();
208 JsonObject scr = new JsonObject();
209 scr.addProperty("open", s != null);
210 if (s != null) {
211 scr.addProperty("class", s.getClass().getSimpleName());
212 scr.addProperty("title", s.getTitle().getString());
213 }
214 o.add("screen", scr);
215 LocalPlayer p = m.player;
216 if (p == null) return o;
217 JsonObject pl = new JsonObject();
218 pl.addProperty("name", p.getName().getString());
219 pl.addProperty("uuid", p.getUUID().toString());
220 pl.add("pos", vec(p.position()));
221 pl.addProperty("yaw", round(p.getYRot()));
222 pl.addProperty("pitch", round(p.getXRot()));
223 pl.addProperty("health", p.getHealth());
224 pl.addProperty("food", p.getFoodData().getFoodLevel());
225 pl.addProperty("xpLevel", p.experienceLevel);
226 pl.addProperty("gameMode", m.gameMode == null ? null : m.gameMode.getPlayerMode().getName());
227 pl.addProperty("dimension", p.level().dimension().identifier().toString());
228 Inventory inv = p.getInventory();
229 pl.addProperty("selectedSlot", inv.getSelectedSlot());
230 JsonArray items = new JsonArray();
231 for (int k = 0; k < inv.getContainerSize(); k++) {
232 ItemStack st = inv.getItem(k);
233 if (st.isEmpty()) continue;
234 JsonObject e = new JsonObject();
235 e.addProperty("slot", k);
236 e.add("item", item(st));
237 items.add(e);
238 }
239 pl.add("inventory", items);
240 o.add("player", pl);
241 o.add("target", hit(m.hitResult));
242 return o;
243 });
244 }
245
246 private static JsonElement hit(HitResult h) {
247 if (h == null || h.getType() == HitResult.Type.MISS) return com.google.gson.JsonNull.INSTANCE;
248 JsonObject o = new JsonObject();
249 if (h instanceof EntityHitResult eh) {
250 o.addProperty("type", "entity");
251 o.add("entity", entity(eh.getEntity(), null));
252 } else if (h instanceof BlockHitResult bh) {
253 o.addProperty("type", "block");
254 BlockPos bp = bh.getBlockPos();
255 o.addProperty("x", bp.getX());
256 o.addProperty("y", bp.getY());
257 o.addProperty("z", bp.getZ());
258 o.addProperty("face", bh.getDirection().getName());
259 ClientLevel lvl = mc().level;
260 if (lvl != null) o.addProperty("block", BuiltInRegistries.BLOCK.getKey(lvl.getBlockState(bp).getBlock()).toString());
261 }
262 return o;
263 }
264
265 private static JsonObject entity(Entity e, Vec3 from) {
266 JsonObject o = new JsonObject();
267 o.addProperty("id", e.getId());
268 o.addProperty("uuid", e.getUUID().toString());
269 o.addProperty("type", BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()).toString());
270 o.addProperty("name", e.getName().getString());
271 Component cn = e.getCustomName();
272 if (cn != null) o.addProperty("customName", cn.getString());
273 o.add("pos", vec(e.position()));
274 if (from != null) o.addProperty("distance", round(from.distanceTo(e.position())));
275 if (e instanceof LivingEntity le) o.addProperty("health", le.getHealth());
276 return o;
277 }
278
279 static JsonObject screen(JsonObject in) {
280 return onClient(() -> {
281 Minecraft m = mc();
282 Screen s = m.gui.screen();
283 JsonObject o = ok();
284 Window w = m.getWindow();
285 o.addProperty("guiWidth", w.getGuiScaledWidth());
286 o.addProperty("guiHeight", w.getGuiScaledHeight());
287 o.addProperty("guiScale", w.getGuiScale());
288 o.addProperty("open", s != null);
289 if (s == null) return o;
290 o.addProperty("class", s.getClass().getSimpleName());
291 o.addProperty("title", s.getTitle().getString());
292 if (s instanceof AbstractContainerScreen<?> cs) {
293 AbstractContainerMenu menu = cs.getMenu();
294 AbstractContainerScreenAccessor acc = (AbstractContainerScreenAccessor) cs;
295 o.addProperty("container", true);
296 o.addProperty("containerId", menu.containerId);
297 try {
298 o.addProperty("menuType", BuiltInRegistries.MENU.getKey(menu.getType()).toString());
299 } catch (UnsupportedOperationException ignored) {
300 o.addProperty("menuType", "minecraft:player_inventory");
301 }
302 int containerSlots = 0;
303 JsonArray slots = new JsonArray();
304 boolean onlyItems = !b(in, "includeEmpty", false);
305 for (Slot sl : menu.slots) {
306 boolean isPlayer = sl.container instanceof Inventory;
307 if (!isPlayer) containerSlots++;
308 ItemStack st = sl.getItem();
309 if (onlyItems && st.isEmpty()) continue;
310 JsonObject e = new JsonObject();
311 e.addProperty("slot", sl.index);
312 e.addProperty("area", isPlayer ? "player" : "container");
313 e.addProperty("containerSlot", sl.getContainerSlot());
314 e.addProperty("x", acc.qa$leftPos() + sl.x + 8);
315 e.addProperty("y", acc.qa$topPos() + sl.y + 8);
316 e.add("item", item(st));
317 slots.add(e);
318 }
319 o.addProperty("containerSlotCount", containerSlots);
320 o.addProperty("totalSlotCount", menu.slots.size());
321 o.add("slots", slots);
322 o.add("carried", item(menu.getCarried()));
323 Slot hov = acc.qa$hoveredSlot();
324 if (hov != null) o.addProperty("hoveredSlot", hov.index);
325 } else {
326 o.addProperty("container", false);
327 }
328 JsonArray widgets = new JsonArray();
329 collectWidgets(s.children(), widgets, 0);
330 o.add("widgets", widgets);
331 return o;
332 });
333 }
334
335 private static void collectWidgets(List<? extends GuiEventListener> children, JsonArray out, int depth) {
336 if (depth > 8) return;
337 for (GuiEventListener l : children) {
338 if (l instanceof AbstractWidget w) {
339 if (!w.visible) continue;
340 JsonObject o = new JsonObject();
341 o.addProperty("index", out.size());
342 o.addProperty("type", w.getClass().getSimpleName());
343 o.addProperty("label", w.getMessage().getString());
344 o.addProperty("x", w.getX());
345 o.addProperty("y", w.getY());
346 o.addProperty("w", w.getWidth());
347 o.addProperty("h", w.getHeight());
348 o.addProperty("cx", w.getX() + w.getWidth() / 2);
349 o.addProperty("cy", w.getY() + w.getHeight() / 2);
350 o.addProperty("active", w.active);
351 o.addProperty("focused", w.isFocused());
352 if (w instanceof EditBox eb) o.addProperty("value", eb.getValue());
353 out.add(o);
354 }
355 if (l instanceof ContainerEventHandler c) collectWidgets(c.children(), out, depth + 1);
356 }
357 }
358
359 static JsonObject chatLog(JsonObject in) {
360 JsonObject o = ChatLog.since(Long.parseLong(str(in, "since", "0")));
361 o.addProperty("ok", true);
362 return o;
363 }
364
365 static JsonObject entities(JsonObject in) {
366 double radius = d(in, "radius", 16);
367 String nameFilter = str(in, "name", null);
368 return onClient(() -> {
369 LocalPlayer p = player();
370 Vec3 from = p.position();
371 List<Entity> list = new ArrayList<>();
372 for (Entity e : mc().level.entitiesForRendering()) {
373 if (e == p) continue;
374 if (e.position().distanceTo(from) > radius) continue;
375 if (nameFilter != null && !e.getName().getString().contains(nameFilter)) continue;
376 list.add(e);
377 }
378 list.sort((a, c) -> Double.compare(a.position().distanceTo(from), c.position().distanceTo(from)));
379 JsonArray arr = new JsonArray();
380 for (Entity e : list) arr.add(entity(e, from));
381 JsonObject o = ok();
382 o.add("entities", arr);
383 return o;
384 });
385 }
386
387 // ------------------------------------------------------------------ screenshot
388
389 static JsonObject screenshot(JsonObject in) {
390 String path = str(in, "path", null);
391 if (path == null) throw new BridgeException("path is required (absolute .png path)");
392 File file = new File(path);
393 File parent = file.getParentFile();
394 if (parent != null) parent.mkdirs();
395 CompletableFuture<JsonObject> done = new CompletableFuture<>();
396 mc().execute(() -> {
397 try {
398 Screenshot.takeScreenshot(mc().gameRenderer.mainRenderTarget(), (NativeImage image) -> {
399 try (image) {
400 int w = image.getWidth();
401 int h = image.getHeight();
402 image.writeToFile(file);
403 JsonObject o = ok();
404 o.addProperty("path", file.getAbsolutePath());
405 o.addProperty("width", w);
406 o.addProperty("height", h);
407 done.complete(o);
408 } catch (Throwable t) {
409 done.completeExceptionally(t);
410 }
411 });
412 } catch (Throwable t) {
413 done.completeExceptionally(t);
414 }
415 });
416 return await(done, 15_000);
417 }
418
419 // ------------------------------------------------------------------ container clicks
420
421 static JsonObject clickSlot(JsonObject in) {
422 int slot = i(in, "slot", Integer.MIN_VALUE);
423 if (slot == Integer.MIN_VALUE) throw new BridgeException("slot is required (menu slot index from /screen, or -999 for outside)");
424 int button = i(in, "button", 0);
425 String modeName = str(in, "mode", "PICKUP").toUpperCase(Locale.ROOT);
426 ContainerInput mode;
427 try {
428 mode = ContainerInput.valueOf(modeName);
429 } catch (IllegalArgumentException e) {
430 throw new BridgeException("mode must be one of PICKUP, QUICK_MOVE, SWAP, CLONE, THROW, QUICK_CRAFT, PICKUP_ALL");
431 }
432 return onClient(() -> {
433 LocalPlayer p = player();
434 Screen s = mc().gui.screen();
435 AbstractContainerMenu menu;
436 if (s instanceof AbstractContainerScreen<?> cs) {
437 menu = cs.getMenu();
438 } else if (b(in, "playerInventory", false)) {
439 menu = p.inventoryMenu;
440 } else {
441 throw new BridgeException("no container screen is open (current: " + (s == null ? "none" : s.getClass().getSimpleName()) + ")");
442 }
443 if (slot != -999 && (slot < 0 || slot >= menu.slots.size()))
444 throw new BridgeException("slot " + slot + " out of range 0.." + (menu.slots.size() - 1));
445 mc().gameMode.handleContainerInput(menu.containerId, slot, button, mode, p);
446 JsonObject o = ok();
447 o.addProperty("containerId", menu.containerId);
448 o.addProperty("slot", slot);
449 o.addProperty("button", button);
450 o.addProperty("mode", mode.name());
451 return o;
452 });
453 }
454
455 // ------------------------------------------------------------------ raw input
456
457 private static int mouseButton(String name) {
458 return switch (name.toLowerCase(Locale.ROOT)) {
459 case "left", "1" -> 1;
460 case "middle", "2" -> 2;
461 case "right", "3" -> 3;
462 default -> throw new BridgeException("button must be left|middle|right");
463 };
464 }
465
466 /** Mouse at GUI-scaled coordinates (same space as /screen x,y). Only while a screen is open. */
467 static JsonObject mouse(JsonObject in) {
468 double gx = d(in, "x", Double.NaN);
469 double gy = d(in, "y", Double.NaN);
470 if (Double.isNaN(gx) || Double.isNaN(gy)) throw new BridgeException("x and y (GUI coordinates) are required");
471 int button = mouseButton(str(in, "button", "left"));
472 String action = str(in, "action", "click");
473 int mods = Keys.mods(b(in, "shift", false), b(in, "ctrl", false), b(in, "alt", false));
474 onClient(() -> {
475 Minecraft m = mc();
476 if (m.gui.screen() == null)
477 throw new BridgeException("no screen open; use /use or /attack for in-world clicks");
478 Window w = m.getWindow();
479 long handle = w.handle();
480 double wx = gx * w.getScreenWidth() / (double) w.getGuiScaledWidth();
481 double wy = gy * w.getScreenHeight() / (double) w.getGuiScaledHeight();
482 m.mouseHandler.onMove(handle, wx, wy, 0, 0);
483 MouseButtonInfo info = new MouseButtonInfo(button, mods);
484 switch (action) {
485 case "move" -> {}
486 case "down" -> m.mouseHandler.onButton(handle, info, 1);
487 case "up" -> m.mouseHandler.onButton(handle, info, 0);
488 case "click" -> {
489 m.mouseHandler.onButton(handle, info, 1);
490 m.mouseHandler.onButton(handle, info, 0);
491 }
492 case "double" -> {
493 for (int k = 0; k < 2; k++) {
494 m.mouseHandler.onButton(handle, info, 1);
495 m.mouseHandler.onButton(handle, info, 0);
496 }
497 }
498 default -> throw new BridgeException("action must be click|double|down|up|move");
499 }
500 return null;
501 });
502 return afterInput();
503 }
504
505 /** Report the screen 2 ticks after an input, when keybind-driven screens (inventory, chat) have opened. */
506 private static JsonObject afterInput() {
507 await(Ticks.wait(2), 5_000);
508 return onClient(() -> {
509 JsonObject o = ok();
510 Screen after = mc().gui.screen();
511 o.addProperty("screenAfter", after == null ? null : after.getClass().getSimpleName());
512 if (after != null) o.addProperty("screenTitle", after.getTitle().getString());
513 return o;
514 });
515 }
516
517 static JsonObject key(JsonObject in) {
518 String name = str(in, "key", null);
519 if (name == null) throw new BridgeException("key is required, e.g. escape, enter, e, 1, f3");
520 Keys.Key k = Keys.get(name);
521 String action = str(in, "action", "press");
522 int mods = Keys.mods(b(in, "shift", false), b(in, "ctrl", false), b(in, "alt", false));
523 onClient(() -> {
524 Minecraft m = mc();
525 long handle = m.getWindow().handle();
526 KeyEvent ev = new KeyEvent(k.scancode(), k.keycode(), mods);
527 switch (action) {
528 case "down" -> m.keyboardHandler.keyPress(handle, 1, ev);
529 case "up" -> m.keyboardHandler.keyPress(handle, 0, ev);
530 case "press" -> {
531 m.keyboardHandler.keyPress(handle, 1, ev);
532 m.keyboardHandler.keyPress(handle, 0, ev);
533 }
534 default -> throw new BridgeException("action must be press|down|up");
535 }
536 return null;
537 });
538 return afterInput();
539 }
540
541 static JsonObject type(JsonObject in) {
542 String text = str(in, "text", null);
543 if (text == null) throw new BridgeException("text is required");
544 return onClient(() -> {
545 Minecraft m = mc();
546 if (m.gui.screen() == null) throw new BridgeException("no screen open to type into (open chat with /key t, or use /chat)");
547 m.keyboardHandler.textInput(m.getWindow().handle(), text);
548 return ok();
549 });
550 }
551
552 private static KeyMapping movementKey(String name) {
553 var o = mc().options;
554 return switch (name.toLowerCase(Locale.ROOT)) {
555 case "forward", "w" -> o.keyUp;
556 case "back", "s" -> o.keyDown;
557 case "left", "a" -> o.keyLeft;
558 case "right", "d" -> o.keyRight;
559 case "jump", "space" -> o.keyJump;
560 case "sneak", "shift" -> o.keyShift;
561 case "sprint" -> o.keySprint;
562 case "use" -> o.keyUse;
563 case "attack" -> o.keyAttack;
564 default -> throw new BridgeException("hold key must be forward|back|left|right|jump|sneak|sprint|use|attack");
565 };
566 }
567
568 /** Hold in-world key mappings for N ms (movement, sneak, continuous use/attack). Waits until released. */
569 static JsonObject hold(JsonObject in) {
570 List<String> names = new ArrayList<>();
571 JsonElement ks = in.get("keys");
572 if (ks == null) throw new BridgeException("keys is required, e.g. [\"forward\",\"jump\"]");
573 if (ks.isJsonArray()) ks.getAsJsonArray().forEach(e -> names.add(e.getAsString()));
574 else for (String s : ks.getAsString().split(",")) names.add(s.trim());
575 int ms = Math.max(50, Math.min(30_000, i(in, "ms", 500)));
576 List<KeyMapping> maps = onClient(() -> {
577 player();
578 List<KeyMapping> l = new ArrayList<>();
579 for (String n : names) l.add(movementKey(n));
580 for (KeyMapping km : l) km.setDown(true);
581 return l;
582 });
583 try {
584 Thread.sleep(ms);
585 } catch (InterruptedException e) {
586 Thread.currentThread().interrupt();
587 } finally {
588 onClient(() -> {
589 for (KeyMapping km : maps) km.setDown(false);
590 return null;
591 });
592 }
593 JsonObject o = ok();
594 o.add("player", onClient(() -> vec(player().position())));
595 return o;
596 }
597
598 static JsonObject closeScreen(JsonObject in) {
599 return onClient(() -> {
600 Minecraft m = mc();
601 Screen s = m.gui.screen();
602 if (s == null) return ok();
603 if (s instanceof AbstractContainerScreen<?> && m.player != null) m.player.closeContainer();
604 else s.onClose();
605 return ok();
606 });
607 }
608
609 // ------------------------------------------------------------------ chat
610
611 static JsonObject chat(JsonObject in) {
612 String text = str(in, "text", null);
613 if (text == null || text.isEmpty()) throw new BridgeException("text is required");
614 return onClient(() -> {
615 LocalPlayer p = player();
616 if (text.startsWith("/")) p.connection.sendCommand(text.substring(1));
617 else p.connection.sendChat(text);
618 JsonObject o = ok();
619 o.addProperty("chatSeq", ChatLog.since(Long.MAX_VALUE).get("next").getAsLong());
620 return o;
621 });
622 }
623
624 // ------------------------------------------------------------------ world interaction
625
626 private static void lookAt(LocalPlayer p, Vec3 target) {
627 Vec3 eye = p.getEyePosition();
628 double dx = target.x - eye.x, dy = target.y - eye.y, dz = target.z - eye.z;
629 double horiz = Math.sqrt(dx * dx + dz * dz);
630 float yaw = (float) (Math.toDegrees(Math.atan2(dz, dx)) - 90.0);
631 float pitch = (float) -Math.toDegrees(Math.atan2(dy, horiz));
632 setRot(p, yaw, pitch);
633 }
634
635 private static void setRot(LocalPlayer p, float yaw, float pitch) {
636 p.setYRot(yaw);
637 p.setXRot(Math.max(-90f, Math.min(90f, pitch)));
638 p.yRotO = p.getYRot();
639 p.xRotO = p.getXRot();
640 p.setYHeadRot(p.getYRot());
641 }
642
643 private static Entity findEntity(JsonObject in) {
644 ClientLevel lvl = mc().level;
645 if (lvl == null) throw new BridgeException("not in a world");
646 if (in.has("id")) {
647 Entity e = lvl.getEntity(i(in, "id", -1));
648 if (e == null) throw new BridgeException("no entity with id " + str(in, "id", ""));
649 return e;
650 }
651 String name = str(in, "name", null);
652 if (name == null) throw new BridgeException("id or name is required");
653 LocalPlayer p = player();
654 Entity best = null;
655 for (Entity e : lvl.entitiesForRendering()) {
656 if (e == p || !e.getName().getString().contains(name)) continue;
657 if (best == null || e.distanceToSqr(p) < best.distanceToSqr(p)) best = e;
658 }
659 if (best == null) throw new BridgeException("no entity named like '" + name + "' is loaded");
660 return best;
661 }
662
663 static JsonObject look(JsonObject in) {
664 return onClient(() -> {
665 LocalPlayer p = player();
666 if (in.has("yaw") || in.has("pitch")) {
667 setRot(p, (float) d(in, "yaw", p.getYRot()), (float) d(in, "pitch", p.getXRot()));
668 } else if (in.has("id") || in.has("name")) {
669 Entity e = findEntity(in);
670 lookAt(p, e.getBoundingBox().getCenter());
671 } else if (in.has("x") && in.has("y") && in.has("z")) {
672 lookAt(p, new Vec3(d(in, "x", 0), d(in, "y", 0), d(in, "z", 0)));
673 } else {
674 throw new BridgeException("give yaw/pitch, x/y/z, or id/name");
675 }
676 JsonObject o = ok();
677 o.addProperty("yaw", round(p.getYRot()));
678 o.addProperty("pitch", round(p.getXRot()));
679 return o;
680 });
681 }
682
683 private static void clickMapping(KeyMapping km) {
684 KeyMapping.click(((KeyMappingAccessor) km).qa$key());
685 }
686
687 private static JsonObject clickAndReport(KeyMapping km) {
688 onClient(() -> {
689 player();
690 clickMapping(km);
691 return null;
692 });
693 await(Ticks.wait(3), 5_000);
694 return onClient(() -> {
695 JsonObject o = ok();
696 o.add("target", hit(mc().hitResult));
697 Screen s = mc().gui.screen();
698 o.addProperty("screenAfter", s == null ? null : s.getClass().getSimpleName());
699 if (s != null) o.addProperty("screenTitle", s.getTitle().getString());
700 return o;
701 });
702 }
703
704 /** Right click with whatever the crosshair is on, exactly like pressing the use button once. */
705 static JsonObject use(JsonObject in) {
706 return clickAndReport(mc().options.keyUse);
707 }
708
709 static JsonObject attack(JsonObject in) {
710 return clickAndReport(mc().options.keyAttack);
711 }
712
713 /** Aim at an entity (by id or name), confirm the crosshair is on it, then right-click (or attack). */
714 static JsonObject interactEntity(JsonObject in) {
715 boolean attack = "attack".equalsIgnoreCase(str(in, "action", "use"));
716 int targetId = onClient(() -> {
717 LocalPlayer p = player();
718 Entity e = findEntity(in);
719 AABB bb = e.getBoundingBox();
720 lookAt(p, bb.getCenter());
721 return e.getId();
722 });
723 await(Ticks.wait(2), 5_000);
724 JsonObject pre = onClient(() -> {
725 HitResult h = mc().hitResult;
726 JsonObject o = new JsonObject();
727 boolean onTarget = h instanceof EntityHitResult eh && eh.getEntity().getId() == targetId;
728 o.addProperty("onTarget", onTarget);
729 o.add("target", hit(h));
730 Entity e = mc().level.getEntity(targetId);
731 if (e != null) o.addProperty("distance", round(player().getEyePosition().distanceTo(e.getBoundingBox().getCenter())));
732 return o;
733 });
734 if (!pre.get("onTarget").getAsBoolean()) {
735 throw new BridgeException("crosshair is not on entity " + targetId + " after aiming (too far or blocked?) "
736 + pre + " - teleport closer (within ~3 blocks) and retry");
737 }
738 JsonObject r = clickAndReport(attack ? mc().options.keyAttack : mc().options.keyUse);
739 r.addProperty("entityId", targetId);
740 return r;
741 }
742
743 /** Aim at a block face center then right-click it (open chest, press button, use NPC block shop...). */
744 static JsonObject useOnBlock(JsonObject in) {
745 if (!(in.has("x") && in.has("y") && in.has("z"))) throw new BridgeException("x, y, z are required");
746 int x = i(in, "x", 0), y = i(in, "y", 0), z = i(in, "z", 0);
747 onClient(() -> {
748 lookAt(player(), new Vec3(x + 0.5, y + 0.5, z + 0.5));
749 return null;
750 });
751 await(Ticks.wait(2), 5_000);
752 boolean onTarget = onClient(() -> mc().hitResult instanceof BlockHitResult bh
753 && bh.getType() == HitResult.Type.BLOCK && bh.getBlockPos().equals(new BlockPos(x, y, z)));
754 if (!onTarget) throw new BridgeException("crosshair is not on block " + x + "," + y + "," + z + " (too far or obstructed)");
755 boolean attack = "attack".equalsIgnoreCase(str(in, "action", "use"));
756 return clickAndReport(attack ? mc().options.keyAttack : mc().options.keyUse);
757 }
758
759 static JsonObject hotbar(JsonObject in) {
760 int slot = i(in, "slot", -1);
761 if (slot < 0 || slot > 8) throw new BridgeException("slot must be 0..8");
762 return onClient(() -> {
763 player().getInventory().setSelectedSlot(slot);
764 return ok();
765 });
766 }
767
768 // ------------------------------------------------------------------ connection
769
770 static JsonObject connect(JsonObject in) {
771 String addr = str(in, "address", null);
772 if (addr == null) throw new BridgeException("address is required, e.g. localhost:25565");
773 return onClient(() -> {
774 Minecraft m = mc();
775 if (m.level != null) m.disconnectFromWorld(ClientLevel.DEFAULT_QUIT_MESSAGE);
776 ConnectScreen.startConnecting(new TitleScreen(), m, ServerAddress.parseString(addr),
777 new ServerData("mc-tester", addr, ServerData.Type.OTHER), false, null);
778 return ok();
779 });
780 }
781
782 static JsonObject disconnect(JsonObject in) {
783 return onClient(() -> {
784 Minecraft m = mc();
785 if (m.level != null) m.disconnectFromWorld(ClientLevel.DEFAULT_QUIT_MESSAGE);
786 return ok();
787 });
788 }
789
790 static JsonObject quit(JsonObject in) {
791 Ticks.later(2, () -> mc().stop());
792 return ok();
793 }
794}