Show resource-pack item icons and edit content translations
This commit is contained in:
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
## Установка и работа
|
## Установка и работа
|
||||||
|
|
||||||
1. Установите `AstraPlusEditor-0.3.1.jar` из `build/libs` в папку `mods` **клиента администратора**.
|
1. Установите `AstraPlusEditor-0.3.2.jar` из `build/libs` в папку `mods` **клиента администратора**.
|
||||||
Этот JAR не устанавливается на сервер. Для меню мобов требуется серверный **AstraPlus 0.5.0 или новее**.
|
Этот JAR не устанавливается на сервер. Для меню мобов требуется серверный **AstraPlus 0.5.0 или новее**.
|
||||||
Версия протокола редактора остаётся 1; каналы необязательны.
|
Версия протокола редактора остаётся 1; каналы необязательны.
|
||||||
2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**.
|
2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**.
|
||||||
@@ -111,6 +111,31 @@
|
|||||||
|
|
||||||
## Протокол и ограничения
|
## Протокол и ограничения
|
||||||
|
|
||||||
|
В каталоге предметов и блоков показывается иконка сохранённого серверного стека: модель
|
||||||
|
из ресурспака, цвет и свечение. Название и идентификатор расположены на отдельных строках.
|
||||||
|
Если модель ещё не загружена, отображается ванильная основа с объяснением в подсказке.
|
||||||
|
Сервер ограничивает данные каждой иконки 16 КиБ: объёмные книги и контейнеры заменяются
|
||||||
|
компактным набором визуальных свойств. Старые серверы без поля `icon` поддерживаются:
|
||||||
|
редактор использует доступную модель, а без неё показывает основу или бумагу.
|
||||||
|
|
||||||
|
Раздел **Переводы** доступен у предметов, блоков и мобов. Выберите язык Minecraft и задайте
|
||||||
|
название; у предметов и блоков можно также перевести строки описания. Пустое название
|
||||||
|
использует основное имя. Пропущенные строки описания используют строки `minecraft:lore`
|
||||||
|
из свойств предмета; пустая строка внутри перевода скрывает текст, но оставляет место.
|
||||||
|
Число строк подсказки общее для всех языков. Настройки языка самого редактора не меняются.
|
||||||
|
**В черновик** переносит перевод в локальное определение; затем нужно сохранить определение
|
||||||
|
на сервере и собрать ресурспак. Для новых ключей переводов получите новый образец предмета.
|
||||||
|
Существующие переводы и неизвестные поля сохраняются при изменении другого языка.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"translations": {
|
||||||
|
"ru_ru": { "name": "Зачарованный клинок", "lore": ["Защищает владельца"] },
|
||||||
|
"en_us": { "name": "Enchanted blade", "lore": ["Protects its owner"] }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
У мобов переводится `name`, строки `lore` для них не задаются.
|
||||||
|
|
||||||
Два канала `astraplus:editor_request` / `astraplus:editor_response` зарегистрированы как
|
Два канала `astraplus:editor_request` / `astraplus:editor_response` зарегистрированы как
|
||||||
**optional**. Клиент проверяет их наличие перед отправкой. Отсутствие редактора у игрока
|
**optional**. Клиент проверяет их наличие перед отправкой. Отсутствие редактора у игрока
|
||||||
или AstraPlus на сервере не создаёт обязательной зависимости для подключения.
|
или AstraPlus на сервере не создаёт обязательной зависимости для подключения.
|
||||||
@@ -132,6 +157,7 @@
|
|||||||
./gradlew.bat runVerificationClient
|
./gradlew.bat runVerificationClient
|
||||||
./gradlew.bat runVerificationClient -PnetworkVerification=true
|
./gradlew.bat runVerificationClient -PnetworkVerification=true
|
||||||
./gradlew.bat runCompatibilityClient
|
./gradlew.bat runCompatibilityClient
|
||||||
|
./gradlew.bat runVerificationClient -PiconVerification=true
|
||||||
```
|
```
|
||||||
|
|
||||||
`build` собирает клиентский JAR и выполняет тесты наследования компонентов и сохранности черновиков: неизвестные
|
`build` собирает клиентский JAR и выполняет тесты наследования компонентов и сохранности черновиков: неизвестные
|
||||||
@@ -146,6 +172,12 @@
|
|||||||
не включён в распространяемый JAR; его запуск защищён специальным JVM-флагом.
|
не включён в распространяемый JAR; его запуск защищён специальным JVM-флагом.
|
||||||
Обычная визуальная проверка использует тестовые данные без входа на сервер.
|
Обычная визуальная проверка использует тестовые данные без входа на сервер.
|
||||||
|
|
||||||
|
`iconVerification` использует отдельный сервер на `127.0.0.1:26702` (порт можно задать
|
||||||
|
`-PiconVerificationPort=...`) и загруженный ресурспак. Проверяются серверные стеки каталога,
|
||||||
|
ограничение больших данных, отсутствие модели, совместимость со старым ответом, открытие
|
||||||
|
определения нажатием иконки, формы переводов, сохранение неизвестных полей и размеры GUI.
|
||||||
|
Снимки настоящего интерфейса сохраняются рядом с остальными PNG проверки.
|
||||||
|
|
||||||
Для сетевых проверок нужен отдельно запущенный **изолированный** сервер AstraPlus на
|
Для сетевых проверок нужен отдельно запущенный **изолированный** сервер AstraPlus на
|
||||||
`127.0.0.1:26700` в offline-режиме. `networkVerification` входит как `AstraEditVerify`
|
`127.0.0.1:26700` в offline-режиме. `networkVerification` входит как `AstraEditVerify`
|
||||||
(нужны права администратора), через реальный протокол проверяет каталог, список, чтение,
|
(нужны права администратора), через реальный протокол проверяет каталог, список, чтение,
|
||||||
|
|||||||
+3
-1
@@ -4,7 +4,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
group = "online.astradev"
|
group = "online.astradev"
|
||||||
version = "0.3.1"
|
version = "0.3.2"
|
||||||
repositories { mavenCentral() }
|
repositories { mavenCentral() }
|
||||||
dependencies {
|
dependencies {
|
||||||
testImplementation("com.google.code.gson:gson:2.14.0")
|
testImplementation("com.google.code.gson:gson:2.14.0")
|
||||||
@@ -48,6 +48,8 @@ neoForge {
|
|||||||
systemProperty("astrapluseditor.isolatedVerification", "true")
|
systemProperty("astrapluseditor.isolatedVerification", "true")
|
||||||
systemProperty("astrapluseditor.networkVerification", providers.gradleProperty("networkVerification").orElse("false").get())
|
systemProperty("astrapluseditor.networkVerification", providers.gradleProperty("networkVerification").orElse("false").get())
|
||||||
systemProperty("astrapluseditor.mobTransportVerification", providers.gradleProperty("mobTransportVerification").orElse("false").get())
|
systemProperty("astrapluseditor.mobTransportVerification", providers.gradleProperty("mobTransportVerification").orElse("false").get())
|
||||||
|
systemProperty("astrapluseditor.iconVerification", providers.gradleProperty("iconVerification").orElse("false").get())
|
||||||
|
systemProperty("astrapluseditor.iconVerificationPort", providers.gradleProperty("iconVerificationPort").orElse("26702").get())
|
||||||
programArgument("--width"); programArgument("1280")
|
programArgument("--width"); programArgument("1280")
|
||||||
programArgument("--height"); programArgument("720")
|
programArgument("--height"); programArgument("720")
|
||||||
programArgument("--username"); programArgument("AstraEditVerify")
|
programArgument("--username"); programArgument("AstraEditVerify")
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package online.astradev.plus.editor.client;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.mojang.serialization.JsonOps;
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
import net.minecraft.core.component.DataComponents;
|
||||||
|
import net.minecraft.core.registries.BuiltInRegistries;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
import net.minecraft.resources.RegistryOps;
|
||||||
|
import net.minecraft.world.item.ItemStack;
|
||||||
|
|
||||||
|
/** Keeps the server's visual stack and falls back to its vanilla material when a pack is missing. */
|
||||||
|
public final class CatalogIcon {
|
||||||
|
private final ItemStack stack;
|
||||||
|
private final ItemStack fallback;
|
||||||
|
private final Identifier model;
|
||||||
|
private final boolean supplied;
|
||||||
|
private final boolean simplified;
|
||||||
|
|
||||||
|
public CatalogIcon(JsonObject entry) {
|
||||||
|
ItemStack decoded = ItemStack.EMPTY;
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
if (entry.has("icon") && minecraft.level != null) {
|
||||||
|
try {
|
||||||
|
var ops = RegistryOps.create(JsonOps.INSTANCE, minecraft.level.registryAccess());
|
||||||
|
decoded = ItemStack.CODEC.parse(ops, entry.get("icon")).result().orElse(ItemStack.EMPTY);
|
||||||
|
} catch (RuntimeException ignored) { /* An invalid preview must not hide the definition. */ }
|
||||||
|
}
|
||||||
|
supplied = !decoded.isEmpty();
|
||||||
|
if (!supplied) {
|
||||||
|
var material = Identifier.tryParse(entry.has("material") ? entry.get("material").getAsString() : "minecraft:paper");
|
||||||
|
decoded = material == null ? ItemStack.EMPTY : BuiltInRegistries.ITEM.getOptional(material).map(ItemStack::new).orElse(ItemStack.EMPTY);
|
||||||
|
var id = Identifier.tryParse(entry.get("id").getAsString());
|
||||||
|
if (!decoded.isEmpty() && id != null) decoded.set(DataComponents.ITEM_MODEL, id);
|
||||||
|
}
|
||||||
|
stack = decoded;
|
||||||
|
model = stack.get(DataComponents.ITEM_MODEL);
|
||||||
|
fallback = stack.copy();
|
||||||
|
if (!fallback.isEmpty()) {
|
||||||
|
var vanillaModel = fallback.getItem().components().get(DataComponents.ITEM_MODEL);
|
||||||
|
if (vanillaModel != null) fallback.set(DataComponents.ITEM_MODEL, vanillaModel);
|
||||||
|
}
|
||||||
|
simplified = entry.has("iconSimplified") && entry.get("iconSimplified").getAsBoolean();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ItemStack stack() { return (available() ? stack : fallback).copy(); }
|
||||||
|
|
||||||
|
public boolean available() {
|
||||||
|
if (model == null) return false;
|
||||||
|
var resource = Identifier.fromNamespaceAndPath(model.getNamespace(), "items/" + model.getPath() + ".json");
|
||||||
|
return Minecraft.getInstance().getResourceManager().getResource(resource).isPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String hint() {
|
||||||
|
if (stack.isEmpty()) return "Нет данных для иконки. Откройте определение и проверьте основу.";
|
||||||
|
if (!available()) return "Показана ванильная основа. Модель " + model + " отсутствует в загруженном ресурспаке.";
|
||||||
|
if (!supplied) return "Сервер не передал свойства иконки. Показана модель из ресурспака.";
|
||||||
|
return simplified ? "Показана компактная иконка. Объёмные данные предмета в каталог не передаются." : "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package online.astradev.plus.editor.form;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
/** Updates one locale while preserving every other translation and unknown field. */
|
||||||
|
public final class ContentTranslations {
|
||||||
|
private ContentTranslations() {}
|
||||||
|
|
||||||
|
public static List<String> locales(ContentDraft draft) {
|
||||||
|
var value = draft.get("translations");
|
||||||
|
return value.isJsonObject() ? value.getAsJsonObject().keySet().stream().sorted().toList() : List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void save(ContentDraft draft, String locale, String name, boolean editLore, boolean overrideLore, String text) {
|
||||||
|
if (!locale.matches("[a-z][a-z0-9_]{1,31}")) throw new IllegalArgumentException("Некорректный код языка.");
|
||||||
|
var languages = draft.get("translations");
|
||||||
|
var translations = languages.isJsonObject() ? languages.getAsJsonObject() : new JsonObject();
|
||||||
|
if (!translations.has(locale) && translations.size() >= 128) throw new IllegalArgumentException("Допустимо не больше 128 языков.");
|
||||||
|
var current = translations.get(locale);
|
||||||
|
var value = current != null && current.isJsonObject() ? current.getAsJsonObject() : new JsonObject();
|
||||||
|
if (name.length() > 256) throw new IllegalArgumentException("Название не должно превышать 256 символов.");
|
||||||
|
if (name.isBlank()) value.remove("name"); else value.addProperty("name", name);
|
||||||
|
if (editLore) {
|
||||||
|
if (!overrideLore) value.remove("lore");
|
||||||
|
else {
|
||||||
|
var lines = text.isEmpty() ? new String[0] : text.split("\\R", -1);
|
||||||
|
if (lines.length > 64) throw new IllegalArgumentException("Описание не должно превышать 64 строки.");
|
||||||
|
var lore = new JsonArray();
|
||||||
|
for (String line : lines) {
|
||||||
|
if (line.length() > 1024) throw new IllegalArgumentException("Строка описания не должна превышать 1024 символа.");
|
||||||
|
lore.add(line);
|
||||||
|
}
|
||||||
|
value.add("lore", lore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (value.isEmpty()) translations.remove(locale); else translations.add(locale, value);
|
||||||
|
draft.set(translations.isEmpty() ? null : translations, "translations");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void remove(ContentDraft draft, String locale) {
|
||||||
|
draft.set(null, "translations", locale);
|
||||||
|
if (locales(draft).isEmpty()) draft.set(null, "translations");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
package online.astradev.plus.editor.screen;
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
import com.google.gson.JsonArray;
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import net.minecraft.client.gui.components.EditBox;
|
import net.minecraft.client.gui.components.EditBox;
|
||||||
import net.minecraft.network.chat.Component;
|
import net.minecraft.network.chat.Component;
|
||||||
@@ -14,8 +11,8 @@ import online.astradev.plus.editor.network.EditorConnection;
|
|||||||
public final class ContentBrowserScreen extends EditorScreen {
|
public final class ContentBrowserScreen extends EditorScreen {
|
||||||
private final EditorConnection connection;
|
private final EditorConnection connection;
|
||||||
private final EditorCatalog catalog = new EditorCatalog();
|
private final EditorCatalog catalog = new EditorCatalog();
|
||||||
private final Map<String, String> rows = new LinkedHashMap<>();
|
private JsonArray rows = new JsonArray();
|
||||||
private ChoiceList list;
|
private ContentList list;
|
||||||
private int page;
|
private int page;
|
||||||
private int pages = 1;
|
private int pages = 1;
|
||||||
private String query = "";
|
private String query = "";
|
||||||
@@ -37,8 +34,8 @@ public final class ContentBrowserScreen extends EditorScreen {
|
|||||||
search.setHint(Component.literal("Найти по имени или namespace:id"));
|
search.setHint(Component.literal("Найти по имени или namespace:id"));
|
||||||
search.setValue(query);
|
search.setValue(query);
|
||||||
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
||||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(25, height - 193), this::load));
|
list = addRenderableWidget(new ContentList(minecraft, 12, 92, width - 24, Math.max(25, height - 193), this::load));
|
||||||
list.values(rows.keySet().stream().toList());
|
list.values(rows);
|
||||||
int row = height - 94;
|
int row = height - 94;
|
||||||
int part = Math.max(50, (width - 48) / 4);
|
int part = Math.max(50, (width - 48) / 4);
|
||||||
button("+ Предмет", 12, row, part, () -> create(false));
|
button("+ Предмет", 12, row, part, () -> create(false));
|
||||||
@@ -72,23 +69,15 @@ public final class ContentBrowserScreen extends EditorScreen {
|
|||||||
connection.request("list", request, response -> {
|
connection.request("list", request, response -> {
|
||||||
if (generation != requestGeneration) return;
|
if (generation != requestGeneration) return;
|
||||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||||
rows.clear();
|
rows = response.has("entries") ? response.getAsJsonArray("entries").deepCopy() : new JsonArray();
|
||||||
if (response.has("entries")) for (var value : response.getAsJsonArray("entries")) {
|
|
||||||
var entry = value.getAsJsonObject();
|
|
||||||
String id = entry.get("id").getAsString();
|
|
||||||
String kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет";
|
|
||||||
rows.put(kind + ": " + entry.get("name").getAsString() + " [" + id + "]", id);
|
|
||||||
}
|
|
||||||
page = response.has("page") ? response.get("page").getAsInt() : page;
|
page = response.has("page") ? response.get("page").getAsInt() : page;
|
||||||
pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1);
|
pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1);
|
||||||
list.values(rows.keySet().stream().toList());
|
list.values(rows);
|
||||||
status("Страница " + (page + 1) + " / " + pages + ": Выберите определение для редактирования.", false);
|
status("Страница " + (page + 1) + " / " + pages + ": Выберите определение для редактирования.", false);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void load(String label) {
|
private void load(String id) {
|
||||||
String id = rows.get(label);
|
|
||||||
if (id == null) return;
|
|
||||||
var request = new JsonObject(); request.addProperty("id", id);
|
var request = new JsonObject(); request.addProperty("id", id);
|
||||||
status("Открывается " + id + "…", false);
|
status("Открывается " + id + "…", false);
|
||||||
connection.request("get", request, response -> {
|
connection.request("get", request, response -> {
|
||||||
|
|||||||
@@ -68,9 +68,11 @@ public final class ContentEditorScreen extends EditorScreen {
|
|||||||
if (pages > 1) {
|
if (pages > 1) {
|
||||||
button("←", 12, bottom, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } }).active = page > 0;
|
button("←", 12, bottom, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } }).active = page > 0;
|
||||||
button("→", 42, bottom, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } }).active = page + 1 < pages;
|
button("→", 42, bottom, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } }).active = page + 1 < pages;
|
||||||
labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
|
if (!draft.block() || width >= 420) labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
|
||||||
}
|
}
|
||||||
if (draft.block()) button("Зачарования", width - 142, bottom, 130, this::enchantments);
|
if (draft.block()) button("Зачарования", width - 142, bottom, 130, this::enchantments);
|
||||||
|
button("Переводы", draft.block() ? (width >= 420 ? width - 254 : 80) : width - 116, bottom, draft.block() && width < 420 ? 96 : 104,
|
||||||
|
() -> minecraft.gui.setScreen(new TranslationsScreen(this, draft, true)));
|
||||||
int size = (width - 40) / 3;
|
int size = (width - 40) / 3;
|
||||||
button("Назад", 12, height - 27, size, this::onClose);
|
button("Назад", 12, height - 27, size, this::onClose);
|
||||||
save = button("Сохранить", 20 + size, height - 27, size, "Проверить и применить определение на сервере.", this::save);
|
save = button("Сохранить", 20 + size, height - 27, size, "Проверить и применить определение на сервере.", this::save);
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
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.GuiGraphicsExtractor;
|
||||||
|
import net.minecraft.client.gui.components.ObjectSelectionList;
|
||||||
|
import net.minecraft.client.input.MouseButtonEvent;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import online.astradev.plus.editor.client.CatalogIcon;
|
||||||
|
|
||||||
|
/** Inventory icons, names and identifiers stay readable independently in the content catalog. */
|
||||||
|
public final class ContentList extends ObjectSelectionList<ContentList.Row> {
|
||||||
|
private final Consumer<String> selected;
|
||||||
|
|
||||||
|
public ContentList(Minecraft minecraft, int x, int y, int width, int height, Consumer<String> selected) {
|
||||||
|
super(minecraft, width, height, y, 36);
|
||||||
|
setX(x);
|
||||||
|
this.selected = selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void values(JsonArray entries) {
|
||||||
|
clearEntries();
|
||||||
|
entries.forEach(entry -> addEntry(new Row(entry.getAsJsonObject())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public int getRowWidth() { return width - 16; }
|
||||||
|
|
||||||
|
public final class Row extends ObjectSelectionList.Entry<Row> {
|
||||||
|
private final String id;
|
||||||
|
private final String name;
|
||||||
|
private final String kind;
|
||||||
|
private final CatalogIcon icon;
|
||||||
|
|
||||||
|
private Row(JsonObject entry) {
|
||||||
|
id = entry.get("id").getAsString();
|
||||||
|
name = entry.get("name").getAsString();
|
||||||
|
kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет";
|
||||||
|
icon = new CatalogIcon(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public Component getNarration() { return Component.literal(kind + ": " + name + ", " + id); }
|
||||||
|
|
||||||
|
@Override public void extractContent(GuiGraphicsExtractor graphics, int mouseX, int mouseY, boolean hovered, float a) {
|
||||||
|
int x = getContentX() + 4, y = getContentY();
|
||||||
|
graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight() - 2,
|
||||||
|
getSelected() == this ? 0xFF304C53 : hovered ? 0xFF293D46 : 0xFF1B2830);
|
||||||
|
graphics.fill(x, y + 4, x + 26, y + 30, 0xFF101C23);
|
||||||
|
var stack = icon.stack();
|
||||||
|
if (stack.isEmpty()) graphics.text(minecraft.font, "?", x + 10, y + 13, 0xFF91A6B2);
|
||||||
|
else graphics.item(stack, x + 5, y + 9);
|
||||||
|
int textX = x + 34, textWidth = Math.max(0, getContentWidth() - 42);
|
||||||
|
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(name, textWidth), textX, y + 5, 0xFFE5EFF1);
|
||||||
|
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(kind + " " + id, textWidth), textX, y + 19, 0xFF9AAFB8);
|
||||||
|
if (hovered) {
|
||||||
|
String hint = icon.hint();
|
||||||
|
String tooltip = kind + ": " + name + "\n" + id + (hint.isEmpty() ? "" : "\n\n" + hint);
|
||||||
|
graphics.setTooltipForNextFrame(minecraft.font, Component.literal(tooltip), mouseX, mouseY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
|
||||||
|
if (event.button() != 0) return false;
|
||||||
|
setSelected(this);
|
||||||
|
selected.accept(id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@ public final class MobEditorScreen extends EditorScreen {
|
|||||||
var sections = new ArrayList<Section>();
|
var sections = new ArrayList<Section>();
|
||||||
sections.add(new Section("Основное", this::basic));
|
sections.add(new Section("Основное", this::basic));
|
||||||
if (!skill) sections.add(new Section("Свойства и защита", this::options));
|
if (!skill) sections.add(new Section("Свойства и защита", this::options));
|
||||||
|
if (!skill) sections.add(new Section("Переводы", () -> minecraft.gui.setScreen(new TranslationsScreen(this, draft, false))));
|
||||||
sections.add(new Section(skill ? "Последовательность" : "События и действия", () -> minecraft.gui.setScreen(new MobActionsScreen(this, draft, catalog, !skill))));
|
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("conditions", "Условия исполнителя") : this::ai));
|
||||||
sections.add(new Section(skill ? "Условия цели" : "Лут", skill ? () -> conditions("targetConditions", "Условия цели") : () -> minecraft.gui.setScreen(new MobDropsScreen(this, draft, catalog))));
|
sections.add(new Section(skill ? "Условия цели" : "Лут", skill ? () -> conditions("targetConditions", "Условия цели") : () -> minecraft.gui.setScreen(new MobDropsScreen(this, draft, catalog))));
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||||
|
import net.minecraft.client.gui.components.EditBox;
|
||||||
|
import net.minecraft.client.gui.components.MultiLineEditBox;
|
||||||
|
import net.minecraft.client.gui.screens.ConfirmScreen;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.ContentTranslations;
|
||||||
|
|
||||||
|
public final class TranslationEditScreen extends EditorScreen {
|
||||||
|
private final TranslationsScreen parent;
|
||||||
|
private final ContentDraft draft;
|
||||||
|
private final String locale;
|
||||||
|
private final boolean lore;
|
||||||
|
private final String originalName, originalText;
|
||||||
|
private final boolean originalOverride;
|
||||||
|
private String name, text;
|
||||||
|
private boolean override;
|
||||||
|
|
||||||
|
public TranslationEditScreen(TranslationsScreen parent, ContentDraft draft, String locale, boolean lore) {
|
||||||
|
super("Перевод: " + locale); this.parent = parent; this.draft = draft; this.locale = locale; this.lore = lore;
|
||||||
|
name = draft.text("", "translations", locale, "name");
|
||||||
|
var lines = new ArrayList<String>();
|
||||||
|
var translated = draft.get("translations", locale, "lore");
|
||||||
|
override = translated.isJsonArray();
|
||||||
|
if (override) translated.getAsJsonArray().forEach(line -> lines.add(line.getAsString()));
|
||||||
|
text = String.join("\n", lines);
|
||||||
|
originalName = name; originalText = text; originalOverride = override;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override protected void init() {
|
||||||
|
var input = addRenderableWidget(new EditBox(font, 12, 58, width - 24, 20, Component.literal("Название на этом языке")));
|
||||||
|
input.setMaxLength(256); input.setValue(name);
|
||||||
|
input.setHint(Component.literal(draft.text(draft.id(), "name")));
|
||||||
|
input.setResponder(value -> name = value);
|
||||||
|
if (lore) {
|
||||||
|
button(override ? "Описание: перевод на этот язык" : "Описание: основное из свойств", 12, 88, width - 24, () -> {
|
||||||
|
override = !override; rebuildWidgets();
|
||||||
|
});
|
||||||
|
var description = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(126).setShowDecorations(false)
|
||||||
|
.setPlaceholder(Component.literal(override ? "Пропущенные строки используют основное описание" : "Наследуется minecraft:lore из свойств предмета"))
|
||||||
|
.build(font, width - 24, Math.max(26, height - 202), Component.literal("Перевод описания")));
|
||||||
|
description.setCharacterLimit(64 * 1025); description.setValue(text);
|
||||||
|
description.setValueListener(value -> text = value); description.active = override;
|
||||||
|
}
|
||||||
|
int part = (width - 40) / 3;
|
||||||
|
button("Отмена", 12, height - 27, part, this::onClose);
|
||||||
|
button("Удалить язык", 20 + part, height - 27, part, () -> {
|
||||||
|
ContentTranslations.remove(draft, locale); minecraft.gui.setScreen(parent);
|
||||||
|
}).active = ContentTranslations.locales(draft).contains(locale);
|
||||||
|
button("В черновик", 28 + part * 2, height - 27, part, () -> {
|
||||||
|
try {
|
||||||
|
ContentTranslations.save(draft, locale, name, lore, override, text);
|
||||||
|
minecraft.gui.setScreen(parent);
|
||||||
|
} catch (IllegalArgumentException error) { status(error.getMessage(), true); }
|
||||||
|
});
|
||||||
|
if (status.isBlank()) status(lore ? "Пропущенные строки используют основное описание. Число строк общее для всех языков. Сохраните определение и соберите ресурспак."
|
||||||
|
: "Пустое название использует основное. «В черновик» не изменяет сервер: сохраните определение и соберите ресурспак.", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||||
|
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||||
|
graphics.text(font, "Название на этом языке", 12, 43, 0xFFB3C8D1);
|
||||||
|
if (lore) graphics.text(font, "Описание: одна строка текста — одна строка подсказки", 12, 114, 0xFFB3C8D1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void onClose() {
|
||||||
|
if (!name.equals(originalName) || !text.equals(originalText) || override != originalOverride)
|
||||||
|
minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
|
||||||
|
Component.literal("Отменить изменения перевода?"), Component.literal("Перевод ещё не перенесён в черновик.")));
|
||||||
|
else minecraft.gui.setScreen(parent);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.ContentTranslations;
|
||||||
|
|
||||||
|
/** Per-definition resource-pack translations; the Minecraft interface language stays unchanged. */
|
||||||
|
public final class TranslationsScreen extends EditorScreen {
|
||||||
|
private final Screen parent;
|
||||||
|
private final ContentDraft draft;
|
||||||
|
private final boolean lore;
|
||||||
|
private final Map<String, String> languages = new LinkedHashMap<>();
|
||||||
|
private String pending;
|
||||||
|
|
||||||
|
public TranslationsScreen(Screen parent, ContentDraft draft, boolean lore) {
|
||||||
|
super("Переводы контента"); this.parent = parent; this.draft = draft; this.lore = lore;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override protected void init() {
|
||||||
|
languages.clear();
|
||||||
|
minecraft.getLanguageManager().getLanguages().forEach((id, info) -> languages.put(id + " " + info.toComponent().getString(), id));
|
||||||
|
var rows = new LinkedHashMap<String, String>();
|
||||||
|
for (String locale : ContentTranslations.locales(draft)) {
|
||||||
|
var info = minecraft.getLanguageManager().getLanguage(locale);
|
||||||
|
String name = draft.text("Основное название", "translations", locale, "name");
|
||||||
|
rows.put(locale + " " + (info == null ? "" : info.toComponent().getString() + " ") + name, locale);
|
||||||
|
}
|
||||||
|
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 42, width - 24, Math.max(26, height - 141),
|
||||||
|
row -> open(rows.get(row))));
|
||||||
|
list.values(rows.keySet().stream().toList());
|
||||||
|
button("+ Добавить язык", 12, height - 90, Math.min(170, width - 24), () -> minecraft.gui.setScreen(new ChoiceScreen(this,
|
||||||
|
"Язык перевода", languages.keySet().stream().filter(label -> !ContentTranslations.locales(draft).contains(languages.get(label))).toList(),
|
||||||
|
label -> pending = languages.get(label)))).active = rows.size() < 128;
|
||||||
|
button("Готово", 12, height - 27, 120, this::onClose);
|
||||||
|
status(rows.isEmpty() ? "Переводов пока нет. Используется основное название" + (lore ? " и описание предмета." : ".")
|
||||||
|
: "Языков: " + rows.size() + ". Сохраните определение и соберите ресурспак. Для новых ключей получите новый образец.", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void open(String locale) { minecraft.gui.setScreen(new TranslationEditScreen(this, draft, locale, lore)); }
|
||||||
|
|
||||||
|
@Override public void tick() {
|
||||||
|
if (pending != null) { String locale = pending; pending = null; open(locale); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package online.astradev.plus.editor.form;
|
||||||
|
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
final class ContentTranslationsTest {
|
||||||
|
@Test void oneLocaleEditPreservesUnknownFieldsAndOtherLocales() {
|
||||||
|
var draft = new ContentDraft(JsonParser.parseString("""
|
||||||
|
{"name":"Fallback","translations":{"ru_ru":{"name":"Старое","extension":{"x":1}},
|
||||||
|
"en_us":{"name":"English","lore":["Original"]}},"components":{"minecraft:lore":["Base"]}}
|
||||||
|
""").getAsJsonObject(), "rev");
|
||||||
|
ContentTranslations.save(draft, "ru_ru", "Новое", true, true, "Один\n\nТри");
|
||||||
|
assertEquals("Новое", draft.text("", "translations", "ru_ru", "name"));
|
||||||
|
assertEquals(1, draft.get("translations", "ru_ru", "extension", "x").getAsInt());
|
||||||
|
assertEquals("English", draft.text("", "translations", "en_us", "name"));
|
||||||
|
assertEquals("", draft.get("translations", "ru_ru", "lore").getAsJsonArray().get(1).getAsString());
|
||||||
|
assertEquals("Base", draft.get("components", "minecraft:lore").getAsJsonArray().get(0).getAsString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void fallbackRemovesOnlyEditedValues() {
|
||||||
|
var draft = new ContentDraft(JsonParser.parseString("""
|
||||||
|
{"name":"Fallback","translations":{"ru_ru":{"name":"Старое","lore":["Описание"],"extension":true}}}
|
||||||
|
""").getAsJsonObject(), "rev");
|
||||||
|
ContentTranslations.save(draft, "ru_ru", "", true, false, "ignored");
|
||||||
|
assertTrue(draft.get("translations", "ru_ru", "name").isJsonNull());
|
||||||
|
assertTrue(draft.get("translations", "ru_ru", "lore").isJsonNull());
|
||||||
|
assertTrue(draft.get("translations", "ru_ru", "extension").getAsBoolean());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void mobNameEditDoesNotRewriteLore() {
|
||||||
|
var draft = new ContentDraft(JsonParser.parseString("""
|
||||||
|
{"translations":{"ru_ru":{"lore":["Future mob description"]}}}
|
||||||
|
""").getAsJsonObject(), "rev");
|
||||||
|
ContentTranslations.save(draft, "ru_ru", "Страж", false, false, "");
|
||||||
|
assertEquals("Future mob description", draft.get("translations", "ru_ru", "lore").getAsJsonArray().get(0).getAsString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void invalidEditDoesNotMutateDraft() {
|
||||||
|
var draft = ContentDraft.create(false);
|
||||||
|
var original = draft.document();
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> ContentTranslations.save(draft, "../ru_ru", "A", true, false, ""));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> ContentTranslations.save(draft, "ru_ru", "A", true, true, "x".repeat(1025)));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> ContentTranslations.save(draft, "ru_ru", "A", true, true, "x\n".repeat(64)));
|
||||||
|
assertEquals(original, draft.document());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void deletingLastLocaleRemovesEmptyContainer() {
|
||||||
|
var draft = ContentDraft.create(false);
|
||||||
|
ContentTranslations.save(draft, "ru_ru", "Имя", true, true, "");
|
||||||
|
assertTrue(draft.get("translations", "ru_ru", "lore").getAsJsonArray().isEmpty());
|
||||||
|
ContentTranslations.remove(draft, "ru_ru");
|
||||||
|
assertTrue(draft.get("translations").isJsonNull());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,6 +42,7 @@ public final class EditorVerification {
|
|||||||
private ContentDraft mobDraft;
|
private ContentDraft mobDraft;
|
||||||
private online.astradev.plus.editor.screen.MobEditorScreen mobEditor;
|
private online.astradev.plus.editor.screen.MobEditorScreen mobEditor;
|
||||||
private final NetworkVerification network = Boolean.getBoolean("astrapluseditor.networkVerification") ? new NetworkVerification() : null;
|
private final NetworkVerification network = Boolean.getBoolean("astrapluseditor.networkVerification") ? new NetworkVerification() : null;
|
||||||
|
private final IconVerification icons = Boolean.getBoolean("astrapluseditor.iconVerification") ? new IconVerification() : null;
|
||||||
|
|
||||||
public EditorVerification() {
|
public EditorVerification() {
|
||||||
if (!Boolean.getBoolean("astrapluseditor.isolatedVerification"))
|
if (!Boolean.getBoolean("astrapluseditor.isolatedVerification"))
|
||||||
@@ -50,6 +51,7 @@ public final class EditorVerification {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void tick(ClientTickEvent.Post event) {
|
private void tick(ClientTickEvent.Post event) {
|
||||||
|
if (icons != null) { icons.tick(); return; }
|
||||||
if (network != null) { network.tick(); return; }
|
if (network != null) { network.tick(); return; }
|
||||||
var minecraft = Minecraft.getInstance();
|
var minecraft = Minecraft.getInstance();
|
||||||
if (!started) {
|
if (!started) {
|
||||||
|
|||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package online.astradev.plus.editor.verification;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.mojang.serialization.JsonOps;
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
import net.minecraft.client.Screenshot;
|
||||||
|
import net.minecraft.client.gui.components.AbstractWidget;
|
||||||
|
import net.minecraft.client.gui.screens.ConnectScreen;
|
||||||
|
import net.minecraft.client.gui.screens.DisconnectedScreen;
|
||||||
|
import net.minecraft.client.multiplayer.ServerData;
|
||||||
|
import net.minecraft.client.multiplayer.resolver.ServerAddress;
|
||||||
|
import net.minecraft.core.component.DataComponents;
|
||||||
|
import net.minecraft.resources.RegistryOps;
|
||||||
|
import net.minecraft.world.item.ItemStack;
|
||||||
|
import online.astradev.plus.editor.client.CatalogIcon;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.network.EditorConnection;
|
||||||
|
import online.astradev.plus.editor.screen.ContentBrowserScreen;
|
||||||
|
import online.astradev.plus.editor.screen.ContentList;
|
||||||
|
import org.lwjgl.glfw.GLFW;
|
||||||
|
|
||||||
|
/** Exercises real catalog packets and native item rendering on an isolated server and installed pack. */
|
||||||
|
final class IconVerification {
|
||||||
|
private final EditorConnection connection = EditorConnection.INSTANCE;
|
||||||
|
private final String id = "verification:icon_" + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
private final long started = System.nanoTime();
|
||||||
|
private boolean connecting, waiting, finished;
|
||||||
|
private int stage, nextTick, tick, available, count;
|
||||||
|
private String visibleNamespace;
|
||||||
|
private volatile int screenshots;
|
||||||
|
private ContentDraft translationDraft;
|
||||||
|
private online.astradev.plus.editor.screen.TranslationsScreen translations;
|
||||||
|
|
||||||
|
void tick() {
|
||||||
|
if (finished) return;
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
try {
|
||||||
|
if (System.nanoTime() - started > 180_000_000_000L) throw new IllegalStateException("Timed out in stage " + stage);
|
||||||
|
tick++;
|
||||||
|
if (!connecting) {
|
||||||
|
if (minecraft.gui.overlay() != null || !minecraft.isGameLoadFinished()) return;
|
||||||
|
connecting = true;
|
||||||
|
minecraft.options.enableVsync().set(false);
|
||||||
|
minecraft.options.framerateLimit().set(60);
|
||||||
|
minecraft.options.pauseOnLostFocus = false;
|
||||||
|
minecraft.options.guiScale().set(2);
|
||||||
|
minecraft.resizeGui();
|
||||||
|
GLFW.glfwHideWindow(minecraft.getWindow().handle());
|
||||||
|
String address = "127.0.0.1:" + Integer.getInteger("astrapluseditor.iconVerificationPort", 26702);
|
||||||
|
ConnectScreen.startConnecting(minecraft.gui.screen(), minecraft, ServerAddress.parseString(address),
|
||||||
|
new ServerData("Isolated icon verification", address, ServerData.Type.OTHER), false, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (minecraft.gui.screen() instanceof DisconnectedScreen) throw new IllegalStateException("Disconnected in stage " + stage);
|
||||||
|
if (minecraft.player == null || !connection.available() || waiting || tick < nextTick) return;
|
||||||
|
minecraft.gui.toastManager().clear();
|
||||||
|
switch (stage) {
|
||||||
|
case 0 -> {
|
||||||
|
var draft = ContentDraft.create(false);
|
||||||
|
draft.string(id, "id");
|
||||||
|
draft.string("Большой предмет для проверки иконки", "name");
|
||||||
|
draft.string("minecraft:leather_chestplate", "material");
|
||||||
|
draft.string("minecraft:item/leather_chestplate", "texture");
|
||||||
|
var data = new JsonObject();
|
||||||
|
var pages = new com.google.gson.JsonArray();
|
||||||
|
for (int page = 0; page < 30; page++) pages.add("x".repeat(700));
|
||||||
|
data.add("pages", pages);
|
||||||
|
draft.component(data, "minecraft:writable_book_content");
|
||||||
|
draft.component(new com.google.gson.JsonPrimitive(true), "minecraft:enchantment_glint_override");
|
||||||
|
var request = new JsonObject();
|
||||||
|
request.addProperty("id", id); request.addProperty("revision", "new"); request.add("document", draft.document());
|
||||||
|
request("save", request, response -> {});
|
||||||
|
}
|
||||||
|
case 1 -> {
|
||||||
|
var request = new JsonObject(); request.addProperty("query", id);
|
||||||
|
request("list", request, response -> {
|
||||||
|
var entry = response.getAsJsonArray("entries").get(0).getAsJsonObject();
|
||||||
|
if (!entry.get("iconSimplified").getAsBoolean() || entry.get("icon").toString().length() > 16384)
|
||||||
|
throw new IllegalStateException("Large icon was not bounded");
|
||||||
|
if (entry.get("icon").toString().contains("x".repeat(100))) throw new IllegalStateException("Large custom data leaked into icon");
|
||||||
|
var preview = new CatalogIcon(entry);
|
||||||
|
if (!preview.stack().hasFoil() || preview.available() || !preview.hint().contains("ванильная основа"))
|
||||||
|
throw new IllegalStateException("Missing-pack fallback lost glint or explanation");
|
||||||
|
var legacy = entry.deepCopy(); legacy.remove("icon");
|
||||||
|
if (new CatalogIcon(legacy).stack().isEmpty()) throw new IllegalStateException("Legacy server fallback is empty");
|
||||||
|
var malformed = entry.deepCopy(); malformed.addProperty("icon", "invalid");
|
||||||
|
if (new CatalogIcon(malformed).stack().isEmpty()) throw new IllegalStateException("Malformed preview hid the definition");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
case 2 -> request("list", new JsonObject(), response -> {
|
||||||
|
var ops = RegistryOps.create(JsonOps.INSTANCE, minecraft.level.registryAccess());
|
||||||
|
for (var value : response.getAsJsonArray("entries")) {
|
||||||
|
var entry = value.getAsJsonObject();
|
||||||
|
var decoded = ItemStack.CODEC.parse(ops, entry.get("icon")).getOrThrow();
|
||||||
|
if (decoded.isEmpty() || !decoded.get(DataComponents.ITEM_MODEL).toString().equals(entry.get("id").getAsString()))
|
||||||
|
throw new IllegalStateException("Catalog icon differs from the server model");
|
||||||
|
var preview = new CatalogIcon(entry);
|
||||||
|
if (preview.available()) {
|
||||||
|
available++;
|
||||||
|
if (visibleNamespace == null) visibleNamespace = entry.get("id").getAsString().split(":", 2)[0] + ":";
|
||||||
|
}
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
if (available == 0) throw new IllegalStateException("No installed resource-pack icons were exercised");
|
||||||
|
minecraft.gui.setScreen(new ContentBrowserScreen(connection));
|
||||||
|
for (var child : minecraft.gui.screen().children())
|
||||||
|
if (child instanceof net.minecraft.client.gui.components.EditBox input) input.setValue(visibleNamespace);
|
||||||
|
nextTick = tick + 40;
|
||||||
|
});
|
||||||
|
case 3 -> { capture("22-content-icons.png"); stage++; nextTick = tick + 10; }
|
||||||
|
case 4 -> {
|
||||||
|
minecraft.options.guiScale().set(3); minecraft.resizeGui();
|
||||||
|
stage++; nextTick = tick + 30;
|
||||||
|
}
|
||||||
|
case 5 -> { capture("23-content-icons-small.png"); stage++; nextTick = tick + 10; }
|
||||||
|
case 6 -> {
|
||||||
|
var screen = minecraft.gui.screen();
|
||||||
|
for (var child : screen.children()) if (child instanceof ContentList list) {
|
||||||
|
if (list.children().isEmpty()) throw new IllegalStateException("Catalog has no rows");
|
||||||
|
var row = list.children().get(0);
|
||||||
|
row.mouseClicked(new net.minecraft.client.input.MouseButtonEvent(row.getX() + 10, row.getY() + 10,
|
||||||
|
new net.minecraft.client.input.MouseButtonInfo(0, 0)), false);
|
||||||
|
}
|
||||||
|
stage++; nextTick = tick + 30;
|
||||||
|
}
|
||||||
|
case 7 -> {
|
||||||
|
if (!(minecraft.gui.screen() instanceof online.astradev.plus.editor.screen.ContentEditorScreen))
|
||||||
|
throw new IllegalStateException("Clicking an icon did not open its definition");
|
||||||
|
minecraft.options.guiScale().set(2); minecraft.resizeGui();
|
||||||
|
translationDraft = ContentDraft.create(false);
|
||||||
|
translationDraft.string("Предмет с переводами", "name");
|
||||||
|
translationDraft.string("Локализованный предмет", "translations", "ru_ru", "name");
|
||||||
|
translationDraft.string("Localized item", "translations", "en_us", "name");
|
||||||
|
translationDraft.bool(true, "translations", "en_us", "future");
|
||||||
|
translations = new online.astradev.plus.editor.screen.TranslationsScreen(minecraft.gui.screen(), translationDraft, true);
|
||||||
|
minecraft.gui.setScreen(translations);
|
||||||
|
stage++; nextTick = tick + 20;
|
||||||
|
}
|
||||||
|
case 8 -> {
|
||||||
|
captureScreen("24-translations.png");
|
||||||
|
minecraft.gui.setScreen(new online.astradev.plus.editor.screen.TranslationEditScreen(translations, translationDraft, "en_us", true));
|
||||||
|
stage++; nextTick = tick + 20;
|
||||||
|
}
|
||||||
|
case 9 -> {
|
||||||
|
click("Описание: основное из свойств");
|
||||||
|
for (var child : minecraft.gui.screen().children()) {
|
||||||
|
if (child instanceof net.minecraft.client.gui.components.EditBox input) input.setValue("English item name");
|
||||||
|
if (child instanceof net.minecraft.client.gui.components.MultiLineEditBox input) input.setValue("English description\nSecond line");
|
||||||
|
}
|
||||||
|
stage++; nextTick = tick + 15;
|
||||||
|
}
|
||||||
|
case 10 -> {
|
||||||
|
captureScreen("25-translation-form.png");
|
||||||
|
minecraft.options.guiScale().set(3); minecraft.resizeGui();
|
||||||
|
stage++; nextTick = tick + 15;
|
||||||
|
}
|
||||||
|
case 11 -> {
|
||||||
|
captureScreen("26-translation-form-small.png");
|
||||||
|
click("В черновик");
|
||||||
|
if (!translationDraft.text("", "translations", "en_us", "name").equals("English item name")
|
||||||
|
|| translationDraft.get("translations", "en_us", "lore").getAsJsonArray().size() != 2
|
||||||
|
|| !translationDraft.get("translations", "en_us", "future").getAsBoolean())
|
||||||
|
throw new IllegalStateException("Translation form did not preserve the edited locale");
|
||||||
|
stage++; nextTick = tick + 10;
|
||||||
|
}
|
||||||
|
case 12 -> {
|
||||||
|
if (screenshots != 5) throw new IllegalStateException("Screenshots were not completed");
|
||||||
|
finish("PASS: " + count + " catalog stacks; " + available + " resource-pack icons; bounded heavy stack; missing/legacy/malformed fallback; icon click opens definition; translation name/lore controls preserve unknown fields; 5 native GUI screenshots on NeoForge .75.");
|
||||||
|
}
|
||||||
|
default -> {}
|
||||||
|
}
|
||||||
|
} catch (Exception failure) { finish("FAIL stage " + stage + ": " + failure); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void request(String action, JsonObject body, Consumer<JsonObject> callback) {
|
||||||
|
waiting = true;
|
||||||
|
connection.request(action, body, response -> {
|
||||||
|
try {
|
||||||
|
if (!EditorConnection.success(response)) throw new IllegalStateException(EditorConnection.message(response));
|
||||||
|
callback.accept(response); stage++; waiting = false;
|
||||||
|
} catch (Exception failure) { finish("FAIL stage " + stage + ": " + failure); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void capture(String file) {
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
var screen = minecraft.gui.screen();
|
||||||
|
if (!(screen instanceof ContentBrowserScreen)) throw new IllegalStateException("Catalog screen was not opened");
|
||||||
|
captureScreen(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void captureScreen(String file) {
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
minecraft.gui.toastManager().clear();
|
||||||
|
var screen = minecraft.gui.screen();
|
||||||
|
for (var child : screen.children()) if (child instanceof AbstractWidget widget)
|
||||||
|
if (widget.getX() < 0 || widget.getY() < 0 || widget.getX() + widget.getWidth() > screen.width
|
||||||
|
|| widget.getY() + widget.getHeight() > screen.height) throw new IllegalStateException("Widget out of bounds");
|
||||||
|
Screenshot.grab(minecraft.gameDirectory, file, minecraft.gameRenderer.mainRenderTarget(), 1, message -> screenshots++);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void click(String label) {
|
||||||
|
for (var child : Minecraft.getInstance().gui.screen().children())
|
||||||
|
if (child instanceof net.minecraft.client.gui.components.Button button && button.getMessage().getString().equals(label)) {
|
||||||
|
button.onPress(new net.minecraft.client.input.KeyEvent(GLFW.GLFW_KEY_ENTER, 0, 0)); return;
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("Missing button: " + label);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finish(String result) {
|
||||||
|
finished = true;
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
try { Files.writeString(minecraft.gameDirectory.toPath().resolve("icon-verification-result.txt"), result); }
|
||||||
|
catch (Exception failure) { throw new IllegalStateException(failure); }
|
||||||
|
minecraft.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user