Add mob and skill catalogs with condition editing and native animation preview
This commit is contained in:
@@ -15,6 +15,7 @@ public final class AstraPlusEditor {
|
||||
var client = new EditorClient(connection);
|
||||
modBus.addListener(connection::register);
|
||||
modBus.addListener(client::registerKeys);
|
||||
modBus.addListener(online.astradev.plus.editor.client.preview.PreviewRenderer::register);
|
||||
NeoForge.EVENT_BUS.addListener(client::registerCommands);
|
||||
NeoForge.EVENT_BUS.addListener(client::tick);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package online.astradev.plus.editor.client.preview;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import online.astradev.plus.editor.client.preview.PreviewModel.Frame;
|
||||
import online.astradev.plus.editor.client.preview.PreviewModel.Vector;
|
||||
|
||||
/** Mirrors the server's numeric Blockbench interpolation without running server behavior. */
|
||||
public final class PreviewAnimation {
|
||||
private PreviewAnimation() {}
|
||||
|
||||
public static Vector sample(List<Frame> frames, float time, boolean loop, Vector fallback) {
|
||||
if (frames.isEmpty()) return fallback;
|
||||
if (time <= frames.getFirst().time()) return frames.getFirst().before();
|
||||
for (int index = 0; index < frames.size() - 1; index++) {
|
||||
Frame from = frames.get(index), to = frames.get(index + 1);
|
||||
if (time > to.time()) continue;
|
||||
if (time == to.time()) return to.before();
|
||||
if (from.interpolation().equals("step")) return from.after();
|
||||
float fraction = (time - from.time()) / (to.time() - from.time());
|
||||
if (from.interpolation().equals("catmullrom") || to.interpolation().equals("catmullrom")) {
|
||||
Vector before = index > 0 ? frames.get(index - 1).after()
|
||||
: loop && frames.size() >= 3 ? frames.get(frames.size() - 2).after() : from.after();
|
||||
Vector after = index + 2 < frames.size() ? frames.get(index + 2).before()
|
||||
: loop && frames.size() >= 3 ? frames.get(1).before() : to.before();
|
||||
return new Vector(cubic(before.x(), from.after().x(), to.before().x(), after.x(), fraction),
|
||||
cubic(before.y(), from.after().y(), to.before().y(), after.y(), fraction),
|
||||
cubic(before.z(), from.after().z(), to.before().z(), after.z(), fraction));
|
||||
}
|
||||
return new Vector(lerp(from.after().x(), to.before().x(), fraction),
|
||||
lerp(from.after().y(), to.before().y(), fraction), lerp(from.after().z(), to.before().z(), fraction));
|
||||
}
|
||||
return frames.getLast().after();
|
||||
}
|
||||
|
||||
private static float lerp(float from, float to, float fraction) { return from + (to - from) * fraction; }
|
||||
private static float cubic(float p0, float p1, float p2, float p3, float time) {
|
||||
return 0.5F * (2 * p1 + (-p0 + p2) * time + (2 * p0 - 5 * p1 + 4 * p2 - p3) * time * time
|
||||
+ (-p0 + 3 * p1 - 3 * p2 + p3) * time * time * time);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package online.astradev.plus.editor.client.preview;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/** Bounded numeric model data received from the administrator endpoint. */
|
||||
public record PreviewModel(String id, List<Bone> bones, List<String> animations, Animation animation,
|
||||
String selectedAnimation) {
|
||||
public PreviewModel { bones = List.copyOf(bones); animations = List.copyOf(animations); }
|
||||
|
||||
public static PreviewModel read(JsonObject value) {
|
||||
if (value.has("preview")) value = value.getAsJsonObject("preview");
|
||||
List<Bone> bones = new ArrayList<>();
|
||||
JsonArray sourceBones = value.getAsJsonArray("bones");
|
||||
if (sourceBones == null || sourceBones.isEmpty() || sourceBones.size() > 256)
|
||||
throw new IllegalArgumentException("В модели должно быть от 1 до 256 частей.");
|
||||
for (JsonElement element : sourceBones) {
|
||||
JsonObject bone = element.getAsJsonObject(); int parent = bone.get("parent").getAsInt();
|
||||
if (parent < -1 || parent >= bones.size()) throw new IllegalArgumentException("Неверная иерархия модели.");
|
||||
float scale = number(bone.get("geometryScale"));
|
||||
if (scale <= 0) throw new IllegalArgumentException("Неверный размер части модели.");
|
||||
bones.add(new Bone(text(bone, "name"), parent, vector(bone.get("origin")), vector(bone.get("rotation")),
|
||||
bone.has("itemModel") ? text(bone, "itemModel") : null, scale));
|
||||
}
|
||||
List<String> animations = new ArrayList<>();
|
||||
JsonArray sourceAnimations = value.getAsJsonArray("animations");
|
||||
if (sourceAnimations != null) for (JsonElement element : sourceAnimations) {
|
||||
if (animations.size() >= 256) throw new IllegalArgumentException("Слишком много анимаций.");
|
||||
animations.add(text(element.getAsJsonObject(), "name"));
|
||||
}
|
||||
Animation animation = null;
|
||||
if (value.has("animation")) {
|
||||
JsonObject source = value.getAsJsonObject("animation"); Map<Integer, Pose> poses = new HashMap<>();
|
||||
int[] count = {0};
|
||||
for (var entry : source.getAsJsonObject("bones").entrySet()) {
|
||||
int index = Integer.parseInt(entry.getKey());
|
||||
if (index < 0 || index >= bones.size()) throw new IllegalArgumentException("Анимация ссылается на неизвестную часть.");
|
||||
JsonObject pose = entry.getValue().getAsJsonObject();
|
||||
poses.put(index, new Pose(track(pose, "position", count), track(pose, "rotation", count), track(pose, "scale", count)));
|
||||
}
|
||||
float length = number(source.get("length"));
|
||||
if (length < 0 || length > 3600) throw new IllegalArgumentException("Неверная продолжительность анимации.");
|
||||
animation = new Animation(text(source, "name"), length, source.get("loop").getAsBoolean(), Map.copyOf(poses));
|
||||
}
|
||||
String selected = value.has("selectedAnimation") ? text(value, "selectedAnimation") : "";
|
||||
if (!selected.isEmpty() && (animation == null || !animation.name().equals(selected)))
|
||||
throw new IllegalArgumentException("Сервер не прислал выбранную анимацию целиком.");
|
||||
return new PreviewModel(text(value, "id"), bones, animations, animation, selected);
|
||||
}
|
||||
|
||||
private static List<Frame> track(JsonObject pose, String name, int[] count) {
|
||||
if (!pose.has(name)) return List.of();
|
||||
List<Frame> frames = new ArrayList<>(); float previous = -1;
|
||||
for (JsonElement element : pose.getAsJsonArray(name)) {
|
||||
if (++count[0] > 100_000) throw new IllegalArgumentException("Слишком много ключевых кадров.");
|
||||
JsonObject frame = element.getAsJsonObject(); float time = number(frame.get("time"));
|
||||
String interpolation = text(frame, "interpolation");
|
||||
if (time <= previous || time > 3600 || !Set.of("linear", "step", "catmullrom").contains(interpolation))
|
||||
throw new IllegalArgumentException("Неверный ключевой кадр анимации.");
|
||||
frames.add(new Frame(time, vector(frame.get("before")), vector(frame.get("after")), interpolation)); previous = time;
|
||||
}
|
||||
return List.copyOf(frames);
|
||||
}
|
||||
|
||||
private static Vector vector(JsonElement element) {
|
||||
JsonArray array = element.getAsJsonArray();
|
||||
if (array.size() != 3) throw new IllegalArgumentException("Координаты должны содержать три числа.");
|
||||
return new Vector(number(array.get(0)), number(array.get(1)), number(array.get(2)));
|
||||
}
|
||||
|
||||
private static float number(JsonElement value) {
|
||||
float result = value.getAsFloat();
|
||||
if (!Float.isFinite(result) || Math.abs(result) > 1_000_000) throw new IllegalArgumentException("Недопустимое число в модели.");
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String text(JsonObject value, String name) {
|
||||
String result = value.get(name).getAsString();
|
||||
if (result.length() > 512) throw new IllegalArgumentException("Слишком длинное имя в модели.");
|
||||
return result;
|
||||
}
|
||||
|
||||
public record Vector(float x, float y, float z) {
|
||||
public static final Vector ZERO = new Vector(0, 0, 0), ONE = new Vector(1, 1, 1);
|
||||
public Vector add(Vector other) { return new Vector(x + other.x, y + other.y, z + other.z); }
|
||||
public Vector subtract(Vector other) { return new Vector(x - other.x, y - other.y, z - other.z); }
|
||||
}
|
||||
public record Bone(String name, int parent, Vector origin, Vector rotation, String itemModel, float geometryScale) {}
|
||||
public record Frame(float time, Vector before, Vector after, String interpolation) {}
|
||||
public record Pose(List<Frame> position, List<Frame> rotation, List<Frame> scale) {}
|
||||
public record Animation(String name, float length, boolean loop, Map<Integer, Pose> bones) {}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package online.astradev.plus.editor.client.preview;
|
||||
|
||||
import online.astradev.plus.editor.client.preview.PreviewModel.Vector;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/** Builds the same parent-relative transforms used by server item displays. */
|
||||
public final class PreviewPose {
|
||||
private static final float RADIANS = (float) (Math.PI / 180);
|
||||
|
||||
private PreviewPose() {}
|
||||
|
||||
public static Matrix4f[] matrices(PreviewModel model, float elapsed) {
|
||||
Matrix4f[] result = new Matrix4f[model.bones().size()];
|
||||
var animation = model.animation(); float time = elapsed;
|
||||
if (animation != null) time = animation.loop() && animation.length() > 0
|
||||
? time % animation.length() : Math.min(time, animation.length());
|
||||
for (int index = 0; index < result.length; index++) {
|
||||
var bone = model.bones().get(index);
|
||||
Vector offset = bone.parent() < 0 ? bone.origin()
|
||||
: bone.origin().subtract(model.bones().get(bone.parent()).origin());
|
||||
Vector rotation = bone.rotation(), scale = Vector.ONE;
|
||||
var pose = animation == null ? null : animation.bones().get(index);
|
||||
if (pose != null) {
|
||||
offset = offset.add(PreviewAnimation.sample(pose.position(), time, animation.loop(), Vector.ZERO));
|
||||
rotation = rotation.add(PreviewAnimation.sample(pose.rotation(), time, animation.loop(), Vector.ZERO));
|
||||
scale = PreviewAnimation.sample(pose.scale(), time, animation.loop(), Vector.ONE);
|
||||
}
|
||||
result[index] = new Matrix4f(bone.parent() < 0 ? new Matrix4f().scale(1 / 16F) : result[bone.parent()])
|
||||
.translate(offset.x(), offset.y(), offset.z())
|
||||
.rotateZYX(rotation.z() * RADIANS, rotation.y() * RADIANS, rotation.x() * RADIANS)
|
||||
.scale(nonzero(scale.x()), nonzero(scale.y()), nonzero(scale.z()));
|
||||
if (!result[index].isFinite()) throw new IllegalArgumentException("Преобразование части модели вышло за числовые пределы.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static float nonzero(float value) { return value == 0 ? 0.00001F : value; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package online.astradev.plus.editor.client.preview;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.client.gui.navigation.ScreenRectangle;
|
||||
import net.minecraft.client.renderer.item.ItemStackRenderState;
|
||||
import net.minecraft.client.renderer.state.gui.pip.PictureInPictureRenderState;
|
||||
import org.joml.Matrix4fc;
|
||||
import org.joml.Vector3fc;
|
||||
|
||||
/** One depth-buffered viewport for every bone, preserving occlusion between parts. */
|
||||
public record PreviewRenderState(List<Part> parts, Vector3fc center, float yaw, float pitch,
|
||||
int x0, int y0, int x1, int y1, float scale,
|
||||
ScreenRectangle scissorArea) implements PictureInPictureRenderState {
|
||||
public PreviewRenderState { parts = List.copyOf(parts); }
|
||||
|
||||
@Override public ScreenRectangle bounds() {
|
||||
return PictureInPictureRenderState.getBounds(x0, y0, x1, y1, scissorArea);
|
||||
}
|
||||
|
||||
public record Part(ItemStackRenderState item, Matrix4fc transform) {}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package online.astradev.plus.editor.client.preview;
|
||||
|
||||
import com.mojang.blaze3d.platform.Lighting;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.render.pip.PictureInPictureRenderer;
|
||||
import net.minecraft.client.renderer.SubmitNodeCollector;
|
||||
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||
import net.neoforged.neoforge.client.event.RegisterPictureInPictureRenderersEvent;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/** NeoForge's native GUI renderer; no world entities or extra game registries. */
|
||||
public final class PreviewRenderer extends PictureInPictureRenderer<PreviewRenderState> {
|
||||
public static void register(RegisterPictureInPictureRenderersEvent event) {
|
||||
event.register(PreviewRenderState.class, PreviewRenderer::new);
|
||||
}
|
||||
|
||||
@Override public Class<PreviewRenderState> getRenderStateClass() { return PreviewRenderState.class; }
|
||||
|
||||
@Override protected void renderToTexture(PreviewRenderState state, PoseStack poses, SubmitNodeCollector collector) {
|
||||
Minecraft.getInstance().gameRenderer.lighting().setupFor(Lighting.Entry.ENTITY_IN_UI);
|
||||
poses.scale(1, -1, 1);
|
||||
poses.mulPose(new Matrix4f().rotationX(state.pitch()).rotateY(state.yaw())
|
||||
.translate(-state.center().x(), -state.center().y(), -state.center().z()));
|
||||
for (var part : state.parts()) {
|
||||
poses.pushPose(); poses.mulPose(part.transform());
|
||||
part.item().submit(poses, collector, 15728880, OverlayTexture.NO_OVERLAY, 0);
|
||||
poses.popPose();
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected float getTranslateY(int height, int guiScale) { return height / 2F; }
|
||||
@Override protected String getTextureLabel() { return "AstraPlus model preview"; }
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package online.astradev.plus.editor.client.preview;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.renderer.item.ItemStackRenderState;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.item.ItemDisplayContext;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
/** Resolves actual resource-pack items and fits their assembled geometry in the viewport. */
|
||||
public final class PreviewScene {
|
||||
private final PreviewModel model;
|
||||
private final List<ItemStack> stacks = new ArrayList<>();
|
||||
private final List<String> missing = new ArrayList<>();
|
||||
private Vector3f center = new Vector3f();
|
||||
private float radius = 1;
|
||||
private boolean fitted;
|
||||
|
||||
public PreviewScene(PreviewModel model) {
|
||||
this.model = model;
|
||||
if (Minecraft.getInstance().level == null)
|
||||
throw new IllegalStateException("Предпросмотр доступен после входа на сервер.");
|
||||
var resources = Minecraft.getInstance().getResourceManager();
|
||||
for (var bone : model.bones()) {
|
||||
ItemStack stack = ItemStack.EMPTY;
|
||||
if (bone.itemModel() != null) {
|
||||
Identifier id = Identifier.tryParse(bone.itemModel());
|
||||
if (id == null || resources.getResource(Identifier.fromNamespaceAndPath(id.getNamespace(), "items/" + id.getPath() + ".json")).isEmpty())
|
||||
missing.add(bone.itemModel());
|
||||
else {
|
||||
stack = new ItemStack(Items.PAPER); stack.set(DataComponents.ITEM_MODEL, id);
|
||||
}
|
||||
}
|
||||
stacks.add(stack);
|
||||
}
|
||||
}
|
||||
|
||||
public PreviewModel model() { return model; }
|
||||
public List<String> missing() { return List.copyOf(missing); }
|
||||
public boolean hasGeometry() { return stacks.stream().anyMatch(stack -> !stack.isEmpty()); }
|
||||
|
||||
public void extract(GuiGraphicsExtractor graphics, int x0, int y0, int x1, int y1,
|
||||
float time, float yaw, float pitch, float zoom) {
|
||||
if (x1 <= x0 || y1 <= y0 || !missing.isEmpty()) return;
|
||||
var minecraft = Minecraft.getInstance();
|
||||
Matrix4f[] transforms = PreviewPose.matrices(model, time);
|
||||
List<PreviewRenderState.Part> parts = new ArrayList<>();
|
||||
Vector3f minimum = new Vector3f(Float.POSITIVE_INFINITY), maximum = new Vector3f(Float.NEGATIVE_INFINITY);
|
||||
for (int index = 0; index < stacks.size(); index++) {
|
||||
if (stacks.get(index).isEmpty()) continue;
|
||||
var item = new ItemStackRenderState();
|
||||
minecraft.getItemModelResolver().updateForTopItem(item, stacks.get(index), ItemDisplayContext.NONE,
|
||||
minecraft.level, minecraft.player, 0);
|
||||
Matrix4f transform = new Matrix4f(transforms[index]).scale(model.bones().get(index).geometryScale() * 16);
|
||||
if (!transform.isFinite()) throw new IllegalArgumentException("Недопустимый масштаб геометрии модели.");
|
||||
if (!fitted) item.visitExtents(point -> {
|
||||
Vector3f transformed = new Vector3f(point).mulPosition(transform);
|
||||
minimum.min(transformed); maximum.max(transformed);
|
||||
});
|
||||
parts.add(new PreviewRenderState.Part(item, transform));
|
||||
}
|
||||
if (!fitted && Float.isFinite(minimum.x)) {
|
||||
center = new Vector3f(minimum).add(maximum).mul(0.5F);
|
||||
radius = Math.max(0.05F, minimum.distance(maximum) / 2);
|
||||
if (!center.isFinite() || !Float.isFinite(radius))
|
||||
throw new IllegalArgumentException("Геометрия модели слишком велика для предпросмотра.");
|
||||
fitted = true;
|
||||
}
|
||||
float fit = Math.min(x1 - x0, y1 - y0) * 0.42F / radius * zoom;
|
||||
graphics.submitPictureInPictureRenderState(new PreviewRenderState(parts, new Vector3f(center), yaw, pitch,
|
||||
x0, y0, x1, y1, fit, graphics.peekScissorStack()));
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@ public final class ContentDraft {
|
||||
public String revision() { return revision; }
|
||||
public boolean dirty() { return fresh() || !document.equals(saved); }
|
||||
public JsonObject document() { return document.deepCopy(); }
|
||||
public void replace(JsonObject document) { this.document = document.deepCopy(); }
|
||||
|
||||
public JsonElement get(String... path) {
|
||||
JsonElement value = document;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/** Mob IDs belong to their file path and may be omitted from the stored JSON body. */
|
||||
public final class MobDocuments {
|
||||
private MobDocuments() {}
|
||||
public static JsonObject document(JsonObject response) {
|
||||
var document = response.getAsJsonObject("document").deepCopy();
|
||||
document.addProperty("id", response.get("id").getAsString());
|
||||
return document;
|
||||
}
|
||||
public static ContentDraft draft(JsonObject response) {
|
||||
return new ContentDraft(document(response), response.get("revision").getAsString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
|
||||
/** Typed controls for supported server settings; untouched defaults remain inherited. */
|
||||
public final class MobFields {
|
||||
private MobFields() {}
|
||||
public static List<FormField> basic(ContentDraft draft, EditorCatalog catalog, boolean skill) {
|
||||
var result = new ArrayList<FormField>();
|
||||
if (draft.fresh()) result.add(DataFields.text(draft, "Идентификатор", "namespace:путь, без пробелов", "", List.of(), "id"));
|
||||
result.add(DataFields.text(draft, "Название", skill ? "Название в каталоге редактора" : "Имя моба в мире", "", List.of(), "name"));
|
||||
if (skill) result.add(DataFields.number(draft, "Перезарядка, секунды", "Пауза перед следующим применением", "0", false, 0, 72000, "cooldown"));
|
||||
else {
|
||||
result.add(DataFields.text(draft, "Ванильная основа", "Определяет базовую физику и поведение", "minecraft:pig", catalog.values("mobEntities"), "entity"));
|
||||
result.add(DataFields.number(draft, "Здоровье", "2 единицы = 1 сердце", "20", false, 0.01, 1000000, "health"));
|
||||
result.add(DataFields.number(draft, "Урон атаки", "Базовое значение для обычной атаки", "0", false, 0, 1000000, "damage"));
|
||||
result.add(DataFields.number(draft, "Броня", "Очки брони", "0", false, 0, 1000000, "armor"));
|
||||
result.add(DataFields.text(draft, "Фракция", "Пусто: фракция не назначена", "", List.of(), "faction"));
|
||||
}
|
||||
result.add(FormField.text("sourceId", "Псевдоним ссылок", "Необязательно. Сохраняет ссылки существующих навыков", () -> draft.text("", "sourceId"),
|
||||
value -> { if (value.isBlank()) draft.set(null, "sourceId"); else draft.string(value.trim(), "sourceId"); }));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<FormField> options(ContentDraft local) {
|
||||
return List.of(
|
||||
optionalNumber(local, "Скорость движения", "Наследуется от ванильной основы", "MovementSpeed"),
|
||||
optionalNumber(local, "Дальность преследования", "Наследуется от ванильной основы", "FollowRange"),
|
||||
optionalNumber(local, "Сопротивление отбрасыванию", "Наследуется от ванильной основы", "KnockbackResistance"),
|
||||
optionalNumber(local, "Неуязвимость после удара, тики", "По умолчанию: 10", "NoDamageTicks"),
|
||||
optionalNumber(local, "Максимальная дистанция боя", "По умолчанию: 256 блоков", "MaxCombatDistance"),
|
||||
DataFields.bool(local, "Без звуков", false, "options", "Silent"),
|
||||
DataFields.bool(local, "Неуязвимость", false, "options", "Invincible"),
|
||||
DataFields.bool(local, "Невидимость основы", false, "options", "Invisible"),
|
||||
DataFields.bool(local, "Физические столкновения", true, "options", "Collidable"),
|
||||
DataFields.bool(local, "Без гравитации", false, "options", "NoGravity"),
|
||||
DataFields.bool(local, "Естественное исчезновение", true, "options", "Despawn"),
|
||||
DataFields.bool(local, "Убрать случайную экипировку", false, "options", "PreventRandomEquipment"),
|
||||
DataFields.bool(local, "Заменить ванильный лут", false, "options", "PreventOtherDrops"),
|
||||
DataFields.bool(local, "Учитывать угрозу при выборе цели", false, "modules", "ThreatTable"),
|
||||
DataFields.number(local, "Множитель урона от падения", "0 = иммунитет, 1 = обычный урон", "1", false, 0, 100, "damageModifiers", "FALL"),
|
||||
DataFields.number(local, "Множитель урона от удушья", "0 = иммунитет, 1 = обычный урон", "1", false, 0, 100, "damageModifiers", "SUFFOCATION"));
|
||||
}
|
||||
|
||||
private static FormField optionalNumber(ContentDraft local, String label, String hint, String key) {
|
||||
return FormField.text("options/" + key, label, hint, () -> local.text("", "options", key),
|
||||
value -> local.number(value, key.equals("NoDamageTicks"), 0, 72000, "options", key));
|
||||
}
|
||||
|
||||
public static List<FormField> condition(ContentDraft local, EditorCatalog catalog, boolean inline) {
|
||||
String name = local.text("incombat", "call", "name");
|
||||
var result = new ArrayList<FormField>();
|
||||
result.add(new FormField("mode", "Когда разрешить действие", "Все условия списка должны выполняться",
|
||||
() -> switch (local.text("true", "mode")) { case "false" -> "Условие ложно"; case "fallback" -> "Иначе вызвать навык"; default -> "Условие истинно"; },
|
||||
value -> local.string(switch (value) { case "Условие ложно" -> "false"; case "Иначе вызвать навык" -> "fallback"; default -> "true"; }, "mode"),
|
||||
inline ? List.of("Условие истинно", "Условие ложно") : List.of("Условие истинно", "Условие ложно", "Иначе вызвать навык"), true));
|
||||
if (name.equals("targetwithin") || name.equals("playerwithin")) {
|
||||
String key = local.get("call", "arguments", "distance").isJsonNull() ? "d" : "distance";
|
||||
result.add(DataFields.number(local, "Расстояние, блоки", "Радиус проверки от моба", "10", false, 0, 72000, "call", "arguments", key));
|
||||
}
|
||||
if (name.equals("hasaura")) {
|
||||
String key = local.get("call", "arguments", "name").isJsonNull() ? "n" : "name";
|
||||
result.add(DataFields.text(local, "Имя ауры", "Имя, указанное действием aura", "", List.of(), "call", "arguments", key));
|
||||
}
|
||||
if (name.equals("modelhaspassenger")) {
|
||||
String key = local.get("call", "arguments", "part").isJsonNull() ? "p" : "part";
|
||||
result.add(DataFields.text(local, "Кость модели", "Пусто: любое место пассажира", "", catalog.values("bones"), "call", "arguments", key));
|
||||
}
|
||||
if (!inline) result.add(DataFields.text(local, "Резервный навык", "Используется только в режиме «Иначе вызвать навык»", "", catalog.values("skills"), "fallback"));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String actionName(String name) {
|
||||
return switch (name) {
|
||||
case "skill" -> "Вызвать навык"; case "randomskill" -> "Случайный навык"; case "delay" -> "Пауза";
|
||||
case "damage" -> "Нанести урон"; case "basedamage" -> "Базовый урон"; case "model" -> "Прикрепить модель";
|
||||
case "state" -> "Запустить анимацию"; case "aura" -> "Аура"; case "potion" -> "Эффект зелья";
|
||||
case "summon" -> "Призвать моба"; case "remove" -> "Удалить сущность"; case "sound" -> "Звук";
|
||||
case "particles", "e:p" -> "Частицы"; case "javascript", "js" -> "JavaScript";
|
||||
case "setai" -> "Управление ИИ"; case "settarget" -> "Назначить цель"; case "setspeed" -> "Скорость";
|
||||
case "cancelevent" -> "Отменить событие"; case "setnodamageticks" -> "Пауза между повреждениями";
|
||||
case "lockmodel" -> "Закрепить поворот модели"; case "mountmodel" -> "Посадить на модель";
|
||||
case "dismountallmodel" -> "Высадить пассажиров"; case "velocity" -> "Скорость по осям";
|
||||
case "teleport", "teleportto" -> "Телепортация"; case "lunge" -> "Рывок"; case "throw" -> "Отбросить";
|
||||
case "missile" -> "Самонаводящийся снаряд"; case "projectile" -> "Снаряд"; case "totem" -> "Область действия";
|
||||
default -> name;
|
||||
};
|
||||
}
|
||||
|
||||
public static String triggerName(String trigger) {
|
||||
String lower = trigger.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.startsWith("ontimer:")) return "Каждые " + trigger.substring(8) + " тиков";
|
||||
return switch (lower) {
|
||||
case "onspawn" -> "При призыве"; case "onload" -> "При загрузке из мира"; case "onattack" -> "При атаке";
|
||||
case "ondeath" -> "При смерти"; case "onentercombat" -> "При вступлении в бой"; case "" -> "В последовательности";
|
||||
default -> trigger;
|
||||
};
|
||||
}
|
||||
|
||||
public static String actionSummary(String source) {
|
||||
try {
|
||||
var value = MobSyntax.action(source);
|
||||
var action = value.getAsJsonObject("action");
|
||||
String suffix = value.getAsJsonArray("conditions").isEmpty() ? "" : " Условия: " + value.getAsJsonArray("conditions").size();
|
||||
return triggerName(value.get("trigger").getAsString()) + ": " + actionName(action.get("name").getAsString()) + suffix;
|
||||
} catch (RuntimeException ignored) { return "Сложная запись: " + source; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/** Lossless editing of nested action arguments; no script code is executed on the client. */
|
||||
public final class MobSyntax {
|
||||
private MobSyntax() {}
|
||||
|
||||
public static List<String> split(String text, char separator) {
|
||||
var values = new ArrayList<String>();
|
||||
int start = 0, depth = 0;
|
||||
boolean quoted = false, escaped = false;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (quoted) {
|
||||
if (escaped) escaped = false;
|
||||
else if (c == '\\') escaped = true;
|
||||
else if (c == '"') quoted = false;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') { quoted = true; continue; }
|
||||
if (c == '{' || c == '[' || c == '<') depth++;
|
||||
if (c == '}' || c == ']' || c == '>') depth--;
|
||||
if (depth < 0) throw new IllegalArgumentException("Нарушен порядок скобок.");
|
||||
if (depth == 0 && c == separator) {
|
||||
String part = text.substring(start, i).trim();
|
||||
if (!part.isEmpty()) values.add(part);
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
if (depth != 0 || quoted) throw new IllegalArgumentException("Закройте скобки и кавычки.");
|
||||
String last = text.substring(start).trim();
|
||||
if (!last.isEmpty()) values.add(last);
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
public static JsonObject call(String source) {
|
||||
int open = source.indexOf('{');
|
||||
var result = new JsonObject();
|
||||
result.addProperty("name", (open < 0 ? source : source.substring(0, open)).trim().toLowerCase(Locale.ROOT));
|
||||
var args = new JsonObject();
|
||||
if (open >= 0) {
|
||||
if (!source.endsWith("}")) throw new IllegalArgumentException("Закройте параметры действия.");
|
||||
for (String part : split(source.substring(open + 1, source.length() - 1), ';')) {
|
||||
int equals = part.indexOf('=');
|
||||
if (equals < 1) throw new IllegalArgumentException("Параметр записывается как имя=значение.");
|
||||
String key = part.substring(0, equals).trim();
|
||||
if (args.has(key)) throw new IllegalArgumentException("Повтор параметра: " + key);
|
||||
args.addProperty(key, part.substring(equals + 1).trim());
|
||||
}
|
||||
}
|
||||
result.add("arguments", args);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String call(JsonObject value) {
|
||||
String name = value.get("name").getAsString().trim();
|
||||
if (name.isEmpty() || name.contains(" ")) throw new IllegalArgumentException("Укажите имя действия или условия.");
|
||||
var args = value.getAsJsonObject("arguments");
|
||||
if (args == null || args.isEmpty()) return name;
|
||||
var fields = new ArrayList<String>();
|
||||
args.entrySet().forEach(entry -> fields.add(entry.getKey() + "=" + (entry.getValue().isJsonPrimitive()
|
||||
? entry.getValue().getAsString() : entry.getValue().toString())));
|
||||
String result = name + "{" + String.join(";", fields) + "}";
|
||||
split(result, ' ');
|
||||
return result;
|
||||
}
|
||||
|
||||
public static JsonObject action(String source) {
|
||||
String cleaned = source.trim();
|
||||
if (cleaned.startsWith("- ")) cleaned = cleaned.substring(2).trim();
|
||||
var words = split(cleaned, ' ');
|
||||
if (words.isEmpty()) throw new IllegalArgumentException("Укажите действие.");
|
||||
var result = new JsonObject();
|
||||
result.add("action", call(words.getFirst()));
|
||||
result.addProperty("trigger", "");
|
||||
result.addProperty("target", "");
|
||||
result.addProperty("chance", 1);
|
||||
var conditions = new JsonArray();
|
||||
for (int i = 1; i < words.size(); i++) {
|
||||
String word = words.get(i);
|
||||
if (word.startsWith("@")) result.addProperty("target", word.substring(1));
|
||||
else if (word.startsWith("~")) result.addProperty("trigger", word.substring(1));
|
||||
else if (word.startsWith("?!")) conditions.add(word.substring(2) + " false");
|
||||
else if (word.startsWith("?")) conditions.add(word.substring(1) + " true");
|
||||
else if (result.getAsJsonObject("action").get("name").getAsString().equals("delay"))
|
||||
result.getAsJsonObject("action").getAsJsonObject("arguments").addProperty("ticks", word);
|
||||
else result.addProperty("chance", Double.parseDouble(word));
|
||||
}
|
||||
result.add("conditions", conditions);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String action(JsonObject value) {
|
||||
var parts = new ArrayList<String>();
|
||||
parts.add(call(value.getAsJsonObject("action")));
|
||||
String target = value.get("target").getAsString().trim(), trigger = value.get("trigger").getAsString().trim();
|
||||
if (!target.isEmpty()) { call(target); parts.add("@" + target); }
|
||||
if (!trigger.isEmpty()) parts.add("~" + trigger);
|
||||
double chance = value.get("chance").getAsDouble();
|
||||
if (!Double.isFinite(chance) || chance < 0 || chance > 1) throw new IllegalArgumentException("Вероятность должна быть от 0 до 1.");
|
||||
if (chance != 1) parts.add(Double.toString(chance));
|
||||
for (var condition : value.getAsJsonArray("conditions")) {
|
||||
var parsed = condition(condition.getAsString());
|
||||
String mode = parsed.get("mode").getAsString();
|
||||
if (mode.equals("fallback")) throw new IllegalArgumentException("Резервный навык задаётся в условиях отдельного навыка.");
|
||||
parts.add((mode.equals("false") ? "?!" : "?") + call(parsed.getAsJsonObject("call")));
|
||||
}
|
||||
return String.join(" ", parts);
|
||||
}
|
||||
|
||||
public static JsonObject condition(String source) {
|
||||
var words = split(source.trim(), ' ');
|
||||
if (words.isEmpty()) throw new IllegalArgumentException("Укажите условие.");
|
||||
var result = new JsonObject();
|
||||
result.add("call", call(words.getFirst()));
|
||||
String mode = words.size() > 1 ? words.get(1) : "true";
|
||||
if (!List.of("true", "false", "orelsecast").contains(mode.toLowerCase(Locale.ROOT)))
|
||||
throw new IllegalArgumentException("Неизвестный режим условия: " + mode);
|
||||
result.addProperty("mode", mode.equalsIgnoreCase("orElseCast") ? "fallback" : mode.toLowerCase(Locale.ROOT));
|
||||
result.addProperty("fallback", words.size() > 2 ? words.get(2) : "");
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String condition(JsonObject value) {
|
||||
String mode = value.get("mode").getAsString();
|
||||
String fallback = value.get("fallback").getAsString().trim();
|
||||
if (mode.equals("fallback") && fallback.isEmpty()) throw new IllegalArgumentException("Выберите резервный навык.");
|
||||
return call(value.getAsJsonObject("call")) + (mode.equals("fallback") ? " orElseCast " + fallback : " " + mode);
|
||||
}
|
||||
|
||||
public static String conditionName(String id) {
|
||||
return switch (id.toLowerCase(Locale.ROOT)) {
|
||||
case "incombat" -> "Моб участвует в бою";
|
||||
case "targetwithin" -> "Цель в радиусе";
|
||||
case "playerwithin" -> "Игрок в радиусе";
|
||||
case "hasaura" -> "Есть аура";
|
||||
case "hasmodel" -> "Модель прикреплена";
|
||||
case "isblocking" -> "Блокирует щитом";
|
||||
case "modelhaspassenger" -> "На модели есть пассажир";
|
||||
default -> id;
|
||||
};
|
||||
}
|
||||
|
||||
public static String conditionSummary(String source) {
|
||||
try {
|
||||
var value = condition(source);
|
||||
var call = value.getAsJsonObject("call");
|
||||
String name = conditionName(call.get("name").getAsString());
|
||||
String mode = value.get("mode").getAsString();
|
||||
if (mode.equals("false")) name = "Не выполняется: " + name;
|
||||
if (!call.getAsJsonObject("arguments").isEmpty()) name += " " + call.getAsJsonObject("arguments").entrySet().stream()
|
||||
.map(entry -> entry.getValue().getAsString()).collect(java.util.stream.Collectors.joining(", "));
|
||||
if (mode.equals("fallback")) name += " Иначе: " + value.get("fallback").getAsString();
|
||||
return name;
|
||||
} catch (RuntimeException ignored) { return source; }
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
|
||||
public final class EditorConnection {
|
||||
public static final EditorConnection INSTANCE = new EditorConnection();
|
||||
private final Map<Integer, Pending> pending = new HashMap<>();
|
||||
private final Map<Integer, ResponseChunks> responses = new HashMap<>();
|
||||
private ClientPacketListener connection;
|
||||
private int nextRequest;
|
||||
|
||||
@@ -45,16 +46,15 @@ public final class EditorConnection {
|
||||
var request = body.deepCopy();
|
||||
request.addProperty("requestId", requestId);
|
||||
request.addProperty("action", action);
|
||||
request.addProperty("responseChunks", true);
|
||||
String json = request.toString();
|
||||
if (json.length() > EditorRequest.LIMIT) {
|
||||
callback.accept(error("Документ превышает лимит сетевого редактора (8192 символа). Сократите данные или измените файл на сервере."));
|
||||
return;
|
||||
}
|
||||
pending.put(requestId, new Pending(System.nanoTime(), callback));
|
||||
long started = System.nanoTime();
|
||||
pending.put(requestId, new Pending(started, started, callback));
|
||||
try {
|
||||
ClientPacketDistributor.sendToServer(new EditorRequest(json));
|
||||
for (String packet : RequestChunks.encode(json, requestId)) ClientPacketDistributor.sendToServer(new EditorRequest(packet));
|
||||
} catch (RuntimeException failure) {
|
||||
pending.remove(requestId);
|
||||
responses.remove(requestId);
|
||||
callback.accept(error("Не удалось отправить запрос: " + failure.getMessage()));
|
||||
}
|
||||
}
|
||||
@@ -64,25 +64,42 @@ public final class EditorConnection {
|
||||
if (current != connection) {
|
||||
var abandoned = Map.copyOf(pending);
|
||||
pending.clear();
|
||||
responses.clear();
|
||||
connection = current;
|
||||
abandoned.values().forEach(value -> value.callback.accept(error("Подключение изменилось. Черновик не сохранён.")));
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
var expired = pending.entrySet().stream()
|
||||
.filter(entry -> now - entry.getValue().started > 15_000_000_000L).toList();
|
||||
.filter(entry -> now - entry.getValue().progressed > 15_000_000_000L || now - entry.getValue().started > 60_000_000_000L).toList();
|
||||
for (var entry : expired) {
|
||||
pending.remove(entry.getKey());
|
||||
responses.remove(entry.getKey());
|
||||
entry.getValue().callback.accept(error("Сервер не ответил. Перед повторным сохранением проверьте актуальную версию."));
|
||||
}
|
||||
}
|
||||
|
||||
private void receive(EditorResponse payload) {
|
||||
Integer requestId = null;
|
||||
try {
|
||||
var response = JsonParser.parseString(payload.json()).getAsJsonObject();
|
||||
var request = pending.remove(response.get("requestId").getAsInt());
|
||||
requestId = response.get("requestId").getAsInt();
|
||||
if (!pending.containsKey(requestId)) return;
|
||||
if (response.has("action") && response.get("action").getAsString().equals("response_chunk")) {
|
||||
response = responses.computeIfAbsent(requestId, ResponseChunks::new).accept(response);
|
||||
if (response == null) {
|
||||
var request = pending.get(requestId);
|
||||
pending.put(requestId, new Pending(request.started, System.nanoTime(), request.callback));
|
||||
return;
|
||||
}
|
||||
} else if (responses.containsKey(requestId)) throw new IllegalArgumentException("Сервер прервал последовательность ответа.");
|
||||
responses.remove(requestId);
|
||||
var request = pending.remove(requestId);
|
||||
if (request != null) request.callback.accept(response);
|
||||
} catch (RuntimeException ignored) {
|
||||
// Malformed or unsolicited replies cannot update a document; pending requests expire normally.
|
||||
} catch (RuntimeException failure) {
|
||||
if (requestId == null) return;
|
||||
responses.remove(requestId);
|
||||
var request = pending.remove(requestId);
|
||||
if (request != null) request.callback.accept(error("Не удалось получить полный ответ сервера: " + failure.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,5 +118,5 @@ public final class EditorConnection {
|
||||
return response;
|
||||
}
|
||||
|
||||
private record Pending(long started, Consumer<JsonObject> callback) {}
|
||||
private record Pending(long started, long progressed, Consumer<JsonObject> callback) {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package online.astradev.plus.editor.network;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/** Large documents use bounded vanilla payloads with one logical request and one response. */
|
||||
public final class RequestChunks {
|
||||
private RequestChunks() {}
|
||||
public static List<String> encode(String json, int requestId) {
|
||||
if (json.length() <= 8192) return List.of(json);
|
||||
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length > 1048576) throw new IllegalArgumentException("Документ превышает 1 МиБ.");
|
||||
String encoded = Base64.getEncoder().encodeToString(bytes);
|
||||
int total = (encoded.length() + 5999) / 6000;
|
||||
var packets = new ArrayList<String>(total);
|
||||
for (int index = 0; index < total; index++) {
|
||||
var chunk = new JsonObject(); chunk.addProperty("action", "request_chunk"); chunk.addProperty("requestId", requestId);
|
||||
chunk.addProperty("index", index); chunk.addProperty("total", total);
|
||||
chunk.addProperty("data", encoded.substring(index * 6000, Math.min(encoded.length(), (index + 1) * 6000)));
|
||||
packets.add(chunk.toString());
|
||||
}
|
||||
return List.copyOf(packets);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package online.astradev.plus.editor.network;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
/** One bounded response assembly, owned by a pending request and discarded with it. */
|
||||
public final class ResponseChunks {
|
||||
private static final int BYTE_LIMIT = 32 * 1024 * 1024;
|
||||
private static final int TEXT_LIMIT = ((BYTE_LIMIT + 2) / 3) * 4;
|
||||
private final int requestId;
|
||||
private final StringBuilder data = new StringBuilder();
|
||||
private int next, total = -1;
|
||||
|
||||
public ResponseChunks(int requestId) { this.requestId = requestId; }
|
||||
|
||||
public JsonObject accept(JsonObject chunk) {
|
||||
int index = integer(chunk, "index"), receivedTotal = integer(chunk, "total");
|
||||
if (integer(chunk, "requestId") != requestId || index != next || receivedTotal < 1 || receivedTotal > 256
|
||||
|| total >= 0 && total != receivedTotal || index >= receivedTotal)
|
||||
throw new IllegalArgumentException("Нарушен порядок частей ответа сервера.");
|
||||
if (!chunk.has("data") || !chunk.get("data").isJsonPrimitive() || !chunk.getAsJsonPrimitive("data").isString())
|
||||
throw new IllegalArgumentException("Некорректные данные части ответа.");
|
||||
String part = chunk.get("data").getAsString();
|
||||
if (part.isEmpty() || part.length() > 180000 || data.length() + part.length() > TEXT_LIMIT)
|
||||
throw new IllegalArgumentException("Ответ сервера превышает допустимый размер.");
|
||||
if (!part.matches("[A-Za-z0-9+/]*={0,2}")) throw new IllegalArgumentException("Некорректная кодировка части ответа.");
|
||||
if (index + 1 < receivedTotal && part.indexOf('=') >= 0) throw new IllegalArgumentException("Кодировка ответа завершилась до последней части.");
|
||||
total = receivedTotal; next++; data.append(part);
|
||||
if (next < total) return null;
|
||||
byte[] bytes = Base64.getDecoder().decode(data.toString());
|
||||
if (bytes.length > BYTE_LIMIT) throw new IllegalArgumentException("Ответ сервера превышает 32 МиБ.");
|
||||
try {
|
||||
String json = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
|
||||
var response = JsonParser.parseString(json).getAsJsonObject();
|
||||
if (integer(response, "requestId") != requestId || response.has("action") && response.get("action").getAsString().equals("response_chunk"))
|
||||
throw new IllegalArgumentException("Ответ сервера не соответствует запросу.");
|
||||
return response;
|
||||
} catch (CharacterCodingException error) { throw new IllegalArgumentException("Ответ сервера содержит некорректный UTF-8.", error); }
|
||||
}
|
||||
|
||||
private static int integer(JsonObject value, String key) {
|
||||
if (!value.has(key) || !value.get(key).isJsonPrimitive() || !value.getAsJsonPrimitive(key).isNumber())
|
||||
throw new IllegalArgumentException("Ответ сервера не содержит " + key + ".");
|
||||
try { return value.get(key).getAsBigDecimal().intValueExact(); }
|
||||
catch (ArithmeticException error) { throw new IllegalArgumentException("Некорректный номер части ответа.", error); }
|
||||
}
|
||||
}
|
||||
@@ -28,12 +28,16 @@ public final class ContentBrowserScreen extends EditorScreen {
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var search = addRenderableWidget(new EditBox(font, 12, 38, width - 24, 20, Component.literal("Поиск")));
|
||||
int tab = (width - 40) / 3;
|
||||
button("Предметы и блоки", 12, 38, tab, () -> {}).active = false;
|
||||
button("Мобы", 20 + tab, 38, tab, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, false)));
|
||||
button("Навыки", 28 + tab * 2, 38, tab, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, true)));
|
||||
var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск")));
|
||||
search.setMaxLength(256);
|
||||
search.setHint(Component.literal("Найти по имени или namespace:id"));
|
||||
search.setValue(query);
|
||||
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 64, width - 24, Math.max(25, height - 165), this::load));
|
||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(25, height - 193), this::load));
|
||||
list.values(rows.keySet().stream().toList());
|
||||
int row = height - 94;
|
||||
int part = Math.max(50, (width - 48) / 4);
|
||||
|
||||
@@ -24,7 +24,7 @@ public final class JsonObjectScreen extends EditorScreen {
|
||||
@Override protected void init() {
|
||||
var input = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(40).setShowDecorations(false)
|
||||
.setPlaceholder(Component.literal("{}")).build(font, width - 24, Math.max(30, height - 113), Component.literal("Параметры JSON")));
|
||||
input.setCharacterLimit(Math.max(8192, value.length()));
|
||||
input.setCharacterLimit(Math.max(1048576, value.length()));
|
||||
input.setValue(value); input.setValueListener(text -> value = text);
|
||||
button("Назад", 12, height - 27, 110, this::onClose);
|
||||
button("В форму", width - 132, height - 27, 120, () -> {
|
||||
@@ -34,7 +34,7 @@ public final class JsonObjectScreen extends EditorScreen {
|
||||
changed.accept(parsed.getAsJsonObject()); minecraft.gui.setScreen(parent);
|
||||
} catch (RuntimeException error) { status("Ошибка JSON: " + error.getMessage(), true); }
|
||||
});
|
||||
if (status.isBlank()) status("Дополнительные параметры сценария. Их названия и смысл определяет автор скрипта.", false);
|
||||
if (status.isBlank()) status("Расширенный JSON текущей формы. Неизвестные поля сохраняются; перед применением сервер проверит определение.", false);
|
||||
}
|
||||
|
||||
@Override public void onClose() {
|
||||
|
||||
@@ -13,7 +13,10 @@ public final class MessageScreen extends EditorScreen {
|
||||
private final String message;
|
||||
|
||||
public MessageScreen(Screen parent, String message) {
|
||||
super("AstraPlus: полное сообщение");
|
||||
this(parent, "AstraPlus: полное сообщение", message);
|
||||
}
|
||||
public MessageScreen(Screen parent, String title, String message) {
|
||||
super(title);
|
||||
this.parent = parent;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.DataFields;
|
||||
import online.astradev.plus.editor.form.FormField;
|
||||
import online.astradev.plus.editor.form.MobFields;
|
||||
import online.astradev.plus.editor.form.MobSyntax;
|
||||
|
||||
/** Common action controls keep nested argument expressions intact until explicitly edited. */
|
||||
public final class MobActionForms {
|
||||
private MobActionForms() {}
|
||||
public static void open(Screen parent, EditorCatalog catalog, String source, boolean mob, Consumer<String> changed) {
|
||||
var initial = MobSyntax.action(source);
|
||||
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Действие: " + MobFields.actionName(initial.getAsJsonObject("action").get("name").getAsString()), initial,
|
||||
local -> fields(local, catalog, mob), accepted -> changed.accept(MobSyntax.action(accepted)), List.of(
|
||||
new SettingsScreen.Action("Параметры действия", (screen, local) -> arguments(screen, local, catalog, "action")),
|
||||
new SettingsScreen.Action("Условия выполнения", (screen, local) -> Minecraft.getInstance().gui.setScreen(new MobConditionsScreen(screen, catalog,
|
||||
"Условия действия", local.get("conditions").getAsJsonArray(), true, values -> local.set(values, "conditions")))),
|
||||
new SettingsScreen.Action("Параметры цели", (screen, local) -> target(screen, local, catalog))),
|
||||
"Изменения попадут в определение после кнопки «В черновик». Вложенные выражения параметров сохраняются."));
|
||||
}
|
||||
|
||||
private static List<FormField> fields(ContentDraft local, EditorCatalog catalog, boolean mob) {
|
||||
var result = new ArrayList<FormField>();
|
||||
result.add(DataFields.text(local, "Действие", "Выберите действие, затем настройте его параметры", "skill", catalog.values("actions"), "action", "name"));
|
||||
result.add(DataFields.text(local, "Цель", "Пусто: цель передаётся вызывающим навыком. Параметры: имя{ключ=значение}", "", catalog.values("targets"), "target"));
|
||||
if (mob) {
|
||||
result.add(new FormField("trigger", "Событие", "Когда моб выполняет действие", () -> MobFields.triggerName(local.text("", "trigger")), selected -> {
|
||||
String trigger = switch (selected) {
|
||||
case "При призыве" -> "onSpawn"; case "При загрузке из мира" -> "onLoad"; case "При атаке" -> "onAttack";
|
||||
case "При смерти" -> "onDeath"; case "При вступлении в бой" -> "onEnterCombat"; case "По таймеру" -> "onTimer:20";
|
||||
default -> "";
|
||||
};
|
||||
local.string(trigger, "trigger");
|
||||
}, List.of("При призыве", "При загрузке из мира", "При атаке", "При смерти", "При вступлении в бой", "По таймеру"), true));
|
||||
if (local.text("", "trigger").toLowerCase(java.util.Locale.ROOT).startsWith("ontimer:")) result.add(FormField.text("interval", "Интервал, тики", "20 тиков = 1 секунда",
|
||||
() -> local.text("onTimer:20", "trigger").substring(8), value -> {
|
||||
int interval = Integer.parseInt(value); if (interval < 1 || interval > 72000) throw new IllegalArgumentException("Допустимо от 1 до 72000 тиков.");
|
||||
local.string("onTimer:" + interval, "trigger");
|
||||
}));
|
||||
}
|
||||
result.add(DataFields.number(local, "Вероятность", "От 0 до 1. 1 = каждый раз, 0.25 = 25%", "1", false, 0, 1, "chance"));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void arguments(Screen parent, ContentDraft owner, EditorCatalog catalog, String key) {
|
||||
String name = owner.text("skill", key, "name");
|
||||
var args = owner.get(key, "arguments").getAsJsonObject();
|
||||
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Параметры: " + MobFields.actionName(name), args,
|
||||
local -> argumentFields(local, catalog, name), value -> owner.set(value, key, "arguments"), List.of(
|
||||
new SettingsScreen.Action("Добавить параметр", (screen, local) -> Minecraft.getInstance().gui.setScreen(new ChoiceScreen(screen, "Параметр действия",
|
||||
parameterNames(name), selected -> local.string("", selected)))),
|
||||
new SettingsScreen.Action("Расширенный JSON параметров", (screen, local) -> Minecraft.getInstance().gui.setScreen(new JsonObjectScreen(screen,
|
||||
"Параметры действия: расширенный режим", local.document(), value -> {
|
||||
for (String old : local.document().keySet()) local.set(null, old);
|
||||
value.entrySet().forEach(entry -> local.set(entry.getValue(), entry.getKey()));
|
||||
})))), "Пустой параметр удаляется из действия. Вложенные последовательности доступны в расширенном режиме."));
|
||||
}
|
||||
|
||||
private static List<FormField> argumentFields(ContentDraft local, EditorCatalog catalog, String action) {
|
||||
var result = new ArrayList<FormField>();
|
||||
var keys = new java.util.LinkedHashSet<>(local.document().keySet());
|
||||
for (String key : parameterNames(action)) if (keys.stream().noneMatch(existing -> aliases(key).contains(existing.toLowerCase(java.util.Locale.ROOT)))) keys.add(key);
|
||||
for (String key : keys) {
|
||||
List<String> choices = switch (key.toLowerCase(java.util.Locale.ROOT)) {
|
||||
case "mid", "model" -> catalog.values("models");
|
||||
case "script" -> catalog.values("scripts");
|
||||
case "s", "skill" -> action.equals("skill") ? catalog.values("skills") : List.of();
|
||||
case "pbone", "part" -> catalog.values("bones");
|
||||
default -> List.of();
|
||||
};
|
||||
result.add(new FormField(key, parameterLabel(key), "Параметр " + key + ". Пустое значение удаляет настройку.",
|
||||
() -> local.get(key).isJsonNull() ? "" : local.get(key).isJsonPrimitive() ? local.text("", key) : local.get(key).toString(), value -> {
|
||||
if (value.isBlank()) local.set(null, key); else local.string(value, key);
|
||||
}, choices, false));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private static List<String> aliases(String key) {
|
||||
return switch (key) {
|
||||
case "duration" -> List.of("duration", "d", "ticks", "md", "maxduration"); case "interval" -> List.of("interval", "i");
|
||||
case "type" -> List.of("type", "t"); case "level" -> List.of("level", "l"); case "amount" -> List.of("amount", "a");
|
||||
case "mid" -> List.of("mid", "model"); case "s" -> List.of("s", "skill", "state");
|
||||
case "sound" -> List.of("sound", "s"); case "volume" -> List.of("volume", "v"); case "pitch" -> List.of("pitch", "p");
|
||||
case "auraname" -> List.of("auraname", "n"); case "ontick" -> List.of("ontick", "ot", "ontickskill"); case "onhit" -> List.of("onhit", "oh");
|
||||
case "refreshduration" -> List.of("refreshduration", "rd"); case "hitradius" -> List.of("hitradius", "hr");
|
||||
case "verticalradius" -> List.of("verticalradius", "vr"); case "velocity" -> List.of("velocity", "v");
|
||||
case "pbone" -> List.of("pbone", "p"); case "lock" -> List.of("lock", "l");
|
||||
case "hs" -> List.of("hs", "hspread"); case "vs" -> List.of("vs", "vspread");
|
||||
default -> List.of(key);
|
||||
};
|
||||
}
|
||||
|
||||
private static List<String> parameterNames(String action) {
|
||||
return switch (action) {
|
||||
case "skill" -> List.of("s"); case "randomskill" -> List.of("skills"); case "delay" -> List.of("ticks");
|
||||
case "damage" -> List.of("a", "preventknockback"); case "basedamage" -> List.of("multiplier", "preventknockback"); case "model" -> List.of("mid", "scale", "step");
|
||||
case "state" -> List.of("s"); case "potion" -> List.of("type", "duration", "level");
|
||||
case "javascript", "js" -> List.of("script", "parameters"); case "sound" -> List.of("sound", "volume", "pitch");
|
||||
case "summon" -> List.of("type", "amount"); case "particles", "e:p" -> List.of("p", "amount", "hs", "vs", "speed", "color");
|
||||
case "aura" -> List.of("auraname", "duration", "interval", "ontick", "refreshduration");
|
||||
case "mountmodel", "dismountallmodel" -> List.of("pbone"); case "lockmodel" -> List.of("lock");
|
||||
case "setai" -> List.of("ai"); case "setspeed" -> List.of("speed"); case "setnodamageticks" -> List.of("ticks");
|
||||
case "velocity" -> List.of("x", "y", "z", "mode"); case "lunge" -> List.of("v"); case "throw" -> List.of("v", "vy");
|
||||
case "teleportto" -> List.of("location");
|
||||
case "missile", "projectile", "totem" -> List.of("ontick", "onhit", "duration", "interval", "velocity", "hitradius", "verticalradius", "origin", "syo", "sfo", "tyo", "vo", "inertia", "maxrange", "stopatblock", "hitplayers", "hitnonplayers", "charges", "stopatentity");
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
private static void target(Screen parent, ContentDraft owner, EditorCatalog catalog) {
|
||||
String current = owner.text("", "target");
|
||||
var parsed = MobSyntax.call(current.isBlank() ? "self" : current);
|
||||
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Выбор цели", parsed, local -> {
|
||||
var fields = new ArrayList<FormField>();
|
||||
fields.add(DataFields.text(local, "Тип цели", "Выберите способ поиска сущностей или позиции", "self", catalog.values("targets"), "name"));
|
||||
String name = local.text("self", "name");
|
||||
if (List.of("pir", "playersinradius", "livinginradius", "entitiesinring", "plir", "playerlocationsinradius", "rlnte", "randomlocationsneartargets", "randomlocationsnearcaster").contains(name)) {
|
||||
String key = local.get("arguments", "radius").isJsonNull() ? "r" : "radius";
|
||||
fields.add(DataFields.number(local, "Радиус, блоки", "От 0 до 256 блоков", "5", false, 0, 256, "arguments", key));
|
||||
}
|
||||
if (name.equals("modelpart") || name.equals("modelpassengers")) fields.add(DataFields.text(local, "Кость модели", "Имя кости", "", catalog.values("bones"), "arguments", "pid"));
|
||||
if (name.equals("forward") || name.equals("projectileforward")) {
|
||||
fields.add(DataFields.number(local, "Дистанция вперёд", "Блоков вдоль направления", "1", false, -256, 256, "arguments", "f"));
|
||||
fields.add(DataFields.bool(local, "Только горизонтальное направление", false, "arguments", "lockpitch"));
|
||||
}
|
||||
return fields;
|
||||
}, value -> owner.string(MobSyntax.call(value), "target"), List.of(), "Неизменённые дополнительные параметры цели сохраняются."));
|
||||
}
|
||||
private static String parameterLabel(String key) {
|
||||
return switch (key.toLowerCase(java.util.Locale.ROOT)) {
|
||||
case "s", "skill" -> "Навык, анимация или звук"; case "mid", "model" -> "Модель"; case "script" -> "Сценарий JavaScript";
|
||||
case "scale" -> "Масштаб"; case "ticks" -> "Время, тики"; case "duration" -> "Длительность, тики";
|
||||
case "interval" -> "Интервал, тики"; case "amount", "a" -> "Количество или сила"; case "radius" -> "Радиус";
|
||||
case "type" -> "Тип"; case "name" -> "Имя"; case "pbone", "part" -> "Кость модели"; case "level" -> "Уровень эффекта";
|
||||
case "speed", "velocity" -> "Скорость"; case "volume" -> "Громкость"; case "pitch" -> "Высота звука";
|
||||
case "onstart" -> "Навык при начале"; case "ontick" -> "Периодический навык"; case "onhit" -> "Навык при попадании";
|
||||
case "onend" -> "Навык при завершении"; case "parameters" -> "Параметры JavaScript, JSON";
|
||||
default -> key;
|
||||
} + " [" + key + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.MobFields;
|
||||
|
||||
public final class MobActionsScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final ContentDraft draft;
|
||||
private final EditorCatalog catalog;
|
||||
private final boolean mob;
|
||||
private int selected = -1;
|
||||
private String pending;
|
||||
public MobActionsScreen(Screen parent, ContentDraft draft, EditorCatalog catalog, boolean mob) {
|
||||
super(mob ? "События и действия моба" : "Последовательность навыка");
|
||||
this.parent = parent; this.draft = draft; this.catalog = catalog; this.mob = mob;
|
||||
}
|
||||
private JsonArray values() { var value = draft.get("skills"); return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
|
||||
@Override protected void init() {
|
||||
var values = values();
|
||||
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 166), label -> {
|
||||
selected = Integer.parseInt(label.substring(0, label.indexOf('.'))) - 1; rebuildWidgets();
|
||||
}));
|
||||
var labels = new java.util.ArrayList<String>();
|
||||
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + (i == selected ? "▶ " : "") + MobFields.actionSummary(values.get(i).getAsString()));
|
||||
list.values(labels);
|
||||
int part = (width - 40) / 3;
|
||||
button("+ Действие", 12, height - 118, part, () -> minecraft.gui.setScreen(new ChoiceScreen(this, "Добавить действие",
|
||||
catalog.values("actions").stream().map(id -> MobFields.actionName(id) + " [" + id + "]").toList(), choice -> pending = choice)));
|
||||
button("Настроить", 20 + part, height - 118, part, this::edit).active = selected >= 0;
|
||||
button("Удалить", 28 + part * 2, height - 118, part, () -> { values.remove(selected); draft.set(values, "skills"); selected = -1; rebuildWidgets(); }).active = selected >= 0;
|
||||
button("Выше ↑", 12, height - 91, part, () -> move(-1)).active = selected > 0;
|
||||
button("Ниже ↓", 20 + part, height - 91, part, () -> move(1)).active = selected >= 0 && selected + 1 < values.size();
|
||||
button("Запись…", 28 + part * 2, height - 91, part, "Расширенный режим сохраняет сложные вложенные выражения.", this::raw).active = selected >= 0;
|
||||
button("Готово", 12, height - 27, 110, this::onClose);
|
||||
status(values.isEmpty() ? "Действий пока нет. Добавьте первое действие из каталога сервера." : "Выберите действие. Порядок, события, цели и условия сохраняются в черновике.", false);
|
||||
}
|
||||
@Override public void tick() {
|
||||
if (pending == null) return;
|
||||
String id = pending.substring(pending.lastIndexOf('[') + 1, pending.length() - 1); pending = null;
|
||||
MobActionForms.open(this, catalog, id + (mob ? " ~onSpawn" : ""), mob, value -> { var values = values(); values.add(value); draft.set(values, "skills"); });
|
||||
}
|
||||
private void edit() {
|
||||
try { MobActionForms.open(this, catalog, values().get(selected).getAsString(), mob, value -> replace(value)); }
|
||||
catch (RuntimeException error) { status("Откройте «Запись…» для этой сложной последовательности: " + error.getMessage(), true); }
|
||||
}
|
||||
private void replace(String value) { var values = values(); values.set(selected, new JsonPrimitive(value)); draft.set(values, "skills"); }
|
||||
private void move(int delta) {
|
||||
var values = values(); var value = values.get(selected); values.set(selected, values.get(selected + delta)); selected += delta;
|
||||
values.set(selected, value); draft.set(values, "skills"); rebuildWidgets();
|
||||
}
|
||||
private void raw() {
|
||||
var initial = new JsonObject(); initial.addProperty("action", values().get(selected).getAsString());
|
||||
minecraft.gui.setScreen(new JsonObjectScreen(this, "Действие: расширенная запись", initial, accepted -> {
|
||||
if (!accepted.has("action") || !accepted.get("action").isJsonPrimitive()) throw new IllegalArgumentException("Нужна строка action.");
|
||||
replace(accepted.get("action").getAsString());
|
||||
}));
|
||||
}
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
|
||||
/** A server-backed catalog; opening an entry never spawns a mob or modifies its file. */
|
||||
public final class MobBrowserScreen extends EditorScreen {
|
||||
private final EditorConnection connection;
|
||||
private final EditorCatalog catalog = new EditorCatalog();
|
||||
private final boolean skill;
|
||||
private final Map<String, String> rows = new LinkedHashMap<>();
|
||||
private ChoiceList list;
|
||||
private net.minecraft.client.gui.components.Button previous, next;
|
||||
private String query = "";
|
||||
private int page, pages = 1, delay, generation;
|
||||
public MobBrowserScreen(EditorConnection connection, boolean skill) {
|
||||
super(skill ? "AstraPlus: навыки" : "AstraPlus: мобы"); this.connection = connection; this.skill = skill;
|
||||
}
|
||||
@Override protected void init() {
|
||||
int part = (width - 40) / 3;
|
||||
button("Предметы и блоки", 12, 38, part, () -> minecraft.gui.setScreen(new ContentBrowserScreen(connection)));
|
||||
button("Мобы", 20 + part, 38, part, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, false))).active = skill;
|
||||
button("Навыки", 28 + part * 2, 38, part, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, true))).active = !skill;
|
||||
var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск")));
|
||||
search.setMaxLength(256); search.setHint(Component.literal("Поиск по названию или namespace:id")); search.setValue(query);
|
||||
search.setResponder(value -> { query = value; page = 0; delay = 6; });
|
||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(26, height - 193), row -> load(rows.get(row))));
|
||||
list.values(rows.keySet().stream().toList());
|
||||
button(skill ? "+ Навык" : "+ Моб", 12, height - 94, 130, this::create);
|
||||
button("Обновить", width - 142, height - 94, 130, this::refresh);
|
||||
previous = button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } }); previous.active = page > 0;
|
||||
next = button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } }); next.active = page + 1 < pages;
|
||||
button("Закрыть", width - 112, height - 27, 100, this::onClose);
|
||||
connection.request("mob_catalog", new JsonObject(), response -> {
|
||||
if (EditorConnection.success(response)) catalog.update(response); else reply(response);
|
||||
});
|
||||
refresh();
|
||||
}
|
||||
@Override public void tick() { if (delay > 0 && --delay == 0) refresh(); }
|
||||
private void refresh() {
|
||||
int current = ++generation;
|
||||
var request = new JsonObject(); request.addProperty("page", page); request.addProperty("query", query);
|
||||
status("Загружается каталог…", false);
|
||||
connection.request(skill ? "skill_list" : "mob_list", request, response -> {
|
||||
if (current != generation) return;
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
rows.clear();
|
||||
if (response.has("entries")) for (var element : response.getAsJsonArray("entries")) {
|
||||
var entry = element.getAsJsonObject(); String id = entry.get("id").getAsString();
|
||||
String label = entry.has("name") ? entry.get("name").getAsString() : id;
|
||||
rows.put(label + " [" + id + "]" + (!skill && entry.has("entity") ? " " + entry.get("entity").getAsString() : ""), id);
|
||||
}
|
||||
page = response.has("page") ? response.get("page").getAsInt() : page;
|
||||
pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1);
|
||||
list.values(rows.keySet().stream().toList());
|
||||
previous.active = page > 0; next.active = page + 1 < pages;
|
||||
status("Страница " + (page + 1) + " / " + pages + ". " + (skill ? "Откройте навык, чтобы изучить действия и условия." : "Откройте моба, чтобы изучить модель, поведение и получить яйцо."), false);
|
||||
});
|
||||
}
|
||||
private void load(String id) {
|
||||
if (id == null) return;
|
||||
var request = new JsonObject(); request.addProperty("id", id);
|
||||
connection.request(skill ? "skill_get" : "mob_get", request, response -> {
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
if (minecraft.gui.screen() != this) return;
|
||||
minecraft.gui.setScreen(new MobEditorScreen(this, connection, catalog,
|
||||
online.astradev.plus.editor.form.MobDocuments.draft(response), skill,
|
||||
response.has("details") ? response.getAsJsonObject("details") : new JsonObject()));
|
||||
});
|
||||
}
|
||||
private void create() {
|
||||
var initial = new JsonObject(); initial.addProperty("id", skill ? "astraplus:new_skill" : "astraplus:new_mob");
|
||||
initial.addProperty("name", skill ? "Новый навык" : "Новый моб");
|
||||
if (!skill) { initial.addProperty("entity", "minecraft:pig"); initial.addProperty("health", 20); }
|
||||
initial.add("skills", new com.google.gson.JsonArray());
|
||||
minecraft.gui.setScreen(new MobEditorScreen(this, connection, catalog, new ContentDraft(initial, "new"), skill, new JsonObject()));
|
||||
}
|
||||
private void reply(JsonObject response) { status(EditorConnection.message(response), !EditorConnection.success(response)); }
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import com.google.gson.JsonArray;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.MobFields;
|
||||
import online.astradev.plus.editor.form.MobSyntax;
|
||||
|
||||
public final class MobConditionsScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final EditorCatalog catalog;
|
||||
private final JsonArray values;
|
||||
private final boolean inline;
|
||||
private final Consumer<JsonArray> changed;
|
||||
private String pending;
|
||||
|
||||
public MobConditionsScreen(Screen parent, EditorCatalog catalog, String title, JsonArray initial, boolean inline, Consumer<JsonArray> changed) {
|
||||
super(title); this.parent = parent; this.catalog = catalog; this.values = initial.deepCopy(); this.inline = inline; this.changed = changed;
|
||||
}
|
||||
@Override protected void init() {
|
||||
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 137), row -> edit(Integer.parseInt(row.substring(0, row.indexOf('.'))) - 1)));
|
||||
var labels = new java.util.ArrayList<String>();
|
||||
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + MobSyntax.conditionSummary(values.get(i).getAsString()));
|
||||
list.values(labels);
|
||||
button("+ Условие", 12, height - 88, 130, () -> minecraft.gui.setScreen(new ChoiceScreen(this, "Добавить условие",
|
||||
catalog.values("conditions").stream().map(id -> MobSyntax.conditionName(id) + " [" + id + "]").toList(), selected -> pending = selected)));
|
||||
button("Готово", 12, height - 27, 110, this::onClose);
|
||||
status(values.isEmpty() ? "Ограничений нет. Добавьте проверки, которые должны пройти перед действием."
|
||||
: "Все проверки выполняются перед применением навыка. Нажмите строку для настройки.", false);
|
||||
}
|
||||
@Override public void tick() {
|
||||
if (pending == null) return;
|
||||
String id = pending.substring(pending.lastIndexOf('[') + 1, pending.length() - 1); pending = null;
|
||||
open(-1, id + " true");
|
||||
}
|
||||
private void edit(int index) { open(index, values.get(index).getAsString()); }
|
||||
private void open(int index, String source) {
|
||||
try {
|
||||
var value = MobSyntax.condition(source);
|
||||
String title = MobSyntax.conditionName(value.getAsJsonObject("call").get("name").getAsString());
|
||||
var actions = new java.util.ArrayList<SettingsScreen.Action>();
|
||||
if (index >= 0) actions.add(new SettingsScreen.Action("Удалить условие", (screen, local) -> {
|
||||
values.remove(index); changed.accept(values.deepCopy()); minecraft.gui.setScreen(this);
|
||||
}));
|
||||
minecraft.gui.setScreen(new SettingsScreen(this, title, value, local -> MobFields.condition(local, catalog, inline), accepted -> {
|
||||
String encoded = MobSyntax.condition(accepted);
|
||||
if (index < 0) values.add(encoded); else values.set(index, new com.google.gson.JsonPrimitive(encoded));
|
||||
changed.accept(values.deepCopy());
|
||||
}, List.copyOf(actions), "Проверка поведения. Эти условия не создают правила природного спавна."));
|
||||
} catch (RuntimeException error) { status(error.getMessage() + " Исходную запись можно изменить в расширенном JSON определения.", true); }
|
||||
}
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.List;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.DataFields;
|
||||
|
||||
public final class MobDropsScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final ContentDraft draft;
|
||||
private final EditorCatalog catalog;
|
||||
public MobDropsScreen(Screen parent, ContentDraft draft, EditorCatalog catalog) {
|
||||
super("Лут моба"); this.parent = parent; this.draft = draft; this.catalog = catalog;
|
||||
}
|
||||
private JsonArray values() { var value = draft.get("drops"); return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
|
||||
@Override protected void init() {
|
||||
var values = values();
|
||||
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 139), row -> edit(Integer.parseInt(row.substring(0, row.indexOf('.'))) - 1)));
|
||||
var labels = new java.util.ArrayList<String>();
|
||||
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + values.get(i).getAsString());
|
||||
list.values(labels);
|
||||
button("+ Предмет лута", 12, height - 90, 145, () -> edit(-1));
|
||||
button("Готово", 12, height - 27, 110, this::onClose);
|
||||
status("Лут поддерживает ванильные предметы, диапазон количества и вероятность. Замена обычного лута задаётся в свойствах моба.", false);
|
||||
}
|
||||
private void edit(int index) {
|
||||
var initial = new JsonObject(); initial.addProperty("item", "minecraft:diamond"); initial.addProperty("minimum", 1); initial.addProperty("maximum", 1); initial.addProperty("chance", 1);
|
||||
if (index >= 0) {
|
||||
String[] parts = values().get(index).getAsString().trim().split("\\s+");
|
||||
if (parts.length != 3) { status("Эта запись доступна через расширенный JSON определения.", true); return; }
|
||||
String[] range = parts[1].split("-");
|
||||
initial.addProperty("item", parts[0]); initial.addProperty("minimum", Integer.parseInt(range[0]));
|
||||
initial.addProperty("maximum", Integer.parseInt(range.length > 1 ? range[1] : range[0])); initial.addProperty("chance", Double.parseDouble(parts[2]));
|
||||
}
|
||||
var actions = index < 0 ? List.<SettingsScreen.Action>of() : List.of(new SettingsScreen.Action("Удалить запись лута", (screen, local) -> {
|
||||
var values = values(); values.remove(index); draft.set(values, "drops"); minecraft.gui.setScreen(this);
|
||||
}));
|
||||
minecraft.gui.setScreen(new SettingsScreen(this, "Предмет лута", initial, local -> List.of(
|
||||
DataFields.text(local, "Предмет", "Ванильный идентификатор предмета", "minecraft:diamond", catalog.values("items"), "item"),
|
||||
DataFields.number(local, "Минимум", "Количество при успешном выпадении", "1", true, 0, 2304, "minimum"),
|
||||
DataFields.number(local, "Максимум", "Случайное количество между минимумом и максимумом", "1", true, 0, 2304, "maximum"),
|
||||
DataFields.number(local, "Вероятность", "От 0 до 1, где 1 = 100%", "1", false, 0, 1, "chance")), accepted -> {
|
||||
int minimum = accepted.get("minimum").getAsInt(), maximum = accepted.get("maximum").getAsInt();
|
||||
if (maximum < minimum) throw new IllegalArgumentException("Максимум должен быть не меньше минимума.");
|
||||
String value = accepted.get("item").getAsString() + " " + minimum + (minimum == maximum ? "" : "-" + maximum) + " " + accepted.get("chance").getAsString();
|
||||
var values = values(); if (index < 0) values.add(value); else values.set(index, new JsonPrimitive(value)); draft.set(values, "drops");
|
||||
}, actions, "Ни один предмет не выдаётся до сохранения определения и смерти моба."));
|
||||
}
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.AbstractWidget;
|
||||
import net.minecraft.client.gui.screens.ConfirmScreen;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.DataFields;
|
||||
import online.astradev.plus.editor.form.MobFields;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
|
||||
/** Mob and skill detail cards share optimistic revisions and explicit saves. */
|
||||
public final class MobEditorScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final EditorConnection connection;
|
||||
private final EditorCatalog catalog;
|
||||
private final ContentDraft draft;
|
||||
private final boolean skill;
|
||||
private JsonObject details;
|
||||
private boolean saving;
|
||||
private int sectionPage;
|
||||
private String pendingSkill, pendingModel;
|
||||
|
||||
public MobEditorScreen(Screen parent, EditorConnection connection, EditorCatalog catalog, ContentDraft draft, boolean skill, JsonObject details) {
|
||||
super(skill ? "AstraPlus: навык" : "AstraPlus: моб"); this.parent = parent; this.connection = connection; this.catalog = catalog;
|
||||
this.draft = draft; this.skill = skill; this.details = details.deepCopy();
|
||||
}
|
||||
@Override protected void init() {
|
||||
int columns = 2, part = (width - 36) / columns;
|
||||
var sections = new ArrayList<Section>();
|
||||
sections.add(new Section("Основное", this::basic));
|
||||
if (!skill) sections.add(new Section("Свойства и защита", this::options));
|
||||
sections.add(new Section(skill ? "Последовательность" : "События и действия", () -> minecraft.gui.setScreen(new MobActionsScreen(this, draft, catalog, !skill))));
|
||||
sections.add(new Section(skill ? "Условия исполнителя" : "ИИ и выбор цели", skill ? () -> conditions("conditions", "Условия исполнителя") : this::ai));
|
||||
sections.add(new Section(skill ? "Условия цели" : "Лут", skill ? () -> conditions("targetConditions", "Условия цели") : () -> minecraft.gui.setScreen(new MobDropsScreen(this, draft, catalog))));
|
||||
sections.add(new Section("Связанные навыки", this::skills));
|
||||
sections.add(new Section("Расширенный JSON", () -> minecraft.gui.setScreen(new JsonObjectScreen(this, "Определение: расширенный режим", draft.document(), draft::replace))));
|
||||
if (!skill) sections.add(new Section("Модели и анимации", this::models));
|
||||
if (!draft.fresh()) sections.add(new Section("Источник и сведения", this::information));
|
||||
if (!skill && !draft.fresh() && height < 330) sections.add(new Section("Призвать рядом", () -> action("mob_spawn")));
|
||||
int perPage = Math.max(1, (height - 200) / 28) * columns;
|
||||
int pages = Math.max(1, (sections.size() + perPage - 1) / perPage);
|
||||
sectionPage = Math.min(sectionPage, pages - 1);
|
||||
for (int index = sectionPage * perPage; index < Math.min(sections.size(), (sectionPage + 1) * perPage); index++) {
|
||||
int relative = index - sectionPage * perPage;
|
||||
var section = sections.get(index);
|
||||
button(section.name, 12 + relative % columns * (part + 12), 102 + relative / columns * 28, part, section.action);
|
||||
}
|
||||
if (pages > 1) {
|
||||
button("←", 12, height - 91, 30, () -> { sectionPage--; rebuildWidgets(); }).active = sectionPage > 0;
|
||||
button("→", 48, height - 91, 30, () -> { sectionPage++; rebuildWidgets(); }).active = sectionPage + 1 < pages;
|
||||
}
|
||||
int size = (width - 40) / 3;
|
||||
button("Назад", 12, height - 27, size, this::onClose);
|
||||
button("Сохранить", 20 + size, height - 27, size, this::save);
|
||||
if (!skill) button("Яйцо призыва", 28 + size * 2, height - 27, size, "Выдаётся яйцо сохранённой серверной версии моба.", () -> action("mob_egg")).active = !draft.fresh();
|
||||
if (!skill && height >= 330) button("Призвать рядом", width - 156, height - 91, 144,
|
||||
"Создаёт настоящего моба рядом с вами. Для изучения модели используйте предпросмотр.", () -> action("mob_spawn")).active = !draft.fresh();
|
||||
if (saving) for (var child : children()) if (child instanceof AbstractWidget widget) widget.active = false;
|
||||
if (status.isBlank()) status(draft.fresh() ? "Новое определение. Настройте его и сохраните на сервере."
|
||||
: "Редактируется локальный черновик. Сервер изменится после «Сохранить».", false);
|
||||
}
|
||||
private void basic() {
|
||||
minecraft.gui.setScreen(new SettingsScreen(this, "Основные настройки", draft.document(), local -> {
|
||||
var fields = new ArrayList<>(MobFields.basic(local, catalog, skill));
|
||||
if (draft.fresh()) fields.addFirst(DataFields.text(local, "Идентификатор", "namespace:путь, без пробелов", draft.id(), List.of(), "id"));
|
||||
return fields;
|
||||
}, draft::replace, List.of(), "Основа задаёт ванильный тип сущности. Пользовательская модель подключается действием model."));
|
||||
}
|
||||
private void options() { minecraft.gui.setScreen(new SettingsScreen(this, "Свойства моба", draft.document(), MobFields::options, draft::replace,
|
||||
List.of(), "Пустые числовые поля наследуются от основы или значения сервера, указанного в подсказке.")); }
|
||||
private void ai() {
|
||||
minecraft.gui.setScreen(new SettingsScreen(this, "Поведение и выбор цели", draft.document(), local -> List.of(
|
||||
DataFields.bool(local, "Учитывать накопленную угрозу", false, "modules", "ThreatTable")), draft::replace, List.of(
|
||||
new SettingsScreen.Action("Действия ИИ", (screen, local) -> minecraft.gui.setScreen(new IdentifierListScreen(screen, "Действия ИИ",
|
||||
array(local, "goals"), List.of("clear", "meleeattack", "gotoplayer", "movetowardstarget", "randomstroll"), 16, false, values -> local.set(values, "goals")))),
|
||||
new SettingsScreen.Action("Выбор цели", (screen, local) -> minecraft.gui.setScreen(new IdentifierListScreen(screen, "Цели моба",
|
||||
array(local, "targets"), List.of("clear", "players", "attacker", "otherfaction", "otherfactionmonsters"), 16, false, values -> local.set(values, "targets"))))),
|
||||
"Пустые списки сохраняют ванильный ИИ. clear удаляет ванильные задачи или цели перед добавлением ваших."));
|
||||
}
|
||||
private void information() {
|
||||
var text = new StringBuilder("Определение: ").append(draft.id()).append("\nФайл сервера: ")
|
||||
.append(details.has("file") ? details.get("file").getAsString() : "Не передан сервером");
|
||||
if (details.has("models")) for (var element : details.getAsJsonArray("models")) {
|
||||
var model = element.getAsJsonObject(); text.append("\n\nМодель: ").append(model.get("id").getAsString());
|
||||
text.append("\nКостей: ").append(model.get("bones").getAsInt());
|
||||
if (model.has("width") && model.has("height")) text.append("\nГабариты: ").append(model.get("width").getAsString())
|
||||
.append(" × ").append(model.get("height").getAsString()).append(" блока");
|
||||
if (model.has("animations")) {
|
||||
var names = new ArrayList<String>(); model.getAsJsonArray("animations").forEach(value -> names.add(value.getAsString()));
|
||||
text.append("\nАнимации: ").append(names.isEmpty() ? "Нет" : String.join(", ", names));
|
||||
}
|
||||
}
|
||||
text.append("\n\nУсловия навыков управляют действиями. Природный спавн отдельно не настроен этим экраном.");
|
||||
minecraft.gui.setScreen(new MessageScreen(this, "AstraPlus: сведения об определении", text.toString()));
|
||||
}
|
||||
private void conditions(String key, String title) { minecraft.gui.setScreen(new MobConditionsScreen(this, catalog, title, array(draft, key), false, values -> draft.set(values, key))); }
|
||||
private static JsonArray array(ContentDraft draft, String key) { var value = draft.get(key); return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
|
||||
private void skills() {
|
||||
var ids = new ArrayList<String>();
|
||||
if (details.has("referencedSkills")) details.getAsJsonArray("referencedSkills").forEach(value -> ids.add(value.getAsString()));
|
||||
if (ids.isEmpty()) ids.addAll(catalog.values("skills"));
|
||||
minecraft.gui.setScreen(new ChoiceScreen(this, "Открыть связанный навык", ids, id -> pendingSkill = id));
|
||||
}
|
||||
private void models() {
|
||||
var ids = new ArrayList<String>();
|
||||
if (details.has("models")) details.getAsJsonArray("models").forEach(value -> ids.add(value.getAsJsonObject().get("id").getAsString()));
|
||||
if (ids.isEmpty()) ids.addAll(catalog.values("models"));
|
||||
minecraft.gui.setScreen(new ChoiceScreen(this, "Модели: предпросмотр и анимации", ids, id -> pendingModel = id));
|
||||
}
|
||||
@Override public void tick() {
|
||||
if (pendingSkill != null) {
|
||||
String id = pendingSkill; pendingSkill = null;
|
||||
var request = new JsonObject(); request.addProperty("id", id);
|
||||
connection.request("skill_get", request, response -> {
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
if (minecraft.gui.screen() != this) return;
|
||||
minecraft.gui.setScreen(new MobEditorScreen(this, connection, catalog, online.astradev.plus.editor.form.MobDocuments.draft(response),
|
||||
true, response.has("details") ? response.getAsJsonObject("details") : new JsonObject()));
|
||||
});
|
||||
}
|
||||
if (pendingModel != null) {
|
||||
String id = pendingModel; pendingModel = null;
|
||||
var request = new JsonObject(); request.addProperty("id", id);
|
||||
status("Загружается модель…", false);
|
||||
connection.request("model_preview", request, response -> {
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
if (minecraft.gui.screen() == this) minecraft.gui.setScreen(new MobPreviewScreen(this, draft.text(draft.id(), "name"), response));
|
||||
});
|
||||
}
|
||||
}
|
||||
private void save() {
|
||||
if (saving) return;
|
||||
var request = new JsonObject(); request.addProperty("id", draft.id()); request.addProperty("revision", draft.revision()); request.add("document", draft.document());
|
||||
saving = true; rebuildWidgets(); status("Сервер проверяет ссылки, условия и сохраняет определение…", false);
|
||||
connection.request(skill ? "skill_save" : "mob_save", request, response -> {
|
||||
saving = false;
|
||||
if (EditorConnection.success(response)) {
|
||||
draft.saved(response.has("document") ? online.astradev.plus.editor.form.MobDocuments.document(response) : request.getAsJsonObject("document"), response.get("revision").getAsString());
|
||||
if (response.has("details")) details = response.getAsJsonObject("details").deepCopy();
|
||||
}
|
||||
reply(response); if (minecraft.gui.screen() == this) rebuildWidgets();
|
||||
});
|
||||
}
|
||||
private void action(String action) {
|
||||
var request = new JsonObject(); request.addProperty("id", draft.id()); request.addProperty("count", 1);
|
||||
connection.request(action, request, this::reply);
|
||||
}
|
||||
private void reply(JsonObject response) { status(EditorConnection.message(response), !EditorConnection.success(response)); }
|
||||
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||
graphics.fill(12, 37, width - 12, 91, 0xFF1B3038);
|
||||
graphics.text(font, font.plainSubstrByWidth(draft.text(draft.id(), "name") + (draft.dirty() ? " Черновик" : " Сохранено"), width - 42), 21, 44, 0xFFE0F4F4);
|
||||
graphics.text(font, font.plainSubstrByWidth(draft.id(), width - 42), 21, 59, 0xFF88B7C4);
|
||||
String summary = skill ? "Действий: " + array(draft, "skills").size() + " Перезарядка: " + draft.text("0", "cooldown") + " с"
|
||||
: "Основа: " + Component.translatable("entity." + draft.text("minecraft:pig", "entity").replace(':', '.')).getString()
|
||||
+ " Здоровье: " + draft.text("20", "health") + " Урон: " + draft.text("0", "damage");
|
||||
graphics.text(font, font.plainSubstrByWidth(summary, width - 42), 21, 76, 0xFFB3CED4);
|
||||
}
|
||||
@Override public void onClose() {
|
||||
if (saving) { status("Дождитесь завершения сохранения.", true); return; }
|
||||
if (draft.dirty()) minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
|
||||
Component.literal("Закрыть без сохранения?"), Component.literal("Локальные изменения определения будут потеряны."), Component.literal("Не сохранять"), Component.literal("Продолжить")));
|
||||
else minecraft.gui.setScreen(parent);
|
||||
}
|
||||
private record Section(String name, Runnable action) {}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.input.MouseButtonEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.preview.PreviewModel;
|
||||
import online.astradev.plus.editor.client.preview.PreviewScene;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
|
||||
/** Interactive, local-only model inspection with the same skeleton and pack as live mobs. */
|
||||
public final class MobPreviewScreen extends EditorScreen {
|
||||
private static final String REST_POSE = "Исходная поза";
|
||||
private final Screen parent;
|
||||
private PreviewScene scene;
|
||||
private float yaw = 0.65F, pitch = -0.15F, zoom = 1;
|
||||
private float elapsed;
|
||||
private long lastFrame = System.nanoTime();
|
||||
private boolean paused, dragging, loading;
|
||||
private Button play;
|
||||
|
||||
public MobPreviewScreen(Screen parent, String name, JsonObject descriptor) {
|
||||
super("Модель: " + name); this.parent = parent;
|
||||
try { scene = new PreviewScene(PreviewModel.read(descriptor)); }
|
||||
catch (RuntimeException error) { status("Не удалось открыть модель: " + error.getMessage(), true); }
|
||||
}
|
||||
|
||||
public String selectedAnimation() { return scene == null ? "" : scene.model().selectedAnimation(); }
|
||||
public float animationTime() { return elapsed; }
|
||||
public boolean isPlaying() { return scene != null && scene.model().animation() != null && !paused; }
|
||||
|
||||
@Override protected void init() {
|
||||
button("Назад", 12, height - 27, 90, this::onClose);
|
||||
int available = Math.max(180, width - 24), gap = 6;
|
||||
int control = Math.max(55, (available - gap * 3) / 4);
|
||||
button("Анимация…", 12, 38, control, this::chooseAnimation).active = scene != null && !scene.model().animations().isEmpty();
|
||||
play = button(paused ? "Продолжить" : "Пауза", 12 + control + gap, 38, control, () -> {
|
||||
paused = !paused; play.setMessage(Component.literal(paused ? "Продолжить" : "Пауза"));
|
||||
});
|
||||
play.active = scene != null && scene.model().animation() != null;
|
||||
button("Сначала", 12 + (control + gap) * 2, 38, control, () -> elapsed = 0);
|
||||
button("Сброс вида", 12 + (control + gap) * 3, 38, control, () -> { yaw = 0.65F; pitch = -0.15F; zoom = 1; });
|
||||
if (scene != null) {
|
||||
if (loading) status("Загрузка анимации…", false);
|
||||
else if (!scene.missing().isEmpty()) status("Для просмотра загрузите актуальный ресурспак сервера. Отсутствуют модели частей: "
|
||||
+ scene.missing().size() + ". Например, " + scene.missing().getFirst(), true);
|
||||
else if (!scene.hasGeometry()) status("У модели нет видимых частей. Проверьте видимость и экспорт геометрии.", true);
|
||||
else status("Перетаскивайте модель для вращения. Колесо мыши меняет масштаб.", false);
|
||||
}
|
||||
lastFrame = System.nanoTime();
|
||||
}
|
||||
|
||||
private void chooseAnimation() {
|
||||
if (scene == null || loading) return;
|
||||
var choices = new ArrayList<String>(); choices.add(REST_POSE);
|
||||
scene.model().animations().forEach(name -> choices.add("Анимация: " + name));
|
||||
minecraft.gui.setScreen(new ChoiceScreen(this, "Анимации модели", choices, selection -> {
|
||||
JsonObject body = new JsonObject(); body.addProperty("id", scene.model().id());
|
||||
body.addProperty("animation", selection.equals(REST_POSE) ? "" : selection.substring("Анимация: ".length()));
|
||||
loading = true; status("Загрузка анимации…", false);
|
||||
EditorConnection.INSTANCE.request("model_preview", body, response -> {
|
||||
loading = false;
|
||||
if (!EditorConnection.success(response)) { status(EditorConnection.message(response), true); return; }
|
||||
try {
|
||||
scene = new PreviewScene(PreviewModel.read(response)); elapsed = 0; lastFrame = System.nanoTime();
|
||||
if (minecraft.gui.screen() == this) rebuildWidgets();
|
||||
} catch (RuntimeException error) { status("Не удалось прочитать анимацию: " + error.getMessage(), true); }
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float partialTick) {
|
||||
super.extractRenderState(graphics, mouseX, mouseY, partialTick);
|
||||
int bottom = Math.max(95, height - 82);
|
||||
graphics.fill(12, 65, width - 12, bottom, 0xFF0C141A);
|
||||
for (int x = 28; x < width - 12; x += 24) graphics.fill(x, 65, x + 1, bottom, 0xFF17242B);
|
||||
for (int y = 77; y < bottom; y += 24) graphics.fill(12, y, width - 12, y + 1, 0xFF17242B);
|
||||
long now = System.nanoTime();
|
||||
if (!paused && minecraft.gui.screen() == this) elapsed += Math.min(0.1F, (now - lastFrame) / 1_000_000_000F);
|
||||
lastFrame = now;
|
||||
if (scene == null) return;
|
||||
try { scene.extract(graphics, 13, 66, width - 13, bottom - 1, elapsed, yaw, pitch, zoom); }
|
||||
catch (RuntimeException error) { scene = null; status("Предпросмотр остановлен: " + error.getMessage(), true); return; }
|
||||
graphics.text(font, font.plainSubstrByWidth(scene.model().id(), width - 36), 18, 71, 0xFF88B7C4);
|
||||
String animation = scene.model().selectedAnimation().isEmpty()
|
||||
? REST_POSE : scene.model().selectedAnimation();
|
||||
String info = animation + " | " + Math.round(zoom * 100) + "%";
|
||||
graphics.text(font, font.plainSubstrByWidth(info, width - 36), 18, bottom - 14, 0xFFBDD1D9);
|
||||
if (!scene.missing().isEmpty()) graphics.text(font, "Требуется ресурспак", Math.max(20, (width - font.width("Требуется ресурспак")) / 2),
|
||||
(65 + bottom) / 2, 0xFFFFC69A);
|
||||
}
|
||||
|
||||
private boolean inside(double x, double y) { return x >= 12 && x < width - 12 && y >= 65 && y < height - 82; }
|
||||
|
||||
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
|
||||
if (event.button() == 0 && inside(event.x(), event.y())) { dragging = true; return true; }
|
||||
return super.mouseClicked(event, doubleClick);
|
||||
}
|
||||
|
||||
@Override public boolean mouseDragged(MouseButtonEvent event, double dx, double dy) {
|
||||
if (dragging && event.button() == 0) {
|
||||
yaw += (float) dx * 0.012F; pitch = Math.clamp(pitch + (float) dy * 0.012F, -1.5F, 1.5F); return true;
|
||||
}
|
||||
return super.mouseDragged(event, dx, dy);
|
||||
}
|
||||
|
||||
@Override public boolean mouseReleased(MouseButtonEvent event) {
|
||||
if (dragging && event.button() == 0) { dragging = false; return true; }
|
||||
return super.mouseReleased(event);
|
||||
}
|
||||
|
||||
@Override public boolean mouseScrolled(double x, double y, double horizontal, double vertical) {
|
||||
if (inside(x, y)) { zoom = Math.clamp(zoom * (float) Math.pow(1.12, vertical), 0.2F, 5F); return true; }
|
||||
return super.mouseScrolled(x, y, horizontal, vertical);
|
||||
}
|
||||
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -46,8 +46,8 @@ public final class SettingsScreen extends EditorScreen {
|
||||
labels.clear();
|
||||
var fields = this.fields.apply(local);
|
||||
if (fields.isEmpty()) {
|
||||
labels.add(new Label("Свойство включится после добавления в черновик.", 18, 53, width - 36));
|
||||
labels.add(new Label(actions.isEmpty() ? "Дополнительных параметров у него нет." : "Состав эффектов задаётся кнопкой ниже.", 18, 73, width - 36));
|
||||
labels.add(new Label("У этой формы нет отдельных полей.", 18, 53, width - 36));
|
||||
labels.add(new Label(actions.isEmpty() ? "Примените её кнопкой «В черновик»." : "Дополнительные настройки открываются кнопкой ниже.", 18, 73, width - 36));
|
||||
}
|
||||
int columns = width >= 570 ? 2 : 1;
|
||||
int rows = Math.max(1, (height - 140) / 48);
|
||||
@@ -91,8 +91,8 @@ public final class SettingsScreen extends EditorScreen {
|
||||
button("Назад", 18, height - 27, 110, this::onClose);
|
||||
button("В черновик", width - 148, height - 27, 130, () -> {
|
||||
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
|
||||
apply.accept(local.document());
|
||||
minecraft.gui.setScreen(parent);
|
||||
try { apply.accept(local.document()); minecraft.gui.setScreen(parent); }
|
||||
catch (IllegalArgumentException error) { status(error.getMessage(), true); }
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user