commit e1328e5c513e3a4f033381ccea700bf43a63242f Author: ScarPC Date: Tue Sep 8 16:47:42 2026 +0300 Create optional AstraPlus admin editor with validated forms and protocol diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e8a50a0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +build/ +.idea/ +*.iml +*.log +*.hprof diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4c6e909 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,16 @@ +# AstraPlusEditor — необязательный клиентский редактор + +- Minecraft 26.2, NeoForge 26.2.0.79, Java 25+. Пакет `online.astradev.plus.editor`. +- Это отдельный клиентский мод для администраторов. Не устанавливать его на сервер; + указания родительского AGENTS.md об установке JAR в Paper здесь не применяются. +- Обычным игрокам достаточно ванильного клиента и ресурспака. Все сетевые каналы optional. +- Сервер AstraPlus проверяет права, данные и версии; клиент никогда не назначает себе права. +- Небольшие final-классы, явная валидация, JSON, минимум зависимостей. Без миксинов. +- В локализованном интерфейсе не использовать декоративную точку-разделитель `·`. + Обычные знаки препинания и многоточие `…` сохранять; это правило касается только разделителей. +- Корень пакета содержит только точку входа; реализации в `client`, `screen`, `form`, `network`. +- Сохранять неизвестные поля документов при редактировании. Не менять сервер до явного сохранения. +- Собрать JAR и выполнить необходимые проверки, сообщить ограничение визуальной проверки. +- Проверить diff и создать коммит текущей задачи. Push только по запросу. +- Не коммитить build, .gradle, JAR сборки, логи, тестовые миры и резервные копии. + `gradle/wrapper/gradle-wrapper.jar` — часть системы сборки. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f1a09c --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +# AstraPlus Editor + +Необязательный административный клиентский мод для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25**. +Сервер использует AstraPlus, обычным игрокам достаточно ванильного клиента и ресурспака. +Серверные изменения разрешены только администраторам с правами команд AstraPlus. + +## Установка и работа + +1. Установите `AstraPlusEditor-0.1.0.jar` из `build/libs` в папку `mods` **клиента администратора**. + Этот JAR не устанавливается на сервер. Серверный AstraPlus должен поддерживать протокол редактора версии 1. +2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**. + Клавиша переназначается в управлении Minecraft. +3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы. + Кнопки `+ Предмет` и `+ Блок` создают локальный черновик. +4. Настройте поля, нажмите **Сохранить**. Сервер проверяет права, текущую версию файла, + ванильные компоненты и все определения, затем применяет изменения. При конфликте двух + администраторов чужая версия не перезаписывается; ваш черновик остаётся открытым. +5. **Выдать образец** выдаёт текущую сохранённую серверную версию. Кнопка **Ресурспак** + в списке определений создаёт ZIP и вызывает настроенную интеграцию AstraPacks. + +Общие параметры мода остаются в `config/astraplus.json`. Каждый предмет и блок сохраняется +в своём файле `astraplus/contents//items|blocks/.json` на сервере. +Тип существующего определения, его ID и постоянный слот блока редактор не меняет. +Для нового блока свободный слот назначает сервер. + +## Возможности первого этапа + +- Название, ванильная основа, текстура или готовая модель, положение инструмента в руке. +- Прочность, размер стопки, неразрушимость, защита от огня/лавы, блеск, зачаровываемость, + питание и насыщение. Пустое поле означает наследование, где это указано в подсказке. +- Визуальные правила зачарований: белый список или ограничения основы, запрет отдельного + зачарования, максимальный уровень, выбор двух несовместимых зачарований. +- Параметры блоков: основа для серверного поведения, твёрдость, взрывоустойчивость, + требование подходящего инструмента и количество выпадающих блоков. +- Каталог ванильных компонентов и отдельное окно JSON для каждого сложного значения: + `tool`, `attribute_modifiers`, `consumable`, заданные `enchantments` и остальные компоненты. + Примеры используют формат Minecraft 26.2. Неизвестные редактору поля сохраняются. +- Поля разделены по вкладкам; на небольшом окне длинные формы разбиты на страницы. + Незавершённое изменение компонента или определения защищено подтверждением закрытия. + +Правила зачарований **дополнительно ограничивают ванильные**: они не создают новые типы +зачарований и не отменяют ванильные несовместимости. Максимальный уровень может уменьшать +ванильный предел. Заданные заранее зачарования предмета находятся в компоненте +`minecraft:enchantments`, правила допуска — в отдельном поле `enchantments` определения. + +Для еды помимо `food` требуется `consumable`, если у ванильной основы его нет. +Сервер проверяет комбинации компонентов; например предмет с прочностью не может иметь +несовместимый размер стопки. Огнестойкость относится к выброшенному предмету. + +Сохранение обновляет определение и серверное поведение блока. Уже выданные предметы +не получают новые компоненты автоматически; проверяйте свежий образец. Изменённая +графика появляется после сборки и доставки ресурспака игрокам. Клиентская коллизия блока +по-прежнему определяется ванильным носителем; произвольная модель её не изменяет. + +Сущности, мебель, блоки с собственными инвентарями и пользовательские мобы относятся +к следующему этапу. В этой версии редактор предназначен для предметов и обычных блоков. + +## Протокол и ограничения + +Два канала `astraplus:editor_request` / `astraplus:editor_response` зарегистрированы как +**optional**. Клиент проверяет их наличие перед отправкой. Отсутствие редактора у игрока +или AstraPlus на сервере не создаёт обязательной зависимости для подключения. + +Сервер является источником истины. Клиент передаёт ID и JSON, а не файловые пути. +Сохранение использует SHA-256 ревизию файла и блокирует ввод до ответа, чтобы поздний ответ +не перезаписал более свежий локальный ввод. Серверные права проверяются при каждом запросе. +Сетевой запрос ограничен 8192 символами, включая обёртку протокола. Большие определения +нужно редактировать непосредственно в файлах сервера. До получения ответа повторная +отправка сохранения недоступна. + +## Сборка и проверки + +```powershell +./gradlew.bat build +./gradlew.bat runVerificationClient +./gradlew.bat runVerificationClient -PnetworkVerification=true +./gradlew.bat runCompatibilityClient +``` + +`build` собирает клиентский JAR и выполняет тесты сохранности черновиков: неизвестные +поля, защита от внешних мутаций, отрицательные component patches, ошибочные числа, +симметричные несовместимости, белый список и формат огнестойкости Minecraft 26.2. + +`runVerificationClient` запускает отдельный тестовый мод в `build/isolated-editor`, +открывает реальные экраны Minecraft, проверяет границы виджетов, сохраняет PNG в +`build/isolated-editor/screenshots` и автоматически завершает клиент. Тестовый мод +не включён в распространяемый JAR; его запуск защищён специальным JVM-флагом. +Обычная визуальная проверка использует тестовые данные без входа на сервер. + +Для сетевых проверок нужен отдельно запущенный **изолированный** сервер AstraPlus на +`127.0.0.1:26700` в offline-режиме. `networkVerification` входит как `AstraEditVerify` +(нужны права администратора), через реальный протокол проверяет каталог, список, чтение, +создание предмета и блока, изменение, конфликт ревизий, выдачу предмета и сборку ZIP. +Проверка создаёт определения с уникальными ID `verification:client_*` только на тестовом сервере. +`runCompatibilityClient` входит как `AstraGuest` с одним тестовым модом и **без AstraPlusEditor**, +проверяет успешный вход и отсутствие редактора в списке модов. Это проверка NeoForge-клиента без +редактора; чистый ванильный клиент этим сценарием не запускается. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..b456da1 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,65 @@ +plugins { + java + id("net.neoforged.moddev") version "2.0.146" +} + +group = "online.astradev" +version = "0.1.0" +repositories { mavenCentral() } +dependencies { + testImplementation("com.google.code.gson:gson:2.14.0") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4") +} +neoForge { + version = "26.2.0.79" + mods { create("astrapluseditor") { sourceSet(sourceSets.main.get()) } } +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) } +tasks.withType().configureEach { + options.encoding = "UTF-8" + options.release.set(25) +} +tasks.processResources { + inputs.property("modVersion", project.version) + filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) } +} +tasks.test { useJUnitPlatform() } + +val verification = sourceSets.create("verification") { + compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath + runtimeClasspath += output + compileClasspath + sourceSets.main.get().runtimeClasspath +} +val compatibility = sourceSets.create("compatibility") { + compileClasspath += sourceSets.main.get().compileClasspath + runtimeClasspath += output + compileClasspath + sourceSets.main.get().runtimeClasspath +} +neoForge { + mods { + create("astrapluseditor_verify") { sourceSet(verification) } + create("astrapluseditor_compat") { sourceSet(compatibility) } + } + runs { + create("verificationClient") { + client() + sourceSet.set(verification) + loadedMods.set(setOf(mods.getByName("astrapluseditor"), mods.getByName("astrapluseditor_verify"))) + gameDirectory.set(layout.buildDirectory.dir("isolated-editor")) + systemProperty("astrapluseditor.isolatedVerification", "true") + systemProperty("astrapluseditor.networkVerification", providers.gradleProperty("networkVerification").orElse("false").get()) + programArgument("--width"); programArgument("1280") + programArgument("--height"); programArgument("720") + programArgument("--username"); programArgument("AstraEditVerify") + } + create("compatibilityClient") { + client() + sourceSet.set(compatibility) + loadedMods.set(setOf(mods.getByName("astrapluseditor_compat"))) + gameDirectory.set(layout.buildDirectory.dir("isolated-noeditor")) + systemProperty("astrapluseditor.isolatedVerification", "true") + programArgument("--width"); programArgument("960") + programArgument("--height"); programArgument("540") + programArgument("--username"); programArgument("AstraGuest") + } + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..00fba3d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionSha256Sum=acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a51ec4f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..c541f71 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" } +rootProject.name = "AstraPlusEditor" diff --git a/src/compatibility/java/online/astradev/plus/compatibility/NoEditorVerification.java b/src/compatibility/java/online/astradev/plus/compatibility/NoEditorVerification.java new file mode 100644 index 0000000..ff5c833 --- /dev/null +++ b/src/compatibility/java/online/astradev/plus/compatibility/NoEditorVerification.java @@ -0,0 +1,59 @@ +package online.astradev.plus.compatibility; + +import java.nio.file.Files; + +import net.minecraft.client.Minecraft; +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.neoforged.api.distmarker.Dist; +import net.neoforged.fml.ModList; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.common.NeoForge; +import org.lwjgl.glfw.GLFW; + +/** No editor classes, channels or runtime mod dependency; this client only verifies a normal join. */ +@Mod(value = "astrapluseditor_compat", dist = Dist.CLIENT) +public final class NoEditorVerification { + private int tick; + private int joined; + private boolean connecting; + private boolean finished; + + public NoEditorVerification() { + if (!Boolean.getBoolean("astrapluseditor.isolatedVerification")) + throw new IllegalStateException("Compatibility check requires an isolated directory."); + NeoForge.EVENT_BUS.addListener(this::tick); + } + + private void tick(ClientTickEvent.Post event) { + if (finished) return; + var minecraft = Minecraft.getInstance(); + try { + if (++tick > 2400) throw new IllegalStateException("Connection timed out."); + if (!connecting) { + if (minecraft.gui.overlay() != null || !minecraft.isGameLoadFinished()) return; + if (ModList.get().isLoaded("astrapluseditor")) throw new IllegalStateException("Editor must not be installed."); + connecting = true; + GLFW.glfwHideWindow(minecraft.getWindow().handle()); + ConnectScreen.startConnecting(minecraft.gui.screen(), minecraft, ServerAddress.parseString("127.0.0.1:26700"), + new ServerData("AstraPlus absent-editor check", "127.0.0.1:26700", ServerData.Type.OTHER), false, null); + } else if (minecraft.gui.screen() instanceof DisconnectedScreen) { + throw new IllegalStateException("Server rejected client without the editor."); + } else if (minecraft.player != null && ++joined >= 30) { + if (ModList.get().isLoaded("astrapluseditor")) throw new IllegalStateException("Editor unexpectedly present."); + finish("PASS: NeoForge client without AstraPlusEditor joined and stayed connected for 30 ticks."); + } + } catch (Exception failure) { finish("FAIL: " + failure); } + } + + private void finish(String message) { + finished = true; + var minecraft = Minecraft.getInstance(); + try { Files.writeString(minecraft.gameDirectory.toPath().resolve("compatibility-result.txt"), message); } + catch (Exception failure) { throw new IllegalStateException(failure); } + minecraft.stop(); + } +} diff --git a/src/compatibility/resources/META-INF/neoforge.mods.toml b/src/compatibility/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..de8a4bd --- /dev/null +++ b/src/compatibility/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,7 @@ +modLoader="javafml" +loaderVersion="[11,)" +license="All Rights Reserved" +[[mods]] +modId="astrapluseditor_compat" +version="1" +displayName="AstraPlus absent-editor compatibility check" diff --git a/src/main/java/online/astradev/plus/editor/AstraPlusEditor.java b/src/main/java/online/astradev/plus/editor/AstraPlusEditor.java new file mode 100644 index 0000000..458b5ec --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/AstraPlusEditor.java @@ -0,0 +1,21 @@ +package online.astradev.plus.editor; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.NeoForge; +import online.astradev.plus.editor.client.EditorClient; +import online.astradev.plus.editor.network.EditorConnection; + +/** Client bootstrap; the server and ordinary players do not install this mod. */ +@Mod(value = "astrapluseditor", dist = Dist.CLIENT) +public final class AstraPlusEditor { + public AstraPlusEditor(IEventBus modBus) { + var connection = EditorConnection.INSTANCE; + var client = new EditorClient(connection); + modBus.addListener(connection::register); + modBus.addListener(client::registerKeys); + NeoForge.EVENT_BUS.addListener(client::registerCommands); + NeoForge.EVENT_BUS.addListener(client::tick); + } +} diff --git a/src/main/java/online/astradev/plus/editor/client/EditorCatalog.java b/src/main/java/online/astradev/plus/editor/client/EditorCatalog.java new file mode 100644 index 0000000..9d9712d --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/client/EditorCatalog.java @@ -0,0 +1,21 @@ +package online.astradev.plus.editor.client; + +import java.util.List; +import java.util.stream.StreamSupport; + +import com.google.gson.JsonObject; + +public final class EditorCatalog { + private JsonObject catalogs = new JsonObject(); + + public void update(JsonObject response) { + if (response.has("catalogs") && response.get("catalogs").isJsonObject()) + catalogs = response.getAsJsonObject("catalogs").deepCopy(); + } + + public List values(String name) { + if (!catalogs.has(name) || !catalogs.get(name).isJsonArray()) return List.of(); + return StreamSupport.stream(catalogs.getAsJsonArray(name).spliterator(), false) + .map(value -> value.getAsString()).toList(); + } +} diff --git a/src/main/java/online/astradev/plus/editor/client/EditorClient.java b/src/main/java/online/astradev/plus/editor/client/EditorClient.java new file mode 100644 index 0000000..9c559c9 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/client/EditorClient.java @@ -0,0 +1,41 @@ +package online.astradev.plus.editor.client; + +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; +import net.minecraft.commands.Commands; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent; +import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent; +import online.astradev.plus.editor.network.EditorConnection; +import online.astradev.plus.editor.screen.ContentBrowserScreen; +import org.lwjgl.glfw.GLFW; + +public final class EditorClient { + private final EditorConnection connection; + private final KeyMapping open = new KeyMapping("key.astrapluseditor.open", GLFW.GLFW_KEY_F8, KeyMapping.Category.MISC); + private boolean requested; + + public EditorClient(EditorConnection connection) { this.connection = connection; } + + public void registerKeys(RegisterKeyMappingsEvent event) { event.register(open); } + + public void registerCommands(RegisterClientCommandsEvent event) { + event.getDispatcher().register(Commands.literal("astraplus-editor").executes(context -> { + requested = true; + return 1; + })); + } + + public void tick(ClientTickEvent.Post event) { + connection.tick(); + if (requested) { requested = false; open(); } + while (open.consumeClick()) { + if (Minecraft.getInstance().gui.screen() == null) open(); + } + } + + private void open() { + if (Minecraft.getInstance().player != null) + Minecraft.getInstance().gui.setScreen(new ContentBrowserScreen(connection)); + } +} diff --git a/src/main/java/online/astradev/plus/editor/form/ComponentExamples.java b/src/main/java/online/astradev/plus/editor/form/ComponentExamples.java new file mode 100644 index 0000000..4ec7afb --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/form/ComponentExamples.java @@ -0,0 +1,24 @@ +package online.astradev.plus.editor.form; + +/** Examples follow the Minecraft 26.2 component codecs; the server remains the validator. */ +public final class ComponentExamples { + private ComponentExamples() {} + + public static String value(String id) { + return switch (id) { + case "minecraft:max_damage" -> "1800"; + case "minecraft:max_stack_size" -> "1"; + case "minecraft:damage", "minecraft:repair_cost" -> "0"; + case "minecraft:enchantment_glint_override" -> "true"; + case "minecraft:damage_resistant" -> "{\"types\":\"#minecraft:is_fire\"}"; + case "minecraft:enchantable" -> "{\"value\":15}"; + case "minecraft:enchantments", "minecraft:stored_enchantments" -> "{\"minecraft:unbreaking\":3}"; + case "minecraft:food" -> "{\"nutrition\":6,\"saturation\":7.2,\"can_always_eat\":false}"; + case "minecraft:consumable" -> "{\"consume_seconds\":1.6,\"animation\":\"eat\"}"; + case "minecraft:tool" -> "{\"rules\":[{\"blocks\":\"#minecraft:mineable/pickaxe\",\"speed\":8.0,\"correct_for_drops\":true}],\"default_mining_speed\":1.0,\"damage_per_block\":1,\"can_destroy_blocks_in_creative\":true}"; + case "minecraft:attribute_modifiers" -> "[{\"type\":\"minecraft:attack_damage\",\"id\":\"astraplus:damage\",\"amount\":5.0,\"operation\":\"add_value\",\"slot\":\"mainhand\"}]"; + case "minecraft:lore" -> "[\"Описание предмета\"]"; + default -> "{}"; + }; + } +} diff --git a/src/main/java/online/astradev/plus/editor/form/ContentDraft.java b/src/main/java/online/astradev/plus/editor/form/ContentDraft.java new file mode 100644 index 0000000..8886e21 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/form/ContentDraft.java @@ -0,0 +1,166 @@ +package online.astradev.plus.editor.form; + +import java.math.BigDecimal; +import java.util.LinkedHashSet; +import java.util.Set; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +/** Lossless local draft: helpers change only the selected fields, never rebuild a server document. */ +public final class ContentDraft { + private JsonObject document; + private JsonObject saved; + private String revision; + + public ContentDraft(JsonObject document, String revision) { + this.document = document.deepCopy(); + this.saved = document.deepCopy(); + this.revision = revision; + } + + public static ContentDraft create(boolean block) { + var json = new JsonObject(); + json.addProperty("id", "astraplus:new_" + (block ? "block" : "item")); + json.addProperty("name", block ? "Новый блок" : "Новый предмет"); + json.addProperty("material", block ? "minecraft:note_block" : "minecraft:paper"); + json.addProperty("texture", block ? "minecraft:block/stone" : "minecraft:item/paper"); + if (block) { + var settings = new JsonObject(); + settings.addProperty("slot", 0); + settings.addProperty("base", "minecraft:stone"); + json.add("block", settings); + } + return new ContentDraft(json, "new"); + } + + public String id() { return text("", "id"); } + public boolean block() { return document.has("block") && document.get("block").isJsonObject(); } + public boolean fresh() { return revision.equals("new"); } + public String revision() { return revision; } + public boolean dirty() { return fresh() || !document.equals(saved); } + public JsonObject document() { return document.deepCopy(); } + + public JsonElement get(String... path) { + JsonElement value = document; + for (String key : path) { + if (!value.isJsonObject() || !value.getAsJsonObject().has(key)) return JsonNull.INSTANCE; + value = value.getAsJsonObject().get(key); + } + return value.deepCopy(); + } + + public String text(String fallback, String... path) { + var value = get(path); + return value.isJsonPrimitive() ? value.getAsString() : fallback; + } + + public void set(JsonElement value, String... path) { + var parent = document; + for (int index = 0; index < path.length - 1; index++) { + String key = path[index]; + if (!parent.has(key) || !parent.get(key).isJsonObject()) parent.add(key, new JsonObject()); + parent = parent.getAsJsonObject(key); + } + if (value == null || value.isJsonNull()) parent.remove(path[path.length - 1]); + else parent.add(path[path.length - 1], value.deepCopy()); + } + + public void string(String value, String... path) { set(new JsonPrimitive(value), path); } + public void bool(boolean value, String... path) { set(new JsonPrimitive(value), path); } + + public void number(String value, boolean integer, double min, double max, String... path) { + if (value.isBlank()) { set(null, path); return; } + BigDecimal number; + try { number = new BigDecimal(value.trim()); } + catch (NumberFormatException error) { throw new IllegalArgumentException("Введите число."); } + if (integer && number.stripTrailingZeros().scale() > 0) throw new IllegalArgumentException("Нужно целое число."); + if (number.compareTo(BigDecimal.valueOf(min)) < 0 || number.compareTo(BigDecimal.valueOf(max)) > 0) + throw new IllegalArgumentException("Допустимо от " + min + " до " + max + "."); + set(new JsonPrimitive(number), path); + } + + public void component(JsonElement value, String id) { + set(null, "components", "!" + id); + set(value, "components", id); + } + + public void removeComponent(String id, boolean removeBase) { + set(null, "components", id); + set(removeBase ? new JsonObject() : null, "components", "!" + id); + } + + public void model(String id, boolean customModel) { + set(null, customModel ? "texture" : "model"); + string(id, customModel ? "model" : "texture"); + } + + public boolean whitelist() { return get("enchantments", "allowed").isJsonArray(); } + + public void whitelist(boolean enabled) { + set(enabled ? new JsonArray() : null, "enchantments", "allowed"); + } + + public Set ids(String key) { + var result = new LinkedHashSet(); + var value = get("enchantments", key); + if (value.isJsonArray()) value.getAsJsonArray().forEach(id -> result.add(id.getAsString())); + return result; + } + + public void enchantment(String id, boolean enabled) { + var denied = ids("denied"); + if (enabled) denied.remove(id); else denied.add(id); + set(strings(denied), "enchantments", "denied"); + if (whitelist()) { + var allowed = ids("allowed"); + if (enabled) allowed.add(id); else allowed.remove(id); + set(strings(allowed), "enchantments", "allowed"); + } + } + + public boolean enabled(String id) { + return !ids("denied").contains(id) && (!whitelist() || ids("allowed").contains(id)); + } + + public boolean conflicts(String first, String second) { + var value = get("enchantments", "conflicts"); + if (!value.isJsonArray()) return false; + for (var pair : value.getAsJsonArray()) { + if (samePair(pair, first, second)) return true; + } + return false; + } + + public void conflict(String first, String second, boolean enabled) { + if (first.equals(second)) throw new IllegalArgumentException("Выберите два разных зачарования."); + var old = get("enchantments", "conflicts"); + var pairs = new JsonArray(); + if (old.isJsonArray()) for (var pair : old.getAsJsonArray()) + if (!samePair(pair, first, second)) pairs.add(pair.deepCopy()); + if (enabled) { + var pair = new JsonArray(); pair.add(first); pair.add(second); pairs.add(pair); + } + set(pairs, "enchantments", "conflicts"); + } + + public void saved(JsonObject accepted, String revision) { + this.document = accepted.deepCopy(); + this.saved = accepted.deepCopy(); + this.revision = revision; + } + + private static JsonArray strings(Set values) { + var array = new JsonArray(); values.forEach(array::add); return array; + } + + private static boolean samePair(JsonElement value, String first, String second) { + if (!value.isJsonArray() || value.getAsJsonArray().size() != 2) return false; + var pair = value.getAsJsonArray(); + String left = pair.get(0).getAsString(), right = pair.get(1).getAsString(); + return left.equals(first) && right.equals(second) || left.equals(second) && right.equals(first); + } +} diff --git a/src/main/java/online/astradev/plus/editor/form/ContentFields.java b/src/main/java/online/astradev/plus/editor/form/ContentFields.java new file mode 100644 index 0000000..3523f6a --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/form/ContentFields.java @@ -0,0 +1,148 @@ +package online.astradev.plus.editor.form; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import online.astradev.plus.editor.client.EditorCatalog; + +public final class ContentFields { + private static final List BOOLEAN = List.of("Наследовать", "Да", "Нет"); + private final ContentDraft draft; + private final EditorCatalog catalog; + + public ContentFields(ContentDraft draft, EditorCatalog catalog) { + this.draft = draft; + this.catalog = catalog; + } + + public List basic() { + var fields = new ArrayList(); + if (draft.fresh()) fields.add(FormField.text("id", "Идентификатор", "namespace:путь. После создания изменить нельзя.", + draft::id, value -> draft.string(value.trim(), "id"))); + fields.add(FormField.text("name", "Название", "Отображаемое имя предмета или блока.", + () -> draft.text("", "name"), value -> draft.string(value, "name"))); + if (!draft.block()) fields.add(new FormField("material", "Ванильная основа", "Предмет, свойства которого наследуются.", + () -> draft.text("minecraft:paper", "material"), value -> draft.string(value.trim(), "material"), catalog.values("items"), false)); + fields.add(new FormField("appearance", "Источник модели", "Текстура создаёт простую модель. Готовая модель задаёт собственную геометрию.", + () -> draft.get("model").isJsonNull() ? "Текстура" : "Готовая модель", + value -> draft.model(draft.text(draft.text("", "texture"), "model"), value.equals("Готовая модель")), + List.of("Текстура", "Готовая модель"), true)); + fields.add(FormField.text("asset", "Путь к текстуре / модели", "Например minecraft:item/diamond_sword. Без расширения файла.", + () -> draft.text(draft.text("", "texture"), "model"), + value -> draft.model(value.trim(), !draft.get("model").isJsonNull()))); + if (!draft.block()) fields.add(new FormField("handheld", "Положение инструмента в руке", "Для простой автоматически созданной модели.", + () -> draft.text("false", "handheld").equals("true") ? "Да" : "Нет", + value -> draft.bool(value.equals("Да"), "handheld"), List.of("Нет", "Да"), true)); + return fields; + } + + public List properties() { + return List.of( + numeric("minecraft:max_damage", "Максимальная прочность", true, 1, Integer.MAX_VALUE), + numeric("minecraft:max_stack_size", "Размер стопки", true, 1, 99), + new FormField("unbreakable", "Неразрушимый предмет", "Запретить расход прочности; пустое значение наследуется от основы.", + () -> state("minecraft:unbreakable"), value -> unit(value, "minecraft:unbreakable"), BOOLEAN, true), + new FormField("fireproof", "Не сгорает в огне и лаве", "Защита лежащего предмета от источников урона #minecraft:is_fire.", + this::fireState, this::fireproof, List.of("Наследовать", "Да", "Нет", "Особая настройка"), true), + new FormField("glint", "Эффект зачарования", "Только визуальный блеск. Сами зачарования задаются компонентом enchantments.", + () -> componentBoolean("minecraft:enchantment_glint_override"), value -> booleanComponent(value, "minecraft:enchantment_glint_override"), BOOLEAN, true), + FormField.text("enchantable", "Зачаровываемость", "Положительное целое число; пусто — наследовать. Влияет на стол зачарований.", + () -> draft.text("", "components", "minecraft:enchantable", "value"), value -> { + if (value.isBlank()) { draft.removeComponent("minecraft:enchantable", false); return; } + draft.number(value, true, 1, Integer.MAX_VALUE, "components", "minecraft:enchantable", "value"); + draft.set(null, "components", "!minecraft:enchantable"); + }), + FormField.text("nutrition", "Еда: питание", "Пусто — не переопределять. Для употребления нужен также компонент consumable.", + () -> draft.text("", "components", "minecraft:food", "nutrition"), value -> + food(value, true, "nutrition")), + FormField.text("saturation", "Еда: насыщение", "Прямое значение насыщения; для еды задайте также питание.", + () -> draft.text("", "components", "minecraft:food", "saturation"), value -> + food(value, false, "saturation"))); + } + + public List block() { + return List.of( + new FormField("base", "Физическая основа на сервере", "Полный ванильный блок без BlockEntity. Коллизия модели остаётся полным блоком.", + () -> draft.text("minecraft:stone", "block", "base"), value -> draft.string(value.trim(), "block", "base"), catalog.values("blocks"), false), + FormField.text("hardness", "Твёрдость", "Пусто — наследовать от основы. -1 — неразрушимый; 0 — мгновенно.", + () -> draft.text("", "block", "hardness"), this::hardness), + FormField.text("resistance", "Взрывоустойчивость", "Пусто — наследовать от основы. Ноль не даёт сопротивления взрыву.", + () -> draft.text("", "block", "explosionResistance"), value -> draft.number(value, false, 0, 3_600_000, "block", "explosionResistance")), + new FormField("tool", "Нужен подходящий инструмент", "Пусто — наследовать. Подходящий тип определяется ванильной основой.", + () -> booleanState("block", "requiresCorrectTool"), value -> booleanValue(value, "block", "requiresCorrectTool"), BOOLEAN, true), + FormField.text("drop", "Количество выпадающих блоков", "От 0 до 64; пусто — обычный дроп 1. Выпадает этот же пользовательский блок.", + () -> draft.text("", "block", "dropCount"), value -> draft.number(value, true, 0, 64, "block", "dropCount"))); + } + + private FormField numeric(String id, String label, boolean integer, double min, double max) { + return FormField.text(id, label, "Пустое поле — наследовать значение от ванильной основы.", + () -> draft.text("", "components", id), value -> { + draft.number(value, integer, min, max, "components", id); + draft.set(null, "components", "!" + id); + }); + } + + private String state(String id) { + if (!draft.get("components", "!" + id).isJsonNull()) return "Нет"; + return draft.get("components", id).isJsonNull() ? "Наследовать" : "Да"; + } + + private void unit(String value, String id) { + if (value.equals("Да")) draft.component(new JsonObject(), id); + else draft.removeComponent(id, value.equals("Нет")); + } + + private String fireState() { + var component = draft.get("components", "minecraft:damage_resistant"); + if (component.isJsonNull()) return state("minecraft:damage_resistant"); + return draft.text("", "components", "minecraft:damage_resistant", "types").equals("#minecraft:is_fire") + ? "Да" : "Особая настройка"; + } + + private void fireproof(String value) { + if (value.equals("Особая настройка")) return; + if (value.equals("Да")) { + var component = new JsonObject(); component.addProperty("types", "#minecraft:is_fire"); + draft.component(component, "minecraft:damage_resistant"); + } else draft.removeComponent("minecraft:damage_resistant", value.equals("Нет")); + } + + private String componentBoolean(String id) { + return booleanState("components", id); + } + + private void booleanComponent(String value, String id) { + if (value.equals("Наследовать")) draft.removeComponent(id, false); + else draft.component(new JsonPrimitive(value.equals("Да")), id); + } + + private String booleanState(String... path) { + String value = draft.text("", path); + return value.isEmpty() ? "Наследовать" : value.equals("true") ? "Да" : "Нет"; + } + + private void booleanValue(String value, String... path) { + if (value.equals("Наследовать")) draft.set(null, path); + else draft.bool(value.equals("Да"), path); + } + + private void food(String value, boolean integer, String key) { + draft.number(value, integer, 0, 1_000_000, "components", "minecraft:food", key); + draft.set(null, "components", "!minecraft:food"); + var food = draft.get("components", "minecraft:food"); + if (food.isJsonObject() && food.getAsJsonObject().isEmpty()) draft.removeComponent("minecraft:food", false); + } + + private void hardness(String value) { + if (!value.isBlank()) { + try { + var number = new java.math.BigDecimal(value.trim()); + if (number.signum() < 0 && number.compareTo(java.math.BigDecimal.valueOf(-1)) != 0) + throw new IllegalArgumentException("Допустимо -1 или неотрицательное число."); + } catch (NumberFormatException error) { throw new IllegalArgumentException("Введите число."); } + } + draft.number(value, false, -1, 1_000_000, "block", "hardness"); + } +} diff --git a/src/main/java/online/astradev/plus/editor/form/FormField.java b/src/main/java/online/astradev/plus/editor/form/FormField.java new file mode 100644 index 0000000..9bc9d3a --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/form/FormField.java @@ -0,0 +1,12 @@ +package online.astradev.plus.editor.form; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public record FormField(String key, String label, String hint, Supplier read, + Consumer write, List choices, boolean cycle) { + public static FormField text(String key, String label, String hint, Supplier read, Consumer write) { + return new FormField(key, label, hint, read, write, List.of(), false); + } +} diff --git a/src/main/java/online/astradev/plus/editor/network/EditorConnection.java b/src/main/java/online/astradev/plus/editor/network/EditorConnection.java new file mode 100644 index 0000000..b6bb7d0 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/network/EditorConnection.java @@ -0,0 +1,105 @@ +package online.astradev.plus.editor.network; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.neoforged.neoforge.client.network.ClientPacketDistributor; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; + +/** Correlates bounded requests; no packet is sent unless the remote server supports the editor. */ +public final class EditorConnection { + public static final EditorConnection INSTANCE = new EditorConnection(); + private final Map pending = new HashMap<>(); + private ClientPacketListener connection; + private int nextRequest; + + private EditorConnection() {} + + public void register(RegisterPayloadHandlersEvent event) { + event.registrar("1").optional() + .playToServer(EditorRequest.TYPE, EditorRequest.CODEC, (request, context) -> {}) + .playToClient(EditorResponse.TYPE, EditorResponse.CODEC, (response, context) -> receive(response)); + } + + public boolean available() { + var listener = Minecraft.getInstance().getConnection(); + return listener != null && listener.hasChannel(EditorRequest.TYPE) && listener.hasChannel(EditorResponse.TYPE); + } + + public void request(String action, JsonObject body, Consumer callback) { + tick(); + if (!available()) { + callback.accept(error("Сервер не поддерживает редактор AstraPlus или подключение ещё не готово.")); + return; + } + if (pending.size() >= 8) { + callback.accept(error("Дождитесь ответа на предыдущие запросы.")); + return; + } + int requestId = ++nextRequest; + var request = body.deepCopy(); + request.addProperty("requestId", requestId); + request.addProperty("action", action); + String json = request.toString(); + if (json.length() > EditorRequest.LIMIT) { + callback.accept(error("Документ превышает лимит сетевого редактора (8192 символа). Сократите данные или измените файл на сервере.")); + return; + } + pending.put(requestId, new Pending(System.nanoTime(), callback)); + try { + ClientPacketDistributor.sendToServer(new EditorRequest(json)); + } catch (RuntimeException failure) { + pending.remove(requestId); + callback.accept(error("Не удалось отправить запрос: " + failure.getMessage())); + } + } + + public void tick() { + var current = Minecraft.getInstance().getConnection(); + if (current != connection) { + var abandoned = Map.copyOf(pending); + pending.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(); + for (var entry : expired) { + pending.remove(entry.getKey()); + entry.getValue().callback.accept(error("Сервер не ответил. Перед повторным сохранением проверьте актуальную версию.")); + } + } + + private void receive(EditorResponse payload) { + try { + var response = JsonParser.parseString(payload.json()).getAsJsonObject(); + var request = pending.remove(response.get("requestId").getAsInt()); + if (request != null) request.callback.accept(response); + } catch (RuntimeException ignored) { + // Malformed or unsolicited replies cannot update a document; pending requests expire normally. + } + } + + public static boolean success(JsonObject response) { + return response.has("ok") && response.get("ok").getAsBoolean(); + } + + public static String message(JsonObject response) { + return response.has("message") ? response.get("message").getAsString() : "Ответ сервера не содержит сообщения."; + } + + private static JsonObject error(String message) { + var response = new JsonObject(); + response.addProperty("ok", false); + response.addProperty("message", message); + return response; + } + + private record Pending(long started, Consumer callback) {} +} diff --git a/src/main/java/online/astradev/plus/editor/network/EditorRequest.java b/src/main/java/online/astradev/plus/editor/network/EditorRequest.java new file mode 100644 index 0000000..fc85c94 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/network/EditorRequest.java @@ -0,0 +1,16 @@ +package online.astradev.plus.editor.network; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; + +public record EditorRequest(String json) implements CustomPacketPayload { + public static final int LIMIT = 8192; + public static final Type TYPE = new Type<>(Identifier.parse("astraplus:editor_request")); + public static final StreamCodec CODEC = StreamCodec.of( + (buffer, request) -> buffer.writeUtf(request.json, LIMIT), + buffer -> new EditorRequest(buffer.readUtf(LIMIT))); + + @Override public Type type() { return TYPE; } +} diff --git a/src/main/java/online/astradev/plus/editor/network/EditorResponse.java b/src/main/java/online/astradev/plus/editor/network/EditorResponse.java new file mode 100644 index 0000000..dd51779 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/network/EditorResponse.java @@ -0,0 +1,16 @@ +package online.astradev.plus.editor.network; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; + +public record EditorResponse(String json) implements CustomPacketPayload { + public static final int LIMIT = 262144; + public static final Type TYPE = new Type<>(Identifier.parse("astraplus:editor_response")); + public static final StreamCodec CODEC = StreamCodec.of( + (buffer, response) -> buffer.writeUtf(response.json, LIMIT), + buffer -> new EditorResponse(buffer.readUtf(LIMIT))); + + @Override public Type type() { return TYPE; } +} diff --git a/src/main/java/online/astradev/plus/editor/screen/ChoiceList.java b/src/main/java/online/astradev/plus/editor/screen/ChoiceList.java new file mode 100644 index 0000000..78d4c78 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/screen/ChoiceList.java @@ -0,0 +1,48 @@ +package online.astradev.plus.editor.screen; + +import java.util.List; +import java.util.function.Consumer; + +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; + +public final class ChoiceList extends ObjectSelectionList { + private final Consumer selected; + + public ChoiceList(Minecraft minecraft, int x, int y, int width, int height, Consumer selected) { + super(minecraft, width, height, y, 26); + setX(x); + this.selected = selected; + } + + public void values(List values) { + clearEntries(); + values.forEach(value -> addEntry(new Row(value))); + } + + @Override public int getRowWidth() { return width - 16; } + + public final class Row extends ObjectSelectionList.Entry { + private final String value; + + private Row(String value) { this.value = value; } + + @Override public Component getNarration() { return Component.literal(value); } + + @Override public void extractContent(GuiGraphicsExtractor graphics, int mouseX, int mouseY, boolean hovered, float a) { + if (hovered) graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0x80365962); + graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(value, getContentWidth()), + getContentX() + 3, getContentY() + 6, 0xFFE4EBED); + } + + @Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + if (event.button() != 0) return false; + setSelected(this); + selected.accept(value); + return true; + } + } +} diff --git a/src/main/java/online/astradev/plus/editor/screen/ChoiceScreen.java b/src/main/java/online/astradev/plus/editor/screen/ChoiceScreen.java new file mode 100644 index 0000000..a8f7379 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/screen/ChoiceScreen.java @@ -0,0 +1,40 @@ +package online.astradev.plus.editor.screen; + +import java.util.List; +import java.util.Locale; +import java.util.function.Consumer; + +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +public final class ChoiceScreen extends EditorScreen { + private final Screen parent; + private final List values; + private final Consumer selected; + + public ChoiceScreen(Screen parent, String title, List values, Consumer selected) { + super(title); + this.parent = parent; + this.values = values; + this.selected = selected; + } + + @Override protected void init() { + var list = addRenderableWidget(new ChoiceList(minecraft, 12, 65, width - 24, Math.max(30, height - 135), value -> { + selected.accept(value); + minecraft.gui.setScreen(parent); + })); + var search = addRenderableWidget(new EditBox(font, 12, 38, width - 24, 20, Component.literal("Поиск"))); + search.setHint(Component.literal("Поиск по идентификатору")); + search.setMaxLength(256); + search.setResponder(query -> list.values(values.stream() + .filter(value -> value.toLowerCase(Locale.ROOT).contains(query.toLowerCase(Locale.ROOT))).toList())); + list.values(values); + button("Назад", 12, height - 27, 100, this::onClose); + if (values.isEmpty()) status("Каталог пуст. Проверьте ответ сервера.", true); + setInitialFocus(search); + } + + @Override public void onClose() { minecraft.gui.setScreen(parent); } +} diff --git a/src/main/java/online/astradev/plus/editor/screen/ComponentListScreen.java b/src/main/java/online/astradev/plus/editor/screen/ComponentListScreen.java new file mode 100644 index 0000000..7307a1f --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/screen/ComponentListScreen.java @@ -0,0 +1,57 @@ +package online.astradev.plus.editor.screen; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import online.astradev.plus.editor.client.EditorCatalog; +import online.astradev.plus.editor.form.ContentDraft; + +public final class ComponentListScreen extends EditorScreen { + private static final Set RESERVED = Set.of("minecraft:custom_data", "minecraft:item_model", "minecraft:item_name", + "minecraft:block_state", "minecraft:block_entity_data"); + private final ContentEditorScreen parent; + private final ContentDraft draft; + private final EditorCatalog catalog; + + public ComponentListScreen(ContentEditorScreen parent, ContentDraft draft, EditorCatalog catalog) { + super("AstraPlus: компоненты предмета"); + this.parent = parent; + this.draft = draft; + this.catalog = catalog; + } + + @Override protected void init() { + var components = draft.get("components"); + var names = new LinkedHashSet(); + if (components.isJsonObject()) components.getAsJsonObject().keySet().stream().sorted() + .forEach(key -> names.add(key.startsWith("!") ? key.substring(1) : key)); + var list = addRenderableWidget(new ChoiceList(minecraft, 12, 38, width - 24, Math.max(30, height - 118), this::open)); + list.values(names.stream().toList()); + button("Добавить компонент", 12, height - 27, Math.min(170, width / 2), () -> { + List available = catalog.values("components").stream().filter(id -> !RESERVED.contains(id)).toList(); + minecraft.gui.setScreen(new ChoiceScreen(this, "Выберите компонент", available, this::scheduleOpen)); + }); + button("Назад", width - 102, height - 27, 90, this::onClose); + status("Выберите переопределение. Сложные свойства редактируются отдельно в JSON; остальные поля сохраняются.", false); + } + + private void scheduleOpen(String id) { + // ChoiceScreen restores this screen after its callback, so open the value editor on the next tick. + selected = id; + } + + private String selected; + + @Override public void tick() { + if (selected != null) { + String id = selected; + selected = null; + open(id); + } + } + + private void open(String id) { minecraft.gui.setScreen(new ComponentValueScreen(this, parent, draft, id)); } + + @Override public void onClose() { minecraft.gui.setScreen(parent); } +} diff --git a/src/main/java/online/astradev/plus/editor/screen/ComponentValueScreen.java b/src/main/java/online/astradev/plus/editor/screen/ComponentValueScreen.java new file mode 100644 index 0000000..efe9ee9 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/screen/ComponentValueScreen.java @@ -0,0 +1,76 @@ +package online.astradev.plus.editor.screen; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParser; +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.ComponentExamples; +import online.astradev.plus.editor.form.ContentDraft; + +public final class ComponentValueScreen extends EditorScreen { + private final ComponentListScreen parent; + private final ContentEditorScreen editor; + private final ContentDraft draft; + private final String id; + private final String initial; + private String value; + + public ComponentValueScreen(ComponentListScreen parent, ContentEditorScreen editor, ContentDraft draft, String id) { + super(id); + this.parent = parent; + this.editor = editor; + this.draft = draft; + this.id = id; + var component = draft.get("components", id); + initial = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson( + component.isJsonNull() ? JsonParser.parseString(ComponentExamples.value(id)) : component); + value = initial; + } + + @Override protected void init() { + var input = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(39).setShowDecorations(false) + .setPlaceholder(Component.literal("Значение компонента в формате JSON")) + .build(font, width - 24, Math.max(30, height - 139), Component.literal("JSON компонента"))); + input.setCharacterLimit(Math.max(8192, value.length())); + input.setValue(value); + input.setValueListener(text -> value = text); + int part = (width - 32) / 3; + button("Наследовать", 12, height - 94, part, "Удалить только переопределение; вернуть свойство ванильной основы.", + () -> remove(false)); + button("Убрать свойство", 16 + part, height - 94, part, "Убрать этот компонент даже у ванильной основы (!component).", + () -> remove(true)); + button("Пример", 20 + part * 2, height - 94, part, () -> { + value = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() + .toJson(JsonParser.parseString(ComponentExamples.value(id))); + rebuildWidgets(); + }); + button("Назад", 12, height - 27, 100, this::onClose); + button("В черновик", width - 142, height - 27, 130, this::apply); + status("Значение одного компонента. Проверка Minecraft выполняется при сохранении определения на сервере.", false); + } + + private void apply() { + try { + var parsed = JsonParser.parseString(value); + if (parsed.isJsonNull()) throw new IllegalArgumentException("Значение null не является компонентом."); + draft.component(parsed, id); + editor.componentChanged(); + minecraft.gui.setScreen(parent); + } catch (RuntimeException error) { + status("Некорректный JSON: " + error.getMessage(), true); + } + } + + private void remove(boolean base) { + draft.removeComponent(id, base); + editor.componentChanged(); + minecraft.gui.setScreen(parent); + } + + @Override public void onClose() { + if (!value.equals(initial)) minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this), + Component.literal("Закрыть компонент?"), Component.literal("Изменения JSON ещё не перенесены в черновик определения."))); + else minecraft.gui.setScreen(parent); + } +} diff --git a/src/main/java/online/astradev/plus/editor/screen/ContentBrowserScreen.java b/src/main/java/online/astradev/plus/editor/screen/ContentBrowserScreen.java new file mode 100644 index 0000000..3cf5f5d --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/screen/ContentBrowserScreen.java @@ -0,0 +1,107 @@ +package online.astradev.plus.editor.screen; + +import java.util.LinkedHashMap; +import java.util.Locale; +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; + +public final class ContentBrowserScreen extends EditorScreen { + private final EditorConnection connection; + private final EditorCatalog catalog = new EditorCatalog(); + private final Map rows = new LinkedHashMap<>(); + private ChoiceList list; + private int page; + private int pages = 1; + private String query = ""; + private int searchDelay; + private int requestGeneration; + private boolean first = true; + + public ContentBrowserScreen(EditorConnection connection) { + super("AstraPlus: предметы и блоки"); + this.connection = connection; + } + + @Override protected void init() { + var search = addRenderableWidget(new EditBox(font, 12, 38, 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.values(rows.keySet().stream().toList()); + int row = height - 94; + int part = Math.max(50, (width - 48) / 4); + button("+ Предмет", 12, row, part, () -> create(false)); + button("+ Блок", 20 + part, row, part, () -> create(true)); + button("Обновить", 28 + part * 2, row, part, this::refresh); + button("Ресурспак", 36 + part * 3, row, part, + "Собрать ресурспак и экспортировать его в AstraPacks, если интеграция включена.", () -> { + status("Запрашивается сборка ресурспака…", false); + connection.request("build", new JsonObject(), this::reply); + }); + button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } }); + button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } }); + button("Закрыть", width - 102, height - 27, 90, this::onClose); + if (first) { + first = false; + connection.request("catalog", new JsonObject(), response -> { + if (EditorConnection.success(response)) catalog.update(response); + else reply(response); + }); + } + refresh(); + } + + @Override public void tick() { + if (searchDelay > 0 && --searchDelay == 0) refresh(); + } + + private void refresh() { + int generation = ++requestGeneration; + var request = new JsonObject(); + request.addProperty("page", page); + request.addProperty("query", query); + status("Загрузка…", false); + connection.request("list", request, response -> { + if (generation != requestGeneration) return; + if (!EditorConnection.success(response)) { reply(response); return; } + rows.clear(); + 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; + pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1); + list.values(rows.keySet().stream().toList()); + status("Страница " + (page + 1) + " / " + pages + ": Выберите определение для редактирования.", false); + }); + } + + private void load(String label) { + String id = rows.get(label); + if (id == null) return; + var request = new JsonObject(); request.addProperty("id", id); + status("Открывается " + id + "…", false); + connection.request("get", request, response -> { + if (!EditorConnection.success(response)) { reply(response); return; } + if (minecraft.gui.screen() != this) return; + var draft = new ContentDraft(response.getAsJsonObject("document"), response.get("revision").getAsString()); + minecraft.gui.setScreen(new ContentEditorScreen(this, connection, catalog, draft)); + }); + } + + private void create(boolean block) { + minecraft.gui.setScreen(new ContentEditorScreen(this, connection, catalog, ContentDraft.create(block))); + } + + private void reply(JsonObject response) { status(EditorConnection.message(response), !EditorConnection.success(response)); } +} diff --git a/src/main/java/online/astradev/plus/editor/screen/ContentEditorScreen.java b/src/main/java/online/astradev/plus/editor/screen/ContentEditorScreen.java new file mode 100644 index 0000000..eadcf18 --- /dev/null +++ b/src/main/java/online/astradev/plus/editor/screen/ContentEditorScreen.java @@ -0,0 +1,169 @@ +package online.astradev.plus.editor.screen; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.JsonObject; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.client.gui.screens.ConfirmScreen; +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.ContentFields; +import online.astradev.plus.editor.form.FormField; +import online.astradev.plus.editor.network.EditorConnection; + +public final class ContentEditorScreen extends EditorScreen { + private final ContentBrowserScreen parent; + private final EditorConnection connection; + private final EditorCatalog catalog; + private final ContentDraft draft; + private final Map typed = new LinkedHashMap<>(); + private final Map errors = new LinkedHashMap<>(); + private final List