Migrate AstraSoups to NeoForge as AstraCauldron
This commit is contained in:
@@ -3,3 +3,4 @@ build/
|
||||
*.log
|
||||
*.jar
|
||||
.test-server/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
@@ -1,55 +1,24 @@
|
||||
# Общие правила работы с плагинами AstraDev
|
||||
# AstraCauldron — серверный мод NeoForge
|
||||
|
||||
Эти правила действуют для всех проектов в `C:\Users\ScarPC\Documents\Plugins`.
|
||||
Общая копия хранится в `Plugins\AGENTS.md`; копии в репозиториях нужны, чтобы правила
|
||||
сохранялись при клонировании отдельного плагина. При изменении общих правил обновлять все копии.
|
||||
Проект переименован из AstraSoups. По запросу пользователя здесь используется
|
||||
Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+, без Paper и ItemsAdder.
|
||||
Эти правила установки заменяют родительские указания о Paper.
|
||||
|
||||
## Расположение проектов и сервера
|
||||
|
||||
- Каждый плагин имеет отдельную папку исходников и собственный 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 непосредственно в корень `C:\Users\ScarPC\Documents\26.2 Paper\plugins`.
|
||||
Не оставлять там одновременно старую и новую версии одного плагина.
|
||||
5. Проверить по SHA-256 именно JAR в корне `plugins`: он должен совпадать с собранным артефактом.
|
||||
6. При обновлении нескольких плагинов выполнить эти действия для каждого изменённого плагина.
|
||||
|
||||
Не заменять конфигурации, данные плагинов и миры при обычном обновлении JAR.
|
||||
Если установка не выполнена, явно сообщить об этом; не объявлять обновление сервера завершённым.
|
||||
Изменения только документации и правил не требуют пересборки и замены неизменного JAR.
|
||||
|
||||
### Только прямая замена в корне plugins
|
||||
|
||||
- Запрошенное обновление означает фактическую замену JAR в корне `plugins`, а не подготовку к следующему запуску.
|
||||
- Не создавать и не использовать `plugins/update`, другие промежуточные папки, отложенную установку,
|
||||
фоновые скрипты замены или второй JAR под другим именем как обход прямой замены.
|
||||
- Если работающий сервер или другой процесс блокирует JAR, сообщить о блокировке и необходимости
|
||||
освободить файл для прямой замены. Блокировка не разрешает переносить обновление в `plugins/update`.
|
||||
- После освобождения файла выполнить обычную процедуру: перенести старый JAR в архив,
|
||||
скопировать новый непосредственно в корень `plugins` и сравнить SHA-256.
|
||||
- Пока новый JAR не находится в корне `plugins` и его SHA-256 не проверен, установка не завершена.
|
||||
Наличие сборки или копии в промежуточной папке не считается установкой.
|
||||
|
||||
## Обязательная фиксация в Git
|
||||
|
||||
- Каждая завершённая задача с изменениями файлов должна быть зафиксирована коммитом
|
||||
в соответствующем репозитории. Коммит — обязательная часть работы, отдельное напоминание пользователя не требуется.
|
||||
- Если задача затрагивает несколько репозиториев, создать отдельный коммит в каждом из них.
|
||||
- Перед коммитом проверить diff и результаты необходимых проверок.
|
||||
- Коммитить изменения текущей задачи. Не включать посторонние изменения пользователя и не откатывать их.
|
||||
- Сообщение коммита должно описывать конкретное изменение.
|
||||
- Не добавлять в Git собранные JAR, каталоги build/.gradle, журналы, тестовые серверы и резервные копии.
|
||||
- Push выполнять, когда он запрошен пользователем или уже разрешён в текущей задаче; сам коммит обязателен независимо от push.
|
||||
- В итоговом ответе указать результат установки JAR, расположение сохранённой старой версии и созданные коммиты,
|
||||
когда соответствующие действия выполнялись в этой задаче.
|
||||
- Рабочий сервер: `C:\Users\ScarPC\Documents\NeoForge Server 26.2`.
|
||||
- После изменений кода/ресурсов собрать и проверить мод, установить основной JAR прямо в `mods`.
|
||||
- Старые JAR именно AstraCauldron (или прежнего AstraSoups) переносить в уникальный
|
||||
`old-mods/YYYYMMDD-HHMMSS/` с сохранением имени. Не оставлять две версии в `mods`.
|
||||
- Сравнивать SHA-256 установленного файла и сборки. При блокировке файла сообщить,
|
||||
не использовать отложенные установки. Конфигурации, данные и миры не заменять.
|
||||
- AstraPlus 0.5.1+ — обязательная зависимость. Публичные интерфейсы `CauldronApi` и
|
||||
`ColoredWaterApi` принадлежат AstraPlus; мод котлов использует их для преобразования
|
||||
предметов и отображения жидкости. Не дублировать здесь модель/рендер цветной воды.
|
||||
- В AstraCauldron живут игровые взаимодействия, расход предметов, варка и сохранение котлов.
|
||||
- Клиенту достаточно ванильного Minecraft и серверного ресурспака. Не регистрировать
|
||||
клиентские предметы/блоки и обязательные сетевые каналы.
|
||||
- Проверки с игровым миром запускать только в отдельном каталоге `build` и с флагом
|
||||
`-Dastracauldron.isolatedVerification=true`; проверочный JAR никогда не устанавливать на рабочий сервер.
|
||||
- Проверить diff и создать коммит задачи. Push только по запросу.
|
||||
- Не коммитить build, .gradle, JAR сборки, логи, миры и резервные копии;
|
||||
`gradle/wrapper/gradle-wrapper.jar` — часть системы сборки.
|
||||
- В итоге сообщать установку, архив старого JAR, коммиты и ограничения проверок.
|
||||
|
||||
@@ -1,116 +1,150 @@
|
||||
# AstraSoups 0.1.3
|
||||
# AstraCauldron
|
||||
|
||||
Отдельный серверный плагин комбинированных супов для **Paper 26.2**, Java 25+.
|
||||
Сборка проекта использует установленный JDK 26. Клиентские моды не требуются. Для цветной иконки используются установленные на сервере AstraPacks и ItemsAdder: модель встроена в JAR и автоматически попадает в общий ресурспак.
|
||||
Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
|
||||
Переименован и перенесён из AstraSoups. Требуется **AstraPlus 0.5.1+**.
|
||||
Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks.
|
||||
|
||||
## Использование
|
||||
## Режимы котла
|
||||
|
||||
1. Полностью наполнить котёл водой.
|
||||
2. Нажать ПКМ по котлу с ингредиентом в основной руке. Каждое нажатие кладёт **одну единицу**. Всего нужно **четыре**; одинаковые ингредиенты разрешены.
|
||||
3. Начать варку: **Shift+ПКМ** или обычный **ПКМ с любым предметом в руке**, когда все четыре ингредиента уже внутри. Предмет для запуска не расходуется. Ингредиенты частично погружены в воду и в течение 4 секунд плавно вращаются по окружности постоянного радиуса. Затем исчезают, а поверхность воды становится цветной. Во время варки нельзя забрать ингредиент или собрать суп; повторный клик не перезапускает таймер.
|
||||
4. **ПКМ миской** по готовому супу выдаёт **одну из четырёх порций** и расходует одну миску. После каждой порции поверхность супа опускается, вода под ней также уменьшается. Последняя порция остаётся видимой на дне даже без ванильного слоя воды. Котёл пустеет после четвёртой порции. Если запускать варку миской, первое нажатие запускает водоворот, следующее нажатие после его завершения собирает порцию.
|
||||
| Действие | Результат |
|
||||
| --- | --- |
|
||||
| ПКМ красителем по котлу с водой | Цветная вода; один краситель расходуется, объём сохраняется |
|
||||
| Ещё один краситель | Смешивание по ванильному алгоритму окрашивания с сохранением яркости |
|
||||
| Кожаная броня, кожаная конская броня или волчья броня по цветной воде | Предмет получает цвет воды; расходуется один уровень |
|
||||
| Любое обычное, взрывное или туманное зелье по пустому котлу | Один из трёх уровней зелья; возвращается стеклянная бутылочка |
|
||||
| Такое же зелье по котлу с зельем | Добавляется уровень до максимума 3 |
|
||||
| Стеклянная бутылочка по зелью | Одна обычная бутылочка этого зелья; минус один уровень |
|
||||
| Обычные стрелы по зелью | До 16/32/64 стрел при 1/2/3 уровнях; стоимость 1/2/3 уровня соответственно |
|
||||
| Еда или зелье по полному котлу чистой воды | Ингредиент супа, максимум четыре |
|
||||
| Shift+ПКМ после четырёх ингредиентов | Начало варки супа |
|
||||
| Пустая рука до варки, без Shift | Возврат последнего ингредиента |
|
||||
| Миска по готовому супу | Одна порция; уровень поверхности уменьшается |
|
||||
|
||||
**Обычный ПКМ пустой рукой** до варки возвращает самый недавно добавленный ингредиент. Такое разделение позволяет и запускать варку, и извлекать ингредиенты без конфликта действий.
|
||||
Каждый режим исключает остальные: в суп нельзя случайно долить зелье для стрел,
|
||||
а в цветную воду нельзя добавить пищу. Зелья хранятся в изначально пустом котле;
|
||||
зелья в полном котле обычной воды используются как ингредиенты супа.
|
||||
Чистая бутылочка воды сохраняет ванильное заполнение водой.
|
||||
|
||||
Ингредиенты показаны через `ItemDisplay`: клиент интерполирует локальное движение между кадрами, сами сущности не телепортируются. Радиус вращения сохраняется до завершения варки. Они не являются выпавшими предметами, не подбираются и не имеют нативной физики покачивания. При запуске варки и заборе порции подходящие визуальные сущности сохраняются, а не создаются заново. Готовый суп отображается горизонтальной RGB-поверхностью внутри котла: непрозрачный фон `TextDisplay` с пробелом, без видимых букв и ресурспака. Цвет — среднее арифметическое RGB четырёх ингредиентов в равных долях. У еды задан характерный цвет: красный глаз паука, жёлтое золотое яблоко, оранжевая морковь и другие. Зелья передают свой фактический цвет, включая пользовательский. Порядок ингредиентов не влияет на результат, повторы учитываются. Повторно используемый комбинированный суп передаёт сохранённый цвет. Разные смеси могут естественно давать похожие или одинаковые оттенки. Название и содержимое миски на иконке окрашиваются в один и тот же цвет смеси. Деревянная миска сохраняет свой цвет. Модель работает в инвентаре, в руках и у отображаемых предметов. Старые комбинированные супы автоматически получают модель при нормализации; обычные ванильные супы сохраняют свои иконки.
|
||||
Разные зелья, вода и красители не смешиваются с хранящимся зельем: действие отклоняется
|
||||
без расходования предмета. Разновидность бутылочки не меняет состав: обычное, взрывное
|
||||
и туманное зелья одинакового состава складываются в один котёл. Обратно выдаётся обычное
|
||||
зелье. Эффекты, их уровни, бесконечность, флаги, пользовательский цвет/имя зелья и явно
|
||||
переопределённый коэффициент длительности сохраняются. Обычный коэффициент облака
|
||||
туманного зелья не сокращает хранящийся состав. Для стрел применяется нативный множитель
|
||||
длительности Java (1/8), а не полная длительность выпитого зелья.
|
||||
|
||||
Все четыре ванильных супа — грибной, кроличий, свекольный и подозрительный — и комбинированные супы получают максимальный стак **16**. Одинаковые рецепты совместимы по стакам независимо от порядка загрузки ингредиентов. Разные составы или эффекты дают разные предметы.
|
||||
Если жидкости хватает только на часть пачки, обрабатывается доступное количество,
|
||||
остальные стрелы остаются в руке. Последний расход опустошает котёл. Железная и прочая
|
||||
неокрашиваемая броня не расходует воду. Имя, прочность, зачарования и остальные компоненты
|
||||
окрашиваемой брони сохраняются. Смывание краски чистой водой остаётся ванильным.
|
||||
|
||||
## Питание и эффекты
|
||||
Полный котёл цветной воды можно забрать ведром, потеряв краситель. Бутылочка забирает
|
||||
один уровень обычной воды без красителя. Ведро чистой воды смывает краситель и снова
|
||||
наполняет котёл. В Creative входящие предметы не расходуются; преобразование брони
|
||||
меняет сам предмет, объём жидкости расходуется и в Creative.
|
||||
|
||||
- Поддерживается вся ванильная еда, включая целый торт: 14 голода и 2,8 насыщения.
|
||||
- Поддерживаются обычные, взрывные и оседающие зелья. Стрелы с эффектами не считаются зельями.
|
||||
- Питание берётся из реальных компонентов предметов, включая изменённую плагинами еду. Насыщение указывается в абсолютных очках, а не коэффициентом.
|
||||
- У зелий сохраняются точные длительности в тиках, уровни, бесконечность и флаги видимости. Взрывные и оседающие зелья передают записанную полную длительность.
|
||||
- Эффекты золотых яблок, подозрительных супов и другой еды сохраняются. Вероятностные эффекты остаются вероятностными, включая вредные. Действия еды вроде телепортации хоруса и снятия яда мёдом также переносятся.
|
||||
- Совпадающие эффекты применяются по ванильным правилам Minecraft: уровни не складываются арифметически, более слабый эффект не заменяет более сильный. Каждый записанный эффект сохраняет свою длительность.
|
||||
- Комбинированный суп можно есть при полном голоде, чтобы получить эффекты. Миска возвращается нативным механизмом Minecraft, в том числе при поедании стака.
|
||||
- Значения в описании супа — сумма ингредиентов. **Фактические голод и насыщение игрока ограничиваются Minecraft: максимум 20; насыщение не выше текущего голода.** Переполнение сверх этих пределов не хранится в резерве.
|
||||
- В одну варку получается четыре порции, каждая с полным суммарным питанием и эффектами состава. Упаковка ингредиентов расходуется вместе с ингредиентами; пустые бутылки и миски исходной еды отдельно не возвращаются. В Creative предметы в руках не расходуются.
|
||||
Механики окрашивания и хранения зелий вдохновлены [описанием котла Mojang](https://www.minecraft.net/en-us/article/cauldron).
|
||||
Это перенос выбранных возможностей Bedrock в Java, без заявления о полной идентичности всех правил Bedrock.
|
||||
|
||||
Пример: продлённое ночное зрение + стейк + светящиеся ягоды + сила II = **10 голода, 13,2 насыщения, ночное зрение I на 8:00 и сила II на 1:30**.
|
||||
## Супы и особая еда
|
||||
|
||||
## Уникальная еда
|
||||
Варка занимает 4 секунды и даёт 4 порции по умолчанию. Каждая порция содержит полную сумму
|
||||
питания и действий употребления четырёх ингредиентов. Поддержаны ванильная еда, целый
|
||||
торт, зелья, подозрительные супы, вероятностные эффекты и действия вроде телепортации хоруса.
|
||||
Насыщение задаётся в абсолютных очках. Суп можно есть при полном голоде; миска возвращается
|
||||
нативно. Четыре ванильных супа и комбинированный суп складываются по 16. Лимиты игрока
|
||||
по голоду/насыщению остаются ванильными. Упаковка добавленного ингредиента расходуется.
|
||||
|
||||
Если у предмета есть нативный компонент еды, он поддерживается автоматически. Для еды, чьи характеристики реализованы обработчиками другого плагина, возьмите предмет и выполните:
|
||||
Еда AstraPlus читается через публичный API и реальные компоненты ItemStack. Питание,
|
||||
добавляемое только сторонним скриптом, автоматически не исполняется как эффект супа.
|
||||
Для такой еды возьмите предмет в руку и выполните:
|
||||
|
||||
```text
|
||||
/soups register my_food 7 4.5
|
||||
/cauldron register my_food 7 4.5
|
||||
/cauldron reload
|
||||
```
|
||||
|
||||
Команда сохраняет образец предмета в `plugins/AstraSoups/config.yml`, задаёт 7 голода и 4,5 насыщения. Количество в стаке не влияет на совпадение, остальные метаданные должны совпадать. Обычный предмет того же материала не станет такой едой. Перерегистрация того же ID заменяет образец и питание.
|
||||
Регистрация предмета AstraPlus привязывается к стабильному ID, поэтому смена его имени или
|
||||
модели не ломает регистрацию. Для остальных предметов сохраняется точный образец без учёта
|
||||
количества. `/soups` сохранён как псевдоним `/cauldron`. Подсказка доступна всем, регистрация
|
||||
и reload требуют ванильных прав администратора (уровень 2).
|
||||
|
||||
В записи `custom-ingredients.my_food` необязательный параметр `color: '#D45B37'` задаёт цвет уникальной еды. Без него берётся цвет базового материала, для неизвестных продуктов — `default-color`.
|
||||
Настройки: `config/astracauldron.json`. Ключи: `brewSeconds` (0.5–60), `servingsPerBrew`
|
||||
(1–16), `requireFullWater`, `soupName`, `defaultColor` (#RRGGBB), `maxNutrition`,
|
||||
`maxSaturation`, `blockedIngredients`, `incompatible`, `customIngredients`.
|
||||
Некорректная перезагрузка сохраняет прежнее рабочее состояние.
|
||||
|
||||
Дополнительные эффекты можно прописать в этой же записи:
|
||||
|
||||
```yaml
|
||||
effects:
|
||||
- type: minecraft:strength
|
||||
duration: 3600
|
||||
amplifier: 1
|
||||
```json
|
||||
{
|
||||
"blockedIngredients": ["material:rotten_flesh"],
|
||||
"incompatible": [["effect:minecraft:strength", "effect:minecraft:weakness"]],
|
||||
"customIngredients": {
|
||||
"my_food": {
|
||||
"astraPlusId": "food:chili", "nutrition": 7, "saturation": 4.5,
|
||||
"color": "#D45B37",
|
||||
"effects": [{"type": "minecraft:strength", "duration": 3600, "amplifier": 1}]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Это сила II на 3 минуты. В описании супа уровни римские, длительность в скобках, без точек-разделителей. Описания ранее созданных супов обновляются при обычной нормализации инвентарей. `amplifier: 0` соответствует I, `duration: -1` — бесконечности. Дополнительные эффекты прибавляются к встроенным свойствам предмета.
|
||||
Селекторы: `material:name`, `astraplus:namespace:id`, `custom:id`, `effect:minecraft:id`,
|
||||
`soup:combined`, `*`. Пара запрета должна совпасть в двух разных слотах. Повторы разрешены,
|
||||
пока не запрещены настройками. Дополнительные эффекты регистрации добавляются к компонентам
|
||||
предмета. `duration: -1` — бесконечность, `amplifier: 0` — первый уровень.
|
||||
|
||||
AstraPacks и ItemsAdder — обязательные зависимости для автоматической установки модели. ItemsAdder также используется для распознавания namespaced ID в правилах совместимости. Эффекты, которые сторонние плагины выдают только своим обработчиком употребления, автоматически не исполняются при поедании супа: задайте их явно в регистрации.
|
||||
## Общий API и внешний вид
|
||||
|
||||
## Запреты сочетаний
|
||||
**AstraPlus** содержит `CauldronApi` (смешивание красителей, окрашивание брони, нормализация
|
||||
зелий и преобразование стрел) и `ColoredWaterApi` (отображение поверхности). Эти интерфейсы
|
||||
не расходуют предметы и не сохраняют игровые котлы. Другие моды могут использовать их
|
||||
без AstraCauldron. Пример API: `AstraPlus/docs/api.md`.
|
||||
|
||||
Пример `config.yml`:
|
||||
**AstraCauldron** обрабатывает действия игроков, рассчитывает игровой расход, сохраняет
|
||||
содержимое и вызывает API. Имена и модель комбинированного супа остаются отдельными ресурсами
|
||||
мода; жидкость внутри котла полностью принадлежит AstraPlus.
|
||||
|
||||
```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']
|
||||
```
|
||||
Старая версия закрывала воду непрозрачным фоном TextDisplay с пробелом: это давало плоский
|
||||
однотонный квадрат. Теперь AstraPlus использует ItemDisplay с горизонтальной моделью,
|
||||
ванильной анимированной текстурой `minecraft:block/water_still` и оттенком из
|
||||
`CUSTOM_MODEL_DATA.colors[0]`. Поверхность 0.75 × 0.75 блока находится внутри ободка;
|
||||
изменение высоты интерполируется. Это визуальная жидкость, а не новый зарегистрированный
|
||||
блок/Fluid. Для заполненного игрового котла используется ванильный пустой котёл под
|
||||
поверхностью: синяя вода не просвечивает через слой. Клиенту нужен обновлённый ресурспак.
|
||||
|
||||
Первый список полностью запрещает ингредиент. Второй содержит пары несовместимых ингредиентов: совпадения должны быть в **разных слотах**. Последнее правило запрещает два золотых яблока в одном котле. Проверка выполняется при запуске варки; при отказе ингредиенты остаются и их можно забрать.
|
||||
Цвет супа — среднее RGB ингредиентов в равных долях, цвет зелья — из его компонентов,
|
||||
цвет окрашенной воды — результат смешивания красителей. Миска супа имеет собственную
|
||||
составную иконку: деревянная часть не окрашивается.
|
||||
|
||||
Селекторы без учёта регистра: `material:NAME`, `effect:minecraft:id`, `custom:registered_id`, `itemsadder:namespace:id`, `soup:combined` и `*` для любого ингредиента. По умолчанию списки пусты — запрещённых комбинаций не выдумано.
|
||||
## Сохранение и установка
|
||||
|
||||
`max-nutrition` и `max-saturation` по умолчанию равны 1000. Они ограничивают рецепт при повторном комбинировании супов и предотвращают переполнение; превышение отклоняет варку без потери ингредиентов. Дополнительно ограничивается число действий употребления до 256.
|
||||
Данные хранятся в `<мир>/astracauldron/cauldrons.json` (супы) и `liquids.json`
|
||||
(крашеная вода/зелья). Каждое действие сначала сохраняется через временный файл и замену;
|
||||
при ошибке предметы не передаются, состояние откатывается. Жёсткий обрыв между сохранениями
|
||||
Minecraft и мода не является общей транзакцией с инвентарём игрока.
|
||||
|
||||
## Команды и права
|
||||
|
||||
| Команда / право | Назначение |
|
||||
| --- | --- |
|
||||
| `/soups` | Подсказка по управлению |
|
||||
| `/soups reload` | Перечитать настройки; ошибка оставляет прежние настройки |
|
||||
| `/soups register <id> <голод> <насыщение>` | Зарегистрировать предмет в основной руке |
|
||||
| `astrasoups.use` | Использование котлов; по умолчанию разрешено всем |
|
||||
| `astrasoups.admin` | Регистрация и перезагрузка; по умолчанию только операторы |
|
||||
|
||||
Длительность задаётся в `brew-seconds` (по умолчанию 4.0, диапазон 0.5–60), количество порций — в `servings-per-brew` (по умолчанию 4, диапазон 1–16). Изменения применяются к новым варкам после `/soups reload`. Старые конфиги поддерживаются без перезаписи: отсутствующие параметры используют значения по умолчанию.
|
||||
|
||||
## Сохранение и взаимодействия
|
||||
|
||||
Состояния котлов записываются в `plugins/AstraSoups/cauldrons.yml` после каждой операции через временный файл и замену. Ошибка сохранения отменяет операцию до передачи предмета. Содержимое, исходный объём варки и число оставшихся порций восстанавливаются после нормального перезапуска; это сохраняет высоту жидкости независимо от изменения настроек. Для старых записей без исходного объёма используется не менее текущего servings-per-brew. Выгрузка чанка приостанавливает анимацию; после перезапуска сервера незавершённая варка начинает полный цикл заново, сохраняя ингредиенты и будущие порции. Чанки принудительно не удерживаются. Старые готовые котлы без поля servings сохраняют одну порцию, чтобы обновление не размножало их содержимое. Файл и инвентарь игрока не являются общей транзакционной базой: жёсткое завершение процесса ровно между сохранениями Minecraft и плагина не даёт гарантии атомарности.
|
||||
|
||||
При разбивании котла сырые ингредиенты выпадают, сваренный суп выливается. Котлы с содержимым защищены от взрывов, поршней и изменения уровня воды. Уже отменённые взаимодействия и ломание блоков уважаются. Внешнее редактирование блоков очищает состояние пропавшего котла и возвращает сырые ингредиенты при следующей проверке.
|
||||
|
||||
Старые ванильные супы получают размер стака при открытии инвентаря, входе игрока, загрузке выпавших предметов, крафте, генерации лута и перемещениях воронок. Открытые инвентари проверяются раз в секунду: выдачи сторонними плагинами нормализуются в пределах этого интервала. Содержимое закрытых незагруженных сундуков не сканируется заранее. `MAX_STACK_SIZE` меняется у экземпляров предметов, а не у глобального прототипа материала.
|
||||
|
||||
## Сборка и установка
|
||||
При перезапуске восстанавливаются содержимое и объём, незавершённая варка начинает таймер
|
||||
заново. Выгрузка чанка приостанавливает работу; чанки принудительно не загружаются. При
|
||||
разрушении сырьё супа возвращается, готовые жидкости выливаются. Занятые котлы защищены
|
||||
от поршней, взрывов и ванильных изменений уровня дождём/капельником/тушением. Отменённые
|
||||
другими модами действия уважаются. Внешняя замена блока очищает состояние при проверке.
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat test jar
|
||||
# Сначала собрать AstraPlus с API-артефактом.
|
||||
.\gradlew.bat test assemble verificationJar
|
||||
```
|
||||
|
||||
Результат: `build/libs/AstraSoups-0.1.3.jar`. Поместить в папку `plugins` Paper 26.2 и запустить/перезапустить сервер. Настройки создаются автоматически. При обновлении заменить только JAR, сохраняя конфигурацию и `cauldrons.yml`.
|
||||
Сборка использует `../AstraPlus/build/libs/AstraPlus-0.5.1-api.jar`; другой путь можно
|
||||
передать через `-PastraPlusApi=...`. В `mods` устанавливаются **только** основные
|
||||
`AstraPlus-0.5.1.jar` и `AstraCauldron-0.2.0.jar`.
|
||||
API/sources/verification JAR на рабочий сервер не устанавливать. Старый JAR перед заменой
|
||||
сохранить в `old-mods`, затем проверить SHA-256 установленного файла.
|
||||
|
||||
Плагин использует [Paper Data Component API](https://docs.papermc.io/paper/dev/data-component-api/), поэтому переход на другие версии Minecraft требует отдельной проверки совместимости.
|
||||
При запуске модель миски экспортируется без перезаписи пользовательских файлов в
|
||||
`astraplus/resources/assets/astradev_soups`; AstraPlus добавляет свою модель жидкости и
|
||||
собирает ZIP. При наличии AstraPacks используется его экспорт/доставка. Для ручной
|
||||
пересборки: `/astraplus build`.
|
||||
|
||||
`tools/smoke` — тестовый плагин для **отдельного временного сервера**. Он изменяет тестовый мир и останавливает сервер, поэтому его нельзя устанавливать на рабочий сервер. Подробности проверок — в `VERIFICATION.md`.
|
||||
|
||||
|
||||
### Цветная модель предмета
|
||||
|
||||
`astra-pack.properties` подключает модуль `astradev_soups` к AstraPacks. Ресурсы находятся в `src/main/resources/astra-itemsadder/astradev_soups/`; после запуска AstraPacks устанавливает их в ItemsAdder и запрашивает общую пересборку. Игроку нужен обновлённый серверный ресурспак.
|
||||
|
||||
`astradev_soups:combined_soup` объединяет ванильную модель пустой миски и три полоски жидкости внутри её ободка. Цвет жидкости — `CUSTOM_MODEL_DATA.colors[0]`, равный сохранённому `astrasoups:soup_color`. Остальные списки и дополнительные цвета CustomModelData сохраняются при миграции. Полоски используют белый пиксель (4, 3) ванильной текстуры костной муки, поэтому дополнительные PNG не требуются. Геометрия и UV рассчитаны на стандартные текстуры Minecraft 26.2; пакет, заменяющий эти ванильные текстуры, может изменить внешний вид.
|
||||
|
||||
Формат модели и источника цвета описан в [официальных примечаниях Minecraft](https://www.minecraft.net/en-us/article/minecraft-java-edition-1-21-4). Проверка файлов настоящими десериализаторами установленного клиента 26.2: `tools/check-models.ps1`.
|
||||
Bukkit-YAML, UUID миров Paper и данные ItemsAdder автоматически не импортируются:
|
||||
Paper-сервер остаётся нетронутым. Git-история AstraSoups сохранена в переименованном репозитории.
|
||||
Проверочный сервер и методика: [VERIFICATION.md](VERIFICATION.md).
|
||||
|
||||
+56
-37
@@ -1,53 +1,72 @@
|
||||
# Проверка AstraSoups 0.1.3
|
||||
# Проверка AstraCauldron 0.2.0 и AstraPlus 0.5.1
|
||||
|
||||
Проверено 6 сентября 2026 года: Windows, Java 26.0.2, Paper 26.2 build 121, ItemsAdder 4.0.18 и AstraPacks 0.1.0.
|
||||
8 сентября 2026 года, Java 26.0.2 (target Java 25), Minecraft 26.2,
|
||||
NeoForge 26.2.0.79. Отдельный новый мир в `build/verification-*`, 127.0.0.1:25639.
|
||||
Рабочий мир не использовался.
|
||||
|
||||
## Результаты
|
||||
- `AstraPlus: test assemble` — успешно, 74 JUnit-теста.
|
||||
- `AstraCauldron: test assemble verificationJar` — успешно, 16 JUnit-тестов.
|
||||
- Первый запуск NeoForge: **85 проверок** — [протокол](verification/gameplay.txt).
|
||||
- Перезапуск той же JVM-конфигурации и того же мира: **9 проверок** — [протокол](verification/restart.txt).
|
||||
- Настоящие `ClientItem.CODEC` и `CuboidModel` Minecraft 26.2 прочитали все четыре
|
||||
модели из ZIP AstraPlus: оба определения предметов и обе геометрии (миска/жидкость).
|
||||
|
||||
`gradlew.bat test jar smokeJar` — успешная сборка, 13 JUnit-тестов. JAR содержит версию 0.1.3, описание модуля AstraPacks, составную модель миски и геометрию жидкости.
|
||||
Проверены нативные питание и употребление супа с возвратом миски из стака, эффекты зелий
|
||||
и еды, порядок рецепта, размеры стаков, ингредиенты AstraPlus и сохранение их регистрации
|
||||
при редактировании определения, отказ некорректной конфигурации и откат при ошибке записи.
|
||||
|
||||
119 проверок первого запуска настоящего Paper прошли. Сохранена регрессия ингредиентов, эффектов, питания, четырёх порций, движения предметов и снижения воды. Дополнительно проверены:
|
||||
Общий API AstraPlus проверен отдельно от рецепта супа: создание воды, смена RGB/высоты
|
||||
без новой сущности, защита владельца, восстановление удалённого отображения, отсутствие
|
||||
принудительной загрузки чанков, очистка и валидация параметров. Модели воды входят
|
||||
в ZIP самого AstraPlus; ресурсы миски экспортируются AstraCauldron до сборки ZIP.
|
||||
|
||||
- Модель комбинированного супа `astradev_soups:combined_soup`.
|
||||
- Совпадение цвета иконки с сохранённым RGB жидкости; разные смеси получают разные цвета.
|
||||
- Миграция старой иконки с сохранением питания и эффектов, идемпотентность нормализации.
|
||||
- Сохранение остальных списков и дополнительных цветов CustomModelData.
|
||||
- Исходные иконки ванильных супов.
|
||||
- Стакуемость одинакового рецепта при другом порядке ингредиентов, бинарная и YAML-сериализация, нативное употребление из стака с возвратом миски.
|
||||
Проверены шесть окрашиваемых видов брони (четыре кожаные части, кожаная конская, волчья),
|
||||
сохранение имён и прочности, смешивание красителей, отказ неокрашиваемой брони, неизменность
|
||||
входного предмета при вызове API. Обычные/взрывные/туманные бутылочки принимаются;
|
||||
разные зелья отклоняются без потери. Проверены возврат стекла, выдача обычной бутылочки,
|
||||
пачки стрел 17/32/64 и частичное преобразование при нехватке жидкости, нативный множитель
|
||||
длительности стрел. Чистая вода всех трёх типов бутылочек наполняет обычный водяной котёл.
|
||||
|
||||
Полный протокол первого запуска: `verification/phase1.txt`.
|
||||
После перезапуска сохранены сырые ингредиенты, готовые порции, незавершённая варка,
|
||||
зелье и цветная вода. API-визуализация восстановлена без дубликатов; последняя порция
|
||||
удаляет содержимое и поверхность. Проверки используют FakePlayer и настоящие события
|
||||
NeoForge. Проверочный JAR явно требует `-Dastracauldron.isolatedVerification=true`.
|
||||
|
||||
## Ресурспак и клиентский формат
|
||||
## Повторение
|
||||
|
||||
На изолированном сервере установлены настоящие AstraPacks, ItemsAdder и ProtocolLib. AstraPacks извлёк модуль из JAR, затем автоматически вызвал сборку после готовности ItemsAdder. В `plugins/ItemsAdder/output/generated.zip` проверены оба файла:
|
||||
Сначала собрать AstraPlus, затем AstraCauldron:
|
||||
|
||||
- `assets/astradev_soups/items/combined_soup.json` — 345 байт после сжатия JSON ItemsAdder.
|
||||
- `assets/astradev_soups/models/item/soup_liquid.json` — 1024 байта после сжатия JSON ItemsAdder.
|
||||
```powershell
|
||||
.\gradlew.bat test assemble verificationJar
|
||||
.\tools\verify-server.ps1 -Java 'C:/Program Files/Java/jdk-26.0.2/bin/java.exe'
|
||||
.\tools\check-models.ps1 -MinecraftDirectory 'C:/Users/ScarPC/AppData/Roaming/.minecraft'
|
||||
```
|
||||
|
||||
Оба JSON корректно читаются. `tools/check-models.ps1` использует настоящий клиентский JAR Minecraft 26.2 и его библиотеки: `ClientItem.CODEC` успешно разбирает составную модель и источник CustomModelData, `CuboidModel.fromStream` — геометрию жидкости и преобразования предмета. Протокол: `verification/models.txt`.
|
||||
`verify-server.ps1` создаёт уникальный каталог, запускает оба прогона и оставляет их
|
||||
логи/мир в build. Он читает только библиотеки установленного NeoForge. На рабочий
|
||||
сервер проверочный JAR не устанавливать. Лимит памяти теста — 1 ГБ.
|
||||
|
||||
Текстуры не копируются и не изменяются. Модель использует ванильную миску и белый пиксель костной муки; расположение жидкости сверено с пикселями миски из установленного клиента 26.2. Проверка отрисовки в открытом игровом клиенте не выполнялась. Замена этих ванильных текстур другим ресурспаком может изменить внешний вид.
|
||||
## Установка
|
||||
|
||||
## Методика
|
||||
Оба основных JAR установлены непосредственно в
|
||||
`C:/Users/ScarPC/Documents/NeoForge Server 26.2/mods`, SHA-256 совпали со сборками:
|
||||
|
||||
Изолированный сервер `.test-server`, адрес 127.0.0.1:25585, отдельный мир и тестовый помощник. Проверки используют настоящий ServerPlayer без сетевого клиента, обработчики Bukkit и нативное употребление. Перед первым прогоном помощник ожидает готовности реестра ItemsAdder и появления собранного ZIP; первоначальный преждевременный запуск во время загрузки библиотек был исправлен в помощнике и повторён успешно. Задержка второго прогона остаётся 40 тиков для проверки незавершённой варки после перезапуска.
|
||||
- AstraPlus-0.5.1.jar: `C47953465AFCE4A5DEA64E9F44F48D9E4D18160156477A12CC7465E662C51B16`.
|
||||
- AstraCauldron-0.2.0.jar: `0F5149CAE4BD32D09D37A30155CC445650C639084D8B37C32509F525ECD6A7F5`.
|
||||
|
||||
Тестовый помощник нельзя устанавливать на рабочий сервер: он изменяет мир и останавливает сервер. Изменения рабочего сервера ограничиваются JAR AstraSoups; конфигурации, миры и данные не заменяются.
|
||||
Старый AstraPlus-0.5.0.jar сохранён в
|
||||
`C:/Users/ScarPC/Documents/NeoForge Server 26.2/old-mods/20260908-193718/`.
|
||||
AstraCauldron/AstraSoups на этом NeoForge-сервере ранее не стоял. AstraPacks и AstraSpears
|
||||
остались в mods. Рабочие конфигурации, миры и Paper-сервер не изменялись.
|
||||
Для загрузки новых JAR нужен запуск/перезапуск рабочего сервера и актуальный ресурспак.
|
||||
|
||||
## Сборка
|
||||
Открытый игровой клиент и реальная отрисовка не проверялись. Проверка формата моделей
|
||||
не заменяет визуальное подтверждение текстуры/освещения. Работа ZIP и API проверена
|
||||
с самостоятельным AstraPlus, без активной доставки AstraPacks. Сохранения Bukkit-YAML
|
||||
не мигрировались. Старые Paper-протоколы заменены актуальными NeoForge-проверками;
|
||||
их история остаётся в Git.
|
||||
|
||||
`build/libs/AstraSoups-0.1.3.jar`
|
||||
|
||||
SHA-256: `F2F8369178C64B6595A6B8C7092E334363D0C0F6689954451817001E3A6E4336`.
|
||||
|
||||
После реального перезапуска JVM прошли все 12 проверок сохранённых порций, сырого ингредиента и незавершённой варки: `verification/phase2.txt`.
|
||||
|
||||
## Установка на рабочий сервер
|
||||
|
||||
6 сентября 2026 года по разрешению пользователя выполнена штатная остановка Bukkit. Журнал подтвердил сохранение всех миров и завершение ввода-вывода. Проверенный JAR установлен непосредственно в `C:/Users/ScarPC/Documents/26.2 Paper/plugins/AstraSoups-0.1.3.jar`; SHA-256 установленного файла совпадает со сборкой.
|
||||
|
||||
Старая версия сохранена в `C:/Users/ScarPC/Documents/26.2 Paper/old-plugins/20260906-115706-AstraSoups/AstraSoups-0.1.2.jar`. Конфигурации, миры и данные плагинов вручную не заменялись.
|
||||
|
||||
Сервер повторно запущен: журнал подтверждает включение AstraSoups 0.1.3, восстановление одного котла и готовность Paper. Первая сборка общего пака столкнулась с AccessDeniedException при замене generated.zip; после повторного штатного вызова ItemsAdder /iazip сборка завершилась. В 11:59:55 AstraPacks подтвердил готовность 9 модулей, файл pending удалён; ItemsAdder сообщил об отправке пака одному подключённому игроку.
|
||||
|
||||
После подтверждения публикации обе JSON-модели astradev_soups прочитаны из защищённого ZIP через Java ZipFile и повторно проверены настоящими десериализаторами клиента Minecraft 26.2. Проверки файлов опубликованного пакета прошли. Во время сборки ZIP не следует открывать средствами .NET без разрешения FileShare.Delete: это может блокировать замену файла на Windows.
|
||||
После финальной нормализации окончаний строк JAR повторно установлен; промежуточная
|
||||
сборка AstraCauldron этой задачи сохранена в "old-mods/20260908-194159/".
|
||||
Побайтово проверено: все классы совпадают с протестированной сборкой; различаются
|
||||
только окончания строк и пустые строки в конце трёх файлов ресурсов.
|
||||
|
||||
+34
-19
@@ -1,28 +1,43 @@
|
||||
plugins { java }
|
||||
group = "online.astradev"
|
||||
version = "0.1.3"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.papermc.io/repository/maven-public/") }
|
||||
plugins {
|
||||
java
|
||||
id("net.neoforged.moddev") version "2.0.146"
|
||||
}
|
||||
group = "online.astradev"
|
||||
version = "0.2.0"
|
||||
repositories { mavenCentral() }
|
||||
val astraPlusApi = providers.gradleProperty("astraPlusApi")
|
||||
.orElse("../AstraPlus/build/libs/AstraPlus-0.5.1-api.jar")
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:26.2.build.121-stable")
|
||||
testImplementation("io.papermc.paper:paper-api:26.2.build.121-stable")
|
||||
compileOnly(files(astraPlusApi))
|
||||
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) }
|
||||
neoForge {
|
||||
version = "26.2.0.79"
|
||||
mods { create("astracauldron") { sourceSet(sourceSets.main.get()) } }
|
||||
}
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||
withSourcesJar()
|
||||
}
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.encoding = "UTF-8"
|
||||
options.release.set(25)
|
||||
}
|
||||
tasks.processResources {
|
||||
inputs.property("pluginVersion", project.version)
|
||||
filesMatching("plugin.yml") { expand("version" to project.version) }
|
||||
inputs.property("modVersion", project.version)
|
||||
filesMatching("META-INF/neoforge.mods.toml") { 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") }
|
||||
sourceSets.test {
|
||||
compileClasspath += sourceSets.main.get().compileClasspath
|
||||
runtimeClasspath += sourceSets.main.get().compileClasspath
|
||||
}
|
||||
val verification = sourceSets.create("verification") {
|
||||
compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath
|
||||
runtimeClasspath += output + compileClasspath
|
||||
}
|
||||
tasks.register<Jar>("verificationJar") {
|
||||
from(verification.output)
|
||||
archiveClassifier.set("verification")
|
||||
}
|
||||
tasks.register<Jar>("smokeJar") { archiveFileName.set("SoupSmokeTest.jar"); from(smoke.output) }
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+10
@@ -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
|
||||
@@ -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" "$@"
|
||||
Vendored
+74
-28
@@ -1,36 +1,82 @@
|
||||
@echo off
|
||||
@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 "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"
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
if exist "%GRADLE_BAT%" goto run
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
if not exist "%DIST_ROOT%" mkdir "%DIST_ROOT%"
|
||||
@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"
|
||||
|
||||
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
|
||||
)
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
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
|
||||
)
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
del /q "%DIST_ZIP%" >nul 2>&1
|
||||
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
|
||||
|
||||
:run
|
||||
call "%GRADLE_BAT%" -p "%APP_HOME%" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
"%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%
|
||||
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
rootProject.name = "AstraSoups"
|
||||
plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" }
|
||||
rootProject.name = "AstraCauldron"
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.mojang.brigadier.arguments.*;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.util.TriState;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.level.*;
|
||||
import net.neoforged.neoforge.event.server.*;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import org.slf4j.*;
|
||||
|
||||
@Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER)
|
||||
public final class AstraCauldron {
|
||||
static final Logger LOG = LoggerFactory.getLogger("AstraCauldron");
|
||||
private static SoupPots pots;
|
||||
private static LiquidPots liquids;
|
||||
public AstraCauldron() {
|
||||
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
|
||||
NeoForge.EVENT_BUS.addListener(this::start);
|
||||
NeoForge.EVENT_BUS.addListener(this::stop);
|
||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::interact);
|
||||
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::breakBlock);
|
||||
NeoForge.EVENT_BUS.addListener(this::explosion);
|
||||
NeoForge.EVENT_BUS.addListener(this::piston);
|
||||
NeoForge.EVENT_BUS.addListener(this::unload);
|
||||
NeoForge.EVENT_BUS.addListener(this::join);
|
||||
NeoForge.EVENT_BUS.addListener(this::commands);
|
||||
}
|
||||
private void resources(ServerAboutToStartEvent event) {
|
||||
try { SoupResources.install(FMLPaths.GAMEDIR.get()); }
|
||||
catch (Exception e) { throw new IllegalStateException("Cannot export AstraCauldron resources", e); }
|
||||
}
|
||||
private void start(ServerStartedEvent event) {
|
||||
try {
|
||||
online.astradev.plus.api.AstraPlusApi.current().orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
|
||||
pots = new SoupPots(event.getServer(), FMLPaths.CONFIGDIR.get().resolve("astracauldron.json"));
|
||||
liquids = new LiquidPots(event.getServer());
|
||||
LOG.info("AstraCauldron ready: NeoForge 26.2, AstraPlus API");
|
||||
} catch (Exception e) { throw new IllegalStateException("Cannot initialize AstraCauldron; existing data preserved", e); }
|
||||
}
|
||||
private void stop(ServerStoppingEvent event) { if (pots != null) pots.close(); if (liquids != null) liquids.close(); pots = null; liquids = null; }
|
||||
private void tick(ServerTickEvent.Post event) { if (pots != null) pots.tick(); if (liquids != null) liquids.tick(); }
|
||||
public static SoupPots pots() { return pots; }
|
||||
public static LiquidPots liquids() { return liquids; }
|
||||
public static boolean occupied(Level level, BlockPos pos) {
|
||||
return level instanceof ServerLevel serverLevel && ((pots != null && pots.contains(serverLevel, pos))
|
||||
|| (liquids != null && liquids.contains(serverLevel,pos)));
|
||||
}
|
||||
private void interact(PlayerInteractEvent.RightClickBlock event) {
|
||||
if (pots == null || event.isCanceled() || event.getUseBlock() == TriState.FALSE || event.getUseItem() == TriState.FALSE) return;
|
||||
if (event.getEntity() instanceof ServerPlayer player && ((!pots.contains(player.level(),event.getPos()) && liquids != null
|
||||
&& liquids.interact(player,event.getPos(),event.getHand())) || pots.interact(player, event.getPos(), event.getHand()))) {
|
||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
private void breakBlock(net.neoforged.neoforge.event.level.block.BreakBlockEvent event) {
|
||||
if (!event.isCanceled() && pots != null && event.getLevel() instanceof ServerLevel level
|
||||
&& (!pots.breakPot(level, event.getPos()) || (liquids != null && !liquids.breakPot(level,event.getPos())))) { event.setCanceled(true); event.setNotifyClient(true); }
|
||||
}
|
||||
private void explosion(ExplosionEvent.Detonate event) {
|
||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||
event.getAffectedBlocks().removeIf(pos -> occupied(level, pos));
|
||||
}
|
||||
private void piston(PistonEvent.Pre event) {
|
||||
if (pots == null || event.isCanceled() || !(event.getLevel() instanceof ServerLevel level)) return;
|
||||
var resolver = event.getStructureHelper();
|
||||
if (resolver != null && resolver.resolve() && (resolver.getToPush().stream().anyMatch(p -> occupied(level, p))
|
||||
|| resolver.getToDestroy().stream().anyMatch(p -> occupied(level, p)))) event.setCanceled(true);
|
||||
}
|
||||
private void unload(ChunkEvent.Unload event) {
|
||||
if (pots != null && event.getLevel() instanceof ServerLevel level)
|
||||
pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z());
|
||||
}
|
||||
private void join(EntityJoinLevelEvent event) {
|
||||
if (event.loadedFromDisk() && event.getEntity().entityTags().contains(SoupDisplay.TAG)) event.setCanceled(true);
|
||||
else if (event.getEntity() instanceof ItemEntity item) Ingredients.normalize(item.getItem());
|
||||
}
|
||||
private void commands(RegisterCommandsEvent event) {
|
||||
var command = Commands.literal("cauldron").executes(c -> {
|
||||
c.getSource().sendSuccess(() -> Component.literal("Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и стрелы с эффектом. Еда/зелья + полный котёл воды: 4 ингредиента супа, Shift+ПКМ — варка, миска — порция."), false); return 1;
|
||||
});
|
||||
command.then(Commands.literal("reload").requires(Commands.hasPermission(Commands.LEVEL_ADMINS)).executes(c -> {
|
||||
try { requirePots().reload(); c.getSource().sendSuccess(() -> Component.literal("AstraCauldron: настройки применены."), true); return 1; }
|
||||
catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка: " + e.getMessage() + ". Прежние настройки сохранены.")); return 0; }
|
||||
}));
|
||||
command.then(Commands.literal("register").requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.then(Commands.argument("id", StringArgumentType.word()).then(Commands.argument("nutrition", IntegerArgumentType.integer(0))
|
||||
.then(Commands.argument("saturation", FloatArgumentType.floatArg(0)).executes(c -> {
|
||||
try {
|
||||
requirePots().register(StringArgumentType.getString(c, "id"), c.getSource().getPlayerOrException(),
|
||||
IntegerArgumentType.getInteger(c, "nutrition"), FloatArgumentType.getFloat(c, "saturation"));
|
||||
c.getSource().sendSuccess(() -> Component.literal("Ингредиент зарегистрирован."), true); return 1;
|
||||
} catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка регистрации: " + e.getMessage())); return 0; }
|
||||
})))));
|
||||
var root = event.getDispatcher().register(command);
|
||||
event.getDispatcher().register(Commands.literal("soups").redirect(root).executes(root.getCommand()));
|
||||
}
|
||||
private static SoupPots requirePots() { if (pots == null) throw new IllegalStateException("AstraCauldron ещё не запущен"); return pots; }
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */
|
||||
public final class CauldronAnimation {
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -0,0 +1,41 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
|
||||
|
||||
|
||||
final class IngredientColors {
|
||||
private IngredientColors() {}
|
||||
|
||||
static int food(String material, int fallback) {
|
||||
int rgb =
|
||||
switch (material) {
|
||||
case "spider_eye", "fermented_spider_eye" -> 0xB52B38;
|
||||
case "golden_apple", "enchanted_golden_apple", "golden_carrot" -> 0xF2C94C;
|
||||
case "apple", "sweet_berries" -> 0xC73735;
|
||||
case "beetroot", "beetroot_soup" -> 0xA52B4B;
|
||||
case "carrot", "pumpkin_pie", "glow_berries" -> 0xE99032;
|
||||
case "dried_kelp" -> 0x47733B;
|
||||
case "poisonous_potato" -> 0x91A340;
|
||||
case "melon_slice" -> 0xD94E58;
|
||||
case "chorus_fruit" -> 0x9C6C9D;
|
||||
case "beef", "mutton", "porkchop", "rabbit" -> 0xC76B70;
|
||||
case "chicken" -> 0xE2A6A0;
|
||||
case "cooked_beef", "cooked_mutton" -> 0x815033;
|
||||
case "cooked_porkchop", "cooked_rabbit", "cooked_chicken" -> 0xBA8551;
|
||||
case "salmon", "cooked_salmon", "tropical_fish" -> 0xD98262;
|
||||
case "cod" -> 0xB0A07B;
|
||||
case "cooked_cod" -> 0xC4B486;
|
||||
case "pufferfish" -> 0xD3B54D;
|
||||
case "bread", "cookie", "baked_potato" -> 0xBA873F;
|
||||
case "potato" -> 0xC7A76B;
|
||||
case "rotten_flesh" -> 0x8F6540;
|
||||
case "honey_bottle" -> 0xE9AC32;
|
||||
case "cake" -> 0xE8CCBA;
|
||||
case "mushroom_stew" -> 0xA37A53;
|
||||
case "rabbit_stew" -> 0xAC8854;
|
||||
case "suspicious_stew" -> 0x867743;
|
||||
default -> fallback;
|
||||
};
|
||||
return rgb;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.effect.MobEffectInstance;
|
||||
import net.minecraft.world.food.FoodProperties;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.component.*;
|
||||
import net.minecraft.world.item.consume_effects.*;
|
||||
import online.astradev.plus.api.AstraPlusApi;
|
||||
|
||||
public final class Ingredients {
|
||||
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, int color) {}
|
||||
private record Custom(String id, ItemStack sample, SoupConfig.Custom definition, List<MobEffectInstance> effects) {}
|
||||
private final SoupConfig config;
|
||||
private final HolderLookup.Provider registries;
|
||||
private final List<Custom> custom = new ArrayList<>();
|
||||
public Ingredients(SoupConfig config, HolderLookup.Provider registries) {
|
||||
config.validate();
|
||||
this.config = config;
|
||||
this.registries = registries;
|
||||
for (var entry : config.customIngredients.entrySet()) {
|
||||
var c = entry.getValue();
|
||||
ItemStack sample = c.item == null ? ItemStack.EMPTY : SoupFiles.decode(c.item, registries);
|
||||
if (c.item != null && (sample.isEmpty() || sample.getCount() != 1))
|
||||
throw new IllegalArgumentException("Некорректный образец " + entry.getKey());
|
||||
normalize(sample);
|
||||
List<MobEffectInstance> effects = new ArrayList<>();
|
||||
for (var e : c.effects) {
|
||||
var type = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(e.type)).orElseThrow();
|
||||
effects.add(new MobEffectInstance(type, e.duration, e.amplifier));
|
||||
}
|
||||
custom.add(new Custom(entry.getKey(), sample, c, List.copyOf(effects)));
|
||||
}
|
||||
}
|
||||
public Ingredient read(ItemStack stack) {
|
||||
if (stack.isEmpty()) return null;
|
||||
var plus = AstraPlusApi.current().flatMap(api -> api.find(stack));
|
||||
Custom match = custom.stream().filter(c -> c.definition.astraPlusId != null
|
||||
? plus.map(p -> p.id().toString().equals(c.definition.astraPlusId)).orElse(false)
|
||||
: ItemStack.isSameItemSameComponents(c.sample, normalizedCopy(stack))).findFirst().orElse(null);
|
||||
var food = stack.get(DataComponents.FOOD);
|
||||
boolean potion = stack.is(Items.POTION) || stack.is(Items.SPLASH_POTION) || stack.is(Items.LINGERING_POTION);
|
||||
boolean cake = stack.is(Items.CAKE);
|
||||
if (food == null && !potion && !cake && match == null) return null;
|
||||
int nutrition = food == null ? (cake ? 14 : 0) : food.nutrition();
|
||||
float saturation = food == null ? (cake ? 2.8f : 0) : food.saturation();
|
||||
var effects = new ArrayList<ConsumeEffect>();
|
||||
var consumable = stack.get(DataComponents.CONSUMABLE);
|
||||
if (consumable != null) effects.addAll(consumable.onConsumeEffects());
|
||||
String material = BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath();
|
||||
int color = IngredientColors.food(material, SoupConfig.rgb(config.defaultColor));
|
||||
if (isCombined(stack)) color = color(stack);
|
||||
var contents = stack.get(DataComponents.POTION_CONTENTS);
|
||||
if (potion && contents != null) {
|
||||
List<MobEffectInstance> potionEffects = new ArrayList<>();
|
||||
contents.forEachEffect(potionEffects::add, stack.transmuteCopy(Items.POTION, 1).getOrDefault(DataComponents.POTION_DURATION_SCALE, 1f));
|
||||
if (!potionEffects.isEmpty()) effects.add(new ApplyStatusEffectsConsumeEffect(potionEffects));
|
||||
color = contents.getColor() & 0xFFFFFF;
|
||||
}
|
||||
var stew = stack.get(DataComponents.SUSPICIOUS_STEW_EFFECTS);
|
||||
if (stew != null && !stew.effects().isEmpty())
|
||||
effects.add(new ApplyStatusEffectsConsumeEffect(stew.effects().stream().map(SuspiciousStewEffects.Entry::createEffectInstance).toList()));
|
||||
Set<String> tags = new HashSet<>();
|
||||
tags.add("material:" + material);
|
||||
if (isCombined(stack)) tags.add("soup:combined");
|
||||
plus.ifPresent(p -> tags.add("astraplus:" + p.id()));
|
||||
if (match != null) {
|
||||
nutrition = match.definition.nutrition;
|
||||
saturation = match.definition.saturation;
|
||||
if (match.definition.color != null) color = SoupConfig.rgb(match.definition.color);
|
||||
if (!match.effects.isEmpty()) effects.add(new ApplyStatusEffectsConsumeEffect(match.effects));
|
||||
tags.add("custom:" + match.id);
|
||||
}
|
||||
for (var effect : effects) if (effect instanceof ApplyStatusEffectsConsumeEffect apply)
|
||||
for (var e : apply.effects()) tags.add("effect:" + BuiltInRegistries.MOB_EFFECT.getKey(e.getEffect().value()));
|
||||
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
|
||||
}
|
||||
public String rejection(List<ItemStack> items) {
|
||||
var data = items.stream().map(this::read).toList();
|
||||
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
|
||||
String error = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), config.blockedIngredients, config.incompatible);
|
||||
if (error != null) return error;
|
||||
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
|
||||
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
|
||||
if (nutrition < 0 || nutrition > config.maxNutrition || !Double.isFinite(saturation)
|
||||
|| saturation < 0 || saturation > config.maxSaturation) 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);
|
||||
var data = items.stream().map(Ingredients::normalizedCopy)
|
||||
.sorted(Comparator.comparing(s -> SoupFiles.encode(s, registries).toString())).map(this::read).toList();
|
||||
int nutrition = data.stream().mapToInt(Ingredient::nutrition).sum();
|
||||
float saturation = (float) data.stream().mapToDouble(Ingredient::saturation).sum();
|
||||
var effects = data.stream().flatMap(i -> i.effects.stream()).toList();
|
||||
int rgb = averageColor(data.stream().mapToInt(Ingredient::color).toArray());
|
||||
var soup = new ItemStack(Items.MUSHROOM_STEW);
|
||||
CustomData.update(DataComponents.CUSTOM_DATA, soup, tag -> {
|
||||
tag.putBoolean("astracauldron:combined_soup", true);
|
||||
tag.putInt("astracauldron:soup_color", rgb);
|
||||
});
|
||||
soup.set(DataComponents.CUSTOM_NAME, Component.literal(config.soupName).withStyle(s -> s.withColor(rgb).withItalic(false)));
|
||||
soup.set(DataComponents.FOOD, new FoodProperties(nutrition, saturation, true));
|
||||
var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE));
|
||||
soup.set(DataComponents.CONSUMABLE, new Consumable(base.consumeSeconds(), base.animation(), base.sound(), base.hasConsumeParticles(), effects));
|
||||
soup.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
|
||||
normalize(soup);
|
||||
return soup;
|
||||
}
|
||||
static int averageColor(int[] colors) {
|
||||
int r = 0, g = 0, b = 0;
|
||||
for (int c : colors) { r += (c >> 16) & 255; g += (c >> 8) & 255; b += c & 255; }
|
||||
return ((r / colors.length) << 16) | ((g / colors.length) << 8) | (b / colors.length);
|
||||
}
|
||||
public static boolean isCombined(ItemStack stack) {
|
||||
return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag().getBooleanOr("astracauldron:combined_soup", false);
|
||||
}
|
||||
public static int color(ItemStack stack) {
|
||||
return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag().getIntOr("astracauldron:soup_color", 0xB77A36) & 0xFFFFFF;
|
||||
}
|
||||
static ItemStack normalizedCopy(ItemStack stack) {
|
||||
var copy = stack.copyWithCount(1); normalize(copy); return copy;
|
||||
}
|
||||
public static void normalize(ItemStack stack) {
|
||||
if (!(stack.is(Items.MUSHROOM_STEW) || stack.is(Items.RABBIT_STEW) || stack.is(Items.BEETROOT_SOUP) || stack.is(Items.SUSPICIOUS_STEW))) return;
|
||||
stack.set(DataComponents.MAX_STACK_SIZE, 16);
|
||||
if (!isCombined(stack)) return;
|
||||
stack.set(DataComponents.ITEM_MODEL, Identifier.parse("astradev_soups:combined_soup"));
|
||||
var data = stack.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.EMPTY);
|
||||
var colors = new ArrayList<>(data.colors());
|
||||
if (colors.isEmpty()) colors.add(color(stack)); else colors.set(0, color(stack));
|
||||
stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(data.floats(), data.flags(), data.strings(), colors));
|
||||
var food = stack.get(DataComponents.FOOD);
|
||||
var consumable = stack.get(DataComponents.CONSUMABLE);
|
||||
if (food != null && consumable != null) stack.set(DataComponents.LORE, new ItemLore(lore(food, consumable.onConsumeEffects())));
|
||||
}
|
||||
private static List<Component> lore(FoodProperties food, List<ConsumeEffect> effects) {
|
||||
var lines = new ArrayList<Component>();
|
||||
lines.add(line("Голод: +" + food.nutrition(), ChatFormatting.YELLOW));
|
||||
lines.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", food.saturation()), ChatFormatting.GOLD));
|
||||
for (var effect : effects) {
|
||||
if (effect instanceof ApplyStatusEffectsConsumeEffect apply) for (var e : apply.effects()) {
|
||||
String duration = e.isInfiniteDuration() ? "∞" : String.format(Locale.ROOT, "%d:%02d", e.getDuration() / 1200, (e.getDuration() / 20) % 60);
|
||||
lines.add(Component.translatable(e.getDescriptionId()).append(" " + SoupText.roman(e.getAmplifier() + 1) + " (" + duration + ")"
|
||||
+ (apply.probability() < 1 ? " " + Math.round(apply.probability() * 100) + "%" : ""))
|
||||
.withStyle(s -> s.withColor(ChatFormatting.AQUA).withItalic(false)));
|
||||
} else lines.add(line(effect instanceof TeleportRandomlyConsumeEffect ? "Случайная телепортация"
|
||||
: effect instanceof ClearAllStatusEffectsConsumeEffect ? "Снятие всех эффектов"
|
||||
: effect instanceof RemoveStatusEffectsConsumeEffect ? "Снятие эффектов" : "Звук при употреблении", ChatFormatting.GRAY));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
private static Component line(String text, ChatFormatting color) {
|
||||
return Component.literal(text).withStyle(s -> s.withColor(color).withItalic(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.*;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.*;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.alchemy.Potions;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import online.astradev.plus.api.*;
|
||||
|
||||
/** Persistent dyed water and potion storage; all item transformations and rendering use AstraPlus API. */
|
||||
public final class LiquidPots implements AutoCloseable {
|
||||
private record Position(String dimension, BlockPos pos) {
|
||||
static Position at(ServerLevel level, BlockPos pos) { return new Position(level.dimension().identifier().toString(), pos.immutable()); }
|
||||
}
|
||||
public record Liquid(int levels, int rgb, CauldronApi.Potion potion) {
|
||||
public Liquid {
|
||||
if (levels < 1 || levels > 3 || rgb < 0 || rgb > 0xFFFFFF) throw new IllegalArgumentException("Invalid liquid");
|
||||
}
|
||||
Liquid withLevels(int value) { return new Liquid(value, rgb, potion); }
|
||||
}
|
||||
private static final Identifier OWNER = Identifier.parse("astracauldron:liquids");
|
||||
private final MinecraftServer server;
|
||||
private final CauldronApi api;
|
||||
private final Path file;
|
||||
private final Map<Position, Liquid> liquids = new LinkedHashMap<>();
|
||||
public LiquidPots(MinecraftServer server) throws IOException {
|
||||
this.server = server;
|
||||
api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
|
||||
file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json");
|
||||
if (Files.exists(file)) {
|
||||
var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
|
||||
if (json.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown liquid data version");
|
||||
for (var entry : json.getAsJsonArray("cauldrons")) {
|
||||
var c = entry.getAsJsonObject();
|
||||
var pos = new Position(Identifier.parse(c.get("dimension").getAsString()).toString(), new BlockPos(c.get("x").getAsInt(), c.get("y").getAsInt(), c.get("z").getAsInt()));
|
||||
CauldronApi.Potion potion = c.has("potion") ? api.potion(SoupFiles.decode(c.get("potion"), server.registryAccess())).orElseThrow() : null;
|
||||
var liquid = new Liquid(c.get("levels").getAsInt(), c.get("rgb").getAsInt(), potion);
|
||||
if (liquids.putIfAbsent(pos, liquid) != null) throw new IllegalArgumentException("Duplicate liquid cauldron");
|
||||
}
|
||||
}
|
||||
}
|
||||
public Liquid get(ServerLevel level, BlockPos pos) { return liquids.get(Position.at(level, pos)); }
|
||||
public boolean contains(ServerLevel level, BlockPos pos) { return get(level, pos) != null; }
|
||||
private boolean change(Position pos, Liquid next) {
|
||||
var old = liquids.get(pos);
|
||||
if (next == null) liquids.remove(pos); else liquids.put(pos, next);
|
||||
try {
|
||||
var root = new JsonObject(); root.addProperty("version", 1); var array = new JsonArray(); root.add("cauldrons", array);
|
||||
for (var entry : liquids.entrySet()) {
|
||||
var p = entry.getKey(); var liquid = entry.getValue(); var c = new JsonObject();
|
||||
c.addProperty("dimension", p.dimension); c.addProperty("x", p.pos.getX()); c.addProperty("y", p.pos.getY()); c.addProperty("z", p.pos.getZ());
|
||||
c.addProperty("levels", liquid.levels); c.addProperty("rgb", liquid.rgb);
|
||||
if (liquid.potion != null) c.add("potion", SoupFiles.encode(api.bottle(liquid.potion), server.registryAccess()));
|
||||
array.add(c);
|
||||
}
|
||||
SoupFiles.write(file, root);
|
||||
if (next == null) removeSurface(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) liquids.remove(pos); else liquids.put(pos, old);
|
||||
AstraCauldron.LOG.error("Не удалось сохранить жидкость; действие отменено", e); return false;
|
||||
}
|
||||
}
|
||||
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
|
||||
if (player.isSpectator()) return false;
|
||||
var level = player.level(); var pos = Position.at(level, blockPos); var liquid = liquids.get(pos);
|
||||
if (hand != InteractionHand.MAIN_HAND) return liquid != null;
|
||||
var state = level.getBlockState(blockPos); var held = player.getMainHandItem();
|
||||
if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false;
|
||||
var potion = api.potion(held);
|
||||
if (liquid == null) {
|
||||
if (potion.isPresent() && plainWater(potion.get())) {
|
||||
int current = state.is(Blocks.WATER_CAULDRON) ? state.getValue(LayeredCauldronBlock.LEVEL) : 0;
|
||||
if (current < 3) {
|
||||
level.setBlock(blockPos,Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,current+1),3);
|
||||
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
var dye = api.mixDye(OptionalInt.empty(), held);
|
||||
if (state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) {
|
||||
var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
|
||||
if (!change(pos, next)) { error(player); return true; }
|
||||
held.consume(1, player); setVisual(level, pos, next);
|
||||
say(player, "Вода окрашена. Добавьте краситель для смешивания или окуните кожаную броню."); return true;
|
||||
}
|
||||
if (state.is(Blocks.CAULDRON) && potion.isPresent()) {
|
||||
var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get());
|
||||
if (!change(pos, next)) { error(player); return true; }
|
||||
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); setVisual(level, pos, next);
|
||||
say(player, "Зелье налито: 1/3. Бутылочка — забрать, стрелы — обработать."); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (liquid.potion == null) {
|
||||
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
|
||||
if (dye.isPresent()) {
|
||||
var next = new Liquid(liquid.levels, dye.getAsInt(), null);
|
||||
if (!change(pos, next)) { error(player); return true; }
|
||||
held.consume(1, player); setVisual(level,pos,next); return true;
|
||||
}
|
||||
var armor = api.dyeArmor(held, liquid.rgb);
|
||||
if (armor.isPresent()) {
|
||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
||||
// Transform the equipped item, including Creative, preserving enchantments/damage/name.
|
||||
if (held.getCount() == 1) player.setItemInHand(hand, armor.get()); else consumeAndGive(player,1,armor.get());
|
||||
sound(level,blockPos); say(player,"Броня окрашена. Израсходован один уровень воды."); return true;
|
||||
}
|
||||
if (held.is(Items.WATER_BUCKET)) {
|
||||
if (!change(pos,null)) { error(player); return true; }
|
||||
level.setBlock(blockPos, Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,3),3);
|
||||
consumeAndGive(player,1,new ItemStack(Items.BUCKET)); return true;
|
||||
}
|
||||
if (held.is(Items.BUCKET) && liquid.levels == 3) {
|
||||
if (!decrease(level,pos,liquid,3)) { error(player); return true; }
|
||||
consumeAndGive(player,1,new ItemStack(Items.WATER_BUCKET)); return true;
|
||||
}
|
||||
if (held.is(Items.GLASS_BOTTLE)) {
|
||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
||||
consumeAndGive(player,1,api.bottle(new CauldronApi.Potion(new net.minecraft.world.item.alchemy.PotionContents(Potions.WATER),1))); return true;
|
||||
}
|
||||
say(player,"Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода."); return true;
|
||||
}
|
||||
if (potion.isPresent()) {
|
||||
if (!potion.get().equals(liquid.potion)) { say(player,"В котле другое зелье. Сначала заберите его бутылочками."); return true; }
|
||||
if (liquid.levels == 3) { say(player,"Котёл уже полон."); return true; }
|
||||
var next = liquid.withLevels(liquid.levels + 1);
|
||||
if (!change(pos,next)) { error(player); return true; }
|
||||
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE)); setVisual(level,pos,next); return true;
|
||||
}
|
||||
if (held.is(Items.GLASS_BOTTLE)) {
|
||||
var bottle = api.bottle(liquid.potion);
|
||||
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
|
||||
consumeAndGive(player,1,bottle); sound(level,blockPos); return true;
|
||||
}
|
||||
var arrows = api.tipArrows(held,liquid.potion,liquid.levels);
|
||||
if (arrows.isPresent()) {
|
||||
var batch = arrows.get(); var result = batch.result();
|
||||
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
|
||||
int count = result.getCount();
|
||||
consumeAndGive(player,count,result); sound(level,blockPos);
|
||||
say(player,"Обработано стрел: " + count + "."); return true;
|
||||
}
|
||||
say(player,"Зелье: " + liquid.levels + "/3. Окуните обычные стрелы или наберите бутылочку."); return true;
|
||||
}
|
||||
private boolean decrease(ServerLevel level, Position pos, Liquid old, int used) {
|
||||
int remaining = old.levels - used; var next = remaining == 0 ? null : old.withLevels(remaining);
|
||||
if (!change(pos,next)) return false;
|
||||
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3);
|
||||
if (next != null) setVisual(level,pos,next); return true;
|
||||
}
|
||||
private static boolean plainWater(CauldronApi.Potion potion) {
|
||||
var contents = potion.contents();
|
||||
return contents.is(Potions.WATER) && contents.customColor().isEmpty() && contents.customName().isEmpty() && potion.durationScale()==1f;
|
||||
}
|
||||
public boolean breakPot(ServerLevel level,BlockPos pos) { var position = Position.at(level,pos); return !liquids.containsKey(position) || change(position,null); }
|
||||
public void tick() {
|
||||
for (var entry : new ArrayList<>(liquids.entrySet())) {
|
||||
var pos=entry.getKey(); var level=level(pos);
|
||||
if (level==null || !level.hasChunkAt(pos.pos)) continue;
|
||||
if (!level.getBlockState(pos.pos).is(Blocks.CAULDRON)) { change(pos,null); continue; }
|
||||
surface(level,pos,entry.getValue());
|
||||
}
|
||||
}
|
||||
private void setVisual(ServerLevel level,Position pos,Liquid liquid) {
|
||||
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3); surface(level,pos,liquid);
|
||||
}
|
||||
private void surface(ServerLevel level,Position pos,Liquid liquid) {
|
||||
api.water().show(level,pos.pos,new ColoredWaterApi.Surface(OWNER,liquid.rgb,.375f+.1875f*liquid.levels));
|
||||
}
|
||||
private ServerLevel level(Position pos) { return server.getLevel(ResourceKey.create(Registries.DIMENSION,Identifier.parse(pos.dimension))); }
|
||||
private void removeSurface(Position pos) { var level=level(pos); if(level!=null) api.water().remove(level,pos.pos,OWNER); }
|
||||
@Override public void close() { api.water().removeAll(OWNER); }
|
||||
private static void consumeAndGive(ServerPlayer player,int count,ItemStack result) {
|
||||
player.getMainHandItem().consume(count,player);
|
||||
player.getInventory().add(result); if(!result.isEmpty()) player.drop(result,false);
|
||||
player.containerMenu.broadcastChanges();
|
||||
}
|
||||
private static void sound(ServerLevel level,BlockPos pos) { level.playSound(null,pos,SoundEvents.BOTTLE_FILL,SoundSource.BLOCKS,.8f,1); }
|
||||
private static void say(ServerPlayer player,String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD),true); }
|
||||
private static void error(ServerPlayer player) { say(player,"Не удалось сохранить котёл. Действие отменено."); }
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
public final class SoupConfig {
|
||||
public int servingsPerBrew = 4;
|
||||
public boolean requireFullWater = true;
|
||||
public double brewSeconds = 4;
|
||||
public String soupName = "Комбинированный суп";
|
||||
public String defaultColor = "#B77A36";
|
||||
public int maxNutrition = 1000;
|
||||
public float maxSaturation = 1000;
|
||||
public List<String> blockedIngredients = new ArrayList<>();
|
||||
public List<List<String>> incompatible = new ArrayList<>();
|
||||
public Map<String, Custom> customIngredients = new LinkedHashMap<>();
|
||||
public static final class Custom {
|
||||
public JsonElement item;
|
||||
public String astraPlusId;
|
||||
public int nutrition;
|
||||
public float saturation;
|
||||
public String color;
|
||||
public List<Effect> effects = new ArrayList<>();
|
||||
}
|
||||
public static final class Effect {
|
||||
public String type;
|
||||
public int duration;
|
||||
public int amplifier;
|
||||
}
|
||||
public static SoupConfig load(Path file) throws IOException {
|
||||
SoupConfig config = Files.exists(file)
|
||||
? SoupFiles.JSON.fromJson(Files.readString(file), SoupConfig.class) : new SoupConfig();
|
||||
if (config == null) throw new IllegalArgumentException("Пустая конфигурация");
|
||||
config.validate();
|
||||
if (!Files.exists(file)) SoupFiles.write(file, SoupFiles.JSON.toJsonTree(config));
|
||||
return config;
|
||||
}
|
||||
public void validate() {
|
||||
if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds)
|
||||
|| brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0
|
||||
|| !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank())
|
||||
throw new IllegalArgumentException("Некорректные настройки варки/питания");
|
||||
rgb(defaultColor);
|
||||
if (blockedIngredients == null || incompatible == null || customIngredients == null)
|
||||
throw new IllegalArgumentException("Списки настроек не могут быть null");
|
||||
blockedIngredients.forEach(SoupConfig::selector);
|
||||
for (var pair : incompatible) {
|
||||
if (pair == null || pair.size() != 2) throw new IllegalArgumentException("В incompatible нужны пары");
|
||||
pair.forEach(SoupConfig::selector);
|
||||
}
|
||||
for (var entry : customIngredients.entrySet()) {
|
||||
var c = entry.getValue();
|
||||
if (!entry.getKey().matches("[a-z0-9_-]+") || c == null || (c.item == null) == (c.astraPlusId == null)
|
||||
|| c.nutrition < 0 || c.nutrition > maxNutrition || !Float.isFinite(c.saturation)
|
||||
|| c.saturation < 0 || c.saturation > maxSaturation || c.effects == null)
|
||||
throw new IllegalArgumentException("Некорректный ингредиент " + entry.getKey());
|
||||
if (c.astraPlusId != null && !c.astraPlusId.matches("[a-z0-9_.-]+:[a-z0-9/._-]+"))
|
||||
throw new IllegalArgumentException("Некорректный AstraPlus ID");
|
||||
if (c.color != null) rgb(c.color);
|
||||
for (var e : c.effects) if (e == null || e.type == null || e.duration < -1 || e.duration == 0
|
||||
|| e.amplifier < 0 || e.amplifier > 255) throw new IllegalArgumentException("Некорректный эффект");
|
||||
}
|
||||
}
|
||||
private static void selector(String s) {
|
||||
if (s == null || !s.toLowerCase(Locale.ROOT).matches("\\*|(?:material|effect|custom|astraplus|soup):[a-z0-9_:./-]+"))
|
||||
throw new IllegalArgumentException("Неизвестный селектор: " + s);
|
||||
}
|
||||
static int rgb(String s) {
|
||||
if (s == null || !s.matches("#[0-9a-fA-F]{6}")) throw new IllegalArgumentException("Цвет: #RRGGBB");
|
||||
return Integer.parseInt(s.substring(1), 16);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.mojang.math.Transformation;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.item.*;
|
||||
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
final class SoupDisplay extends Display.ItemDisplay {
|
||||
static final String TAG = "astracauldron:cauldron_visual";
|
||||
SoupDisplay(ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||
super(EntityTypes.ITEM_DISPLAY, level);
|
||||
setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5);
|
||||
getSlot(0).set(stack.copy());
|
||||
setItemTransform(ItemDisplayContext.FIXED);
|
||||
setNoGravity(true);
|
||||
setInvulnerable(true);
|
||||
setSilent(true);
|
||||
addTag(TAG);
|
||||
setTransformationInterpolationDuration(2);
|
||||
}
|
||||
void ingredient(int slot, int water, int ticks, int elapsed, int duration) {
|
||||
var frame = CauldronAnimation.frame(slot, water, ticks, elapsed, duration);
|
||||
setTransformationInterpolationDelay(0);
|
||||
setTransformation(new Transformation(new Vector3f((float)frame.x() - .5f, (float)frame.y() - .5f, (float)frame.z() - .5f),
|
||||
new Quaternionf(), new Vector3f(.3f), new Quaternionf().rotationY(ticks * .035f + slot)));
|
||||
}
|
||||
@Override public boolean shouldBeSaved() { return false; }
|
||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
final class SoupFiles {
|
||||
static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
private SoupFiles() {}
|
||||
static void write(Path path, JsonElement json) throws IOException {
|
||||
Files.createDirectories(path.getParent());
|
||||
Path temp = Files.createTempFile(path.getParent(), "soups-", ".tmp");
|
||||
try {
|
||||
Files.writeString(temp, JSON.toJson(json));
|
||||
try { Files.move(temp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING); }
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
}
|
||||
static JsonElement encode(ItemStack stack, HolderLookup.Provider registries) {
|
||||
return ItemStack.CODEC.encodeStart(RegistryOps.create(JsonOps.INSTANCE, registries), stack).getOrThrow();
|
||||
}
|
||||
static ItemStack decode(JsonElement json, HolderLookup.Provider registries) {
|
||||
return ItemStack.CODEC.parse(RegistryOps.create(JsonOps.INSTANCE, registries), json).getOrThrow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.particles.ParticleTypes;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.*;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.*;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
|
||||
public final class SoupPots implements AutoCloseable {
|
||||
record Position(String dimension, BlockPos pos) {
|
||||
static Position at(ServerLevel level, BlockPos pos) { return new Position(level.dimension().identifier().toString(), pos.immutable()); }
|
||||
}
|
||||
public record Pot(List<ItemStack> items, ItemStack soup, int brewTicks, int servings, int capacity) {
|
||||
public Pot { items = List.copyOf(items); }
|
||||
boolean brewing() { return brewTicks > 0; }
|
||||
boolean ready() { return !soup.isEmpty() && !brewing(); }
|
||||
static Pot raw(List<ItemStack> items) { return new Pot(items, ItemStack.EMPTY, 0, 0, 0); }
|
||||
}
|
||||
private final MinecraftServer server;
|
||||
private static final Identifier WATER_OWNER = Identifier.parse("astracauldron:cauldrons");
|
||||
private final online.astradev.plus.api.ColoredWaterApi water;
|
||||
private final Path file;
|
||||
private final Path configFile;
|
||||
private SoupConfig config;
|
||||
private Ingredients ingredients;
|
||||
private final Map<Position, Pot> pots = new LinkedHashMap<>();
|
||||
private final Map<Position, List<SoupDisplay>> visuals = new HashMap<>();
|
||||
private final Map<Position, Integer> elapsed = new HashMap<>();
|
||||
private int ticks;
|
||||
public SoupPots(MinecraftServer server, Path configFile) throws IOException {
|
||||
this.server = server;
|
||||
this.water = online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.coloredWater()).orElseThrow();
|
||||
this.file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json");
|
||||
this.configFile = configFile;
|
||||
reload();
|
||||
load();
|
||||
}
|
||||
public Ingredients ingredients() { return ingredients; }
|
||||
public boolean contains(ServerLevel level, BlockPos pos) { return pots.containsKey(Position.at(level, pos)); }
|
||||
public Pot get(ServerLevel level, BlockPos pos) { return pots.get(Position.at(level, pos)); }
|
||||
public void reload() throws IOException {
|
||||
var next = SoupConfig.load(configFile);
|
||||
var nextIngredients = new Ingredients(next, server.registryAccess());
|
||||
config = next;
|
||||
ingredients = nextIngredients;
|
||||
}
|
||||
public void register(String id, ServerPlayer player, int nutrition, float saturation) throws IOException {
|
||||
if (!id.matches("[a-z0-9_-]+") || player.getMainHandItem().isEmpty()) throw new IllegalArgumentException("Нужны ID и предмет в руке");
|
||||
var next = SoupFiles.JSON.fromJson(SoupFiles.JSON.toJson(config), SoupConfig.class);
|
||||
var custom = new SoupConfig.Custom();
|
||||
// Resolve by stable AstraPlus identity; definitions can evolve without invalidating the registration.
|
||||
var plus = online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.find(player.getMainHandItem()));
|
||||
if (plus.isPresent()) custom.astraPlusId = plus.get().id().toString();
|
||||
else custom.item = SoupFiles.encode(Ingredients.normalizedCopy(player.getMainHandItem()), server.registryAccess());
|
||||
custom.nutrition = nutrition;
|
||||
custom.saturation = saturation;
|
||||
next.customIngredients.put(id, custom);
|
||||
var validated = new Ingredients(next, server.registryAccess());
|
||||
SoupFiles.write(configFile, SoupFiles.JSON.toJsonTree(next));
|
||||
config = next;
|
||||
ingredients = validated;
|
||||
}
|
||||
private void load() throws IOException {
|
||||
if (!Files.exists(file)) return;
|
||||
var root = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
|
||||
if (root.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown cauldron data version");
|
||||
for (var value : root.getAsJsonArray("cauldrons")) {
|
||||
var c = value.getAsJsonObject();
|
||||
String dimension = Identifier.parse(c.get("dimension").getAsString()).toString();
|
||||
var pos = new Position(dimension, new BlockPos(c.get("x").getAsInt(), c.get("y").getAsInt(), c.get("z").getAsInt()));
|
||||
var items = new ArrayList<ItemStack>();
|
||||
for (var i : c.getAsJsonArray("items")) items.add(SoupFiles.decode(i, server.registryAccess()));
|
||||
var soup = c.has("soup") ? SoupFiles.decode(c.get("soup"), server.registryAccess()) : ItemStack.EMPTY;
|
||||
var pot = new Pot(items, soup, c.get("brewTicks").getAsInt(), c.get("servings").getAsInt(), c.get("capacity").getAsInt());
|
||||
validate(pot);
|
||||
if (pots.putIfAbsent(pos, pot) != null) throw new IllegalArgumentException("Duplicate cauldron " + pos);
|
||||
}
|
||||
}
|
||||
private static void validate(Pot p) {
|
||||
if (p.items.size() > 4 || p.items.stream().anyMatch(i -> i.isEmpty() || i.getCount() != 1)
|
||||
|| p.brewTicks < 0 || p.brewTicks > 1200
|
||||
|| (p.soup.isEmpty() ? p.servings != 0 || p.capacity != 0 || p.brewing() || p.items.isEmpty()
|
||||
: p.soup.getCount() != 1 || !Ingredients.isCombined(p.soup) || p.servings < 1 || p.capacity < p.servings || p.capacity > 16
|
||||
|| (p.brewing() ? p.items.size() != 4 : !p.items.isEmpty())))
|
||||
throw new IllegalArgumentException("Invalid cauldron contents");
|
||||
}
|
||||
private boolean change(Position pos, Pot next) {
|
||||
Pot old = pots.get(pos);
|
||||
if (next == null) pots.remove(pos); else { validate(next); pots.put(pos, next); }
|
||||
try {
|
||||
var root = new JsonObject(); root.addProperty("version", 1);
|
||||
var array = new JsonArray(); root.add("cauldrons", array);
|
||||
for (var e : pots.entrySet()) {
|
||||
var c = new JsonObject(); var p = e.getKey(); var pot = e.getValue();
|
||||
c.addProperty("dimension", p.dimension); c.addProperty("x", p.pos.getX()); c.addProperty("y", p.pos.getY()); c.addProperty("z", p.pos.getZ());
|
||||
var items = new JsonArray(); pot.items.forEach(i -> items.add(SoupFiles.encode(i, server.registryAccess()))); c.add("items", items);
|
||||
if (!pot.soup.isEmpty()) c.add("soup", SoupFiles.encode(pot.soup, server.registryAccess()));
|
||||
c.addProperty("brewTicks", pot.brewTicks); c.addProperty("servings", pot.servings); c.addProperty("capacity", pot.capacity);
|
||||
array.add(c);
|
||||
}
|
||||
SoupFiles.write(file, root);
|
||||
if (old == null || next == null || old.ready() != next.ready() || old.items.size() != next.items.size()) removeVisuals(pos);
|
||||
elapsed.remove(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
||||
AstraCauldron.LOG.error("Не удалось сохранить котёл; действие отменено", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** Returns whether vanilla interaction should be consumed. Saves before taking/giving items. */
|
||||
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
|
||||
var level = player.level(); var pos = Position.at(level, blockPos); var pot = pots.get(pos);
|
||||
if (player.isSpectator()) return false;
|
||||
if (hand != InteractionHand.MAIN_HAND) return pot != null;
|
||||
var state = level.getBlockState(blockPos);
|
||||
if (!valid(state, pot)) return false;
|
||||
var held = player.getMainHandItem();
|
||||
if (pot == null && ingredients.read(held) == null) return false;
|
||||
if (pot == null) {
|
||||
if (config.requireFullWater && state.getValue(LayeredCauldronBlock.LEVEL) != 3) {
|
||||
say(player, "Сначала наполните котёл водой доверху."); return true;
|
||||
}
|
||||
pot = Pot.raw(List.of());
|
||||
}
|
||||
if (pot.brewing()) { say(player, "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с."); return true; }
|
||||
if (pot.ready()) {
|
||||
if (!held.is(Items.BOWL)) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return true; }
|
||||
int left = pot.servings - 1; var result = pot.soup.copy();
|
||||
if (!change(pos, left == 0 ? null : new Pot(List.of(), pot.soup, 0, left, pot.capacity))) { saveError(player); return true; }
|
||||
held.consume(1, player); give(player, result);
|
||||
level.setBlock(blockPos, Blocks.CAULDRON.defaultBlockState(), 3);
|
||||
if (left > 0) show(level, pos, pots.get(pos));
|
||||
sound(level, blockPos, SoundEvents.BOTTLE_FILL);
|
||||
say(player, left == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + left + "."); return true;
|
||||
}
|
||||
if (pot.items.size() == 4 && (player.isShiftKeyDown() || !held.isEmpty())) {
|
||||
String rejection = ingredients.rejection(pot.items);
|
||||
if (rejection != null) { say(player, rejection + " ПКМ пустой рукой возвращает последний ингредиент."); return true; }
|
||||
var next = new Pot(pot.items, ingredients.brew(pot.items), (int)Math.round(config.brewSeconds * 20), config.servingsPerBrew, config.servingsPerBrew);
|
||||
if (!change(pos, next)) { saveError(player); return true; }
|
||||
sound(level, blockPos, SoundEvents.BREWING_STAND_BREW); say(player, "Варка началась! Дождитесь окончания водоворота."); return true;
|
||||
}
|
||||
if (held.isEmpty()) {
|
||||
if (pot.items.isEmpty()) return true;
|
||||
var remaining = new ArrayList<>(pot.items); var last = remaining.removeLast();
|
||||
if (!change(pos, remaining.isEmpty() ? null : Pot.raw(remaining))) { saveError(player); return true; }
|
||||
give(player, last.copy()); say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4."); return true;
|
||||
}
|
||||
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return true; }
|
||||
var items = new ArrayList<>(pot.items); items.add(held.copyWithCount(1));
|
||||
if (!change(pos, Pot.raw(items))) { saveError(player); return true; }
|
||||
held.consume(1, player); show(level, pos, pots.get(pos)); sound(level, blockPos, SoundEvents.GENERIC_SPLASH);
|
||||
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
|
||||
return true;
|
||||
}
|
||||
public boolean breakPot(ServerLevel level, BlockPos blockPos) {
|
||||
var pos = Position.at(level, blockPos); var old = pots.get(pos);
|
||||
if (old == null) return true;
|
||||
if (!change(pos, null)) return false;
|
||||
old.items.forEach(i -> Block.popResource(level, blockPos, i.copy()));
|
||||
return true;
|
||||
}
|
||||
private static boolean valid(BlockState state, Pot pot) {
|
||||
return state.is(Blocks.WATER_CAULDRON) || (state.is(Blocks.CAULDRON) && pot != null && pot.ready());
|
||||
}
|
||||
public void tick() {
|
||||
ticks++;
|
||||
for (var entry : new ArrayList<>(pots.entrySet())) {
|
||||
var pos = entry.getKey(); var pot = entry.getValue();
|
||||
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
|
||||
if (level == null || !level.hasChunkAt(pos.pos)) { removeVisuals(pos); continue; }
|
||||
if (!valid(level.getBlockState(pos.pos), pot)) { breakPot(level, pos.pos); continue; }
|
||||
if (pot.brewing()) {
|
||||
int time = elapsed.merge(pos, 1, Integer::sum);
|
||||
if (time >= pot.brewTicks && (time - pot.brewTicks) % 20 == 0
|
||||
&& change(pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
||||
pot = pots.get(pos);
|
||||
level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3);
|
||||
sound(level, pos.pos, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP);
|
||||
level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01);
|
||||
}
|
||||
}
|
||||
show(level, pos, pot);
|
||||
if (ticks % 2 == 0 && !pot.ready()) {
|
||||
var displays = visuals.get(pos);
|
||||
int water = level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL);
|
||||
for (int i = 0; i < displays.size(); i++) displays.get(i).ingredient(i, water, ticks + 2, elapsed.getOrDefault(pos, 0) + 2, pot.brewTicks);
|
||||
if (pot.brewing() && ticks % 10 == 0)
|
||||
level.sendParticles(ParticleTypes.SPLASH, pos.pos.getX() + .5, pos.pos.getY() + .95, pos.pos.getZ() + .5, 2, .2, 0, .2, 0);
|
||||
}
|
||||
}
|
||||
if (ticks % 20 == 0) for (var player : server.getPlayerList().getPlayers()) {
|
||||
for (var slot : player.containerMenu.slots) Ingredients.normalize(slot.getItem());
|
||||
for (int i = 0; i < player.getInventory().getContainerSize(); i++) Ingredients.normalize(player.getInventory().getItem(i));
|
||||
Ingredients.normalize(player.containerMenu.getCarried());
|
||||
player.containerMenu.broadcastChanges();
|
||||
}
|
||||
}
|
||||
private void show(ServerLevel level, Position pos, Pot pot) {
|
||||
if (pot.ready()) {
|
||||
water.show(level, pos.pos, new online.astradev.plus.api.ColoredWaterApi.Surface(WATER_OWNER,
|
||||
Ingredients.color(pot.soup), (float)CauldronAnimation.liquidHeight(pot.servings, pot.capacity)));
|
||||
return;
|
||||
}
|
||||
var existing = visuals.get(pos);
|
||||
if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { removeVisuals(pos); existing = null; }
|
||||
if (existing != null) return;
|
||||
var displays = new ArrayList<SoupDisplay>();
|
||||
for (int i = 0; i < pot.items.size(); i++) {
|
||||
var display = new SoupDisplay(level, pos.pos, pot.items.get(i));
|
||||
display.ingredient(i, level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL), ticks, elapsed.getOrDefault(pos, 0), pot.brewTicks);
|
||||
displays.add(display);
|
||||
}
|
||||
displays.forEach(level::addFreshEntity); visuals.put(pos, displays);
|
||||
}
|
||||
public void unload(ServerLevel level, int chunkX, int chunkZ) {
|
||||
for (var pos : new ArrayList<>(visuals.keySet())) if (pos.dimension.equals(level.dimension().identifier().toString())
|
||||
&& (pos.pos.getX() >> 4) == chunkX && (pos.pos.getZ() >> 4) == chunkZ) removeVisuals(pos);
|
||||
}
|
||||
private void removeVisuals(Position pos) {
|
||||
var list = visuals.remove(pos); if (list != null) list.forEach(SoupDisplay::discard);
|
||||
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
|
||||
if (level != null) water.remove(level, pos.pos, WATER_OWNER);
|
||||
}
|
||||
@Override public void close() {
|
||||
for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
||||
water.removeAll(WATER_OWNER);
|
||||
}
|
||||
private static void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { level.playSound(null, pos, sound, SoundSource.BLOCKS, .8f, 1f); }
|
||||
private static void give(ServerPlayer player, ItemStack item) { Ingredients.normalize(item); player.getInventory().add(item); if (!item.isEmpty()) player.drop(item, false); player.containerMenu.broadcastChanges(); }
|
||||
private static void say(ServerPlayer player, String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD), true); }
|
||||
private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
|
||||
/** Export before AstraPlus's startup pack build; never overwrite administrator resources. */
|
||||
final class SoupResources {
|
||||
private SoupResources() {}
|
||||
static void install(Path root) throws IOException {
|
||||
for (String name : List.of("items/combined_soup.json",
|
||||
"models/item/soup_liquid.json")) {
|
||||
String relative = "assets/astradev_soups/" + name;
|
||||
Path target = root.resolve("astraplus/resources").resolve(relative);
|
||||
Files.createDirectories(target.getParent());
|
||||
if (Files.exists(target)) continue;
|
||||
try (var input = SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
|
||||
if (input == null) throw new IOException("Missing resource " + relative);
|
||||
Files.copy(input, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
final class SoupText {
|
||||
private SoupText() {}
|
||||
@@ -0,0 +1,25 @@
|
||||
package online.astradev.cauldron.mixin;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.Fluid;
|
||||
import online.astradev.cauldron.AstraCauldron;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
/** NeoForge has no cancellable event for these vanilla cauldron mutations. */
|
||||
@Mixin({CauldronBlock.class, LayeredCauldronBlock.class})
|
||||
abstract class CauldronWeatherMixin {
|
||||
@Inject(method = "handlePrecipitation", at = @At("HEAD"), cancellable = true)
|
||||
private void soups$rain(BlockState state, Level level, BlockPos pos, Biome.Precipitation precipitation, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
@Inject(method = "receiveStalactiteDrip", at = @At("HEAD"), cancellable = true)
|
||||
private void soups$drip(BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package online.astradev.cauldron.mixin;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.LayeredCauldronBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import online.astradev.cauldron.AstraCauldron;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(LayeredCauldronBlock.class)
|
||||
abstract class LayeredCauldronMixin {
|
||||
@Inject(method = "lowerFillLevel", at = @At("HEAD"), cancellable = true)
|
||||
private static void soups$lower(BlockState state, Level level, BlockPos pos, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package online.astradev.cauldron.mixin;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.component.*;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
/** Per-stack patch is sent to vanilla clients; no change to their assumed item defaults. */
|
||||
@Mixin(ItemStack.class)
|
||||
abstract class SoupStackMixin {
|
||||
@Inject(method = "<init>(Lnet/minecraft/core/Holder;ILnet/minecraft/core/component/PatchedDataComponentMap;)V", at = @At("RETURN"))
|
||||
private void soups$stackSize(Holder<Item> item, int count, PatchedDataComponentMap components, CallbackInfo ci) {
|
||||
var key = item.unwrapKey().orElse(null);
|
||||
if (key == null || !key.identifier().getNamespace().equals("minecraft")) return;
|
||||
switch (key.identifier().getPath()) {
|
||||
case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> components.set(DataComponents.MAX_STACK_SIZE, 16);
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,824 +0,0 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
|
||||
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.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
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 final Map<Position, Integer> brewElapsed = 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, int brewTicks, int servings, int capacity) {
|
||||
Pot {
|
||||
items = List.copyOf(items);
|
||||
}
|
||||
|
||||
Pot(List<ItemStack> items, ItemStack soup) {
|
||||
this(items, soup, 0, soup == null ? 0 : 1, soup == null ? 0 : 1);
|
||||
}
|
||||
|
||||
boolean brewing() {
|
||||
return brewTicks > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
pots.clear();
|
||||
brewElapsed.clear();
|
||||
ticks = 0;
|
||||
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, 1);
|
||||
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");
|
||||
int brewTicks = c.getInt("brew-ticks", 0);
|
||||
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
||||
int capacity =
|
||||
c.getInt(
|
||||
"capacity",
|
||||
soup == null
|
||||
? 0
|
||||
: Math.max(
|
||||
servings, getConfig().getInt("servings-per-brew", 4)));
|
||||
if (items.size() > 4
|
||||
|| brewTicks < 0
|
||||
|| brewTicks > 1200
|
||||
|| (soup == null ? capacity != 0 : capacity < servings || capacity > 16)
|
||||
|| (soup == null ? servings != 0 : servings < 1 || servings > 16)
|
||||
|| (soup != null && (soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||
|| (brewTicks > 0
|
||||
? items.size() != 4 || soup == null
|
||||
: (soup != null ? !items.isEmpty() : items.isEmpty()))) {
|
||||
throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||
}
|
||||
pots.put(Position.parse(id), new Pot(items, soup, brewTicks, servings, capacity));
|
||||
}
|
||||
}
|
||||
|
||||
/** 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);
|
||||
if (entry.getValue().brewing())
|
||||
data.set(prefix + ".brew-ticks", entry.getValue().brewTicks);
|
||||
if (entry.getValue().soup != null)
|
||||
data.set(prefix + ".servings", entry.getValue().servings);
|
||||
if (entry.getValue().soup != null)
|
||||
data.set(prefix + ".capacity", entry.getValue().capacity);
|
||||
}
|
||||
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);
|
||||
}
|
||||
// Keep the same visuals when starting a brew or taking a portion: no respawn flash.
|
||||
if (old == null || next == null || !old.items.equals(next.items)) removeVisuals(pos);
|
||||
brewElapsed.remove(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 (!validBlock(block, pot)) 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.brewing()) {
|
||||
int remaining =
|
||||
Math.max(1, (pot.brewTicks - brewElapsed.getOrDefault(pos, 0) + 19) / 20);
|
||||
say(player, "Суп варится… Осталось: " + remaining + " с.");
|
||||
return;
|
||||
}
|
||||
if (pot.soup != null) {
|
||||
if (!bowl) {
|
||||
say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ.");
|
||||
return;
|
||||
}
|
||||
ItemStack result = pot.soup.clone();
|
||||
int remaining = pot.servings - 1;
|
||||
if (!change(
|
||||
pos,
|
||||
remaining == 0
|
||||
? null
|
||||
: new Pot(List.of(), pot.soup, 0, remaining, pot.capacity))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
takeOne(player);
|
||||
give(player, result);
|
||||
if (remaining == 0) block.setType(Material.CAULDRON);
|
||||
else {
|
||||
syncWater(block, pots.get(pos));
|
||||
show(pos, pots.get(pos), block);
|
||||
}
|
||||
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
||||
say(
|
||||
player,
|
||||
remaining == 0
|
||||
? "Последняя порция собрана. Котёл пуст."
|
||||
: "Осталось порций: " + remaining + ".");
|
||||
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);
|
||||
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
||||
int capacity = getConfig().getInt("servings-per-brew", 4);
|
||||
if (!change(pos, new Pot(pot.items, soup, duration, capacity, capacity))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||
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++;
|
||||
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 (!validBlock(block, entry.getValue())) {
|
||||
// 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;
|
||||
}
|
||||
Pot pot = entry.getValue();
|
||||
if (pot.brewing()) {
|
||||
int elapsed = brewElapsed.merge(pos, 1, Integer::sum);
|
||||
// On a save failure keep ingredients locked and retry once per second.
|
||||
if (elapsed >= pot.brewTicks
|
||||
&& (elapsed - pot.brewTicks) % 20 == 0
|
||||
&& change(
|
||||
pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
||||
syncWater(block, pots.get(pos));
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld()
|
||||
.playSound(
|
||||
block.getLocation(),
|
||||
Sound.BLOCK_BUBBLE_COLUMN_BUBBLE_POP,
|
||||
.8f,
|
||||
1.2f);
|
||||
block.getWorld()
|
||||
.spawnParticle(
|
||||
Particle.CLOUD,
|
||||
block.getLocation().add(.5, 1.05, .5),
|
||||
12,
|
||||
.2,
|
||||
.12,
|
||||
.2,
|
||||
.01);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (pot.soup != null && !pot.brewing()) syncWater(block, pot);
|
||||
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 ItemDisplay item && ticks % 2 == 0) {
|
||||
// Client interpolates the local transform; the entity itself never
|
||||
// teleports.
|
||||
item.setInterpolationDelay(0);
|
||||
item.setTransformation(itemTransform(block, i, pot, 2));
|
||||
if (pot.brewing() && ticks % 5 == 0) {
|
||||
Vector3f offset = item.getTransformation().getTranslation();
|
||||
double height =
|
||||
.375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||
block.getWorld()
|
||||
.spawnParticle(
|
||||
Particle.SPLASH,
|
||||
block.getLocation()
|
||||
.add(
|
||||
.5 + offset.x,
|
||||
height + .01,
|
||||
.5 + offset.z),
|
||||
1,
|
||||
.015,
|
||||
0,
|
||||
.015,
|
||||
0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 boolean validBlock(Block block, Pot pot) {
|
||||
return block.getType() == Material.WATER_CAULDRON
|
||||
|| (block.getType() == Material.CAULDRON
|
||||
&& pot != null
|
||||
&& pot.soup != null
|
||||
&& !pot.brewing());
|
||||
}
|
||||
|
||||
private void syncWater(Block block, Pot pot) {
|
||||
int level = CauldronAnimation.waterLevel(pot.servings, pot.capacity);
|
||||
if (level == 0) {
|
||||
if (block.getType() != Material.CAULDRON) block.setType(Material.CAULDRON);
|
||||
} else {
|
||||
if (block.getType() != Material.WATER_CAULDRON) block.setType(Material.WATER_CAULDRON);
|
||||
Levelled water = (Levelled) block.getBlockData();
|
||||
if (water.getLevel() != level) {
|
||||
water.setLevel(level);
|
||||
block.setBlockData(water);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Transformation itemTransform(Block block, int i, Pot pot, int ahead) {
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
CauldronAnimation.Offset frame =
|
||||
CauldronAnimation.frame(
|
||||
i,
|
||||
waterLevel,
|
||||
ticks + ahead,
|
||||
brewElapsed.getOrDefault(Position.at(block), 0) + ahead,
|
||||
pot.brewTicks);
|
||||
return new Transformation(
|
||||
new Vector3f(
|
||||
(float) frame.x() - .5f, (float) frame.y() - .5f, (float) frame.z() - .5f),
|
||||
new Quaternionf(),
|
||||
new Vector3f(.3f),
|
||||
new Quaternionf().rotationY((ticks + ahead) * .035f + i));
|
||||
}
|
||||
|
||||
private Transformation liquidTransform(Pot pot) {
|
||||
return new Transformation(
|
||||
new Vector3f(
|
||||
-.075f,
|
||||
(float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity)
|
||||
+ .005f
|
||||
- .5f,
|
||||
.375f),
|
||||
new Quaternionf().rotationX((float) (-Math.PI / 2)),
|
||||
new Vector3f(6, 3, 1),
|
||||
new Quaternionf());
|
||||
}
|
||||
|
||||
private void show(Position pos, Pot pot, Block block) {
|
||||
if (visuals.containsKey(pos)) {
|
||||
if (pot.soup != null && !pot.brewing())
|
||||
for (Entity entity : visuals.get(pos))
|
||||
if (entity instanceof TextDisplay display) {
|
||||
display.setInterpolationDelay(0);
|
||||
display.setTransformation(liquidTransform(pot));
|
||||
}
|
||||
return;
|
||||
}
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
visuals.put(pos, entities);
|
||||
if (pot.soup != null && !pot.brewing()) {
|
||||
int rgb =
|
||||
pot.soup
|
||||
.getItemMeta()
|
||||
.getPersistentDataContainer()
|
||||
.getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||
TextDisplay display =
|
||||
block.getWorld()
|
||||
.spawn(
|
||||
block.getLocation().add(.5, .5, .5),
|
||||
TextDisplay.class,
|
||||
d -> {
|
||||
markVisual(d);
|
||||
// One default-font space: native background spans 5x10
|
||||
// pixels at 0.025 blocks/pixel.
|
||||
// Center the rectangle, scale to 0.75x0.75 and face upwards
|
||||
// inside the cauldron.
|
||||
d.text(
|
||||
Component.text(" ")
|
||||
.font(
|
||||
net.kyori.adventure.key.Key.key(
|
||||
"minecraft:default")));
|
||||
d.setDefaultBackground(false);
|
||||
d.setBackgroundColor(Color.fromARGB(0xFF000000 | rgb));
|
||||
d.setShadowed(false);
|
||||
d.setSeeThrough(false);
|
||||
d.setTransformation(liquidTransform(pot));
|
||||
d.setInterpolationDuration(5);
|
||||
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();
|
||||
int slot = i;
|
||||
ItemDisplay item =
|
||||
block.getWorld()
|
||||
.spawn(
|
||||
block.getLocation().add(.5, .5, .5),
|
||||
ItemDisplay.class,
|
||||
e -> {
|
||||
markVisual(e);
|
||||
e.setItemStack(stack);
|
||||
e.setItemDisplayTransform(
|
||||
ItemDisplay.ItemDisplayTransform.FIXED);
|
||||
e.setTransformation(itemTransform(block, slot, pot, 0));
|
||||
e.setInterpolationDuration(2);
|
||||
e.setViewRange(.5f);
|
||||
});
|
||||
entities.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
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 && !pot.brewing())
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Material;
|
||||
|
||||
final class IngredientColors {
|
||||
private IngredientColors() {}
|
||||
|
||||
static Color food(Material material, Color fallback) {
|
||||
int rgb =
|
||||
switch (material) {
|
||||
case SPIDER_EYE, FERMENTED_SPIDER_EYE -> 0xB52B38;
|
||||
case GOLDEN_APPLE, ENCHANTED_GOLDEN_APPLE, GOLDEN_CARROT -> 0xF2C94C;
|
||||
case APPLE, SWEET_BERRIES -> 0xC73735;
|
||||
case BEETROOT, BEETROOT_SOUP -> 0xA52B4B;
|
||||
case CARROT, PUMPKIN_PIE, GLOW_BERRIES -> 0xE99032;
|
||||
case DRIED_KELP -> 0x47733B;
|
||||
case POISONOUS_POTATO -> 0x91A340;
|
||||
case MELON_SLICE -> 0xD94E58;
|
||||
case CHORUS_FRUIT -> 0x9C6C9D;
|
||||
case BEEF, MUTTON, PORKCHOP, RABBIT -> 0xC76B70;
|
||||
case CHICKEN -> 0xE2A6A0;
|
||||
case COOKED_BEEF, COOKED_MUTTON -> 0x815033;
|
||||
case COOKED_PORKCHOP, COOKED_RABBIT, COOKED_CHICKEN -> 0xBA8551;
|
||||
case SALMON, COOKED_SALMON, TROPICAL_FISH -> 0xD98262;
|
||||
case COD -> 0xB0A07B;
|
||||
case COOKED_COD -> 0xC4B486;
|
||||
case PUFFERFISH -> 0xD3B54D;
|
||||
case BREAD, COOKIE, BAKED_POTATO -> 0xBA873F;
|
||||
case POTATO -> 0xC7A76B;
|
||||
case ROTTEN_FLESH -> 0x8F6540;
|
||||
case HONEY_BOTTLE -> 0xE9AC32;
|
||||
case CAKE -> 0xE8CCBA;
|
||||
case MUSHROOM_STEW -> 0xA37A53;
|
||||
case RABBIT_STEW -> 0xAC8854;
|
||||
case SUSPICIOUS_STEW -> 0x867743;
|
||||
default -> fallback.asRGB();
|
||||
};
|
||||
return Color.fromRGB(rgb);
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import io.papermc.paper.datacomponent.DataComponentTypes;
|
||||
import io.papermc.paper.datacomponent.item.Consumable;
|
||||
import io.papermc.paper.datacomponent.item.CustomModelData;
|
||||
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.key.Key;
|
||||
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,
|
||||
Color color) {}
|
||||
|
||||
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;
|
||||
double seconds = plugin.getConfig().getDouble("brew-seconds", 4.0);
|
||||
if (!Double.isFinite(seconds) || seconds < .5 || seconds > 60) {
|
||||
throw new IllegalArgumentException("brew-seconds должно быть от 0.5 до 60");
|
||||
}
|
||||
int servings = plugin.getConfig().getInt("servings-per-brew", 4);
|
||||
if (servings < 1 || servings > 16)
|
||||
throw new IllegalArgumentException("servings-per-brew должно быть от 1 до 16");
|
||||
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);
|
||||
Color customColor =
|
||||
c.isString("color")
|
||||
? Color.fromRGB(
|
||||
Integer.parseInt(c.getString("color").replace("#", ""), 16))
|
||||
: null;
|
||||
custom.add(
|
||||
new Custom(
|
||||
id,
|
||||
sample.asOne(),
|
||||
nutrition,
|
||||
saturation,
|
||||
List.copyOf(effects),
|
||||
customColor));
|
||||
}
|
||||
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 = IngredientColors.food(item.getType(), defaultColor);
|
||||
if (isCombined(item))
|
||||
color =
|
||||
Color.fromRGB(
|
||||
meta.getPersistentDataContainer()
|
||||
.getOrDefault(
|
||||
plugin.colorKey,
|
||||
PersistentDataType.INTEGER,
|
||||
defaultColor.asRGB()));
|
||||
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 (match.color != null) color = match.color;
|
||||
}
|
||||
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", "Комбинированный суп"),
|
||||
net.kyori.adventure.text.format.TextColor.color(
|
||||
color(ingredients).asRGB()))
|
||||
.decoration(TextDecoration.ITALIC, false));
|
||||
meta.lore(soupLore(nutrition, saturation, effects));
|
||||
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 static List<Component> soupLore(
|
||||
int nutrition, float saturation, List<ConsumeEffect> effects) {
|
||||
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(
|
||||
" "
|
||||
+ SoupText.roman(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));
|
||||
}
|
||||
return lore;
|
||||
}
|
||||
|
||||
private static 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;
|
||||
}) return false;
|
||||
boolean changed = false;
|
||||
if (!Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
||||
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
|
||||
changed = true;
|
||||
}
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
FoodProperties food = item.getData(DataComponentTypes.FOOD);
|
||||
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
||||
if (meta.getPersistentDataContainer()
|
||||
.has(
|
||||
new NamespacedKey("astrasoups", "combined_soup"),
|
||||
PersistentDataType.BYTE)
|
||||
&& food != null
|
||||
&& consumable != null) {
|
||||
List<Component> lore =
|
||||
soupLore(food.nutrition(), food.saturation(), consumable.consumeEffects());
|
||||
if (!Objects.equals(meta.lore(), lore)) {
|
||||
meta.lore(lore);
|
||||
item.setItemMeta(meta);
|
||||
changed = true;
|
||||
}
|
||||
int rgb = meta.getPersistentDataContainer().getOrDefault(
|
||||
new NamespacedKey("astrasoups", "soup_color"),
|
||||
PersistentDataType.INTEGER, 0xB77A36);
|
||||
Key model = Key.key("astradev_soups", "combined_soup");
|
||||
if (!Objects.equals(item.getData(DataComponentTypes.ITEM_MODEL), model)) {
|
||||
item.setData(DataComponentTypes.ITEM_MODEL, model);
|
||||
changed = true;
|
||||
}
|
||||
CustomModelData data = item.getData(DataComponentTypes.CUSTOM_MODEL_DATA);
|
||||
Color tint = Color.fromRGB(rgb & 0xFFFFFF);
|
||||
if (data == null || data.colors().isEmpty() || !data.colors().getFirst().equals(tint)) {
|
||||
var builder = CustomModelData.customModelData().addColor(tint);
|
||||
if (data != null) {
|
||||
builder.addFloats(data.floats()).addFlags(data.flags()).addStrings(data.strings());
|
||||
builder.addColors(data.colors().stream().skip(1).toList());
|
||||
}
|
||||
item.setData(DataComponentTypes.CUSTOM_MODEL_DATA, builder.build());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
public net.minecraft.world.entity.Display setTransformation(Lcom/mojang/math/Transformation;)V
|
||||
public net.minecraft.world.entity.Display setTransformationInterpolationDuration(I)V
|
||||
public net.minecraft.world.entity.Display setTransformationInterpolationDelay(I)V
|
||||
public net.minecraft.world.entity.Display setPosRotInterpolationDuration(I)V
|
||||
public net.minecraft.world.entity.Display$ItemDisplay setItemTransform(Lnet/minecraft/world/item/ItemDisplayContext;)V
|
||||
@@ -0,0 +1,26 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[11,)"
|
||||
license="All Rights Reserved"
|
||||
[[mods]]
|
||||
modId="astracauldron"
|
||||
version="${version}"
|
||||
displayName="AstraCauldron"
|
||||
description='''Server-side cauldron soups with AstraPlus ingredients and resources.'''
|
||||
[[mixins]]
|
||||
config="astracauldron.mixins.json"
|
||||
[[dependencies.astracauldron]]
|
||||
modId="neoforge"
|
||||
type="required"
|
||||
versionRange="[26.2.0.79,26.3)"
|
||||
side="SERVER"
|
||||
[[dependencies.astracauldron]]
|
||||
modId="minecraft"
|
||||
type="required"
|
||||
versionRange="[26.2,26.3)"
|
||||
side="SERVER"
|
||||
[[dependencies.astracauldron]]
|
||||
modId="astraplus"
|
||||
type="required"
|
||||
versionRange="[0.5.1,0.6)"
|
||||
ordering="AFTER"
|
||||
side="SERVER"
|
||||
@@ -1,3 +0,0 @@
|
||||
schema=1
|
||||
plugin=AstraSoups
|
||||
folder=astradev_soups
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"required": true,
|
||||
"package": "online.astradev.cauldron.mixin",
|
||||
"compatibilityLevel": "JAVA_25",
|
||||
"server": ["CauldronWeatherMixin", "LayeredCauldronMixin", "SoupStackMixin"],
|
||||
"injectors": {"defaultRequire": 1}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
# Ровно четыре предмета, по одной единице каждого. Повторы разрешены.
|
||||
# Одна варка даёт четыре порции; каждая получает питание и эффекты всего состава.
|
||||
servings-per-brew: 4
|
||||
require-full-water: true
|
||||
# Время варки в секундах (0.5–60).
|
||||
brew-seconds: 4.0
|
||||
soup-name: 'Комбинированный суп'
|
||||
# Цвет ингредиентов, для которых не задан собственный RGB.
|
||||
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. Эффекты добавляются к исходным.
|
||||
# Необязательный color: '#D45B37' задаёт цвет уникальной еды для смешивания.
|
||||
custom-ingredients: {}
|
||||
@@ -1,16 +0,0 @@
|
||||
name: AstraSoups
|
||||
version: '${version}'
|
||||
main: online.astradev.soups.AstraSoupsPlugin
|
||||
api-version: '26.2'
|
||||
description: Four-ingredient cauldron soups with food and potion properties
|
||||
author: AstraDev
|
||||
depend: [AstraPacks, ItemsAdder]
|
||||
commands:
|
||||
soups:
|
||||
description: Комбинированные супы
|
||||
usage: /soups [reload|register <id> <голод> <насыщение>]
|
||||
permissions:
|
||||
astrasoups.use:
|
||||
default: true
|
||||
astrasoups.admin:
|
||||
default: op
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SoupConfigTest {
|
||||
@TempDir Path root;
|
||||
@Test void writesDefaultsAndRejectsInvalidFileWithoutReplacingIt() throws Exception {
|
||||
Path path = root.resolve("config.json");
|
||||
assertEquals(4, SoupConfig.load(path).servingsPerBrew);
|
||||
String broken = "{\"brewSeconds\":0}";
|
||||
Files.writeString(path, broken);
|
||||
assertThrows(IllegalArgumentException.class, () -> SoupConfig.load(path));
|
||||
assertEquals(broken, Files.readString(path));
|
||||
}
|
||||
@Test void validatesSelectorsAndDistinctCustomIdentityModes() {
|
||||
var c = new SoupConfig();
|
||||
c.blockedIngredients = List.of("astraplus:foods:chili");
|
||||
c.validate();
|
||||
c.blockedIngredients = List.of("itemsadder:foods:chili");
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
c.blockedIngredients = List.of();
|
||||
var food = new SoupConfig.Custom();
|
||||
food.astraPlusId = "foods:chili"; food.nutrition = 4; food.saturation = 2;
|
||||
c.customIngredients.put("chili", food); c.validate();
|
||||
food.item = new com.google.gson.JsonObject();
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
}
|
||||
@Test void rejectsNonfiniteNutritionAndInvalidColors() {
|
||||
var c = new SoupConfig(); c.maxSaturation = Float.NaN;
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
c.maxSaturation = 1000; c.defaultColor = "#1234567";
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package online.astradev.soups;
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
package online.astradev.cauldron.verification;
|
||||
|
||||
import com.google.gson.*;
|
||||
import online.astradev.cauldron.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipFile;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.*;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.effect.*;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.alchemy.*;
|
||||
import net.minecraft.world.item.component.*;
|
||||
import net.minecraft.world.item.consume_effects.*;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.storage.LevelResource;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.common.util.FakePlayerFactory;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.level.block.BreakBlockEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import online.astradev.plus.api.*;
|
||||
|
||||
/** Requires a fresh isolated world. Writes fixtures and stops this server. Never install in production. */
|
||||
@Mod(value = "astracauldron_verify", dist = Dist.DEDICATED_SERVER)
|
||||
public final class SoupVerification {
|
||||
private static final BlockPos READY = new BlockPos(8, 100, 8), RAW = new BlockPos(10, 100, 8), BREW = new BlockPos(12, 100, 8);
|
||||
private final List<String> passed = new ArrayList<>();
|
||||
private int tick;
|
||||
private boolean finished, restart;
|
||||
private ServerPlayer player;
|
||||
public SoupVerification() {
|
||||
if (!Boolean.getBoolean("astracauldron.isolatedVerification")) throw new IllegalStateException("Isolated verification flag required");
|
||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||
}
|
||||
private void tick(ServerTickEvent.Post event) {
|
||||
if (finished) return;
|
||||
var server = event.getServer(); var level = server.overworld();
|
||||
try {
|
||||
tick++;
|
||||
if (tick == 1) {
|
||||
restart = Files.exists(Path.of("first-pass.txt"));
|
||||
server.getCommands().performPrefixedCommand(server.createCommandSourceStack(), "forceload add 0 0 31 15");
|
||||
level.getChunk(0, 0); level.getChunk(1, 0);
|
||||
player = FakePlayerFactory.getMinecraft(level); player.setGameMode(GameType.SURVIVAL); player.setPos(8, 101, 8);
|
||||
}
|
||||
if (restart) {
|
||||
if (tick == 10) {
|
||||
require(AstraCauldron.pots().get(level, READY).servings() == 2, "ready servings restored");
|
||||
require(AstraCauldron.pots().get(level, RAW).items().size() == 1, "raw ingredient restored");
|
||||
require(AstraCauldron.pots().get(level, BREW).brewTicks() > 0, "unfinished brew restarts its timer");
|
||||
require(water().find(level, READY).isPresent(), "AstraPlus water restored by soup owner");
|
||||
require(displays(level, READY).size() == 1, "single colored water display after restart");
|
||||
var storedPotion = AstraCauldron.liquids().get(level,new BlockPos(24,100,8));
|
||||
require(storedPotion.levels() == 2 && storedPotion.potion().contents().is(Potions.LONG_NIGHT_VISION), "potion contents and volume survive restart");
|
||||
require(AstraCauldron.liquids().get(level,new BlockPos(26,100,8)).levels() == 2, "dyed water volume survives restart");
|
||||
}
|
||||
if (tick == 110) {
|
||||
require(AstraCauldron.pots().get(level, BREW).brewTicks() == 0, "restored brew finishes");
|
||||
use(READY, new ItemStack(Items.BOWL)); use(READY, new ItemStack(Items.BOWL));
|
||||
require(AstraCauldron.pots().get(level, READY) == null && water().find(level, READY).isEmpty(), "last serving clears saved pot and water API");
|
||||
finish(server, "restart");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (tick == 10) {
|
||||
checkIngredients(server, level);
|
||||
checkWater(level);
|
||||
checkInteractions(server, level);
|
||||
checkLiquids(level);
|
||||
fill(level, READY); for (int i = 0; i < 4; i++) use(READY, new ItemStack(Items.CARROT));
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(AstraCauldron.pots().get(level, READY).brewTicks() > 0, "four ingredients start timed brew");
|
||||
require(displays(level, READY).size() == 4, "four ingredient displays while brewing");
|
||||
require(displays(level, READY).stream().noneMatch(Display::shouldBeSaved), "ingredient displays never persist as entities");
|
||||
}
|
||||
if (tick == 100) {
|
||||
require(AstraCauldron.pots().get(level, READY).brewTicks() == 0, "brew finishes after 80 ticks");
|
||||
require(displays(level, READY).size() == 1, "AstraPlus owns single liquid display");
|
||||
require(displays(level, READY).getFirst().entityTags().contains("astraplus:colored_water"), "liquid belongs to AstraPlus");
|
||||
var id = displays(level, READY).getFirst().getUUID();
|
||||
float height = water().find(level, READY).orElseThrow().height();
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(AstraCauldron.pots().get(level, READY).servings() == 3 && water().find(level, READY).orElseThrow().height() < height, "portion lowers water API height");
|
||||
require(displays(level, READY).getFirst().getUUID().equals(id), "portion interpolates same display");
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(AstraCauldron.pots().get(level, READY).servings() == 2, "two saved servings remain");
|
||||
checkSaveFailure(server, level);
|
||||
fill(level, RAW); use(RAW, new ItemStack(Items.APPLE));
|
||||
fill(level, BREW); for (int i = 0; i < 4; i++) use(BREW, new ItemStack(Items.BREAD)); use(BREW, new ItemStack(Items.BOWL));
|
||||
try (var zip = new ZipFile("astraplus/output/AstraPlus.zip")) {
|
||||
require(zip.getEntry("assets/astraplus/items/colored_water.json") != null, "AstraPlus packs its own water resource");
|
||||
require(zip.getEntry("assets/astradev_soups/items/combined_soup.json") != null, "AstraCauldron bowl exported before AstraPlus pack build");
|
||||
}
|
||||
Files.writeString(Path.of("first-pass.txt"), "passed"); finish(server, "gameplay");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
finished = true; e.printStackTrace();
|
||||
try { Files.writeString(Path.of("verification-result.txt"), "FAIL at tick " + tick + ": " + e + "\n" + String.join("\n", passed)); } catch (Exception ignored) {}
|
||||
server.halt(false);
|
||||
}
|
||||
}
|
||||
private void checkIngredients(MinecraftServer server, ServerLevel level) throws Exception {
|
||||
var ingredients = AstraCauldron.pots().ingredients();
|
||||
for (var item : List.of(Items.MUSHROOM_STEW, Items.RABBIT_STEW, Items.BEETROOT_SOUP, Items.SUSPICIOUS_STEW))
|
||||
require(new ItemStack(item).getMaxStackSize() == 16, "native per-stack size " + item);
|
||||
require(ingredients.read(new ItemStack(Items.CAKE)).nutrition() == 14, "whole cake nutrition");
|
||||
require(ingredients.read(new ItemStack(Items.TIPPED_ARROW)) == null, "arrows rejected");
|
||||
var potion = new ItemStack(Items.POTION); potion.set(DataComponents.POTION_CONTENTS, new PotionContents(Potions.LONG_NIGHT_VISION));
|
||||
var recipe = List.of(potion, new ItemStack(Items.COOKED_BEEF), new ItemStack(Items.GLOW_BERRIES), new ItemStack(Items.GOLDEN_APPLE));
|
||||
var soup = ingredients.brew(recipe);
|
||||
require(soup.get(DataComponents.FOOD).nutrition() == 14, "summed native food nutrition");
|
||||
require(soup.get(DataComponents.FOOD).canAlwaysEat(), "soup consumable at full hunger");
|
||||
var reversed = new ArrayList<>(recipe); Collections.reverse(reversed);
|
||||
require(ItemStack.isSameItemSameComponents(soup, ingredients.brew(reversed)), "recipe order independent stacking");
|
||||
require(ItemStack.isSameItemSameComponents(soup, decode(encode(soup, server.registryAccess()), server.registryAccess())), "native item codec preserves full soup");
|
||||
var applied = soup.get(DataComponents.CONSUMABLE).onConsumeEffects().stream().filter(e -> e instanceof ApplyStatusEffectsConsumeEffect)
|
||||
.map(e -> (ApplyStatusEffectsConsumeEffect)e).flatMap(e -> e.effects().stream()).toList();
|
||||
require(applied.stream().anyMatch(e -> e.getEffect().equals(MobEffects.NIGHT_VISION) && e.getDuration() == 9600), "potion full duration preserved");
|
||||
require(applied.stream().anyMatch(e -> e.getEffect().equals(MobEffects.REGENERATION)), "golden apple effects preserved");
|
||||
player.getInventory().clearContent(); player.getFoodData().setFoodLevel(1); player.removeAllEffects();
|
||||
var eaten = soup.copyWithCount(2); eaten.finishUsingItem(level, player);
|
||||
require(eaten.getCount() == 1 && player.getFoodData().getFoodLevel() == 15 && player.hasEffect(MobEffects.NIGHT_VISION), "native consumption feeds and applies effects");
|
||||
require(player.getInventory().countItem(Items.BOWL) == 1, "native stacked consumption returns bowl");
|
||||
require(ingredients.read(new ItemStack(Items.CHORUS_FRUIT)).effects().stream().anyMatch(e -> e instanceof TeleportRandomlyConsumeEffect), "chorus teleport retained");
|
||||
require(ingredients.read(new ItemStack(Items.POISONOUS_POTATO)).effects().stream().anyMatch(e -> e instanceof ApplyStatusEffectsConsumeEffect a && a.probability() < 1), "probabilistic effects retained");
|
||||
var api = AstraPlusApi.current().orElseThrow(); var id = Identifier.parse("verify:soup_food");
|
||||
api.save(id, AstraPlusApi.NEW_REVISION, JsonParser.parseString("""
|
||||
{"name":"Test food","material":"minecraft:paper","texture":"minecraft:item/paper",
|
||||
"components":{"minecraft:food":{"nutrition":7,"saturation":4.5,"can_always_eat":true},"minecraft:consumable":{}}}
|
||||
""").getAsJsonObject());
|
||||
var food = api.create(id, 1);
|
||||
require(ingredients.read(food).nutrition() == 7 && ingredients.read(food).tags().contains("astraplus:verify:soup_food"), "AstraPlus identity and native food read via public API");
|
||||
require(ingredients.read(new ItemStack(Items.PAPER)) == null, "ordinary carrier is not custom food");
|
||||
player.setItemInHand(InteractionHand.MAIN_HAND, food);
|
||||
AstraCauldron.pots().register("plus_food", player, 9, 6);
|
||||
require(AstraCauldron.pots().ingredients().read(food).nutrition() == 9, "custom AstraPlus registration overrides nutrition");
|
||||
var c = api.find(id).orElseThrow(); var doc = c.document();
|
||||
doc.addProperty("name", "Changed name"); api.save(id, c.revision(), doc);
|
||||
require(AstraCauldron.pots().ingredients().read(api.create(id, 1)).nutrition() == 9, "registration survives AstraPlus definition edits");
|
||||
String original = Files.readString(Path.of("config/astracauldron.json"));
|
||||
Files.writeString(Path.of("config/astracauldron.json"), "{\"brewSeconds\":-1}");
|
||||
try { AstraCauldron.pots().reload(); throw new AssertionError("invalid config accepted"); } catch (IllegalArgumentException expected) { require(true, "invalid reload rejected"); }
|
||||
finally { Files.writeString(Path.of("config/astracauldron.json"), original); }
|
||||
require(AstraCauldron.pots().ingredients().read(api.create(id, 1)).nutrition() == 9, "invalid reload leaves previous runtime intact");
|
||||
}
|
||||
private void checkWater(ServerLevel level) throws Exception {
|
||||
var pos = new BlockPos(22, 100, 8); level.setBlock(pos, Blocks.CAULDRON.defaultBlockState(), 3);
|
||||
var owner = Identifier.parse("verify:water"); var other = Identifier.parse("verify:other"); var water = water();
|
||||
require(water.show(level, pos, new ColoredWaterApi.Surface(owner, 0xFF0000, .8f)), "independent water API creates surface without soup");
|
||||
var display = displays(level, pos).getFirst();
|
||||
require(display.getSlot(0).get().get(DataComponents.ITEM_MODEL).equals(Identifier.parse("astraplus:colored_water")), "AstraPlus generic water model");
|
||||
require(!water.show(level, pos, new ColoredWaterApi.Surface(other, 0, .5f)) && !water.remove(level, pos, other), "water owner isolation");
|
||||
require(water.show(level, pos, new ColoredWaterApi.Surface(owner, 0x00FF00, .6f)), "color and height update");
|
||||
require(displays(level, pos).getFirst().getUUID().equals(display.getUUID()), "API update reuses entity");
|
||||
display.discard();
|
||||
water.show(level, pos, new ColoredWaterApi.Surface(owner, 0x00FF00, .6f));
|
||||
require(displays(level, pos).size() == 1 && !displays(level, pos).getFirst().getUUID().equals(display.getUUID()), "removed entity recreated once");
|
||||
require(!water.show(level, new BlockPos(100000,100,100000), new ColoredWaterApi.Surface(owner, 0, .5f)), "API never loads chunks");
|
||||
// API JAR intentionally does not expose the concrete service; tested through the live API below.
|
||||
water.removeAll(owner);
|
||||
require(displays(level, pos).isEmpty() && water.find(level,pos).isEmpty(), "owner cleanup removes surface");
|
||||
try { new ColoredWaterApi.Surface(owner, 0x1000000, .5f); throw new AssertionError("invalid RGB"); } catch (IllegalArgumentException expected) { require(true, "API validates RGB"); }
|
||||
try { new ColoredWaterApi.Surface(owner, 0, Float.NaN); throw new AssertionError("invalid height"); } catch (IllegalArgumentException expected) { require(true, "API validates finite height"); }
|
||||
}
|
||||
private void checkInteractions(MinecraftServer server, ServerLevel level) {
|
||||
var pos = new BlockPos(4,100,8); fill(level, pos);
|
||||
player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.APPLE, 2));
|
||||
var denied = click(pos); denied.setCanceled(true); NeoForge.EVENT_BUS.post(denied);
|
||||
require(AstraCauldron.pots().get(level, pos) == null && player.getMainHandItem().getCount() == 2, "cancelled interaction is respected");
|
||||
NeoForge.EVENT_BUS.post(click(pos));
|
||||
require(AstraCauldron.pots().get(level,pos).items().size() == 1 && player.getMainHandItem().getCount() == 1, "event insertion consumes one");
|
||||
LayeredCauldronBlock.lowerFillLevel(level.getBlockState(pos), level, pos);
|
||||
require(level.getBlockState(pos).getValue(LayeredCauldronBlock.LEVEL) == 3, "vanilla level mutation blocked for occupied pot");
|
||||
var blockedBreak = new BreakBlockEvent(level, pos, level.getBlockState(pos), player); blockedBreak.setCanceled(true); NeoForge.EVENT_BUS.post(blockedBreak);
|
||||
require(AstraCauldron.pots().get(level,pos) != null, "cancelled breaking preserves ingredients");
|
||||
use(pos, ItemStack.EMPTY);
|
||||
require(AstraCauldron.pots().get(level,pos) == null, "empty hand returns ingredient and removes pot");
|
||||
LayeredCauldronBlock.lowerFillLevel(level.getBlockState(pos), level, pos);
|
||||
require(level.getBlockState(pos).getValue(LayeredCauldronBlock.LEVEL) == 2, "ordinary cauldron retains vanilla behavior");
|
||||
use(pos, new ItemStack(Items.APPLE)); require(AstraCauldron.pots().get(level,pos) == null, "full water required");
|
||||
}
|
||||
private void checkSaveFailure(MinecraftServer server, ServerLevel level) throws Exception {
|
||||
Path file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json");
|
||||
Path backup = file.resolveSibling("cauldrons.saved.json"); Files.move(file, backup); Files.createDirectory(file);
|
||||
try {
|
||||
use(READY, new ItemStack(Items.BOWL, 2));
|
||||
require(AstraCauldron.pots().get(level, READY).servings() == 2 && player.getMainHandItem().getCount() == 2, "failed save rolls back pot and consumes no bowl");
|
||||
} finally { Files.delete(file); Files.move(backup, file); }
|
||||
}
|
||||
private void checkLiquids(ServerLevel level) throws Exception {
|
||||
var api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
|
||||
var plain = new BlockPos(20,100,8); level.setBlock(plain,Blocks.CAULDRON.defaultBlockState(),3);
|
||||
for(var type:List.of(Items.POTION,Items.SPLASH_POTION,Items.LINGERING_POTION)) use(plain,PotionContents.createItemStack(type,Potions.WATER));
|
||||
require(level.getBlockState(plain).is(Blocks.WATER_CAULDRON) && level.getBlockState(plain).getValue(LayeredCauldronBlock.LEVEL)==3
|
||||
&& !AstraCauldron.liquids().contains(level,plain),"all water bottle kinds fill vanilla water, never become soup");
|
||||
var dye = new ItemStack(Items.DYE.pick(DyeColor.RED));
|
||||
int red = api.mixDye(OptionalInt.empty(),dye).orElseThrow();
|
||||
var pos = new BlockPos(18,100,8);
|
||||
for (var armor : List.of(Items.LEATHER_HELMET,Items.LEATHER_CHESTPLATE,Items.LEATHER_LEGGINGS,Items.LEATHER_BOOTS,Items.LEATHER_HORSE_ARMOR,Items.WOLF_ARMOR)) {
|
||||
AstraCauldron.liquids().breakPot(level,pos); fill(level,pos);
|
||||
use(pos,dye.copyWithCount(2));
|
||||
require(player.getMainHandItem().getCount()==1 && AstraCauldron.liquids().get(level,pos).levels()==3,"dye consumes one, keeps water volume: " + armor);
|
||||
var stack = new ItemStack(armor); stack.set(DataComponents.CUSTOM_NAME,net.minecraft.network.chat.Component.literal("Keep name"));
|
||||
if (stack.isDamageableItem()) stack.setDamageValue(3);
|
||||
use(pos,stack);
|
||||
var result=player.getMainHandItem();
|
||||
require(result.is(armor) && result.get(DataComponents.DYED_COLOR).rgb()==red && result.get(DataComponents.CUSTOM_NAME).getString().equals("Keep name"),"armor dyed with metadata preserved: " + armor);
|
||||
require(AstraCauldron.liquids().get(level,pos).levels()==2,"armor costs one water level: " + armor);
|
||||
if(result.isDamageableItem()) require(result.getDamageValue()==3,"armor damage preserved: " + armor);
|
||||
}
|
||||
use(pos,new ItemStack(Items.DYE.pick(DyeColor.BLUE)));
|
||||
require(AstraCauldron.liquids().get(level,pos).rgb()!=red,"second dye mixes water color");
|
||||
var originalArmor = new ItemStack(Items.LEATHER_HELMET);
|
||||
var transformedArmor = api.dyeArmor(originalArmor,red).orElseThrow();
|
||||
require(!originalArmor.has(DataComponents.DYED_COLOR) && transformedArmor.has(DataComponents.DYED_COLOR),"AstraPlus armor API never mutates input");
|
||||
use(pos,new ItemStack(Items.IRON_CHESTPLATE));
|
||||
require(!player.getMainHandItem().has(DataComponents.DYED_COLOR) && AstraCauldron.liquids().get(level,pos).levels()==2,"non-leather armor rejected without water loss");
|
||||
AstraCauldron.liquids().breakPot(level,pos); level.setBlock(pos,Blocks.CAULDRON.defaultBlockState(),3);
|
||||
player.getInventory().clearContent();
|
||||
for(var type:List.of(Items.POTION,Items.SPLASH_POTION,Items.LINGERING_POTION)) {
|
||||
use(pos,PotionContents.createItemStack(type,Potions.LONG_NIGHT_VISION));
|
||||
}
|
||||
require(AstraCauldron.liquids().get(level,pos).levels()==3 && player.getInventory().countItem(Items.GLASS_BOTTLE)==3,"all three potion bottle kinds fill same potion, return glass");
|
||||
var different=PotionContents.createItemStack(Items.POTION,Potions.STRONG_STRENGTH);
|
||||
use(pos,different);
|
||||
require(player.getMainHandItem().getCount()==1 && AstraCauldron.liquids().get(level,pos).levels()==3,"different potion rejected without item loss");
|
||||
player.getInventory().clearContent(); use(pos,new ItemStack(Items.ARROW,17));
|
||||
require(player.getInventory().countItem(Items.TIPPED_ARROW)==17 && AstraCauldron.liquids().get(level,pos).levels()==1,"17 tipped arrows cost two levels");
|
||||
use(pos,new ItemStack(Items.ARROW,32));
|
||||
require(player.getMainHandItem().getCount()==16 && player.getInventory().countItem(Items.TIPPED_ARROW)==33 && !AstraCauldron.liquids().contains(level,pos),"partial arrow conversion respects remaining potion volume");
|
||||
for(int i=0;i<3;i++)use(pos,PotionContents.createItemStack(Items.POTION,Potions.LONG_NIGHT_VISION));
|
||||
player.getInventory().clearContent(); use(pos,new ItemStack(Items.ARROW,64));
|
||||
require(player.getInventory().countItem(Items.TIPPED_ARROW)==64 && !AstraCauldron.liquids().contains(level,pos),"full potion cauldron tips entire 64 arrow stack");
|
||||
var arrow=player.getInventory().getItem(0);
|
||||
if(!arrow.is(Items.TIPPED_ARROW)) for(int i=0;i<player.getInventory().getContainerSize();i++)if(player.getInventory().getItem(i).is(Items.TIPPED_ARROW))arrow=player.getInventory().getItem(i);
|
||||
require(arrow.get(DataComponents.POTION_CONTENTS).is(Potions.LONG_NIGHT_VISION) && arrow.get(DataComponents.POTION_DURATION_SCALE)==.125f,"arrows preserve effects with vanilla duration multiplier");
|
||||
use(pos,PotionContents.createItemStack(Items.SPLASH_POTION,Potions.LONG_NIGHT_VISION));
|
||||
player.getInventory().clearContent(); use(pos,new ItemStack(Items.GLASS_BOTTLE));
|
||||
require(player.getInventory().countItem(Items.POTION)==1 && !AstraCauldron.liquids().contains(level,pos),"potion storage drains back into drinkable bottle");
|
||||
var savedPotion=new BlockPos(24,100,8); level.setBlock(savedPotion,Blocks.CAULDRON.defaultBlockState(),3);
|
||||
for(int i=0;i<2;i++)use(savedPotion,PotionContents.createItemStack(Items.POTION,Potions.LONG_NIGHT_VISION));
|
||||
var savedDye=new BlockPos(26,100,8); fill(level,savedDye); use(savedDye,dye.copy()); use(savedDye,new ItemStack(Items.LEATHER_HELMET));
|
||||
}
|
||||
private static JsonElement encode(ItemStack stack, net.minecraft.core.HolderLookup.Provider registries) {
|
||||
return ItemStack.CODEC.encodeStart(net.minecraft.resources.RegistryOps.create(com.mojang.serialization.JsonOps.INSTANCE,registries),stack).getOrThrow();
|
||||
}
|
||||
private static ItemStack decode(JsonElement json, net.minecraft.core.HolderLookup.Provider registries) {
|
||||
return ItemStack.CODEC.parse(net.minecraft.resources.RegistryOps.create(com.mojang.serialization.JsonOps.INSTANCE,registries),json).getOrThrow();
|
||||
}
|
||||
private void use(BlockPos pos, ItemStack item) {
|
||||
var previous = player.getMainHandItem();
|
||||
player.setItemInHand(InteractionHand.MAIN_HAND,item);
|
||||
// Simulate selecting another slot without deleting a returned bottle from the old hand slot.
|
||||
if(!previous.isEmpty()) {
|
||||
for(int slot=9;slot<36;slot++) if(player.getInventory().getItem(slot).isEmpty()) {
|
||||
player.getInventory().setItem(slot,previous); break;
|
||||
}
|
||||
}
|
||||
NeoForge.EVENT_BUS.post(click(pos));
|
||||
}
|
||||
private PlayerInteractEvent.RightClickBlock click(BlockPos pos) { return new PlayerInteractEvent.RightClickBlock(player, InteractionHand.MAIN_HAND, pos, new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false)); }
|
||||
private static void fill(ServerLevel level, BlockPos pos) { level.setBlock(pos, Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL, 3), 3); }
|
||||
private static ColoredWaterApi water() { return AstraPlusApi.current().flatMap(AstraPlusApi::coloredWater).orElseThrow(); }
|
||||
private static List<Display> displays(ServerLevel level, BlockPos pos) { return level.getEntitiesOfClass(Display.class, new AABB(pos).inflate(.05), e -> !e.isRemoved()); }
|
||||
private void require(boolean condition, String label) { if (!condition) throw new AssertionError(label); passed.add("PASS " + label); }
|
||||
private void finish(MinecraftServer server, String phase) throws Exception { finished = true; Files.writeString(Path.of("verification-result.txt"), String.join("\n", passed) + "\nPASS " + phase + ": " + passed.size()); server.halt(false); }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[11,)"
|
||||
license="All Rights Reserved"
|
||||
[[mods]]
|
||||
modId="astracauldron_verify"
|
||||
version="1.0.0"
|
||||
displayName="AstraCauldron isolated verification"
|
||||
[[dependencies.astracauldron_verify]]
|
||||
modId="astracauldron"
|
||||
type="required"
|
||||
versionRange="[0.2.0,)"
|
||||
ordering="AFTER"
|
||||
side="SERVER"
|
||||
@@ -5,21 +5,26 @@ import net.minecraft.client.renderer.item.ItemModels;
|
||||
import net.minecraft.client.color.item.ItemTintSources;
|
||||
import net.minecraft.client.resources.model.cuboid.CuboidModel;
|
||||
import java.nio.file.*;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
// Run with the Minecraft 26.2 client and its libraries on the classpath.
|
||||
class CheckSoupModels {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ItemModels.bootstrap();
|
||||
ItemTintSources.bootstrap();
|
||||
Path assets = Path.of(args[0]);
|
||||
try (var reader = Files.newBufferedReader(assets.resolve("items/combined_soup.json"))) {
|
||||
ClientItem item = ClientItem.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseReader(reader)).getOrThrow();
|
||||
System.out.println("PASS: Minecraft 26.2 decodes composite bowl and custom model color tint: " + item.model());
|
||||
}
|
||||
try (var reader = Files.newBufferedReader(assets.resolve("models/item/soup_liquid.json"))) {
|
||||
CuboidModel model = CuboidModel.fromStream(reader);
|
||||
if (model.geometry() == null || model.transforms() == null) throw new AssertionError("Missing geometry/transforms");
|
||||
System.out.println("PASS: Minecraft 26.2 decodes liquid geometry and item display transforms");
|
||||
try (var zip = new ZipFile(args[0])) {
|
||||
for (String name : new String[]{"assets/astradev_soups/items/combined_soup.json", "assets/astraplus/items/colored_water.json",
|
||||
"assets/astradev_soups/models/item/soup_liquid.json", "assets/astraplus/models/internal/colored_water.json"}) {
|
||||
var entry = zip.getEntry(name);
|
||||
if (entry == null) throw new AssertionError("Missing packed model " + name);
|
||||
try (var reader = new InputStreamReader(zip.getInputStream(entry), StandardCharsets.UTF_8)) {
|
||||
if (name.contains("/items/")) ClientItem.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseReader(reader)).getOrThrow();
|
||||
else if (CuboidModel.fromStream(reader).geometry() == null) throw new AssertionError("Missing geometry " + name);
|
||||
System.out.println("PASS Minecraft 26.2 model decoder: " + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
param([string]$MinecraftDirectory = "$env:APPDATA/.minecraft")
|
||||
param([string]$MinecraftDirectory = "$env:APPDATA/.minecraft", [string]$ResourcePack)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = Split-Path $PSScriptRoot -Parent
|
||||
if (!$ResourcePack) {
|
||||
$run = (Get-Content -LiteralPath "$repo/build/active-verification.txt" -Raw).Trim()
|
||||
$ResourcePack = Join-Path $run 'astraplus/output/AstraPlus.zip'
|
||||
}
|
||||
$version = Get-Content -Raw -LiteralPath "$MinecraftDirectory/versions/26.2/26.2.json" | ConvertFrom-Json
|
||||
$classpath = @("$MinecraftDirectory/versions/26.2/26.2.jar") + @(
|
||||
$version.libraries | Where-Object { $_.downloads.artifact.path } | ForEach-Object {
|
||||
@@ -11,7 +15,7 @@ New-Item -ItemType Directory -Force -Path "$repo/build" | Out-Null
|
||||
$arguments = @(
|
||||
'--class-path', ('"' + (($classpath -join ';').Replace('\', '/')) + '"'),
|
||||
('"' + "$PSScriptRoot/CheckSoupModels.java".Replace('\', '/') + '"'),
|
||||
('"' + "$repo/src/main/resources/astra-itemsadder/astradev_soups/resourcepack/assets/astradev_soups".Replace('\', '/') + '"')
|
||||
('"' + $ResourcePack.Replace('\', '/') + '"')
|
||||
)
|
||||
$argumentFile = "$repo/build/check-models.args"
|
||||
Set-Content -Encoding utf8 -LiteralPath $argumentFile -Value $arguments
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
name: SoupSmokeTest
|
||||
version: '1.0'
|
||||
main: smoke.SoupSmokeTest
|
||||
api-version: '26.2'
|
||||
depend: [AstraSoups]
|
||||
@@ -1,328 +0,0 @@
|
||||
package smoke;
|
||||
|
||||
import online.astradev.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() {
|
||||
new org.bukkit.scheduler.BukkitRunnable() {
|
||||
int attempts;
|
||||
@Override public void run() {
|
||||
String phase = Files.exists(getDataFolder().toPath().resolve("phase1.txt")) ? "phase2" : "phase1";
|
||||
try {
|
||||
if (phase.equals("phase1")) {
|
||||
var ia = Bukkit.getPluginManager().getPlugin("ItemsAdder");
|
||||
var api = Class.forName("dev.lone.itemsadder.api.ItemsAdder", true, ia.getClass().getClassLoader());
|
||||
if (!(boolean) api.getMethod("areItemsLoaded").invoke(null)
|
||||
|| !Files.exists(Path.of("plugins/ItemsAdder/output/generated.zip"))) {
|
||||
if (++attempts < 180) return;
|
||||
throw new IllegalStateException("ItemsAdder pack did not become ready");
|
||||
}
|
||||
}
|
||||
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);
|
||||
cancel();
|
||||
Bukkit.shutdown();
|
||||
}
|
||||
}.runTaskTimer(this, 40, 20);
|
||||
}
|
||||
|
||||
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 void advance(int ticks) throws Exception {
|
||||
var refresh = AstraSoupsPlugin.class.getDeclaredMethod("refresh"); refresh.setAccessible(true);
|
||||
for (int i = 0; i < ticks; i++) refresh.invoke(plugin);
|
||||
}
|
||||
private List<ItemDisplay> visualItems(Block block) {
|
||||
return world.getNearbyEntities(block.getLocation().add(.5, .5, .5), .5, .5, .5).stream()
|
||||
.filter(e -> e instanceof ItemDisplay && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual")))
|
||||
.map(e -> (ItemDisplay) e).toList();
|
||||
}
|
||||
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);
|
||||
check(!stack.hasData(DataComponentTypes.CUSTOM_MODEL_DATA), "Vanilla soup keeps its original icon: " + 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");
|
||||
check(soup.getData(DataComponentTypes.ITEM_MODEL).asString().equals("astradev_soups:combined_soup"), "Combined soup selects the bundled colored bowl model");
|
||||
ItemStack legacyIcon = soup.clone();
|
||||
legacyIcon.resetData(DataComponentTypes.ITEM_MODEL);
|
||||
legacyIcon.unsetData(DataComponentTypes.CUSTOM_MODEL_DATA);
|
||||
check(Ingredients.normalize(legacyIcon) && legacyIcon.isSimilar(soup), "Old soup icon migrates while retaining all recipe components");
|
||||
check(!Ingredients.normalize(legacyIcon), "Icon migration is idempotent");
|
||||
ItemStack extendedData = soup.clone();
|
||||
extendedData.setData(DataComponentTypes.CUSTOM_MODEL_DATA,
|
||||
io.papermc.paper.datacomponent.item.CustomModelData.customModelData()
|
||||
.addFloat(42).addFlag(true).addString("keep").addColor(Color.BLACK).addColor(Color.BLUE).build());
|
||||
Ingredients.normalize(extendedData);
|
||||
var retained = extendedData.getData(DataComponentTypes.CUSTOM_MODEL_DATA);
|
||||
check(retained.floats().equals(List.of(42f)) && retained.flags().equals(List.of(true))
|
||||
&& retained.strings().equals(List.of("keep")) && retained.colors().get(1).equals(Color.BLUE),
|
||||
"Icon migration preserves unrelated custom model data slots");
|
||||
var plain = net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText();
|
||||
List<String> lore = soup.lore().stream().map(plain::serialize).toList();
|
||||
check(lore.stream().anyMatch(s -> s.contains(" II (1:30)")) && lore.stream().anyMatch(s -> s.contains(" I (8:00)")), "Potion levels use Roman numerals with parenthesized durations");
|
||||
check(lore.stream().noneMatch(s -> s.contains("\u2022")), "Soup descriptions contain no floating dot separators");
|
||||
ItemStack oldSoup = soup.clone(); ItemMeta oldMeta = oldSoup.getItemMeta();
|
||||
oldMeta.lore(List.of(net.kyori.adventure.text.Component.text("Strength 2 \u2022 1:30"))); oldSoup.setItemMeta(oldMeta);
|
||||
check(Ingredients.normalize(oldSoup) && oldSoup.isSimilar(soup), "Existing soup descriptions migrate without changing effects or food");
|
||||
ItemStack purple = potion(Material.POTION, PotionType.WATER), green = purple.clone();
|
||||
PotionMeta purpleMeta = (PotionMeta) purple.getItemMeta(); purpleMeta.setColor(Color.fromRGB(0x8B3AC7)); purple.setItemMeta(purpleMeta);
|
||||
PotionMeta greenMeta = (PotionMeta) green.getItemMeta(); greenMeta.setColor(Color.fromRGB(0x45B649)); green.setItemMeta(greenMeta);
|
||||
ItemStack colorExample = ingredients.brew(List.of(item(Material.SPIDER_EYE), item(Material.GOLDEN_APPLE), purple, green));
|
||||
NamespacedKey colorKey = new NamespacedKey(plugin, "soup_color");
|
||||
check(colorExample.getItemMeta().getPersistentDataContainer().get(colorKey, org.bukkit.persistence.PersistentDataType.INTEGER) == 0x9D7965, "Red eye, golden apple, purple and green potions blend into exact brown RGB");
|
||||
check(colorExample.getData(DataComponentTypes.CUSTOM_MODEL_DATA).colors().getFirst().asRGB() == 0x9D7965, "Bowl liquid tint uses exactly the cauldron mixed RGB");
|
||||
ItemStack redSoup = ingredients.brew(Collections.nCopies(4, item(Material.APPLE)));
|
||||
ItemStack orangeSoup = ingredients.brew(Collections.nCopies(4, item(Material.CARROT)));
|
||||
check(!redSoup.getItemMeta().getPersistentDataContainer().get(colorKey, org.bukkit.persistence.PersistentDataType.INTEGER)
|
||||
.equals(orangeSoup.getItemMeta().getPersistentDataContainer().get(colorKey, org.bukkit.persistence.PersistentDataType.INTEGER)), "Different food colors produce different soup colors");
|
||||
check(ingredients.read(redSoup).color().asRGB() == 0xC73735, "Reusing a combined soup preserves its stored liquid color");
|
||||
check(!redSoup.getData(DataComponentTypes.CUSTOM_MODEL_DATA).colors()
|
||||
.equals(orangeSoup.getData(DataComponentTypes.CUSTOM_MODEL_DATA).colors()), "Different mixtures have different icon tints");
|
||||
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 = visualItems(pot).size();
|
||||
check(count == 4, "Four ItemDisplays visualize the ingredients");
|
||||
check(visualItems(pot).stream().allMatch(e -> e.getLocation().getY() + e.getTransformation().getTranslation().y < pot.getY() + .9375 - .05), "Display centers are partly submerged without client item bobbing");
|
||||
for (ItemDisplay drop : visualItems(pot)) {
|
||||
check(!drop.hasGravity() && drop.getInterpolationDuration() == 2, "Display ingredient has client interpolation and no dropped-item physics");
|
||||
}
|
||||
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 TextDisplay), "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().noneMatch(e -> e instanceof TextDisplay), "Starting a brew does not create soup immediately");
|
||||
check(visualItems(pot).size() == 4, "Brewing retains four animated ingredient entities");
|
||||
ItemDisplay tracked = visualItems(pot).getFirst(); Location anchor = tracked.getLocation();
|
||||
org.joml.Vector3f start = new org.joml.Vector3f(tracked.getTransformation().getTranslation());
|
||||
click(pot, new ItemStack(Material.BOWL, 2), false, false);
|
||||
check(player.getInventory().getItemInMainHand().getAmount() == 2
|
||||
&& Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).noneMatch(plugin.ingredients()::isCombined), "An early bowl cannot collect soup or be consumed");
|
||||
click(pot, item(Material.AIR), false, false);
|
||||
check(player.getInventory().getItemInMainHand().getType().isAir() && visualItems(pot).size() == 4, "Empty hand cannot withdraw ingredients during brewing");
|
||||
advance(40);
|
||||
org.joml.Vector3f moved = tracked.getTransformation().getTranslation();
|
||||
check(tracked.isValid() && tracked.getLocation().equals(anchor) && moved.distance(start) > .1, "Same stationary entity moves its interpolated model without teleporting");
|
||||
check(Math.abs(Math.hypot(moved.x, moved.z) - .23) < .00001, "Whirlpool maintains its radius instead of collapsing to center");
|
||||
click(pot, item(Material.STICK), true, false);
|
||||
advance(39);
|
||||
check(world.getEntities().stream().noneMatch(e -> e instanceof TextDisplay), "No soup before the configured 80th tick");
|
||||
advance(1);
|
||||
check(world.getEntities().stream().anyMatch(e -> e instanceof TextDisplay), "Brew creates colored soup surface");
|
||||
TextDisplay surface = world.getEntities().stream().filter(e -> e instanceof TextDisplay).map(e -> (TextDisplay) e).findFirst().orElseThrow();
|
||||
check(surface.getBackgroundColor().asRGB() == soup.getItemMeta().getPersistentDataContainer().get(colorKey, org.bukkit.persistence.PersistentDataType.INTEGER)
|
||||
&& surface.getBackgroundColor().getAlpha() == 255 && !surface.isSeeThrough(), "Liquid surface uses the exact opaque mixed RGB, not a terracotta palette");
|
||||
check(visualItems(pot).isEmpty(), "Brew removes ingredient visuals");
|
||||
double previousHeight = surface.getTransformation().getTranslation().y;
|
||||
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.WATER_CAULDRON, "Cauldron retains soup after the first of four portions");
|
||||
check(((Levelled) pot.getBlockData()).getLevel() == 2 && surface.isValid()
|
||||
&& surface.getTransformation().getTranslation().y < previousHeight, "First portion lowers both water and the same interpolated soup surface");
|
||||
for (int i = 0; i < 3; i++) {
|
||||
previousHeight = surface.getTransformation().getTranslation().y;
|
||||
click(pot, item(Material.BOWL), false, false);
|
||||
if (i < 2) check(surface.isValid() && surface.getTransformation().getTranslation().y < previousHeight,
|
||||
"Each remaining portion visibly lowers soup without respawning the surface");
|
||||
if (i == 1) check(pot.getType() == Material.CAULDRON && surface.isValid(), "Last portion uses a low colored surface with no blue water above it");
|
||||
}
|
||||
check(!surface.isValid(), "Final portion removes the liquid surface");
|
||||
check(soupInInventory().getAmount() == 4 && pot.getType() == Material.CAULDRON, "Four bowls collect exactly four stackable portions and empty the cauldron");
|
||||
click(pot, item(Material.BOWL), false, false);
|
||||
check(soupInInventory().getAmount() == 4, "A fifth bowl cannot obtain another portion");
|
||||
// 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");
|
||||
advance(80);
|
||||
click(pot, item(Material.BOWL), false, false);
|
||||
click(pot, item(Material.BOWL), false, false);
|
||||
Block raw = world.getBlockAt(5, 80, 2); fill(raw); click(raw, item(Material.GOLDEN_CARROT), false, false);
|
||||
Block brewing = world.getBlockAt(8, 80, 2); fill(brewing); addFour(brewing); click(brewing, item(Material.STICK), false, false);
|
||||
check(visualItems(brewing).size() == 4, "In-flight brew saved for restart with its four ingredients");
|
||||
check(new java.io.File(plugin.getDataFolder(), "cauldrons.yml").length() > 0, "Cauldron states saved before restart");
|
||||
}
|
||||
private void second() throws Exception {
|
||||
advance(1); // setup loaded the chunk this tick; give visuals their first refresh.
|
||||
check(pot.getType() == Material.WATER_CAULDRON, "Ready cauldron block survives restart");
|
||||
check(((Levelled) pot.getBlockData()).getLevel() == 1, "Restart preserves the reduced water level for two of four servings");
|
||||
click(pot, new ItemStack(Material.BOWL, 2), false, false);
|
||||
ItemStack soup = soupInInventory();
|
||||
check(soup.getMaxStackSize() == 16 && effects(soup).size() == 2, "Ready soup keeps stack size and effects across process restart");
|
||||
click(pot, item(Material.BOWL), false, false);
|
||||
check(soupInInventory().getAmount() == 2 && pot.getType() == Material.CAULDRON, "Restart preserves exactly two remaining portions instead of refilling the cauldron");
|
||||
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");
|
||||
Block brewing = world.getBlockAt(8, 80, 2);
|
||||
check(visualItems(brewing).size() == 4, "In-flight brew restores animated ingredients after process restart");
|
||||
click(brewing, item(Material.BOWL), false, false);
|
||||
check(player.getInventory().getItemInMainHand().getType() == Material.BOWL
|
||||
&& Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).noneMatch(plugin.ingredients()::isCombined), "Restart cannot turn an in-flight brew into instant soup");
|
||||
advance(80);
|
||||
click(brewing, new ItemStack(Material.BOWL, 4), false, false);
|
||||
check(soupInInventory().getMaxStackSize() == 16 && effects(soupInInventory()).size() == 2, "Resumed brew completes and yields the expected soup once");
|
||||
for (int i = 0; i < 3; i++) click(brewing, player.getInventory().getItemInMainHand(), false, false);
|
||||
check(soupInInventory().getAmount() == 4 && brewing.getType() == Material.CAULDRON, "Resumed in-flight brew produces exactly four portions");
|
||||
player.getInventory().clear();
|
||||
click(brewing, item(Material.BOWL), false, false);
|
||||
check(Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).noneMatch(plugin.ingredients()::isCombined), "Repeated collection cannot duplicate a completed brew");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
param(
|
||||
[string]$ServerDirectory = 'C:/Users/ScarPC/Documents/NeoForge Server 26.2',
|
||||
[string]$Java = 'java',
|
||||
[int]$Port = 25639
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = Split-Path $PSScriptRoot -Parent
|
||||
$plus = Join-Path (Split-Path $repo -Parent) 'AstraPlus'
|
||||
$run = Join-Path $repo ('build/verification-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,6))
|
||||
New-Item -ItemType Directory -Path (Join-Path $run 'mods') -Force | Out-Null
|
||||
foreach ($jar in @("$plus/build/libs/AstraPlus-0.5.1.jar", "$repo/build/libs/AstraCauldron-0.2.0.jar", "$repo/build/libs/AstraCauldron-0.2.0-verification.jar")) {
|
||||
Copy-Item -LiteralPath $jar -Destination (Join-Path $run 'mods')
|
||||
}
|
||||
$serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/')
|
||||
$argsLines = Get-Content -LiteralPath "$ServerDirectory/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt"
|
||||
$argsText = (@(foreach ($line in $argsLines) {
|
||||
if ($line -eq '-DlibraryDirectory=libraries') { '"-DlibraryDirectory=' + $serverRoot + '/libraries"' }
|
||||
elseif ($line.StartsWith('libraries/')) { '"' + $line.Replace('libraries/', "$serverRoot/libraries/") + '"' }
|
||||
else { $line }
|
||||
}) -join "`n")
|
||||
[IO.File]::WriteAllText((Join-Path $run 'server-args.txt'), $argsText, [Text.UTF8Encoding]::new($false))
|
||||
[IO.File]::WriteAllText((Join-Path $run 'eula.txt'), 'eula=true')
|
||||
$properties = @"
|
||||
server-ip=127.0.0.1
|
||||
server-port=$Port
|
||||
online-mode=false
|
||||
level-type=minecraft:flat
|
||||
generator-settings={"layers":[{"block":"minecraft:bedrock","height":1},{"block":"minecraft:dirt","height":2},{"block":"minecraft:grass_block","height":1}],"biome":"minecraft:plains"}
|
||||
generate-structures=false
|
||||
spawn-protection=0
|
||||
view-distance=2
|
||||
simulation-distance=2
|
||||
max-tick-time=90000
|
||||
use-native-transport=false
|
||||
motd=AstraCauldron isolated verification
|
||||
"@
|
||||
[IO.File]::WriteAllText((Join-Path $run 'server.properties'), $properties)
|
||||
Set-Content -LiteralPath "$repo/build/active-verification.txt" -Value $run
|
||||
Push-Location $run
|
||||
try {
|
||||
foreach ($phase in @('gameplay','restart')) {
|
||||
& $Java '-Xms256M' '-Xmx1G' '-Dastracauldron.isolatedVerification=true' '@server-args.txt' nogui *> "$phase.log"
|
||||
if ($LASTEXITCODE -ne 0) { throw "Server failed: $run/$phase.log" }
|
||||
$result = Get-Content -LiteralPath 'verification-result.txt' -Raw
|
||||
if ($result -match '(?m)^FAIL' -or $result -notmatch "PASS ${phase}:") { throw "Verification failed: $run/verification-result.txt" }
|
||||
Copy-Item -LiteralPath 'verification-result.txt' -Destination "$phase-result.txt"
|
||||
Write-Output (($result -split "`n")[-1])
|
||||
}
|
||||
} finally { Pop-Location }
|
||||
Write-Output "Verified both launches: $run"
|
||||
@@ -0,0 +1,86 @@
|
||||
PASS native per-stack size minecraft:mushroom_stew
|
||||
PASS native per-stack size minecraft:rabbit_stew
|
||||
PASS native per-stack size minecraft:beetroot_soup
|
||||
PASS native per-stack size minecraft:suspicious_stew
|
||||
PASS whole cake nutrition
|
||||
PASS arrows rejected
|
||||
PASS summed native food nutrition
|
||||
PASS soup consumable at full hunger
|
||||
PASS recipe order independent stacking
|
||||
PASS native item codec preserves full soup
|
||||
PASS potion full duration preserved
|
||||
PASS golden apple effects preserved
|
||||
PASS native consumption feeds and applies effects
|
||||
PASS native stacked consumption returns bowl
|
||||
PASS chorus teleport retained
|
||||
PASS probabilistic effects retained
|
||||
PASS AstraPlus identity and native food read via public API
|
||||
PASS ordinary carrier is not custom food
|
||||
PASS custom AstraPlus registration overrides nutrition
|
||||
PASS registration survives AstraPlus definition edits
|
||||
PASS invalid reload rejected
|
||||
PASS invalid reload leaves previous runtime intact
|
||||
PASS independent water API creates surface without soup
|
||||
PASS AstraPlus generic water model
|
||||
PASS water owner isolation
|
||||
PASS color and height update
|
||||
PASS API update reuses entity
|
||||
PASS removed entity recreated once
|
||||
PASS API never loads chunks
|
||||
PASS owner cleanup removes surface
|
||||
PASS API validates RGB
|
||||
PASS API validates finite height
|
||||
PASS cancelled interaction is respected
|
||||
PASS event insertion consumes one
|
||||
PASS vanilla level mutation blocked for occupied pot
|
||||
PASS cancelled breaking preserves ingredients
|
||||
PASS empty hand returns ingredient and removes pot
|
||||
PASS ordinary cauldron retains vanilla behavior
|
||||
PASS full water required
|
||||
PASS all water bottle kinds fill vanilla water, never become soup
|
||||
PASS dye consumes one, keeps water volume: minecraft:leather_helmet
|
||||
PASS armor dyed with metadata preserved: minecraft:leather_helmet
|
||||
PASS armor costs one water level: minecraft:leather_helmet
|
||||
PASS armor damage preserved: minecraft:leather_helmet
|
||||
PASS dye consumes one, keeps water volume: minecraft:leather_chestplate
|
||||
PASS armor dyed with metadata preserved: minecraft:leather_chestplate
|
||||
PASS armor costs one water level: minecraft:leather_chestplate
|
||||
PASS armor damage preserved: minecraft:leather_chestplate
|
||||
PASS dye consumes one, keeps water volume: minecraft:leather_leggings
|
||||
PASS armor dyed with metadata preserved: minecraft:leather_leggings
|
||||
PASS armor costs one water level: minecraft:leather_leggings
|
||||
PASS armor damage preserved: minecraft:leather_leggings
|
||||
PASS dye consumes one, keeps water volume: minecraft:leather_boots
|
||||
PASS armor dyed with metadata preserved: minecraft:leather_boots
|
||||
PASS armor costs one water level: minecraft:leather_boots
|
||||
PASS armor damage preserved: minecraft:leather_boots
|
||||
PASS dye consumes one, keeps water volume: minecraft:leather_horse_armor
|
||||
PASS armor dyed with metadata preserved: minecraft:leather_horse_armor
|
||||
PASS armor costs one water level: minecraft:leather_horse_armor
|
||||
PASS dye consumes one, keeps water volume: minecraft:wolf_armor
|
||||
PASS armor dyed with metadata preserved: minecraft:wolf_armor
|
||||
PASS armor costs one water level: minecraft:wolf_armor
|
||||
PASS armor damage preserved: minecraft:wolf_armor
|
||||
PASS second dye mixes water color
|
||||
PASS AstraPlus armor API never mutates input
|
||||
PASS non-leather armor rejected without water loss
|
||||
PASS all three potion bottle kinds fill same potion, return glass
|
||||
PASS different potion rejected without item loss
|
||||
PASS 17 tipped arrows cost two levels
|
||||
PASS partial arrow conversion respects remaining potion volume
|
||||
PASS full potion cauldron tips entire 64 arrow stack
|
||||
PASS arrows preserve effects with vanilla duration multiplier
|
||||
PASS potion storage drains back into drinkable bottle
|
||||
PASS four ingredients start timed brew
|
||||
PASS four ingredient displays while brewing
|
||||
PASS ingredient displays never persist as entities
|
||||
PASS brew finishes after 80 ticks
|
||||
PASS AstraPlus owns single liquid display
|
||||
PASS liquid belongs to AstraPlus
|
||||
PASS portion lowers water API height
|
||||
PASS portion interpolates same display
|
||||
PASS two saved servings remain
|
||||
PASS failed save rolls back pot and consumes no bowl
|
||||
PASS AstraPlus packs its own water resource
|
||||
PASS AstraCauldron bowl exported before AstraPlus pack build
|
||||
PASS gameplay: 85
|
||||
@@ -1,2 +0,0 @@
|
||||
PASS: Minecraft 26.2 decodes composite bowl and custom model color tint: Unbaked[models=[Unbaked[model=minecraft:item/bowl, transformation=Optional.empty, tints=[]], Unbaked[model=astradev_soups:item/soup_liquid, transformation=Optional.empty, tints=[CustomModelDataSource[index=0, defaultColor=12024374]]]], transformation=Optional.empty]
|
||||
PASS: Minecraft 26.2 decodes liquid geometry and item display transforms
|
||||
@@ -1,120 +0,0 @@
|
||||
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 keeps its original icon: MUSHROOM_STEW
|
||||
PASS: Vanilla soup stack size: RABBIT_STEW
|
||||
PASS: Vanilla soup keeps its original icon: RABBIT_STEW
|
||||
PASS: Vanilla soup stack size: BEETROOT_SOUP
|
||||
PASS: Vanilla soup keeps its original icon: BEETROOT_SOUP
|
||||
PASS: Vanilla soup stack size: SUSPICIOUS_STEW
|
||||
PASS: Vanilla soup keeps its original icon: SUSPICIOUS_STEW
|
||||
PASS: Example combines 10 hunger points
|
||||
PASS: Example combines 13.2 saturation points
|
||||
PASS: Combined soup stacks to sixteen
|
||||
PASS: Combined soup selects the bundled colored bowl model
|
||||
PASS: Old soup icon migrates while retaining all recipe components
|
||||
PASS: Icon migration is idempotent
|
||||
PASS: Icon migration preserves unrelated custom model data slots
|
||||
PASS: Potion levels use Roman numerals with parenthesized durations
|
||||
PASS: Soup descriptions contain no floating dot separators
|
||||
PASS: Existing soup descriptions migrate without changing effects or food
|
||||
PASS: Red eye, golden apple, purple and green potions blend into exact brown RGB
|
||||
PASS: Bowl liquid tint uses exactly the cauldron mixed RGB
|
||||
PASS: Different food colors produce different soup colors
|
||||
PASS: Reusing a combined soup preserves its stored liquid color
|
||||
PASS: Different mixtures have different icon tints
|
||||
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 ItemDisplays visualize the ingredients
|
||||
PASS: Display centers are partly submerged without client item bobbing
|
||||
PASS: Display ingredient has client interpolation and no dropped-item physics
|
||||
PASS: Display ingredient has client interpolation and no dropped-item physics
|
||||
PASS: Display ingredient has client interpolation and no dropped-item physics
|
||||
PASS: Display ingredient has client interpolation and no dropped-item physics
|
||||
PASS: Empty-hand withdrawal is LIFO
|
||||
PASS: Incompatible recipe does not create ready soup
|
||||
PASS: Rejected recipe retains its ingredients
|
||||
PASS: Starting a brew does not create soup immediately
|
||||
PASS: Brewing retains four animated ingredient entities
|
||||
PASS: An early bowl cannot collect soup or be consumed
|
||||
PASS: Empty hand cannot withdraw ingredients during brewing
|
||||
PASS: Same stationary entity moves its interpolated model without teleporting
|
||||
PASS: Whirlpool maintains its radius instead of collapsing to center
|
||||
PASS: No soup before the configured 80th tick
|
||||
PASS: Brew creates colored soup surface
|
||||
PASS: Liquid surface uses the exact opaque mixed RGB, not a terracotta palette
|
||||
PASS: Brew removes ingredient visuals
|
||||
PASS: Collecting soup consumes one bowl
|
||||
PASS: Collecting yields exactly the expected recipe
|
||||
PASS: Cauldron retains soup after the first of four portions
|
||||
PASS: First portion lowers both water and the same interpolated soup surface
|
||||
PASS: Each remaining portion visibly lowers soup without respawning the surface
|
||||
PASS: Each remaining portion visibly lowers soup without respawning the surface
|
||||
PASS: Last portion uses a low colored surface with no blue water above it
|
||||
PASS: Final portion removes the liquid surface
|
||||
PASS: Four bowls collect exactly four stackable portions and empty the cauldron
|
||||
PASS: A fifth bowl cannot obtain another portion
|
||||
PASS: Ordinary right-click with an item starts cooking without consuming the tool
|
||||
PASS: In-flight brew saved for restart with its four ingredients
|
||||
PASS: Cauldron states saved before restart
|
||||
PASS: ALL 119 CHECKS (phase1)
|
||||
@@ -1,13 +0,0 @@
|
||||
PASS: Plugin enables on Paper 26.2
|
||||
PASS: Ready cauldron block survives restart
|
||||
PASS: Restart preserves the reduced water level for two of four servings
|
||||
PASS: Ready soup keeps stack size and effects across process restart
|
||||
PASS: Restart preserves exactly two remaining portions instead of refilling the cauldron
|
||||
PASS: Raw ingredient can be withdrawn after process restart
|
||||
PASS: Withdrawn ingredient cannot be obtained twice
|
||||
PASS: In-flight brew restores animated ingredients after process restart
|
||||
PASS: Restart cannot turn an in-flight brew into instant soup
|
||||
PASS: Resumed brew completes and yields the expected soup once
|
||||
PASS: Resumed in-flight brew produces exactly four portions
|
||||
PASS: Repeated collection cannot duplicate a completed brew
|
||||
PASS: ALL 12 CHECKS (phase2)
|
||||
@@ -0,0 +1,10 @@
|
||||
PASS ready servings restored
|
||||
PASS raw ingredient restored
|
||||
PASS unfinished brew restarts its timer
|
||||
PASS AstraPlus water restored by soup owner
|
||||
PASS single colored water display after restart
|
||||
PASS potion contents and volume survive restart
|
||||
PASS dyed water volume survives restart
|
||||
PASS restored brew finishes
|
||||
PASS last serving clears saved pot and water API
|
||||
PASS restart: 9
|
||||
Reference in New Issue
Block a user