Add four-ingredient cauldron soups with persistent brewing and stackable food
This commit is contained in:
@@ -0,0 +1,5 @@
|
|||||||
|
.gradle/
|
||||||
|
build/
|
||||||
|
*.log
|
||||||
|
*.jar
|
||||||
|
.test-server/
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Общие правила работы с плагинами AstraCraft
|
||||||
|
|
||||||
|
Эти правила действуют для всех проектов в `C:\Users\ScarPC\Documents\Plugins`.
|
||||||
|
Общая копия хранится в `Plugins\AGENTS.md`; копии в репозиториях нужны, чтобы правила
|
||||||
|
сохранялись при клонировании отдельного плагина. При изменении общих правил обновлять все копии.
|
||||||
|
|
||||||
|
## Расположение проектов и сервера
|
||||||
|
|
||||||
|
- Каждый плагин имеет отдельную папку исходников и собственный Git-репозиторий в `C:\Users\ScarPC\Documents\Plugins`.
|
||||||
|
- Рабочий сервер: `C:\Users\ScarPC\Documents\26.2 Paper`.
|
||||||
|
- Установленные JAR: `C:\Users\ScarPC\Documents\26.2 Paper\plugins`.
|
||||||
|
- Архив старых JAR: `C:\Users\ScarPC\Documents\26.2 Paper\old-plugins`.
|
||||||
|
|
||||||
|
## Обязательная установка собранного JAR
|
||||||
|
|
||||||
|
После изменений кода, встроенных ресурсов или сборки плагина работа включает не только
|
||||||
|
сборку артефакта, но и обновление соответствующего JAR в папке плагинов рабочего сервера.
|
||||||
|
|
||||||
|
1. Выполнить сборку и проверки, необходимые для сделанных изменений. Устанавливать только успешно собранный JAR.
|
||||||
|
2. Найти установленный JAR именно этого плагина. Сопоставлять имя плагина, а не только номер версии файла.
|
||||||
|
3. Перед заменой перенести старую версию в `old-plugins\YYYYMMDD-HHMMSS\`, сохранив исходное имя JAR.
|
||||||
|
Если папка уже существует, выбрать уникальное имя. Не удалять и не перезаписывать старые версии в архиве.
|
||||||
|
4. Скопировать новый JAR в `plugins`. Не оставлять там одновременно старую и новую версии одного плагина.
|
||||||
|
5. Проверить, что установленный файл совпадает с собранным артефактом по SHA-256.
|
||||||
|
6. При обновлении нескольких плагинов выполнить эти действия для каждого изменённого плагина.
|
||||||
|
|
||||||
|
Не заменять конфигурации, данные плагинов и миры при обычном обновлении JAR.
|
||||||
|
Если установка не выполнена, явно сообщить об этом; не объявлять обновление сервера завершённым.
|
||||||
|
Изменения только документации и правил не требуют пересборки и замены неизменного JAR.
|
||||||
|
|
||||||
|
## Обязательная фиксация в Git
|
||||||
|
|
||||||
|
- Каждая завершённая задача с изменениями файлов должна быть зафиксирована коммитом
|
||||||
|
в соответствующем репозитории. Коммит — обязательная часть работы, отдельное напоминание пользователя не требуется.
|
||||||
|
- Если задача затрагивает несколько репозиториев, создать отдельный коммит в каждом из них.
|
||||||
|
- Перед коммитом проверить diff и результаты необходимых проверок.
|
||||||
|
- Коммитить изменения текущей задачи. Не включать посторонние изменения пользователя и не откатывать их.
|
||||||
|
- Сообщение коммита должно описывать конкретное изменение.
|
||||||
|
- Не добавлять в Git собранные JAR, каталоги build/.gradle, журналы, тестовые серверы и резервные копии.
|
||||||
|
- Push выполнять, когда он запрошен пользователем или уже разрешён в текущей задаче; сам коммит обязателен независимо от push.
|
||||||
|
- В итоговом ответе указать результат установки JAR, расположение сохранённой старой версии и созданные коммиты,
|
||||||
|
когда соответствующие действия выполнялись в этой задаче.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# AstraSoups 0.1.0
|
||||||
|
|
||||||
|
Отдельный серверный плагин комбинированных супов для **Paper 26.2**, Java 25+.
|
||||||
|
Сборка проекта использует установленный JDK 26. Клиентские моды и ресурспак не требуются.
|
||||||
|
|
||||||
|
## Использование
|
||||||
|
|
||||||
|
1. Полностью наполнить котёл водой.
|
||||||
|
2. Нажать ПКМ по котлу с ингредиентом в основной руке. Каждое нажатие кладёт **одну единицу**. Всего нужно **четыре**; одинаковые ингредиенты разрешены.
|
||||||
|
3. Начать варку: **Shift+ПКМ** или обычный **ПКМ с любым предметом в руке**, когда все четыре ингредиента уже внутри. Предмет для запуска не расходуется. Ингредиенты исчезнут, поверхность воды станет цветной.
|
||||||
|
4. **ПКМ миской** по готовому супу выдаёт **одну порцию**, расходует одну миску и опустошает котёл. Если запускать варку миской, первое нажатие варит, второе собирает.
|
||||||
|
|
||||||
|
**Обычный ПКМ пустой рукой** до варки возвращает самый недавно добавленный ингредиент. Такое разделение позволяет и запускать варку, и извлекать ингредиенты без конфликта действий.
|
||||||
|
|
||||||
|
Ингредиенты показаны настоящими левитирующими `Item`-сущностями: их нельзя подобрать, собрать воронкой, объединить с выпавшими предметами или уничтожить обычным уроном. Готовый суп отображается тонкой `BlockDisplay`-поверхностью внутри котла. Цвет смешивается из ингредиентов и округляется до ближайшего оттенка терракоты. Это приближение средствами ванильного клиента, а не изменение настоящего цвета воды.
|
||||||
|
|
||||||
|
Все четыре ванильных супа — грибной, кроличий, свекольный и подозрительный — и комбинированные супы получают максимальный стак **16**. Одинаковые рецепты совместимы по стакам независимо от порядка загрузки ингредиентов. Разные составы или эффекты дают разные предметы.
|
||||||
|
|
||||||
|
## Питание и эффекты
|
||||||
|
|
||||||
|
- Поддерживается вся ванильная еда, включая целый торт: 14 голода и 2,8 насыщения.
|
||||||
|
- Поддерживаются обычные, взрывные и оседающие зелья. Стрелы с эффектами не считаются зельями.
|
||||||
|
- Питание берётся из реальных компонентов предметов, включая изменённую плагинами еду. Насыщение указывается в абсолютных очках, а не коэффициентом.
|
||||||
|
- У зелий сохраняются точные длительности в тиках, уровни, бесконечность и флаги видимости. Взрывные и оседающие зелья передают записанную полную длительность.
|
||||||
|
- Эффекты золотых яблок, подозрительных супов и другой еды сохраняются. Вероятностные эффекты остаются вероятностными, включая вредные. Действия еды вроде телепортации хоруса и снятия яда мёдом также переносятся.
|
||||||
|
- Совпадающие эффекты применяются по ванильным правилам Minecraft: уровни не складываются арифметически, более слабый эффект не заменяет более сильный. Каждый записанный эффект сохраняет свою длительность.
|
||||||
|
- Комбинированный суп можно есть при полном голоде, чтобы получить эффекты. Миска возвращается нативным механизмом Minecraft, в том числе при поедании стака.
|
||||||
|
- Значения в описании супа — сумма ингредиентов. **Фактические голод и насыщение игрока ограничиваются Minecraft: максимум 20; насыщение не выше текущего голода.** Переполнение сверх этих пределов не хранится в резерве.
|
||||||
|
- В одну варку получается одна порция. Упаковка ингредиентов расходуется вместе с ингредиентами; пустые бутылки и миски исходной еды отдельно не возвращаются. В Creative предметы в руках не расходуются.
|
||||||
|
|
||||||
|
Пример: продлённое ночное зрение + стейк + светящиеся ягоды + сила II = **10 голода, 13,2 насыщения, ночное зрение I на 8:00 и сила II на 1:30**.
|
||||||
|
|
||||||
|
## Уникальная еда
|
||||||
|
|
||||||
|
Если у предмета есть нативный компонент еды, он поддерживается автоматически. Для еды, чьи характеристики реализованы обработчиками другого плагина, возьмите предмет и выполните:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/soups register my_food 7 4.5
|
||||||
|
```
|
||||||
|
|
||||||
|
Команда сохраняет образец предмета в `plugins/AstraSoups/config.yml`, задаёт 7 голода и 4,5 насыщения. Количество в стаке не влияет на совпадение, остальные метаданные должны совпадать. Обычный предмет того же материала не станет такой едой. Перерегистрация того же ID заменяет образец и питание.
|
||||||
|
|
||||||
|
Дополнительные эффекты можно прописать в записи `custom-ingredients.my_food`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
effects:
|
||||||
|
- type: minecraft:strength
|
||||||
|
duration: 3600
|
||||||
|
amplifier: 1
|
||||||
|
```
|
||||||
|
|
||||||
|
Это сила II на 3 минуты. `amplifier: 0` соответствует I, `duration: -1` — бесконечности. Дополнительные эффекты прибавляются к встроенным свойствам предмета.
|
||||||
|
|
||||||
|
ItemsAdder — необязательная зависимость. При его наличии плагин умеет распознавать namespaced ID для правил совместимости. Эффекты, которые сторонние плагины выдают только своим обработчиком употребления, автоматически не исполняются при поедании супа: задайте их явно в регистрации.
|
||||||
|
|
||||||
|
## Запреты сочетаний
|
||||||
|
|
||||||
|
Пример `config.yml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
blocked-ingredients:
|
||||||
|
- material:ROTTEN_FLESH
|
||||||
|
incompatible:
|
||||||
|
- ['effect:minecraft:strength', 'effect:minecraft:weakness']
|
||||||
|
- ['custom:my_food', 'itemsadder:my_pack:another_food']
|
||||||
|
- ['material:GOLDEN_APPLE', 'material:GOLDEN_APPLE']
|
||||||
|
```
|
||||||
|
|
||||||
|
Первый список полностью запрещает ингредиент. Второй содержит пары несовместимых ингредиентов: совпадения должны быть в **разных слотах**. Последнее правило запрещает два золотых яблока в одном котле. Проверка выполняется при запуске варки; при отказе ингредиенты остаются и их можно забрать.
|
||||||
|
|
||||||
|
Селекторы без учёта регистра: `material:NAME`, `effect:minecraft:id`, `custom:registered_id`, `itemsadder:namespace:id`, `soup:combined` и `*` для любого ингредиента. По умолчанию списки пусты — запрещённых комбинаций не выдумано.
|
||||||
|
|
||||||
|
`max-nutrition` и `max-saturation` по умолчанию равны 1000. Они ограничивают рецепт при повторном комбинировании супов и предотвращают переполнение; превышение отклоняет варку без потери ингредиентов. Дополнительно ограничивается число действий употребления до 256.
|
||||||
|
|
||||||
|
## Команды и права
|
||||||
|
|
||||||
|
| Команда / право | Назначение |
|
||||||
|
| --- | --- |
|
||||||
|
| `/soups` | Подсказка по управлению |
|
||||||
|
| `/soups reload` | Перечитать настройки; ошибка оставляет прежние настройки |
|
||||||
|
| `/soups register <id> <голод> <насыщение>` | Зарегистрировать предмет в основной руке |
|
||||||
|
| `astrasoups.use` | Использование котлов; по умолчанию разрешено всем |
|
||||||
|
| `astrasoups.admin` | Регистрация и перезагрузка; по умолчанию только операторы |
|
||||||
|
|
||||||
|
## Сохранение и взаимодействия
|
||||||
|
|
||||||
|
Состояния котлов записываются в `plugins/AstraSoups/cauldrons.yml` после каждой операции через временный файл и замену. Ошибка сохранения отменяет операцию до передачи предмета. Содержимое восстанавливается после нормального перезапуска, выгрузка чанков не требует держать их загруженными. Файл и инвентарь игрока не являются общей транзакционной базой: жёсткое завершение процесса ровно между сохранениями Minecraft и плагина не даёт гарантии атомарности.
|
||||||
|
|
||||||
|
При разбивании котла сырые ингредиенты выпадают, сваренный суп выливается. Котлы с содержимым защищены от взрывов, поршней и изменения уровня воды. Уже отменённые взаимодействия и ломание блоков уважаются. Внешнее редактирование блоков очищает состояние пропавшего котла и возвращает сырые ингредиенты при следующей проверке.
|
||||||
|
|
||||||
|
Старые ванильные супы получают размер стака при открытии инвентаря, входе игрока, загрузке выпавших предметов, крафте, генерации лута и перемещениях воронок. Открытые инвентари проверяются раз в секунду: выдачи сторонними плагинами нормализуются в пределах этого интервала. Содержимое закрытых незагруженных сундуков не сканируется заранее. `MAX_STACK_SIZE` меняется у экземпляров предметов, а не у глобального прототипа материала.
|
||||||
|
|
||||||
|
## Сборка и установка
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\gradlew.bat test jar
|
||||||
|
```
|
||||||
|
|
||||||
|
Результат: `build/libs/AstraSoups-0.1.0.jar`. Поместить в папку `plugins` Paper 26.2 и запустить/перезапустить сервер. Настройки создаются автоматически. При обновлении заменить только JAR, сохраняя конфигурацию и `cauldrons.yml`.
|
||||||
|
|
||||||
|
Плагин использует [Paper Data Component API](https://docs.papermc.io/paper/dev/data-component-api/), поэтому переход на другие версии Minecraft требует отдельной проверки совместимости.
|
||||||
|
|
||||||
|
`tools/smoke` — тестовый плагин для **отдельного временного сервера**. Он изменяет тестовый мир и останавливает сервер, поэтому его нельзя устанавливать на рабочий сервер. Подробности проверок — в `VERIFICATION.md`.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Проверка AstraSoups 0.1.0
|
||||||
|
|
||||||
|
Среда: Windows 11, Java 26.0.2, Paper 26.2 build 121. Проверено 5 сентября 2026 года.
|
||||||
|
|
||||||
|
## Автоматические проверки
|
||||||
|
|
||||||
|
`gradlew.bat test jar smokeJar`: успешная сборка основного JAR и отдельного тестового помощника.
|
||||||
|
|
||||||
|
6 JUnit-тестов проверяют требование ровно четырёх ингредиентов, регистр селекторов, симметрию несовместимости, отсутствие конфликта предмета с самим собой, запрет повторов и wildcard.
|
||||||
|
|
||||||
|
Изолированный сервер `.test-server`, адрес `127.0.0.1:25585`, отдельный плоский мир, только AstraSoups и SoupSmokeTest. Реальные игроки не подключались. Проверки используют настоящий `ServerPlayer` без сетевого клиента, реальные предметы и реестр Paper, обработчики Bukkit и нативное употребление предметов Minecraft. Тестовый помощник не входит в основной JAR.
|
||||||
|
|
||||||
|
Первый запуск: **86 проверок**, в том числе:
|
||||||
|
|
||||||
|
- Вся еда из `Material.isEdible()`, торт, отсев камня и стрел с эффектами.
|
||||||
|
- Суммарные голод и насыщение, все четыре ванильных супа со стаком 16.
|
||||||
|
- Совместимость по стакам одинакового рецепта с обратным порядком ингредиентов.
|
||||||
|
- Обычные, взрывные и оседающие зелья; точные длительности, усиление и флаги эффекта.
|
||||||
|
- Эффекты зачарованного золотого яблока и подозрительного супа.
|
||||||
|
- Сериализация компонентов супа в binary и YAML.
|
||||||
|
- Реальное употребление: питание и эффекты один раз, остаток стака, миска, ванильное ограничение 20.
|
||||||
|
- Регистрация уникальной еды на материале PAPER; обычная бумага остаётся несъедобной.
|
||||||
|
- Некорректный YAML при reload не сбрасывает рабочую регистрацию.
|
||||||
|
- Отменённое взаимодействие не забирает предмет.
|
||||||
|
- Четыре `Item`-сущности с отключённым подбором, гравитацией и старением.
|
||||||
|
- Возврат последнего ингредиента; несовместимость не уничтожает ингредиенты.
|
||||||
|
- Варка создаёт цветную поверхность и удаляет визуальные ингредиенты.
|
||||||
|
- Выдача ожидаемого супа, расход одной миски, опустошение воды.
|
||||||
|
- ПКМ с предметом запускает варку без расходования предмета запуска.
|
||||||
|
- Запись сырого и готового котлов для перезапуска процесса.
|
||||||
|
|
||||||
|
Второй запуск: **5 проверок** восстановления настоящего сохранённого мира и `cauldrons.yml`: загрузка плагина, готовый котёл, эффекты и стак супа после рестарта, возврат сырого ингредиента и невозможность получить его повторно.
|
||||||
|
|
||||||
|
Полный текст результатов: `verification/phase1.txt` и `verification/phase2.txt`.
|
||||||
|
|
||||||
|
## Границы проверки
|
||||||
|
|
||||||
|
В игровом клиенте внешний вид не просматривался: проверены тип, количество, свойства и геометрия сущностей на сервере. Цвет поверхности — приближение терракотой, без ресурспака. Живой сценарий с клиентом и сочетание с конкретными защитными плагинами остаются ручной проверкой.
|
||||||
|
|
||||||
|
ItemsAdder не запускался в изолированном тесте. Нативная еда и регистрация образца проверены; интеграция с ItemsAdder использует его публичные методы `CustomStack.byItemStack` и `getNamespacedID`. Произвольные сторонние обработчики еды автоматически не переносятся.
|
||||||
|
|
||||||
|
В журнале тестового сервера есть системное предупреждение OSHI о счётчиках производительности Windows. Оно не относится к AstraSoups; все проверки плагина завершились успешно.
|
||||||
|
|
||||||
|
## Установка на рабочий сервер
|
||||||
|
|
||||||
|
Установлен `C:\Users\ScarPC\Documents\26.2 Paper\plugins\AstraSoups-0.1.0.jar`.
|
||||||
|
Старого плагина с именем `AstraSoups` не было; архивирование не потребовалось.
|
||||||
|
SHA-256 установленного JAR совпадает со сборкой:
|
||||||
|
|
||||||
|
```text
|
||||||
|
E4477AD5EFEF3F8E13C872E8651612F604C61EB554E826627215E42E4553DBA4
|
||||||
|
```
|
||||||
|
|
||||||
|
Рабочий сервер в рамках задачи не перезапускался. Плагин активируется при следующем запуске сервера. Тестовый помощник на рабочий сервер не устанавливался.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
plugins { java }
|
||||||
|
group = "online.astracraft"
|
||||||
|
version = "0.1.0"
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven { url = uri("https://repo.papermc.io/repository/maven-public/") }
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
compileOnly("io.papermc.paper:paper-api:26.2.build.121-stable")
|
||||||
|
testImplementation("io.papermc.paper:paper-api:26.2.build.121-stable")
|
||||||
|
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||||
|
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
|
||||||
|
}
|
||||||
|
java { toolchain.languageVersion.set(JavaLanguageVersion.of(26)) }
|
||||||
|
tasks.withType<JavaCompile>().configureEach { options.encoding = "UTF-8"; options.release.set(25) }
|
||||||
|
tasks.processResources { filesMatching("plugin.yml") { expand("version" to project.version) } }
|
||||||
|
tasks.test { useJUnitPlatform() }
|
||||||
|
val smoke = sourceSets.create("smoke") {
|
||||||
|
java.srcDir("tools/smoke")
|
||||||
|
resources.srcDir("tools/smoke-resources")
|
||||||
|
compileClasspath += sourceSets.main.get().compileClasspath + sourceSets.main.get().output
|
||||||
|
compileClasspath += files("../../26.2 Paper/versions/26.2/paper-26.2.jar")
|
||||||
|
compileClasspath += fileTree("../../26.2 Paper/libraries") { include("**/*.jar") }
|
||||||
|
}
|
||||||
|
tasks.register<Jar>("smokeJar") { archiveFileName.set("SoupSmokeTest.jar"); from(smoke.output) }
|
||||||
Vendored
+36
@@ -0,0 +1,36 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal EnableExtensions
|
||||||
|
|
||||||
|
set "GRADLE_VERSION=9.7.1"
|
||||||
|
set "APP_HOME=%~dp0"
|
||||||
|
if "%APP_HOME:~-1%"=="\" set "APP_HOME=%APP_HOME:~0,-1%"
|
||||||
|
set "DIST_ROOT=%USERPROFILE%\.gradle\pixelbanners-bootstrap"
|
||||||
|
set "DIST_DIR=%DIST_ROOT%\gradle-%GRADLE_VERSION%"
|
||||||
|
set "DIST_ZIP=%DIST_ROOT%\gradle-%GRADLE_VERSION%-bin.zip"
|
||||||
|
set "GRADLE_BAT=%DIST_DIR%\bin\gradle.bat"
|
||||||
|
|
||||||
|
if exist "%GRADLE_BAT%" goto run
|
||||||
|
|
||||||
|
if not exist "%DIST_ROOT%" mkdir "%DIST_ROOT%"
|
||||||
|
|
||||||
|
echo [AstraSoups] Gradle %GRADLE_VERSION% not found. Downloading...
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Invoke-WebRequest -UseBasicParsing 'https://services.gradle.org/distributions/gradle-%GRADLE_VERSION%-bin.zip' -OutFile '%DIST_ZIP%'"
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo.
|
||||||
|
echo [AstraSoups] ERROR: Could not download Gradle %GRADLE_VERSION%.
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo [AstraSoups] Extracting Gradle...
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Expand-Archive -LiteralPath '%DIST_ZIP%' -DestinationPath '%DIST_ROOT%' -Force"
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo.
|
||||||
|
echo [AstraSoups] ERROR: Could not extract Gradle.
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
del /q "%DIST_ZIP%" >nul 2>&1
|
||||||
|
|
||||||
|
:run
|
||||||
|
call "%GRADLE_BAT%" -p "%APP_HOME%" %*
|
||||||
|
exit /b %ERRORLEVEL%
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
rootProject.name = "AstraSoups"
|
||||||
@@ -0,0 +1,434 @@
|
|||||||
|
package online.astracraft.soups;
|
||||||
|
|
||||||
|
import org.bukkit.*;
|
||||||
|
import org.bukkit.block.Block;
|
||||||
|
import org.bukkit.block.data.Levelled;
|
||||||
|
import org.bukkit.command.Command;
|
||||||
|
import org.bukkit.command.CommandSender;
|
||||||
|
import org.bukkit.configuration.ConfigurationSection;
|
||||||
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
|
import org.bukkit.entity.*;
|
||||||
|
import org.bukkit.event.*;
|
||||||
|
import org.bukkit.event.block.*;
|
||||||
|
import org.bukkit.event.entity.*;
|
||||||
|
import org.bukkit.event.inventory.*;
|
||||||
|
import org.bukkit.event.player.*;
|
||||||
|
import org.bukkit.event.world.*;
|
||||||
|
import org.bukkit.inventory.*;
|
||||||
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
import org.bukkit.util.Transformation;
|
||||||
|
import org.bukkit.util.Vector;
|
||||||
|
import org.joml.Quaternionf;
|
||||||
|
import org.joml.Vector3f;
|
||||||
|
import net.kyori.adventure.text.Component;
|
||||||
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
|
||||||
|
public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||||
|
NamespacedKey soupKey, colorKey, visualKey;
|
||||||
|
private Ingredients ingredients;
|
||||||
|
private final Map<Position, Pot> pots = new LinkedHashMap<>();
|
||||||
|
private final Map<Position, List<Entity>> visuals = new HashMap<>();
|
||||||
|
private File dataFile;
|
||||||
|
private int ticks;
|
||||||
|
|
||||||
|
record Position(UUID world, int x, int y, int z) {
|
||||||
|
static Position at(Block b) { return new Position(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ()); }
|
||||||
|
Block loadedBlock() {
|
||||||
|
World w = Bukkit.getWorld(world);
|
||||||
|
return w == null || !w.isChunkLoaded(x >> 4, z >> 4) ? null : w.getBlockAt(x, y, z);
|
||||||
|
}
|
||||||
|
String id() { return world + "," + x + "," + y + "," + z; }
|
||||||
|
static Position parse(String s) {
|
||||||
|
String[] p = s.split(",");
|
||||||
|
if (p.length != 4) throw new IllegalArgumentException("Invalid cauldron position " + s);
|
||||||
|
return new Position(UUID.fromString(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
record Pot(List<ItemStack> items, ItemStack soup) { Pot { items = List.copyOf(items); } }
|
||||||
|
|
||||||
|
@Override public void onEnable() {
|
||||||
|
pots.clear();
|
||||||
|
soupKey = new NamespacedKey(this, "combined_soup");
|
||||||
|
colorKey = new NamespacedKey(this, "soup_color");
|
||||||
|
visualKey = new NamespacedKey(this, "cauldron_visual");
|
||||||
|
saveDefaultConfig();
|
||||||
|
dataFile = new File(getDataFolder(), "cauldrons.yml");
|
||||||
|
try {
|
||||||
|
// Unlike loadConfiguration(), load() reports malformed YAML instead of silently using defaults.
|
||||||
|
new YamlConfiguration().load(new File(getDataFolder(), "config.yml"));
|
||||||
|
ingredients = new Ingredients(this);
|
||||||
|
loadPots();
|
||||||
|
} catch (Exception e) {
|
||||||
|
getLogger().log(Level.SEVERE, "Не удалось прочитать конфигурацию/котлы; данные оставлены без изменений", e);
|
||||||
|
Bukkit.getPluginManager().disablePlugin(this);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Bukkit.getPluginManager().registerEvents(this, this);
|
||||||
|
for (World world : Bukkit.getWorlds()) for (Entity entity : world.getEntities()) {
|
||||||
|
if (isVisual(entity)) entity.remove();
|
||||||
|
else if (entity instanceof Item item) normalizeEntity(item);
|
||||||
|
}
|
||||||
|
for (Player p : Bukkit.getOnlinePlayers()) normalizeInventory(p.getInventory());
|
||||||
|
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 10);
|
||||||
|
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void onDisable() {
|
||||||
|
for (Position pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Ingredients ingredients() { return ingredients; }
|
||||||
|
|
||||||
|
private void loadPots() throws Exception {
|
||||||
|
if (!dataFile.exists()) return;
|
||||||
|
YamlConfiguration data = new YamlConfiguration();
|
||||||
|
data.load(dataFile);
|
||||||
|
ConfigurationSection section = data.getConfigurationSection("cauldrons");
|
||||||
|
if (section == null && !data.getKeys(false).isEmpty()) throw new IllegalArgumentException("Invalid cauldrons.yml");
|
||||||
|
if (section == null) return;
|
||||||
|
for (String id : section.getKeys(false)) {
|
||||||
|
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
|
||||||
|
List<ItemStack> items = new ArrayList<>();
|
||||||
|
for (Object value : c.getList("items", List.of())) {
|
||||||
|
if (!(value instanceof ItemStack item) || item.getAmount() != 1 || item.getType().isAir()) throw new IllegalArgumentException("Invalid ingredient at " + id);
|
||||||
|
items.add(item);
|
||||||
|
}
|
||||||
|
ItemStack soup = c.getItemStack("soup");
|
||||||
|
if (items.size() > 4 || (soup != null && (!items.isEmpty() || soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||||
|
|| (items.isEmpty() && soup == null)) throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||||
|
pots.put(Position.parse(id), new Pot(items, soup));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Save before transferring real items. A failed save rolls back the in-memory change. */
|
||||||
|
private boolean change(Position pos, Pot next) {
|
||||||
|
Pot old = pots.get(pos);
|
||||||
|
if (next == null) pots.remove(pos); else pots.put(pos, next);
|
||||||
|
try {
|
||||||
|
YamlConfiguration data = new YamlConfiguration();
|
||||||
|
data.createSection("cauldrons");
|
||||||
|
for (Map.Entry<Position, Pot> entry : pots.entrySet()) {
|
||||||
|
String prefix = "cauldrons." + entry.getKey().id();
|
||||||
|
data.set(prefix + ".items", entry.getValue().items);
|
||||||
|
data.set(prefix + ".soup", entry.getValue().soup);
|
||||||
|
}
|
||||||
|
Path temp = dataFile.toPath().resolveSibling("cauldrons.yml.tmp");
|
||||||
|
Files.writeString(temp, data.saveToString());
|
||||||
|
try { Files.move(temp, dataFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||||
|
catch (AtomicMoveNotSupportedException e) { Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
|
||||||
|
removeVisuals(pos);
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
||||||
|
getLogger().log(Level.SEVERE, "Ошибка сохранения котла; действие отменено", e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST)
|
||||||
|
public void interact(PlayerInteractEvent event) {
|
||||||
|
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null) return;
|
||||||
|
Block block = event.getClickedBlock();
|
||||||
|
Position pos = Position.at(block);
|
||||||
|
Pot pot = pots.get(pos);
|
||||||
|
if (event.getHand() != EquipmentSlot.HAND) {
|
||||||
|
if (pot != null) event.setCancelled(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.useInteractedBlock() == Event.Result.DENY || event.useItemInHand() == Event.Result.DENY) return;
|
||||||
|
if (block.getType() != Material.WATER_CAULDRON) return;
|
||||||
|
Player player = event.getPlayer();
|
||||||
|
if (!player.hasPermission("astrasoups.use") || player.getGameMode() == GameMode.SPECTATOR) return;
|
||||||
|
ItemStack held = player.getInventory().getItemInMainHand();
|
||||||
|
boolean empty = held.getType().isAir();
|
||||||
|
boolean bowl = held.getType() == Material.BOWL;
|
||||||
|
if (pot == null && ingredients.read(held) == null) return;
|
||||||
|
event.setCancelled(true);
|
||||||
|
if (pot == null) {
|
||||||
|
if (getConfig().getBoolean("require-full-water", true)
|
||||||
|
&& block.getBlockData() instanceof Levelled level && level.getLevel() != level.getMaximumLevel()) {
|
||||||
|
say(player, "Сначала наполните котёл водой доверху."); return;
|
||||||
|
}
|
||||||
|
pot = new Pot(List.of(), null);
|
||||||
|
}
|
||||||
|
if (pot.soup != null) {
|
||||||
|
if (!bowl) { say(player, "Суп готов. Возьмите его миской — ПКМ."); return; }
|
||||||
|
ItemStack result = pot.soup.clone();
|
||||||
|
if (!change(pos, null)) { saveError(player); return; }
|
||||||
|
takeOne(player);
|
||||||
|
give(player, result);
|
||||||
|
block.setType(Material.CAULDRON);
|
||||||
|
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
boolean cook = pot.items.size() == 4 && (player.isSneaking() || !empty);
|
||||||
|
if (cook) {
|
||||||
|
String error = ingredients.rejection(pot.items);
|
||||||
|
if (error != null) { say(player, error + " ПКМ пустой рукой возвращает последний ингредиент."); return; }
|
||||||
|
ItemStack soup = ingredients.brew(pot.items);
|
||||||
|
if (!change(pos, new Pot(List.of(), soup))) { saveError(player); return; }
|
||||||
|
show(pos, pots.get(pos), block);
|
||||||
|
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||||
|
block.getWorld().spawnParticle(Particle.CLOUD, block.getLocation().add(.5, 1.05, .5), 12, .2, .12, .2, .01);
|
||||||
|
say(player, "Суп готов! Соберите его миской.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (empty) {
|
||||||
|
if (pot.items.isEmpty()) return;
|
||||||
|
List<ItemStack> remaining = new ArrayList<>(pot.items);
|
||||||
|
ItemStack last = remaining.removeLast();
|
||||||
|
if (!change(pos, remaining.isEmpty() ? null : new Pot(remaining, null))) { saveError(player); return; }
|
||||||
|
give(player, last.clone());
|
||||||
|
say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (pot.items.size() == 4) { say(player, "Для варки: Shift+ПКМ или ПКМ с предметом в руке."); return; }
|
||||||
|
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return; }
|
||||||
|
List<ItemStack> items = new ArrayList<>(pot.items);
|
||||||
|
items.add(held.asOne());
|
||||||
|
if (!change(pos, new Pot(items, null))) { saveError(player); return; }
|
||||||
|
takeOne(player);
|
||||||
|
show(pos, pots.get(pos), block);
|
||||||
|
block.getWorld().playSound(block.getLocation(), Sound.ENTITY_GENERIC_SPLASH, .3f, 1.6f);
|
||||||
|
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void takeOne(Player p) {
|
||||||
|
if (p.getGameMode() == GameMode.CREATIVE) return;
|
||||||
|
ItemStack held = p.getInventory().getItemInMainHand();
|
||||||
|
p.getInventory().setItemInMainHand(held.getAmount() == 1 ? null : held.subtract(1));
|
||||||
|
}
|
||||||
|
private void give(Player p, ItemStack item) {
|
||||||
|
Ingredients.normalize(item);
|
||||||
|
p.getInventory().addItem(item).values().forEach(left -> p.getWorld().dropItemNaturally(p.getLocation(), left));
|
||||||
|
}
|
||||||
|
private void say(Player p, String text) { p.sendActionBar(Component.text(text, NamedTextColor.GOLD)); }
|
||||||
|
private void saveError(Player p) { say(p, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||||
|
|
||||||
|
private void refresh() {
|
||||||
|
ticks += 10;
|
||||||
|
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
|
||||||
|
Position pos = entry.getKey();
|
||||||
|
Block block = pos.loadedBlock();
|
||||||
|
if (block == null) { removeVisuals(pos); continue; }
|
||||||
|
if (block.getType() != Material.WATER_CAULDRON) {
|
||||||
|
// External block editing: return raw ingredients only once, never resurrect a missing block.
|
||||||
|
if (change(pos, null)) for (ItemStack item : entry.getValue().items) block.getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<Entity> entities = visuals.get(pos);
|
||||||
|
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
|
||||||
|
removeVisuals(pos); show(pos, entry.getValue(), block);
|
||||||
|
} else {
|
||||||
|
for (int i = 0; i < entities.size(); i++) if (entities.get(i) instanceof Item item) {
|
||||||
|
item.teleport(itemLocation(block, i));
|
||||||
|
item.setVelocity(new Vector());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ticks % 20 == 0) for (Player player : Bukkit.getOnlinePlayers()) {
|
||||||
|
normalizeInventory(player.getInventory());
|
||||||
|
normalizeInventory(player.getOpenInventory().getTopInventory());
|
||||||
|
ItemStack cursor = player.getItemOnCursor();
|
||||||
|
if (Ingredients.normalize(cursor)) player.setItemOnCursor(cursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Location itemLocation(Block block, int i) {
|
||||||
|
double[][] offsets = {{.32, .32}, {.68, .32}, {.32, .68}, {.68, .68}};
|
||||||
|
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||||
|
double height = .375 + .1875 * waterLevel;
|
||||||
|
return block.getLocation().add(offsets[i][0], height - .11 + Math.sin(ticks * .06 + i) * .025, offsets[i][1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void show(Position pos, Pot pot, Block block) {
|
||||||
|
if (visuals.containsKey(pos)) return;
|
||||||
|
List<Entity> entities = new ArrayList<>();
|
||||||
|
visuals.put(pos, entities);
|
||||||
|
if (pot.soup != null) {
|
||||||
|
int rgb = pot.soup.getItemMeta().getPersistentDataContainer().getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||||
|
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||||
|
BlockDisplay display = block.getWorld().spawn(block.getLocation().add(.125, .375 + .1875 * waterLevel + .005, .125), BlockDisplay.class, d -> {
|
||||||
|
markVisual(d);
|
||||||
|
d.setBlock(surface(rgb).createBlockData());
|
||||||
|
d.setTransformation(new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(.75f, .012f, .75f), new Quaternionf()));
|
||||||
|
d.setBrightness(new Display.Brightness(12, 12));
|
||||||
|
d.setViewRange(.5f);
|
||||||
|
});
|
||||||
|
entities.add(display);
|
||||||
|
} else for (int i = 0; i < pot.items.size(); i++) {
|
||||||
|
ItemStack stack = pot.items.get(i).clone();
|
||||||
|
Item item = block.getWorld().spawn(itemLocation(block, i), Item.class, e -> {
|
||||||
|
markVisual(e);
|
||||||
|
e.setItemStack(stack);
|
||||||
|
e.setCanPlayerPickup(false);
|
||||||
|
e.setCanMobPickup(false);
|
||||||
|
e.setPickupDelay(Integer.MAX_VALUE);
|
||||||
|
e.setUnlimitedLifetime(true);
|
||||||
|
e.setVelocity(new Vector());
|
||||||
|
});
|
||||||
|
entities.add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Material surface(int rgb) {
|
||||||
|
Material[] materials = {Material.ORANGE_TERRACOTTA, Material.YELLOW_TERRACOTTA, Material.RED_TERRACOTTA,
|
||||||
|
Material.BROWN_TERRACOTTA, Material.GREEN_TERRACOTTA, Material.LIME_TERRACOTTA,
|
||||||
|
Material.BLUE_TERRACOTTA, Material.CYAN_TERRACOTTA, Material.PURPLE_TERRACOTTA,
|
||||||
|
Material.PINK_TERRACOTTA, Material.WHITE_TERRACOTTA, Material.BLACK_TERRACOTTA};
|
||||||
|
int[] colors = {0xA15325, 0xBA8523, 0x8E3C2E, 0x4D3323, 0x4C532A, 0x677535,
|
||||||
|
0x4A3B5B, 0x565B5B, 0x764656, 0xA14E4E, 0xD1B2A1, 0x251610};
|
||||||
|
Color wanted = Color.fromRGB(rgb);
|
||||||
|
int best = 0, distance = Integer.MAX_VALUE;
|
||||||
|
for (int i = 0; i < colors.length; i++) {
|
||||||
|
Color candidate = Color.fromRGB(colors[i]);
|
||||||
|
int r = candidate.getRed() - wanted.getRed(), g = candidate.getGreen() - wanted.getGreen(), b = candidate.getBlue() - wanted.getBlue();
|
||||||
|
int d = r * r + g * g + b * b;
|
||||||
|
if (d < distance) { best = i; distance = d; }
|
||||||
|
}
|
||||||
|
return materials[best];
|
||||||
|
}
|
||||||
|
private void markVisual(Entity entity) {
|
||||||
|
entity.getPersistentDataContainer().set(visualKey, PersistentDataType.BYTE, (byte) 1);
|
||||||
|
entity.setPersistent(false);
|
||||||
|
entity.setGravity(false);
|
||||||
|
entity.setInvulnerable(true);
|
||||||
|
entity.setSilent(true);
|
||||||
|
}
|
||||||
|
private boolean isVisual(Entity entity) { return entity.getPersistentDataContainer().has(visualKey, PersistentDataType.BYTE); }
|
||||||
|
private void removeVisuals(Position pos) {
|
||||||
|
List<Entity> entities = visuals.remove(pos);
|
||||||
|
if (entities != null) entities.forEach(Entity::remove);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void breakBlock(BlockBreakEvent e) {
|
||||||
|
Position pos = Position.at(e.getBlock()); Pot pot = pots.get(pos);
|
||||||
|
if (pot == null) return;
|
||||||
|
if (!change(pos, null)) { e.setCancelled(true); saveError(e.getPlayer()); return; }
|
||||||
|
for (ItemStack item : pot.items) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(.5, .5, .5), item.clone());
|
||||||
|
if (pot.soup != null) say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
||||||
|
}
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void cauldronChange(CauldronLevelChangeEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void explode(EntityExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void blockExplode(BlockExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void piston(BlockPistonExtendEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void pistonRetract(BlockPistonRetractEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void entityBlock(EntityChangeBlockEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void pickup(EntityPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void hopperPickup(InventoryPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void merge(ItemMergeEvent e) { if (isVisual(e.getEntity()) || isVisual(e.getTarget())) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void damage(EntityDamageEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void portal(EntityPortalEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void despawn(ItemDespawnEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
||||||
|
@EventHandler public void unload(ChunkUnloadEvent e) {
|
||||||
|
for (Position p : new ArrayList<>(visuals.keySet())) if (p.world.equals(e.getWorld().getUID()) && (p.x >> 4) == e.getChunk().getX() && (p.z >> 4) == e.getChunk().getZ()) removeVisuals(p);
|
||||||
|
}
|
||||||
|
@EventHandler public void entitiesLoad(EntitiesLoadEvent e) {
|
||||||
|
for (Entity entity : e.getEntities()) {
|
||||||
|
if (isVisual(entity) && visuals.values().stream().noneMatch(list -> list.contains(entity))) entity.remove();
|
||||||
|
else if (entity instanceof Item item && !isVisual(entity)) normalizeEntity(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void normalizeEntity(Item item) { ItemStack stack = item.getItemStack(); if (Ingredients.normalize(stack)) item.setItemStack(stack); }
|
||||||
|
private void normalizeInventory(Inventory inv) {
|
||||||
|
for (int i = 0; i < inv.getSize(); i++) {
|
||||||
|
ItemStack item = inv.getItem(i);
|
||||||
|
if (Ingredients.normalize(item)) inv.setItem(i, item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@EventHandler public void join(PlayerJoinEvent e) { normalizeInventory(e.getPlayer().getInventory()); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void open(InventoryOpenEvent e) { normalizeInventory(e.getInventory()); normalizeInventory(e.getPlayer().getInventory()); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void spawn(ItemSpawnEvent e) { normalizeEntity(e.getEntity()); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST)
|
||||||
|
public void craft(PrepareItemCraftEvent e) {
|
||||||
|
ItemStack result = e.getInventory().getResult();
|
||||||
|
if (Ingredients.normalize(result)) e.getInventory().setResult(result);
|
||||||
|
}
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void crafted(CraftItemEvent e) {
|
||||||
|
ItemStack result = e.getCurrentItem();
|
||||||
|
if (Ingredients.normalize(result)) e.setCurrentItem(result);
|
||||||
|
}
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void loot(LootGenerateEvent e) { e.getLoot().forEach(Ingredients::normalize); }
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
public void transfer(InventoryMoveItemEvent e) { ItemStack item = e.getItem(); if (Ingredients.normalize(item)) e.setItem(item); }
|
||||||
|
|
||||||
|
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||||
|
if (args.length == 0) {
|
||||||
|
sender.sendMessage(Component.text("ПКМ с едой/зельем: добавить (4 предмета). ПКМ пустой рукой: забрать последний. Shift+ПКМ или ПКМ с предметом после заполнения: сварить. ПКМ миской по готовому супу: собрать.", NamedTextColor.GOLD));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!sender.hasPermission("astrasoups.admin")) { sender.sendMessage("Недостаточно прав."); return true; }
|
||||||
|
if (args[0].equalsIgnoreCase("reload") && args.length == 1) {
|
||||||
|
String previous = getConfig().saveToString();
|
||||||
|
try {
|
||||||
|
YamlConfiguration candidate = new YamlConfiguration();
|
||||||
|
candidate.load(new File(getDataFolder(), "config.yml"));
|
||||||
|
getConfig().loadFromString(candidate.saveToString());
|
||||||
|
Ingredients next = new Ingredients(this);
|
||||||
|
ingredients = next;
|
||||||
|
sender.sendMessage("AstraSoups: конфигурация перезагружена.");
|
||||||
|
} catch (Exception ex) {
|
||||||
|
// Restore prior settings in memory; leave the invalid file for the administrator to fix.
|
||||||
|
restoreConfig(previous);
|
||||||
|
sender.sendMessage("Ошибка конфигурации: " + ex.getMessage() + ". Продолжают действовать прежние настройки.");
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (args[0].equalsIgnoreCase("register") && args.length == 4 && sender instanceof Player player) {
|
||||||
|
if (!args[1].matches("[a-z0-9_-]+")) { sender.sendMessage("ID: только a-z, 0-9, _ и -."); return true; }
|
||||||
|
ItemStack item = player.getInventory().getItemInMainHand().asOne();
|
||||||
|
if (item.getType().isAir()) { sender.sendMessage("Возьмите уникальную еду в основную руку."); return true; }
|
||||||
|
String previous = getConfig().saveToString();
|
||||||
|
try {
|
||||||
|
int nutrition = Integer.parseInt(args[2]); float saturation = Float.parseFloat(args[3]);
|
||||||
|
if (nutrition < 0 || nutrition > getConfig().getInt("max-nutrition", 1000) || saturation < 0 || !Float.isFinite(saturation)
|
||||||
|
|| saturation > getConfig().getDouble("max-saturation", 1000)) throw new IllegalArgumentException();
|
||||||
|
String path = "custom-ingredients." + args[1];
|
||||||
|
getConfig().set(path + ".item", item);
|
||||||
|
getConfig().set(path + ".nutrition", nutrition);
|
||||||
|
getConfig().set(path + ".saturation", saturation);
|
||||||
|
Ingredients next = new Ingredients(this);
|
||||||
|
getConfig().save(new File(getDataFolder(), "config.yml"));
|
||||||
|
ingredients = next;
|
||||||
|
sender.sendMessage("Зарегистрирован ингредиент: " + args[1]);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
restoreConfig(previous);
|
||||||
|
sender.sendMessage("Не удалось зарегистрировать: проверьте числа и конфигурацию. " + ex.getMessage());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
private void restoreConfig(String yaml) {
|
||||||
|
try { getConfig().loadFromString(yaml); }
|
||||||
|
catch (org.bukkit.configuration.InvalidConfigurationException ex) { throw new IllegalStateException("Cannot restore validated config", ex); }
|
||||||
|
}
|
||||||
|
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||||
|
if (!sender.hasPermission("astrasoups.admin")) return List.of();
|
||||||
|
return args.length == 1 ? List.of("reload", "register").stream().filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList() : List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package online.astracraft.soups;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** Pure matching logic: incompatible selectors must occur in distinct slots. */
|
||||||
|
public final class CombinationRules {
|
||||||
|
private CombinationRules() {}
|
||||||
|
|
||||||
|
public static boolean matches(Set<String> tags, String selector) {
|
||||||
|
return selector.equals("*") || tags.contains(selector.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String rejection(List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
|
||||||
|
if (ingredients.size() != 4) return "Нужно ровно 4 ингредиента.";
|
||||||
|
for (Set<String> tags : ingredients) {
|
||||||
|
for (String selector : blocked) {
|
||||||
|
if (matches(tags, selector)) return "Запрещён ингредиент: " + selector;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (List<String> pair : pairs) {
|
||||||
|
for (int i = 0; i < ingredients.size(); i++) {
|
||||||
|
for (int j = 0; j < ingredients.size(); j++) {
|
||||||
|
if (i != j && matches(ingredients.get(i), pair.get(0)) && matches(ingredients.get(j), pair.get(1))) {
|
||||||
|
return "Несовместимые ингредиенты: " + String.join(" + ", pair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
package online.astracraft.soups;
|
||||||
|
|
||||||
|
import io.papermc.paper.datacomponent.DataComponentTypes;
|
||||||
|
import io.papermc.paper.datacomponent.item.Consumable;
|
||||||
|
import io.papermc.paper.datacomponent.item.FoodProperties;
|
||||||
|
import io.papermc.paper.datacomponent.item.UseRemainder;
|
||||||
|
import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect;
|
||||||
|
import net.kyori.adventure.text.Component;
|
||||||
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
import net.kyori.adventure.text.format.TextDecoration;
|
||||||
|
import org.bukkit.Color;
|
||||||
|
import org.bukkit.Material;
|
||||||
|
import org.bukkit.NamespacedKey;
|
||||||
|
import org.bukkit.Registry;
|
||||||
|
import org.bukkit.configuration.ConfigurationSection;
|
||||||
|
import org.bukkit.inventory.ItemStack;
|
||||||
|
import org.bukkit.inventory.meta.ItemMeta;
|
||||||
|
import org.bukkit.inventory.meta.PotionMeta;
|
||||||
|
import org.bukkit.inventory.meta.SuspiciousStewMeta;
|
||||||
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
|
import org.bukkit.potion.PotionEffect;
|
||||||
|
import org.bukkit.potion.PotionEffectType;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
public final class Ingredients {
|
||||||
|
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, Color color) {}
|
||||||
|
private record Custom(String id, ItemStack sample, int nutrition, float saturation, List<PotionEffect> effects) {}
|
||||||
|
private final AstraSoupsPlugin plugin;
|
||||||
|
private final List<Custom> custom = new ArrayList<>();
|
||||||
|
private List<String> blocked;
|
||||||
|
private final List<List<String>> pairs = new ArrayList<>();
|
||||||
|
private Method iaLookup, iaId;
|
||||||
|
private Color defaultColor;
|
||||||
|
|
||||||
|
public Ingredients(AstraSoupsPlugin plugin) {
|
||||||
|
this.plugin = plugin;
|
||||||
|
defaultColor = Color.fromRGB(Integer.parseInt(plugin.getConfig().getString("default-color", "#B77A36").replace("#", ""), 16));
|
||||||
|
blocked = plugin.getConfig().getStringList("blocked-ingredients");
|
||||||
|
for (Object value : plugin.getConfig().getList("incompatible", List.of())) {
|
||||||
|
if (!(value instanceof List<?> list) || list.size() != 2 || list.stream().anyMatch(x -> !(x instanceof String))) {
|
||||||
|
throw new IllegalArgumentException("Каждое правило incompatible должно содержать два селектора");
|
||||||
|
}
|
||||||
|
pairs.add(List.of((String) list.get(0), (String) list.get(1)));
|
||||||
|
}
|
||||||
|
if (plugin.getConfig().getInt("max-nutrition", 1000) < 0
|
||||||
|
|| !Float.isFinite((float) plugin.getConfig().getDouble("max-saturation", 1000))
|
||||||
|
|| plugin.getConfig().getDouble("max-saturation", 1000) < 0) {
|
||||||
|
throw new IllegalArgumentException("Некорректные ограничения питания");
|
||||||
|
}
|
||||||
|
ConfigurationSection section = plugin.getConfig().getConfigurationSection("custom-ingredients");
|
||||||
|
if (section != null) for (String id : section.getKeys(false)) {
|
||||||
|
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
|
||||||
|
ItemStack sample = c.getItemStack("item");
|
||||||
|
int nutrition = c.getInt("nutrition");
|
||||||
|
float saturation = (float) c.getDouble("saturation");
|
||||||
|
if (sample == null || sample.getType().isAir() || nutrition < 0 || saturation < 0 || !Float.isFinite(saturation)) {
|
||||||
|
throw new IllegalArgumentException("Некорректный custom-ingredients." + id);
|
||||||
|
}
|
||||||
|
List<PotionEffect> effects = new ArrayList<>();
|
||||||
|
for (Map<?, ?> map : c.getMapList("effects")) {
|
||||||
|
PotionEffectType type = Registry.EFFECT.get(Objects.requireNonNull(NamespacedKey.fromString(String.valueOf(map.get("type")))));
|
||||||
|
if (type == null) throw new IllegalArgumentException("Неизвестный эффект в " + id);
|
||||||
|
int duration = Integer.parseInt(String.valueOf(map.get("duration")));
|
||||||
|
int amplifier = Integer.parseInt(String.valueOf(map.get("amplifier")));
|
||||||
|
if (duration < -1 || duration == 0 || amplifier < 0 || amplifier > 255) throw new IllegalArgumentException("Некорректный эффект в " + id);
|
||||||
|
effects.add(new PotionEffect(type, duration, amplifier));
|
||||||
|
}
|
||||||
|
normalize(sample);
|
||||||
|
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects)));
|
||||||
|
}
|
||||||
|
if (plugin.getServer().getPluginManager().isPluginEnabled("ItemsAdder")) {
|
||||||
|
try {
|
||||||
|
Class<?> cls = Class.forName("dev.lone.itemsadder.api.CustomStack");
|
||||||
|
iaLookup = cls.getMethod("byItemStack", ItemStack.class);
|
||||||
|
iaId = cls.getMethod("getNamespacedID");
|
||||||
|
} catch (ReflectiveOperationException e) {
|
||||||
|
throw new IllegalStateException("Не удалось подключить API ItemsAdder", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Ingredient read(ItemStack item) {
|
||||||
|
if (item == null || item.getType().isAir()) return null;
|
||||||
|
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
||||||
|
ItemMeta meta = item.getItemMeta();
|
||||||
|
Custom match = custom.stream().filter(c -> c.sample.isSimilar(item)).findFirst().orElse(null);
|
||||||
|
boolean potion = switch (item.getType()) { case POTION, SPLASH_POTION, LINGERING_POTION -> true; default -> false; };
|
||||||
|
// Cake is edible as a placed block and has no FOOD component.
|
||||||
|
boolean cake = item.getType() == Material.CAKE;
|
||||||
|
if (food == null && !potion && match == null && !cake) return null;
|
||||||
|
int nutrition = food == null ? (cake ? 14 : 0) : food.nutrition();
|
||||||
|
float saturation = food == null ? (cake ? 2.8f : 0) : food.saturation();
|
||||||
|
List<ConsumeEffect> effects = new ArrayList<>();
|
||||||
|
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
||||||
|
if (consumable != null) effects.addAll(consumable.consumeEffects());
|
||||||
|
Color color = defaultColor;
|
||||||
|
if (potion && meta instanceof PotionMeta pm) {
|
||||||
|
if (!pm.getAllEffects().isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(pm.getAllEffects(), 1));
|
||||||
|
color = pm.computeEffectiveColor();
|
||||||
|
}
|
||||||
|
if (meta instanceof SuspiciousStewMeta stew && stew.hasCustomEffects()) {
|
||||||
|
effects.add(ConsumeEffect.applyStatusEffects(stew.getCustomEffects(), 1));
|
||||||
|
}
|
||||||
|
Set<String> tags = new HashSet<>();
|
||||||
|
tags.add("material:" + item.getType().name().toLowerCase(Locale.ROOT));
|
||||||
|
if (isCombined(item)) tags.add("soup:combined");
|
||||||
|
if (match != null) {
|
||||||
|
nutrition = match.nutrition;
|
||||||
|
saturation = match.saturation;
|
||||||
|
tags.add("custom:" + match.id.toLowerCase(Locale.ROOT));
|
||||||
|
if (!match.effects.isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(match.effects, 1));
|
||||||
|
}
|
||||||
|
if (iaLookup != null) try {
|
||||||
|
Object ia = iaLookup.invoke(null, item);
|
||||||
|
if (ia != null) tags.add("itemsadder:" + iaId.invoke(ia).toString().toLowerCase(Locale.ROOT));
|
||||||
|
} catch (ReflectiveOperationException e) {
|
||||||
|
throw new IllegalStateException("Ошибка чтения уникальной еды ItemsAdder", e);
|
||||||
|
}
|
||||||
|
for (ConsumeEffect effect : effects) if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
||||||
|
for (PotionEffect pe : apply.effects()) tags.add("effect:" + pe.getType().getKey());
|
||||||
|
}
|
||||||
|
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String rejection(List<ItemStack> items) {
|
||||||
|
List<Ingredient> data = items.stream().map(this::read).toList();
|
||||||
|
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
|
||||||
|
String rule = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), blocked, pairs);
|
||||||
|
if (rule != null) return rule;
|
||||||
|
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
|
||||||
|
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
|
||||||
|
if (nutrition > plugin.getConfig().getInt("max-nutrition", 1000)
|
||||||
|
|| saturation > plugin.getConfig().getDouble("max-saturation", 1000)) return "Превышен лимит питания супа.";
|
||||||
|
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256) return "В супе слишком много эффектов.";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ItemStack brew(List<ItemStack> items) {
|
||||||
|
String error = rejection(items);
|
||||||
|
if (error != null) throw new IllegalArgumentException(error);
|
||||||
|
// Stable order makes the same recipe stack regardless of insertion order.
|
||||||
|
List<Ingredient> ingredients = items.stream().map(ItemStack::asOne)
|
||||||
|
.peek(Ingredients::normalize)
|
||||||
|
.sorted(Comparator.comparing(stack -> Base64.getEncoder().encodeToString(stack.serializeAsBytes())))
|
||||||
|
.map(this::read).toList();
|
||||||
|
int nutrition = ingredients.stream().mapToInt(Ingredient::nutrition).sum();
|
||||||
|
float saturation = (float) ingredients.stream().mapToDouble(Ingredient::saturation).sum();
|
||||||
|
List<ConsumeEffect> effects = ingredients.stream().flatMap(i -> i.effects.stream()).toList();
|
||||||
|
ItemStack soup = new ItemStack(Material.MUSHROOM_STEW);
|
||||||
|
ItemMeta meta = soup.getItemMeta();
|
||||||
|
meta.displayName(Component.text(plugin.getConfig().getString("soup-name", "Комбинированный суп"), NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false));
|
||||||
|
List<Component> lore = new ArrayList<>();
|
||||||
|
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
|
||||||
|
lore.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", saturation), NamedTextColor.GOLD));
|
||||||
|
for (ConsumeEffect effect : effects) {
|
||||||
|
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
||||||
|
for (PotionEffect pe : apply.effects()) {
|
||||||
|
String duration = pe.isInfinite() ? "∞" : (pe.getDuration() / 1200) + ":" + String.format(Locale.ROOT, "%02d", (pe.getDuration() / 20) % 60);
|
||||||
|
lore.add(Component.translatable(pe.getType().translationKey()).color(NamedTextColor.AQUA)
|
||||||
|
.append(Component.text(" " + (pe.getAmplifier() + 1) + " • " + duration
|
||||||
|
+ (apply.probability() < 1 ? " • " + Math.round(apply.probability() * 100) + "%" : "")))
|
||||||
|
.decoration(TextDecoration.ITALIC, false));
|
||||||
|
}
|
||||||
|
} else lore.add(line(effect instanceof ConsumeEffect.TeleportRandomly ? "Случайная телепортация"
|
||||||
|
: effect instanceof ConsumeEffect.ClearAllStatusEffects ? "Снятие всех эффектов"
|
||||||
|
: effect instanceof ConsumeEffect.RemoveStatusEffects ? "Снятие эффектов" : "Звук при употреблении", NamedTextColor.GRAY));
|
||||||
|
}
|
||||||
|
meta.lore(lore);
|
||||||
|
meta.getPersistentDataContainer().set(plugin.soupKey, PersistentDataType.BYTE, (byte) 1);
|
||||||
|
meta.getPersistentDataContainer().set(plugin.colorKey, PersistentDataType.INTEGER, color(ingredients).asRGB());
|
||||||
|
soup.setItemMeta(meta);
|
||||||
|
soup.setData(DataComponentTypes.FOOD, FoodProperties.food().nutrition(nutrition).saturation(saturation).canAlwaysEat(true).build());
|
||||||
|
soup.setData(DataComponentTypes.CONSUMABLE, Consumable.consumable().effects(effects).build());
|
||||||
|
soup.setData(DataComponentTypes.USE_REMAINDER, UseRemainder.useRemainder(new ItemStack(Material.BOWL)));
|
||||||
|
normalize(soup);
|
||||||
|
return soup;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
|
||||||
|
private Color color(List<Ingredient> ingredients) {
|
||||||
|
return Color.fromRGB((int) ingredients.stream().mapToInt(i -> i.color.getRed()).average().orElse(183),
|
||||||
|
(int) ingredients.stream().mapToInt(i -> i.color.getGreen()).average().orElse(122),
|
||||||
|
(int) ingredients.stream().mapToInt(i -> i.color.getBlue()).average().orElse(54));
|
||||||
|
}
|
||||||
|
public boolean isCombined(ItemStack item) {
|
||||||
|
return item.hasItemMeta() && item.getItemMeta().getPersistentDataContainer().has(plugin.soupKey, PersistentDataType.BYTE);
|
||||||
|
}
|
||||||
|
public static boolean normalize(ItemStack item) {
|
||||||
|
if (item == null) return false;
|
||||||
|
if (switch (item.getType()) { case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true; default -> false; }
|
||||||
|
&& !Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
||||||
|
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Ровно четыре предмета, по одной единице каждого. Повторы разрешены.
|
||||||
|
# Одна варка дает одну миску: питание и эффекты не размножаются.
|
||||||
|
require-full-water: true
|
||||||
|
soup-name: 'Комбинированный суп'
|
||||||
|
# Цвет поверхности — ближайший оттенок терракоты без ресурспака.
|
||||||
|
default-color: '#B77A36'
|
||||||
|
# Ограничения предотвращают переполнение при многократной варке супов из супов.
|
||||||
|
max-nutrition: 1000
|
||||||
|
max-saturation: 1000.0
|
||||||
|
# Селекторы: material:BEEF, effect:minecraft:poison, custom:my_food,
|
||||||
|
# itemsadder:namespace:id, soup:combined, * (любой ингредиент).
|
||||||
|
blocked-ingredients: []
|
||||||
|
# Каждое правило запрещает одновременное присутствие двух РАЗНЫХ слотов.
|
||||||
|
# incompatible:
|
||||||
|
# - ['effect:minecraft:strength', 'effect:minecraft:weakness']
|
||||||
|
# - ['material:ROTTEN_FLESH', 'material:GOLDEN_APPLE']
|
||||||
|
incompatible: []
|
||||||
|
# Регистрируется командой /soups register <id> <голод> <насыщение>.
|
||||||
|
# Сохраняется образец предмета; количество не участвует в сравнении.
|
||||||
|
# nutrition — единицы голода (2 = один значок), saturation — очки насыщения.
|
||||||
|
# Необязательные effects: [{type: 'minecraft:strength', duration: 3600, amplifier: 1}]
|
||||||
|
# duration в тиках; amplifier: 0 = I, 1 = II. Эффекты добавляются к исходным.
|
||||||
|
custom-ingredients: {}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
name: AstraSoups
|
||||||
|
version: '${version}'
|
||||||
|
main: online.astracraft.soups.AstraSoupsPlugin
|
||||||
|
api-version: '26.2'
|
||||||
|
description: Four-ingredient cauldron soups with food and potion properties
|
||||||
|
author: AstraCraft
|
||||||
|
softdepend: [ItemsAdder]
|
||||||
|
commands:
|
||||||
|
soups:
|
||||||
|
description: Комбинированные супы
|
||||||
|
usage: /soups [reload|register <id> <голод> <насыщение>]
|
||||||
|
permissions:
|
||||||
|
astrasoups.use:
|
||||||
|
default: true
|
||||||
|
astrasoups.admin:
|
||||||
|
default: op
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package online.astracraft.soups;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import java.util.*;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class CombinationRulesTest {
|
||||||
|
private final List<Set<String>> four = List.of(Set.of("material:beef", "effect:minecraft:strength"), Set.of("material:carrot"), Set.of("material:beef"), Set.of("material:potion", "effect:minecraft:weakness"));
|
||||||
|
@Test void exactlyFour() {
|
||||||
|
assertNotNull(CombinationRules.rejection(four.subList(0, 3), List.of(), List.of()));
|
||||||
|
assertNull(CombinationRules.rejection(four, List.of(), List.of()));
|
||||||
|
}
|
||||||
|
@Test void blockedSelectorsAreCaseInsensitive() {
|
||||||
|
assertNotNull(CombinationRules.rejection(four, List.of("material:BEEF"), List.of()));
|
||||||
|
}
|
||||||
|
@Test void compatibilityIsSymmetricAcrossSlots() {
|
||||||
|
assertNotNull(CombinationRules.rejection(four, List.of(), List.of(List.of("effect:minecraft:weakness", "effect:minecraft:strength"))));
|
||||||
|
}
|
||||||
|
@Test void oneIngredientDoesNotConflictWithItself() {
|
||||||
|
assertNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:potion", "effect:minecraft:weakness"))));
|
||||||
|
}
|
||||||
|
@Test void duplicatesCanBeForbiddenExplicitly() {
|
||||||
|
assertNotNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:beef", "material:beef"))));
|
||||||
|
assertNull(CombinationRules.rejection(four, List.of(), List.of(List.of("material:carrot", "material:carrot"))));
|
||||||
|
}
|
||||||
|
@Test void wildcardAndUnknownSelector() {
|
||||||
|
assertNotNull(CombinationRules.rejection(four, List.of("*"), List.of()));
|
||||||
|
assertNull(CombinationRules.rejection(four, List.of("custom:other"), List.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
name: SoupSmokeTest
|
||||||
|
version: '1.0'
|
||||||
|
main: smoke.SoupSmokeTest
|
||||||
|
api-version: '26.2'
|
||||||
|
depend: [AstraSoups]
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package smoke;
|
||||||
|
|
||||||
|
import online.astracraft.soups.*;
|
||||||
|
import io.papermc.paper.datacomponent.DataComponentTypes;
|
||||||
|
import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect;
|
||||||
|
import org.bukkit.*;
|
||||||
|
import org.bukkit.block.*;
|
||||||
|
import org.bukkit.block.data.Levelled;
|
||||||
|
import org.bukkit.entity.*;
|
||||||
|
import org.bukkit.event.Event;
|
||||||
|
import org.bukkit.event.block.*;
|
||||||
|
import org.bukkit.event.player.PlayerInteractEvent;
|
||||||
|
import org.bukkit.inventory.*;
|
||||||
|
import org.bukkit.inventory.meta.*;
|
||||||
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
import org.bukkit.potion.*;
|
||||||
|
import org.bukkit.craftbukkit.CraftServer;
|
||||||
|
import org.bukkit.craftbukkit.CraftWorld;
|
||||||
|
import org.bukkit.craftbukkit.inventory.CraftItemStack;
|
||||||
|
import com.mojang.authlib.GameProfile;
|
||||||
|
import net.minecraft.network.Connection;
|
||||||
|
import net.minecraft.network.protocol.PacketFlow;
|
||||||
|
import net.minecraft.server.level.ClientInformation;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.server.network.CommonListenerCookie;
|
||||||
|
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** ONLY for the disposable isolated server; never install this helper on the working server. */
|
||||||
|
public final class SoupSmokeTest extends JavaPlugin {
|
||||||
|
private final List<String> results = new ArrayList<>();
|
||||||
|
private AstraSoupsPlugin plugin;
|
||||||
|
private Player player;
|
||||||
|
private ServerPlayer nativePlayer;
|
||||||
|
private World world;
|
||||||
|
private Block pot;
|
||||||
|
|
||||||
|
@Override public void onEnable() {
|
||||||
|
Bukkit.getScheduler().runTaskLater(this, () -> {
|
||||||
|
String phase = Files.exists(getDataFolder().toPath().resolve("phase1.txt")) ? "phase2" : "phase1";
|
||||||
|
try {
|
||||||
|
setup();
|
||||||
|
if (phase.equals("phase1")) first(); else second();
|
||||||
|
results.add("PASS: ALL " + results.size() + " CHECKS (" + phase + ")");
|
||||||
|
} catch (Throwable ex) {
|
||||||
|
getLogger().log(java.util.logging.Level.SEVERE, "SMOKE FAILED", ex);
|
||||||
|
results.add("FAIL: " + ex);
|
||||||
|
}
|
||||||
|
try { Files.createDirectories(getDataFolder().toPath()); Files.write(getDataFolder().toPath().resolve(phase + ".txt"), results); }
|
||||||
|
catch (Exception e) { throw new RuntimeException(e); }
|
||||||
|
results.forEach(getLogger()::info);
|
||||||
|
Bukkit.shutdown();
|
||||||
|
}, 40);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setup() {
|
||||||
|
plugin = (AstraSoupsPlugin) Bukkit.getPluginManager().getPlugin("AstraSoups");
|
||||||
|
check(plugin != null && plugin.isEnabled(), "Plugin enables on Paper 26.2");
|
||||||
|
world = Bukkit.getWorlds().getFirst();
|
||||||
|
world.getChunkAt(0, 0).addPluginChunkTicket(this);
|
||||||
|
var server = ((CraftServer) Bukkit.getServer()).getServer();
|
||||||
|
var level = ((CraftWorld) world).getHandle();
|
||||||
|
var profile = new GameProfile(UUID.randomUUID(), "SoupTest");
|
||||||
|
nativePlayer = new ServerPlayer(server, level, profile, ClientInformation.createDefault());
|
||||||
|
nativePlayer.connection = new ServerGamePacketListenerImpl(server, new Connection(PacketFlow.SERVERBOUND), nativePlayer, CommonListenerCookie.createInitial(profile, false));
|
||||||
|
nativePlayer.setPos(2, 80, 2);
|
||||||
|
player = nativePlayer.getBukkitEntity();
|
||||||
|
player.setGameMode(GameMode.SURVIVAL);
|
||||||
|
pot = world.getBlockAt(2, 80, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void check(boolean value, String name) { if (!value) throw new AssertionError(name); results.add("PASS: " + name); }
|
||||||
|
private ItemStack item(Material material) { return new ItemStack(material); }
|
||||||
|
private ItemStack potion(Material material, PotionType type) {
|
||||||
|
ItemStack stack = item(material); PotionMeta meta = (PotionMeta) stack.getItemMeta();
|
||||||
|
meta.setBasePotionType(type); stack.setItemMeta(meta); return stack;
|
||||||
|
}
|
||||||
|
private ItemStack[] recipe() {
|
||||||
|
return new ItemStack[]{potion(Material.POTION, PotionType.LONG_NIGHT_VISION), item(Material.COOKED_BEEF), item(Material.GLOW_BERRIES), potion(Material.SPLASH_POTION, PotionType.STRONG_STRENGTH)};
|
||||||
|
}
|
||||||
|
private void fill(Block b) { b.setType(Material.WATER_CAULDRON); Levelled l = (Levelled) b.getBlockData(); l.setLevel(3); b.setBlockData(l); }
|
||||||
|
private PlayerInteractEvent click(Block block, ItemStack held, boolean sneak, boolean denied) {
|
||||||
|
player.getInventory().setItemInMainHand(held);
|
||||||
|
player.setSneaking(sneak);
|
||||||
|
PlayerInteractEvent event = new PlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, held, block, BlockFace.UP, EquipmentSlot.HAND);
|
||||||
|
if (denied) event.setUseInteractedBlock(Event.Result.DENY);
|
||||||
|
Bukkit.getPluginManager().callEvent(event);
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
private void addFour(Block block) { for (ItemStack i : recipe()) click(block, i, false, false); }
|
||||||
|
private ItemStack soupInInventory() {
|
||||||
|
return Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(plugin.ingredients()::isCombined).findFirst().orElseThrow();
|
||||||
|
}
|
||||||
|
private List<PotionEffect> effects(ItemStack soup) {
|
||||||
|
return soup.getData(DataComponentTypes.CONSUMABLE).consumeEffects().stream().filter(e -> e instanceof ConsumeEffect.ApplyStatusEffects)
|
||||||
|
.flatMap(e -> ((ConsumeEffect.ApplyStatusEffects) e).effects().stream()).toList();
|
||||||
|
}
|
||||||
|
private void first() throws Exception {
|
||||||
|
Ingredients ingredients = plugin.ingredients();
|
||||||
|
check(Math.abs(ingredients.read(item(Material.COOKED_BEEF)).saturation() - 12.8f) < .001, "Steak saturation is 12.8 absolute points");
|
||||||
|
for (Material material : Material.values()) if (material.isItem() && material.isEdible()) {
|
||||||
|
check(ingredients.read(item(material)) != null, "Edible accepted: " + material);
|
||||||
|
}
|
||||||
|
check(ingredients.read(item(Material.CAKE)).nutrition() == 14, "Whole cake accepted as seven slices");
|
||||||
|
check(ingredients.read(item(Material.TIPPED_ARROW)) == null, "Tipped arrows are not potion ingredients");
|
||||||
|
check(ingredients.read(item(Material.STONE)) == null, "Nonfood rejected");
|
||||||
|
for (Material material : List.of(Material.MUSHROOM_STEW, Material.RABBIT_STEW, Material.BEETROOT_SOUP, Material.SUSPICIOUS_STEW)) {
|
||||||
|
ItemStack stack = item(material); Ingredients.normalize(stack);
|
||||||
|
check(stack.getMaxStackSize() == 16, "Vanilla soup stack size: " + material);
|
||||||
|
}
|
||||||
|
ItemStack soup = ingredients.brew(Arrays.asList(recipe()));
|
||||||
|
check(soup.getData(DataComponentTypes.FOOD).nutrition() == 10, "Example combines 10 hunger points");
|
||||||
|
check(Math.abs(soup.getData(DataComponentTypes.FOOD).saturation() - 13.2f) < .001, "Example combines 13.2 saturation points");
|
||||||
|
check(soup.getMaxStackSize() == 16, "Combined soup stacks to sixteen");
|
||||||
|
List<ItemStack> reversed = new ArrayList<>(Arrays.asList(recipe())); Collections.reverse(reversed);
|
||||||
|
check(ingredients.brew(reversed).isSimilar(soup), "Same recipe stacks regardless of ingredient insertion order");
|
||||||
|
check(effects(soup).stream().anyMatch(e -> e.getType().equals(PotionEffectType.NIGHT_VISION) && e.getDuration() == 9600 && e.getAmplifier() == 0), "Extended night vision preserved");
|
||||||
|
check(effects(soup).stream().anyMatch(e -> e.getType().equals(PotionEffectType.STRENGTH) && e.getDuration() == 1800 && e.getAmplifier() == 1), "Strength II from splash potion preserved without splash reduction");
|
||||||
|
ItemStack roundTrip = ItemStack.deserializeBytes(soup.serializeAsBytes());
|
||||||
|
check(roundTrip.isSimilar(soup), "All soup components survive binary serialization");
|
||||||
|
var yaml = new org.bukkit.configuration.file.YamlConfiguration(); yaml.set("soup", soup);
|
||||||
|
var loaded = new org.bukkit.configuration.file.YamlConfiguration(); loaded.loadFromString(yaml.saveToString());
|
||||||
|
check(soup.isSimilar(loaded.getItemStack("soup")), "Soup survives YAML serialization");
|
||||||
|
ItemStack appleSoup = ingredients.brew(Collections.nCopies(4, item(Material.ENCHANTED_GOLDEN_APPLE)));
|
||||||
|
check(effects(appleSoup).stream().anyMatch(e -> e.getType().equals(PotionEffectType.ABSORPTION) && e.getAmplifier() == 3), "Unique vanilla food effects preserved");
|
||||||
|
ItemStack stew = item(Material.SUSPICIOUS_STEW); SuspiciousStewMeta sm = (SuspiciousStewMeta) stew.getItemMeta();
|
||||||
|
sm.addCustomEffect(new PotionEffect(PotionEffectType.BLINDNESS, 240, 0), true); stew.setItemMeta(sm);
|
||||||
|
ItemStack stewSoup = ingredients.brew(List.of(stew, item(Material.APPLE), item(Material.APPLE), item(Material.APPLE)));
|
||||||
|
check(effects(stewSoup).stream().anyMatch(e -> e.getType().equals(PotionEffectType.BLINDNESS) && e.getDuration() == 240), "Suspicious stew effect retained");
|
||||||
|
ItemStack customPotion = potion(Material.LINGERING_POTION, PotionType.WATER);
|
||||||
|
PotionMeta pm = (PotionMeta) customPotion.getItemMeta(); pm.addCustomEffect(new PotionEffect(PotionEffectType.HASTE, 1234, 2, true, false, false), true); customPotion.setItemMeta(pm);
|
||||||
|
ItemStack customPotionSoup = ingredients.brew(List.of(customPotion, item(Material.APPLE), item(Material.APPLE), item(Material.APPLE)));
|
||||||
|
check(effects(customPotionSoup).stream().anyMatch(e -> e.getDuration() == 1234 && e.getAmplifier() == 2 && e.isAmbient() && !e.hasParticles() && !e.hasIcon()), "Custom lingering potion flags and exact ticks preserved");
|
||||||
|
// Real Minecraft consumption and vanilla remainder handling, using a disconnected native server player.
|
||||||
|
player.getInventory().clear(); player.setFoodLevel(5); player.setSaturation(0);
|
||||||
|
ItemStack stack = soup.clone(); stack.setAmount(2);
|
||||||
|
var nms = CraftItemStack.asNMSCopy(stack);
|
||||||
|
var remaining = nms.finishUsingItem(((CraftWorld) world).getHandle(), nativePlayer);
|
||||||
|
check(player.getFoodLevel() == 15 && Math.abs(player.getSaturation() - 13.2f) < .001, "Native eating applies summed hunger and saturation exactly once");
|
||||||
|
check(player.getPotionEffect(PotionEffectType.STRENGTH).getAmplifier() == 1
|
||||||
|
&& player.getPotionEffect(PotionEffectType.NIGHT_VISION).getDuration() == 9600, "Native eating applies strength and night vision");
|
||||||
|
check(remaining.getCount() == 1 && CraftItemStack.asBukkitCopy(remaining).isSimilar(soup), "Native eating keeps the remaining stacked soup");
|
||||||
|
check(player.getInventory().contains(Material.BOWL), "Native eating returns one bowl from a stack");
|
||||||
|
var last = remaining.finishUsingItem(((CraftWorld) world).getHandle(), nativePlayer);
|
||||||
|
check(CraftItemStack.asBukkitCopy(last).getType() == Material.BOWL, "Final soup becomes a bowl");
|
||||||
|
check(player.getFoodLevel() == 20 && player.getSaturation() == 20, "Native hunger and saturation remain capped at twenty");
|
||||||
|
|
||||||
|
player.addAttachment(this, "astrasoups.admin", true);
|
||||||
|
ItemStack unique = item(Material.PAPER); ItemMeta uniqueMeta = unique.getItemMeta();
|
||||||
|
uniqueMeta.displayName(net.kyori.adventure.text.Component.text("Custom test food")); unique.setItemMeta(uniqueMeta);
|
||||||
|
player.getInventory().setItemInMainHand(unique);
|
||||||
|
plugin.onCommand(player, plugin.getCommand("soups"), "soups", new String[]{"register", "test_food", "7", "4.5"});
|
||||||
|
check(plugin.ingredients().read(unique).nutrition() == 7 && plugin.ingredients().read(unique).tags().contains("custom:test_food"), "Registered nonvanilla food supplies custom nutrition and selector");
|
||||||
|
check(plugin.ingredients().read(item(Material.PAPER)) == null, "Registered custom food does not match plain base material");
|
||||||
|
var configPath = plugin.getDataFolder().toPath().resolve("config.yml");
|
||||||
|
String goodConfig = Files.readString(configPath);
|
||||||
|
Files.writeString(configPath, "incompatible: [broken");
|
||||||
|
plugin.onCommand(Bukkit.getConsoleSender(), plugin.getCommand("soups"), "soups", new String[]{"reload"});
|
||||||
|
check(plugin.ingredients().read(unique).nutrition() == 7, "Malformed reload retains previous working ingredient configuration");
|
||||||
|
Files.writeString(configPath, goodConfig);
|
||||||
|
plugin.onCommand(Bukkit.getConsoleSender(), plugin.getCommand("soups"), "soups", new String[]{"reload"});
|
||||||
|
|
||||||
|
player.getInventory().clear(); fill(pot);
|
||||||
|
ItemStack denied = new ItemStack(Material.APPLE, 2);
|
||||||
|
click(pot, denied, false, true);
|
||||||
|
check(player.getInventory().getItemInMainHand().getAmount() == 2, "Cancelled protected interaction does not take an ingredient");
|
||||||
|
addFour(pot);
|
||||||
|
check(player.getInventory().getItemInMainHand().getType().isAir(), "Adding a fourth ingredient consumes exactly one item");
|
||||||
|
long count = world.getEntities().stream().filter(e -> e instanceof Item && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual"))).count();
|
||||||
|
check(count == 4, "Four real item entities visualize the ingredients");
|
||||||
|
for (Entity e : world.getEntities()) if (e instanceof Item drop && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual"))) {
|
||||||
|
check(!drop.canPlayerPickup() && !drop.canMobPickup() && !drop.hasGravity() && drop.isUnlimitedLifetime(), "Display ingredient cannot be picked up or expire");
|
||||||
|
}
|
||||||
|
click(pot, item(Material.AIR), false, false);
|
||||||
|
check(player.getInventory().getItemInMainHand().getType() == Material.SPLASH_POTION, "Empty-hand withdrawal is LIFO");
|
||||||
|
click(pot, recipe()[3], false, false);
|
||||||
|
plugin.getConfig().set("incompatible", List.of(List.of("material:cooked_beef", "effect:minecraft:strength")));
|
||||||
|
plugin.saveConfig(); plugin.onCommand(Bukkit.getConsoleSender(), plugin.getCommand("soups"), "soups", new String[]{"reload"});
|
||||||
|
click(pot, item(Material.AIR), true, false);
|
||||||
|
check(world.getEntities().stream().noneMatch(e -> e instanceof BlockDisplay), "Incompatible recipe does not create ready soup");
|
||||||
|
click(pot, item(Material.AIR), false, false);
|
||||||
|
check(player.getInventory().getItemInMainHand().getType() == Material.SPLASH_POTION, "Rejected recipe retains its ingredients");
|
||||||
|
plugin.getConfig().set("incompatible", List.of()); plugin.saveConfig();
|
||||||
|
plugin.onCommand(Bukkit.getConsoleSender(), plugin.getCommand("soups"), "soups", new String[]{"reload"});
|
||||||
|
click(pot, recipe()[3], false, false);
|
||||||
|
click(pot, item(Material.AIR), true, false);
|
||||||
|
check(world.getEntities().stream().anyMatch(e -> e instanceof BlockDisplay), "Brew creates colored soup surface");
|
||||||
|
check(world.getEntities().stream().noneMatch(e -> e instanceof Item && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual"))), "Brew removes ingredient visuals");
|
||||||
|
click(pot, new ItemStack(Material.BOWL, 2), false, false);
|
||||||
|
check(player.getInventory().getItemInMainHand().getAmount() == 1, "Collecting soup consumes one bowl");
|
||||||
|
check(soupInInventory().isSimilar(soup), "Collecting yields exactly the expected recipe");
|
||||||
|
check(pot.getType() == Material.CAULDRON, "Collecting consumes cauldron water");
|
||||||
|
// Persist one raw and one cooked cauldron for a true process restart.
|
||||||
|
fill(pot); addFour(pot); click(pot, item(Material.STICK), false, false);
|
||||||
|
check(player.getInventory().getItemInMainHand().getType() == Material.STICK, "Ordinary right-click with an item starts cooking without consuming the tool");
|
||||||
|
Block raw = world.getBlockAt(5, 80, 2); fill(raw); click(raw, item(Material.GOLDEN_CARROT), false, false);
|
||||||
|
check(new java.io.File(plugin.getDataFolder(), "cauldrons.yml").length() > 0, "Cauldron states saved before restart");
|
||||||
|
}
|
||||||
|
private void second() {
|
||||||
|
check(pot.getType() == Material.WATER_CAULDRON, "Ready cauldron block survives restart");
|
||||||
|
click(pot, item(Material.BOWL), false, false);
|
||||||
|
ItemStack soup = soupInInventory();
|
||||||
|
check(soup.getMaxStackSize() == 16 && effects(soup).size() == 2, "Ready soup keeps stack size and effects across process restart");
|
||||||
|
player.getInventory().clear();
|
||||||
|
Block raw = world.getBlockAt(5, 80, 2);
|
||||||
|
click(raw, item(Material.AIR), false, false);
|
||||||
|
check(player.getInventory().getItemInMainHand().getType() == Material.GOLDEN_CARROT, "Raw ingredient can be withdrawn after process restart");
|
||||||
|
click(raw, item(Material.AIR), false, false);
|
||||||
|
check(player.getInventory().isEmpty(), "Withdrawn ingredient cannot be obtained twice");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
PASS: Plugin enables on Paper 26.2
|
||||||
|
PASS: Steak saturation is 12.8 absolute points
|
||||||
|
PASS: Edible accepted: APPLE
|
||||||
|
PASS: Edible accepted: BAKED_POTATO
|
||||||
|
PASS: Edible accepted: BEEF
|
||||||
|
PASS: Edible accepted: BEETROOT
|
||||||
|
PASS: Edible accepted: BEETROOT_SOUP
|
||||||
|
PASS: Edible accepted: BREAD
|
||||||
|
PASS: Edible accepted: CARROT
|
||||||
|
PASS: Edible accepted: CHICKEN
|
||||||
|
PASS: Edible accepted: CHORUS_FRUIT
|
||||||
|
PASS: Edible accepted: COD
|
||||||
|
PASS: Edible accepted: COOKED_BEEF
|
||||||
|
PASS: Edible accepted: COOKED_CHICKEN
|
||||||
|
PASS: Edible accepted: COOKED_COD
|
||||||
|
PASS: Edible accepted: COOKED_MUTTON
|
||||||
|
PASS: Edible accepted: COOKED_PORKCHOP
|
||||||
|
PASS: Edible accepted: COOKED_RABBIT
|
||||||
|
PASS: Edible accepted: COOKED_SALMON
|
||||||
|
PASS: Edible accepted: COOKIE
|
||||||
|
PASS: Edible accepted: DRIED_KELP
|
||||||
|
PASS: Edible accepted: ENCHANTED_GOLDEN_APPLE
|
||||||
|
PASS: Edible accepted: GLOW_BERRIES
|
||||||
|
PASS: Edible accepted: GOLDEN_APPLE
|
||||||
|
PASS: Edible accepted: GOLDEN_CARROT
|
||||||
|
PASS: Edible accepted: HONEY_BOTTLE
|
||||||
|
PASS: Edible accepted: MELON_SLICE
|
||||||
|
PASS: Edible accepted: MUSHROOM_STEW
|
||||||
|
PASS: Edible accepted: MUTTON
|
||||||
|
PASS: Edible accepted: POISONOUS_POTATO
|
||||||
|
PASS: Edible accepted: PORKCHOP
|
||||||
|
PASS: Edible accepted: POTATO
|
||||||
|
PASS: Edible accepted: PUFFERFISH
|
||||||
|
PASS: Edible accepted: PUMPKIN_PIE
|
||||||
|
PASS: Edible accepted: RABBIT
|
||||||
|
PASS: Edible accepted: RABBIT_STEW
|
||||||
|
PASS: Edible accepted: ROTTEN_FLESH
|
||||||
|
PASS: Edible accepted: SALMON
|
||||||
|
PASS: Edible accepted: SPIDER_EYE
|
||||||
|
PASS: Edible accepted: SUSPICIOUS_STEW
|
||||||
|
PASS: Edible accepted: SWEET_BERRIES
|
||||||
|
PASS: Edible accepted: TROPICAL_FISH
|
||||||
|
PASS: Whole cake accepted as seven slices
|
||||||
|
PASS: Tipped arrows are not potion ingredients
|
||||||
|
PASS: Nonfood rejected
|
||||||
|
PASS: Vanilla soup stack size: MUSHROOM_STEW
|
||||||
|
PASS: Vanilla soup stack size: RABBIT_STEW
|
||||||
|
PASS: Vanilla soup stack size: BEETROOT_SOUP
|
||||||
|
PASS: Vanilla soup stack size: SUSPICIOUS_STEW
|
||||||
|
PASS: Example combines 10 hunger points
|
||||||
|
PASS: Example combines 13.2 saturation points
|
||||||
|
PASS: Combined soup stacks to sixteen
|
||||||
|
PASS: Same recipe stacks regardless of ingredient insertion order
|
||||||
|
PASS: Extended night vision preserved
|
||||||
|
PASS: Strength II from splash potion preserved without splash reduction
|
||||||
|
PASS: All soup components survive binary serialization
|
||||||
|
PASS: Soup survives YAML serialization
|
||||||
|
PASS: Unique vanilla food effects preserved
|
||||||
|
PASS: Suspicious stew effect retained
|
||||||
|
PASS: Custom lingering potion flags and exact ticks preserved
|
||||||
|
PASS: Native eating applies summed hunger and saturation exactly once
|
||||||
|
PASS: Native eating applies strength and night vision
|
||||||
|
PASS: Native eating keeps the remaining stacked soup
|
||||||
|
PASS: Native eating returns one bowl from a stack
|
||||||
|
PASS: Final soup becomes a bowl
|
||||||
|
PASS: Native hunger and saturation remain capped at twenty
|
||||||
|
PASS: Registered nonvanilla food supplies custom nutrition and selector
|
||||||
|
PASS: Registered custom food does not match plain base material
|
||||||
|
PASS: Malformed reload retains previous working ingredient configuration
|
||||||
|
PASS: Cancelled protected interaction does not take an ingredient
|
||||||
|
PASS: Adding a fourth ingredient consumes exactly one item
|
||||||
|
PASS: Four real item entities visualize the ingredients
|
||||||
|
PASS: Display ingredient cannot be picked up or expire
|
||||||
|
PASS: Display ingredient cannot be picked up or expire
|
||||||
|
PASS: Display ingredient cannot be picked up or expire
|
||||||
|
PASS: Display ingredient cannot be picked up or expire
|
||||||
|
PASS: Empty-hand withdrawal is LIFO
|
||||||
|
PASS: Incompatible recipe does not create ready soup
|
||||||
|
PASS: Rejected recipe retains its ingredients
|
||||||
|
PASS: Brew creates colored soup surface
|
||||||
|
PASS: Brew removes ingredient visuals
|
||||||
|
PASS: Collecting soup consumes one bowl
|
||||||
|
PASS: Collecting yields exactly the expected recipe
|
||||||
|
PASS: Collecting consumes cauldron water
|
||||||
|
PASS: Ordinary right-click with an item starts cooking without consuming the tool
|
||||||
|
PASS: Cauldron states saved before restart
|
||||||
|
PASS: ALL 86 CHECKS (phase1)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
PASS: Plugin enables on Paper 26.2
|
||||||
|
PASS: Ready cauldron block survives restart
|
||||||
|
PASS: Ready soup keeps stack size and effects across process restart
|
||||||
|
PASS: Raw ingredient can be withdrawn after process restart
|
||||||
|
PASS: Withdrawn ingredient cannot be obtained twice
|
||||||
|
PASS: ALL 5 CHECKS (phase2)
|
||||||
Reference in New Issue
Block a user