Add submerged whirlpool brewing, four servings and mixed soup colors
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
# AstraSoups 0.1.0
|
||||
# AstraSoups 0.1.1
|
||||
|
||||
Отдельный серверный плагин комбинированных супов для **Paper 26.2**, Java 25+.
|
||||
Сборка проекта использует установленный JDK 26. Клиентские моды и ресурспак не требуются.
|
||||
@@ -7,12 +7,12 @@
|
||||
|
||||
1. Полностью наполнить котёл водой.
|
||||
2. Нажать ПКМ по котлу с ингредиентом в основной руке. Каждое нажатие кладёт **одну единицу**. Всего нужно **четыре**; одинаковые ингредиенты разрешены.
|
||||
3. Начать варку: **Shift+ПКМ** или обычный **ПКМ с любым предметом в руке**, когда все четыре ингредиента уже внутри. Предмет для запуска не расходуется. Ингредиенты исчезнут, поверхность воды станет цветной.
|
||||
4. **ПКМ миской** по готовому супу выдаёт **одну порцию**, расходует одну миску и опустошает котёл. Если запускать варку миской, первое нажатие варит, второе собирает.
|
||||
3. Начать варку: **Shift+ПКМ** или обычный **ПКМ с любым предметом в руке**, когда все четыре ингредиента уже внутри. Предмет для запуска не расходуется. Ингредиенты частично погружены в воду и в течение 4 секунд вращаются водоворотом, ускоряясь и сближаясь к центру. Затем исчезают, а поверхность воды становится цветной. Во время варки нельзя забрать ингредиент или собрать суп; повторный клик не перезапускает таймер.
|
||||
4. **ПКМ миской** по готовому супу выдаёт **одну из четырёх порций** и расходует одну миску. Котёл пустеет после четвёртой порции. Если запускать варку миской, первое нажатие запускает водоворот, следующее нажатие после его завершения собирает порцию.
|
||||
|
||||
**Обычный ПКМ пустой рукой** до варки возвращает самый недавно добавленный ингредиент. Такое разделение позволяет и запускать варку, и извлекать ингредиенты без конфликта действий.
|
||||
|
||||
Ингредиенты показаны настоящими левитирующими `Item`-сущностями: их нельзя подобрать, собрать воронкой, объединить с выпавшими предметами или уничтожить обычным уроном. Готовый суп отображается тонкой `BlockDisplay`-поверхностью внутри котла. Цвет смешивается из ингредиентов и округляется до ближайшего оттенка терракоты. Это приближение средствами ванильного клиента, а не изменение настоящего цвета воды.
|
||||
Ингредиенты показаны настоящими левитирующими `Item`-сущностями: их нельзя подобрать, собрать воронкой, объединить с выпавшими предметами или уничтожить обычным уроном. Готовый суп отображается горизонтальной RGB-поверхностью внутри котла: непрозрачный фон `TextDisplay` с пробелом, без видимых букв и ресурспака. Цвет — среднее арифметическое RGB четырёх ингредиентов в равных долях. У еды задан характерный цвет: красный глаз паука, жёлтое золотое яблоко, оранжевая морковь и другие. Зелья передают свой фактический цвет, включая пользовательский. Порядок ингредиентов не влияет на результат, повторы учитываются. Повторно используемый комбинированный суп передаёт сохранённый цвет. Разные смеси могут естественно давать похожие или одинаковые оттенки. Название нового супа окрашивается в цвет смеси; ванильная иконка миски сохраняется.
|
||||
|
||||
Все четыре ванильных супа — грибной, кроличий, свекольный и подозрительный — и комбинированные супы получают максимальный стак **16**. Одинаковые рецепты совместимы по стакам независимо от порядка загрузки ингредиентов. Разные составы или эффекты дают разные предметы.
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
- Совпадающие эффекты применяются по ванильным правилам Minecraft: уровни не складываются арифметически, более слабый эффект не заменяет более сильный. Каждый записанный эффект сохраняет свою длительность.
|
||||
- Комбинированный суп можно есть при полном голоде, чтобы получить эффекты. Миска возвращается нативным механизмом Minecraft, в том числе при поедании стака.
|
||||
- Значения в описании супа — сумма ингредиентов. **Фактические голод и насыщение игрока ограничиваются Minecraft: максимум 20; насыщение не выше текущего голода.** Переполнение сверх этих пределов не хранится в резерве.
|
||||
- В одну варку получается одна порция. Упаковка ингредиентов расходуется вместе с ингредиентами; пустые бутылки и миски исходной еды отдельно не возвращаются. В Creative предметы в руках не расходуются.
|
||||
- В одну варку получается четыре порции, каждая с полным суммарным питанием и эффектами состава. Упаковка ингредиентов расходуется вместе с ингредиентами; пустые бутылки и миски исходной еды отдельно не возвращаются. В Creative предметы в руках не расходуются.
|
||||
|
||||
Пример: продлённое ночное зрение + стейк + светящиеся ягоды + сила II = **10 голода, 13,2 насыщения, ночное зрение I на 8:00 и сила II на 1:30**.
|
||||
|
||||
@@ -40,7 +40,9 @@
|
||||
|
||||
Команда сохраняет образец предмета в `plugins/AstraSoups/config.yml`, задаёт 7 голода и 4,5 насыщения. Количество в стаке не влияет на совпадение, остальные метаданные должны совпадать. Обычный предмет того же материала не станет такой едой. Перерегистрация того же ID заменяет образец и питание.
|
||||
|
||||
Дополнительные эффекты можно прописать в записи `custom-ingredients.my_food`:
|
||||
В записи `custom-ingredients.my_food` необязательный параметр `color: '#D45B37'` задаёт цвет уникальной еды. Без него берётся цвет базового материала, для неизвестных продуктов — `default-color`.
|
||||
|
||||
Дополнительные эффекты можно прописать в этой же записи:
|
||||
|
||||
```yaml
|
||||
effects:
|
||||
@@ -49,7 +51,7 @@ effects:
|
||||
amplifier: 1
|
||||
```
|
||||
|
||||
Это сила II на 3 минуты. `amplifier: 0` соответствует I, `duration: -1` — бесконечности. Дополнительные эффекты прибавляются к встроенным свойствам предмета.
|
||||
Это сила II на 3 минуты. В описании супа уровни римские, длительность в скобках, без точек-разделителей. Описания ранее созданных супов обновляются при обычной нормализации инвентарей. `amplifier: 0` соответствует I, `duration: -1` — бесконечности. Дополнительные эффекты прибавляются к встроенным свойствам предмета.
|
||||
|
||||
ItemsAdder — необязательная зависимость. При его наличии плагин умеет распознавать namespaced ID для правил совместимости. Эффекты, которые сторонние плагины выдают только своим обработчиком употребления, автоматически не исполняются при поедании супа: задайте их явно в регистрации.
|
||||
|
||||
@@ -82,9 +84,11 @@ incompatible:
|
||||
| `astrasoups.use` | Использование котлов; по умолчанию разрешено всем |
|
||||
| `astrasoups.admin` | Регистрация и перезагрузка; по умолчанию только операторы |
|
||||
|
||||
Длительность задаётся в `brew-seconds` (по умолчанию 4.0, диапазон 0.5–60), количество порций — в `servings-per-brew` (по умолчанию 4, диапазон 1–16). Изменения применяются к новым варкам после `/soups reload`. Старые конфиги поддерживаются без перезаписи: отсутствующие параметры используют значения по умолчанию.
|
||||
|
||||
## Сохранение и взаимодействия
|
||||
|
||||
Состояния котлов записываются в `plugins/AstraSoups/cauldrons.yml` после каждой операции через временный файл и замену. Ошибка сохранения отменяет операцию до передачи предмета. Содержимое восстанавливается после нормального перезапуска, выгрузка чанков не требует держать их загруженными. Файл и инвентарь игрока не являются общей транзакционной базой: жёсткое завершение процесса ровно между сохранениями Minecraft и плагина не даёт гарантии атомарности.
|
||||
Состояния котлов записываются в `plugins/AstraSoups/cauldrons.yml` после каждой операции через временный файл и замену. Ошибка сохранения отменяет операцию до передачи предмета. Содержимое и число оставшихся порций восстанавливаются после нормального перезапуска. Выгрузка чанка приостанавливает анимацию; после перезапуска сервера незавершённая варка начинает полный цикл заново, сохраняя ингредиенты и будущие порции. Чанки принудительно не удерживаются. Старые готовые котлы без поля servings сохраняют одну порцию, чтобы обновление не размножало их содержимое. Файл и инвентарь игрока не являются общей транзакционной базой: жёсткое завершение процесса ровно между сохранениями Minecraft и плагина не даёт гарантии атомарности.
|
||||
|
||||
При разбивании котла сырые ингредиенты выпадают, сваренный суп выливается. Котлы с содержимым защищены от взрывов, поршней и изменения уровня воды. Уже отменённые взаимодействия и ломание блоков уважаются. Внешнее редактирование блоков очищает состояние пропавшего котла и возвращает сырые ингредиенты при следующей проверке.
|
||||
|
||||
@@ -96,7 +100,7 @@ incompatible:
|
||||
.\gradlew.bat test jar
|
||||
```
|
||||
|
||||
Результат: `build/libs/AstraSoups-0.1.0.jar`. Поместить в папку `plugins` Paper 26.2 и запустить/перезапустить сервер. Настройки создаются автоматически. При обновлении заменить только JAR, сохраняя конфигурацию и `cauldrons.yml`.
|
||||
Результат: `build/libs/AstraSoups-0.1.1.jar`. Поместить в папку `plugins` Paper 26.2 и запустить/перезапустить сервер. Настройки создаются автоматически. При обновлении заменить только JAR, сохраняя конфигурацию и `cauldrons.yml`.
|
||||
|
||||
Плагин использует [Paper Data Component API](https://docs.papermc.io/paper/dev/data-component-api/), поэтому переход на другие версии Minecraft требует отдельной проверки совместимости.
|
||||
|
||||
|
||||
+31
-32
@@ -1,54 +1,53 @@
|
||||
# Проверка AstraSoups 0.1.0
|
||||
# Проверка AstraSoups 0.1.1
|
||||
|
||||
Среда: Windows 11, Java 26.0.2, Paper 26.2 build 121. Проверено 5 сентября 2026 года.
|
||||
|
||||
## Автоматические проверки
|
||||
|
||||
`gradlew.bat test jar smokeJar`: успешная сборка основного JAR и отдельного тестового помощника.
|
||||
`gradlew.bat test jar smokeJar`: успешная сборка. **11 JUnit-тестов** проверяют правила комбинаций, границы движения при всех уровнях воды, погружение ингредиентов, спираль к центру, отсутствие скачка при запуске и римские уровни эффектов.
|
||||
|
||||
6 JUnit-тестов проверяют требование ровно четырёх ингредиентов, регистр селекторов, симметрию несовместимости, отсутствие конфликта предмета с самим собой, запрет повторов и wildcard.
|
||||
Изолированный сервер `.test-server`, `127.0.0.1:25585`, отдельный плоский мир, только AstraSoups и SoupSmokeTest. Использованы настоящий ServerPlayer без сетевого клиента, реальные предметы и реестр Paper, обработчики Bukkit и нативное употребление предметов. Тестовый помощник не входит в основной JAR.
|
||||
|
||||
Изолированный сервер `.test-server`, адрес `127.0.0.1:25585`, отдельный плоский мир, только AstraSoups и SoupSmokeTest. Реальные игроки не подключались. Проверки используют настоящий `ServerPlayer` без сетевого клиента, реальные предметы и реестр Paper, обработчики Bukkit и нативное употребление предметов Minecraft. Тестовый помощник не входит в основной JAR.
|
||||
Первый запуск: **104 проверки**. Кроме регрессии питания, эффектов, стаков, регистрации уникальной еды, запретов и сериализации проверены:
|
||||
|
||||
Первый запуск: **86 проверок**, в том числе:
|
||||
- Погружение четырёх Item-сущностей; движение тех же сущностей по спирали внутрь и вниз.
|
||||
- Отсутствие готового супа до 80-го тика и появление после него.
|
||||
- Миска до готовности не расходуется; пустая рука не извлекает ингредиент; повторный запуск не сбрасывает таймер.
|
||||
- Римские уровни, длительность в скобках, отсутствие точек-разделителей и обновление старого описания без изменения эффектов.
|
||||
- Красный глаз паука, золотое яблоко, фиолетовое и зелёное зелья дают точный RGB #9D7965 для используемых в тесте оттенков.
|
||||
- Разные продукты дают разные оттенки, порядок не меняет результат, повторно используемый суп сохраняет цвет.
|
||||
- Поверхность использует точный непрозрачный RGB смеси без округления до терракоты.
|
||||
- Четыре миски дают четыре порции; после четвёртой котёл пуст; пятая порция недоступна.
|
||||
- Сохранение котла с двумя оставшимися порциями, сырого котла и незавершённой варки.
|
||||
|
||||
- Вся еда из `Material.isEdible()`, торт, отсев камня и стрел с эффектами.
|
||||
- Суммарные голод и насыщение, все четыре ванильных супа со стаком 16.
|
||||
- Совместимость по стакам одинакового рецепта с обратным порядком ингредиентов.
|
||||
- Обычные, взрывные и оседающие зелья; точные длительности, усиление и флаги эффекта.
|
||||
- Эффекты зачарованного золотого яблока и подозрительного супа.
|
||||
- Сериализация компонентов супа в binary и YAML.
|
||||
- Реальное употребление: питание и эффекты один раз, остаток стака, миска, ванильное ограничение 20.
|
||||
- Регистрация уникальной еды на материале PAPER; обычная бумага остаётся несъедобной.
|
||||
- Некорректный YAML при reload не сбрасывает рабочую регистрацию.
|
||||
- Отменённое взаимодействие не забирает предмет.
|
||||
- Четыре `Item`-сущности с отключённым подбором, гравитацией и старением.
|
||||
- Возврат последнего ингредиента; несовместимость не уничтожает ингредиенты.
|
||||
- Варка создаёт цветную поверхность и удаляет визуальные ингредиенты.
|
||||
- Выдача ожидаемого супа, расход одной миски, опустошение воды.
|
||||
- ПКМ с предметом запускает варку без расходования предмета запуска.
|
||||
- Запись сырого и готового котлов для перезапуска процесса.
|
||||
Второй запуск: **11 проверок** после настоящего перезапуска JVM. Подтверждены восстановление двух оставшихся порций без пополнения до четырёх, сырого ингредиента и незавершённой варки. Незавершённая варка не превращается в мгновенный суп, после завершения даёт четыре порции. Повторная выдача после опустошения невозможна.
|
||||
|
||||
Второй запуск: **5 проверок** восстановления настоящего сохранённого мира и `cauldrons.yml`: загрузка плагина, готовый котёл, эффекты и стак супа после рестарта, возврат сырого ингредиента и невозможность получить его повторно.
|
||||
Точные временные границы проверены пошаговым вызовом тика плагина на основном потоке настоящего Paper. Перезапуск и восстановление выполнялись между отдельными запусками JVM; полноценный сетевой клиент не эмулировался.
|
||||
|
||||
Полный текст результатов: `verification/phase1.txt` и `verification/phase2.txt`.
|
||||
Полные результаты: `verification/phase1.txt` и `verification/phase2.txt`.
|
||||
|
||||
## Границы проверки
|
||||
## Геометрия и границы проверки
|
||||
|
||||
В игровом клиенте внешний вид не просматривался: проверены тип, количество, свойства и геометрия сущностей на сервере. Цвет поверхности — приближение терракотой, без ресурспака. Живой сценарий с клиентом и сочетание с конкретными защитными плагинами остаются ручной проверкой.
|
||||
Геометрия RGB-поверхности сверена с установленным клиентским JAR Minecraft 26.2: DisplayRenderer.TextDisplayRenderer рисует фон одного пробела размером 5×10 пикселей при масштабе 0.025 блока/пиксель. Ширина пробела 4 подтверждена assets/minecraft/font/include/space.json. Применены масштаб 6×3, поворот вверх и смещение к центру: квадрат 0.75×0.75 внутри котла. Погружение учитывает дополнительное вертикальное покачивание нативного рендерера предметов.
|
||||
|
||||
ItemsAdder не запускался в изолированном тесте. Нативная еда и регистрация образца проверены; интеграция с ItemsAdder использует его публичные методы `CustomStack.byItemStack` и `getNamespacedID`. Произвольные сторонние обработчики еды автоматически не переносятся.
|
||||
Внешний вид непосредственно в игровом клиенте не просматривался. Ресурспак, меняющий метрики стандартного шрифта, может влиять на геометрию поверхности. Живой сценарий с клиентом и сочетание с конкретными защитными плагинами остаются ручной проверкой.
|
||||
|
||||
В журнале тестового сервера есть системное предупреждение OSHI о счётчиках производительности Windows. Оно не относится к AstraSoups; все проверки плагина завершились успешно.
|
||||
ItemsAdder не запускался в изолированном тесте. Регистрация образца проверена; интеграция использует его публичные методы CustomStack.byItemStack и getNamespacedID. Произвольные сторонние обработчики еды автоматически не переносятся.
|
||||
|
||||
## Установка на рабочий сервер
|
||||
Предупреждение OSHI о счётчиках производительности Windows не относится к AstraSoups. Все финальные проверки плагина завершились успешно.
|
||||
|
||||
## Установка
|
||||
|
||||
После остановки рабочего сервера пользователем выполнена прямая замена JAR:
|
||||
|
||||
- Установлен: `C:\Users\ScarPC\Documents\26.2 Paper\plugins\AstraSoups-0.1.1.jar`.
|
||||
- Старая версия: `C:\Users\ScarPC\Documents\26.2 Paper\old-plugins\20260905-151108-AstraSoups\AstraSoups-0.1.0.jar`.
|
||||
- Конфигурация и данные рабочего сервера сохранены. Тестовый помощник на рабочий сервер не установлен.
|
||||
|
||||
Установлен `C:\Users\ScarPC\Documents\26.2 Paper\plugins\AstraSoups-0.1.0.jar`.
|
||||
Старого плагина с именем `AstraSoups` не было; архивирование не потребовалось.
|
||||
SHA-256 установленного JAR совпадает со сборкой:
|
||||
|
||||
```text
|
||||
E4477AD5EFEF3F8E13C872E8651612F604C61EB554E826627215E42E4553DBA4
|
||||
88799B4C54965C2BA79E27FD23BD8C670855FB803C72CCEC3688F3EA92519BFA
|
||||
```
|
||||
|
||||
Рабочий сервер в рамках задачи не перезапускался. Плагин активируется при следующем запуске сервера. Тестовый помощник на рабочий сервер не устанавливался.
|
||||
Рабочий сервер можно запускать с новой версией.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
plugins { java }
|
||||
group = "online.astracraft"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.papermc.io/repository/maven-public/") }
|
||||
|
||||
@@ -34,6 +34,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
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;
|
||||
|
||||
@@ -50,10 +51,16 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
return new Position(UUID.fromString(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]));
|
||||
}
|
||||
}
|
||||
record Pot(List<ItemStack> items, ItemStack soup) { Pot { items = List.copyOf(items); } }
|
||||
record Pot(List<ItemStack> items, ItemStack soup, int brewTicks, int servings) {
|
||||
Pot { items = List.copyOf(items); }
|
||||
Pot(List<ItemStack> items, ItemStack soup) { this(items, soup, 0, 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");
|
||||
@@ -75,7 +82,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
else if (entity instanceof Item item) normalizeEntity(item);
|
||||
}
|
||||
for (Player p : Bukkit.getOnlinePlayers()) normalizeInventory(p.getInventory());
|
||||
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 10);
|
||||
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 1);
|
||||
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
|
||||
}
|
||||
|
||||
@@ -100,9 +107,16 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
items.add(item);
|
||||
}
|
||||
ItemStack soup = c.getItemStack("soup");
|
||||
if (items.size() > 4 || (soup != null && (!items.isEmpty() || soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||
|| (items.isEmpty() && soup == null)) throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||
pots.put(Position.parse(id), new Pot(items, soup));
|
||||
int brewTicks = c.getInt("brew-ticks", 0);
|
||||
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
||||
if (items.size() > 4 || brewTicks < 0 || brewTicks > 1200
|
||||
|| (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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,12 +131,15 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
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);
|
||||
}
|
||||
Path temp = dataFile.toPath().resolveSibling("cauldrons.yml.tmp");
|
||||
Files.writeString(temp, data.saveToString());
|
||||
try { Files.move(temp, dataFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
|
||||
removeVisuals(pos);
|
||||
brewElapsed.remove(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
||||
@@ -157,14 +174,22 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
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, "Суп готов. Возьмите его миской — ПКМ."); return; }
|
||||
if (!bowl) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return; }
|
||||
ItemStack result = pot.soup.clone();
|
||||
if (!change(pos, null)) { saveError(player); return; }
|
||||
int remaining = pot.servings - 1;
|
||||
if (!change(pos, remaining == 0 ? null : new Pot(List.of(), pot.soup, 0, remaining))) { saveError(player); return; }
|
||||
takeOne(player);
|
||||
give(player, result);
|
||||
block.setType(Material.CAULDRON);
|
||||
if (remaining == 0) block.setType(Material.CAULDRON);
|
||||
else 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);
|
||||
@@ -172,11 +197,11 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
String error = ingredients.rejection(pot.items);
|
||||
if (error != null) { say(player, error + " ПКМ пустой рукой возвращает последний ингредиент."); return; }
|
||||
ItemStack soup = ingredients.brew(pot.items);
|
||||
if (!change(pos, new Pot(List.of(), soup))) { saveError(player); return; }
|
||||
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
||||
if (!change(pos, new Pot(pot.items, soup, duration, getConfig().getInt("servings-per-brew", 4)))) { saveError(player); return; }
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||
block.getWorld().spawnParticle(Particle.CLOUD, block.getLocation().add(.5, 1.05, .5), 12, .2, .12, .2, .01);
|
||||
say(player, "Суп готов! Соберите его миской.");
|
||||
say(player, "Варка началась! Дождитесь окончания водоворота.");
|
||||
return;
|
||||
}
|
||||
if (empty) {
|
||||
@@ -212,7 +237,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
private void saveError(Player p) { say(p, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||
|
||||
private void refresh() {
|
||||
ticks += 10;
|
||||
ticks++;
|
||||
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
|
||||
Position pos = entry.getKey();
|
||||
Block block = pos.loadedBlock();
|
||||
@@ -222,13 +247,32 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
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))) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
List<Entity> entities = visuals.get(pos);
|
||||
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
|
||||
removeVisuals(pos); show(pos, entry.getValue(), block);
|
||||
} else {
|
||||
for (int i = 0; i < entities.size(); i++) if (entities.get(i) instanceof Item item) {
|
||||
item.teleport(itemLocation(block, i));
|
||||
Location location = itemLocation(block, i, pot);
|
||||
item.teleport(location);
|
||||
item.setVelocity(new Vector());
|
||||
if (pot.brewing() && ticks % 5 == 0) {
|
||||
double height = .375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||
block.getWorld().spawnParticle(Particle.SPLASH,
|
||||
new Location(block.getWorld(), location.getX(), block.getY() + height + .01, location.getZ()),
|
||||
1, .015, 0, .015, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,31 +284,38 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
private Location itemLocation(Block block, int i) {
|
||||
double[][] offsets = {{.32, .32}, {.68, .32}, {.32, .68}, {.68, .68}};
|
||||
private Location itemLocation(Block block, int i, Pot pot) {
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
double height = .375 + .1875 * waterLevel;
|
||||
return block.getLocation().add(offsets[i][0], height - .11 + Math.sin(ticks * .06 + i) * .025, offsets[i][1]);
|
||||
CauldronAnimation.Offset frame = CauldronAnimation.frame(i, waterLevel, ticks,
|
||||
brewElapsed.getOrDefault(Position.at(block), 0), pot.brewTicks);
|
||||
return block.getLocation().add(frame.x(), frame.y(), frame.z());
|
||||
}
|
||||
|
||||
private void show(Position pos, Pot pot, Block block) {
|
||||
if (visuals.containsKey(pos)) return;
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
visuals.put(pos, entities);
|
||||
if (pot.soup != null) {
|
||||
if (pot.soup != null && !pot.brewing()) {
|
||||
int rgb = pot.soup.getItemMeta().getPersistentDataContainer().getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
BlockDisplay display = block.getWorld().spawn(block.getLocation().add(.125, .375 + .1875 * waterLevel + .005, .125), BlockDisplay.class, d -> {
|
||||
TextDisplay display = block.getWorld().spawn(block.getLocation().add(.5, .375 + .1875 * waterLevel + .005, .5), TextDisplay.class, d -> {
|
||||
markVisual(d);
|
||||
d.setBlock(surface(rgb).createBlockData());
|
||||
d.setTransformation(new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(.75f, .012f, .75f), new Quaternionf()));
|
||||
// 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(new Transformation(new Vector3f(-.075f, 0, .375f),
|
||||
new Quaternionf().rotationX((float) (-Math.PI / 2)), new Vector3f(6, 3, 1), new Quaternionf()));
|
||||
d.setBrightness(new Display.Brightness(12, 12));
|
||||
d.setViewRange(.5f);
|
||||
});
|
||||
entities.add(display);
|
||||
} else for (int i = 0; i < pot.items.size(); i++) {
|
||||
ItemStack stack = pot.items.get(i).clone();
|
||||
Item item = block.getWorld().spawn(itemLocation(block, i), Item.class, e -> {
|
||||
Item item = block.getWorld().spawn(itemLocation(block, i, pot), Item.class, e -> {
|
||||
markVisual(e);
|
||||
e.setItemStack(stack);
|
||||
e.setCanPlayerPickup(false);
|
||||
@@ -277,23 +328,6 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
private Material surface(int rgb) {
|
||||
Material[] materials = {Material.ORANGE_TERRACOTTA, Material.YELLOW_TERRACOTTA, Material.RED_TERRACOTTA,
|
||||
Material.BROWN_TERRACOTTA, Material.GREEN_TERRACOTTA, Material.LIME_TERRACOTTA,
|
||||
Material.BLUE_TERRACOTTA, Material.CYAN_TERRACOTTA, Material.PURPLE_TERRACOTTA,
|
||||
Material.PINK_TERRACOTTA, Material.WHITE_TERRACOTTA, Material.BLACK_TERRACOTTA};
|
||||
int[] colors = {0xA15325, 0xBA8523, 0x8E3C2E, 0x4D3323, 0x4C532A, 0x677535,
|
||||
0x4A3B5B, 0x565B5B, 0x764656, 0xA14E4E, 0xD1B2A1, 0x251610};
|
||||
Color wanted = Color.fromRGB(rgb);
|
||||
int best = 0, distance = Integer.MAX_VALUE;
|
||||
for (int i = 0; i < colors.length; i++) {
|
||||
Color candidate = Color.fromRGB(colors[i]);
|
||||
int r = candidate.getRed() - wanted.getRed(), g = candidate.getGreen() - wanted.getGreen(), b = candidate.getBlue() - wanted.getBlue();
|
||||
int d = r * r + g * g + b * b;
|
||||
if (d < distance) { best = i; distance = d; }
|
||||
}
|
||||
return materials[best];
|
||||
}
|
||||
private void markVisual(Entity entity) {
|
||||
entity.getPersistentDataContainer().set(visualKey, PersistentDataType.BYTE, (byte) 1);
|
||||
entity.setPersistent(false);
|
||||
@@ -313,7 +347,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
if (pot == null) return;
|
||||
if (!change(pos, null)) { e.setCancelled(true); saveError(e.getPlayer()); return; }
|
||||
for (ItemStack item : pot.items) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(.5, .5, .5), item.clone());
|
||||
if (pot.soup != null) say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
||||
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); }
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
/** Coordinates relative to a cauldron; item renderers add their own bob above the entity origin. */
|
||||
public final class CauldronAnimation {
|
||||
private CauldronAnimation() {}
|
||||
public record Offset(double x, double y, double z) {}
|
||||
|
||||
public static Offset frame(int slot, int waterLevel, int tick, int elapsed, int duration) {
|
||||
double progress = duration > 0 ? Math.clamp((double) elapsed / duration, 0, 1) : 0;
|
||||
double eased = progress * progress * (3 - 2 * progress);
|
||||
double[] phases = {-3 * Math.PI / 4, -Math.PI / 4, 3 * Math.PI / 4, Math.PI / 4};
|
||||
double angle = phases[slot] + 2 * Math.PI * (2 * progress + 2 * progress * progress);
|
||||
double radius = .255 * (1 - .85 * eased);
|
||||
double surface = .375 + .1875 * waterLevel;
|
||||
double bob = Math.sin(tick * .06 + slot) * .01 * (1 - progress);
|
||||
return new Offset(.5 + Math.cos(angle) * radius,
|
||||
Math.max(.26, surface - .28 - .14 * eased + bob), .5 + Math.sin(angle) * radius);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Material;
|
||||
|
||||
/** Representative food colors; potion contents and custom food overrides are read separately. */
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ import java.util.*;
|
||||
|
||||
public final class Ingredients {
|
||||
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, Color color) {}
|
||||
private record Custom(String id, ItemStack sample, int nutrition, float saturation, List<PotionEffect> effects) {}
|
||||
private 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;
|
||||
@@ -36,6 +36,12 @@ public final class Ingredients {
|
||||
|
||||
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())) {
|
||||
@@ -68,7 +74,8 @@ public final class Ingredients {
|
||||
effects.add(new PotionEffect(type, duration, amplifier));
|
||||
}
|
||||
normalize(sample);
|
||||
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects)));
|
||||
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 {
|
||||
@@ -95,7 +102,8 @@ public final class Ingredients {
|
||||
List<ConsumeEffect> effects = new ArrayList<>();
|
||||
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
||||
if (consumable != null) effects.addAll(consumable.consumeEffects());
|
||||
Color color = defaultColor;
|
||||
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();
|
||||
@@ -111,6 +119,7 @@ public final class Ingredients {
|
||||
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);
|
||||
@@ -150,24 +159,9 @@ public final class Ingredients {
|
||||
List<ConsumeEffect> effects = ingredients.stream().flatMap(i -> i.effects.stream()).toList();
|
||||
ItemStack soup = new ItemStack(Material.MUSHROOM_STEW);
|
||||
ItemMeta meta = soup.getItemMeta();
|
||||
meta.displayName(Component.text(plugin.getConfig().getString("soup-name", "Комбинированный суп"), NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false));
|
||||
List<Component> lore = new ArrayList<>();
|
||||
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
|
||||
lore.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", saturation), NamedTextColor.GOLD));
|
||||
for (ConsumeEffect effect : effects) {
|
||||
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
|
||||
for (PotionEffect pe : apply.effects()) {
|
||||
String duration = pe.isInfinite() ? "∞" : (pe.getDuration() / 1200) + ":" + String.format(Locale.ROOT, "%02d", (pe.getDuration() / 20) % 60);
|
||||
lore.add(Component.translatable(pe.getType().translationKey()).color(NamedTextColor.AQUA)
|
||||
.append(Component.text(" " + (pe.getAmplifier() + 1) + " • " + duration
|
||||
+ (apply.probability() < 1 ? " • " + Math.round(apply.probability() * 100) + "%" : "")))
|
||||
.decoration(TextDecoration.ITALIC, false));
|
||||
}
|
||||
} else lore.add(line(effect instanceof ConsumeEffect.TeleportRandomly ? "Случайная телепортация"
|
||||
: effect instanceof ConsumeEffect.ClearAllStatusEffects ? "Снятие всех эффектов"
|
||||
: effect instanceof ConsumeEffect.RemoveStatusEffects ? "Снятие эффектов" : "Звук при употреблении", NamedTextColor.GRAY));
|
||||
}
|
||||
meta.lore(lore);
|
||||
meta.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);
|
||||
@@ -178,7 +172,27 @@ public final class Ingredients {
|
||||
return soup;
|
||||
}
|
||||
|
||||
private Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
|
||||
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),
|
||||
@@ -189,11 +203,20 @@ public final class Ingredients {
|
||||
}
|
||||
public static boolean normalize(ItemStack item) {
|
||||
if (item == null) return false;
|
||||
if (switch (item.getType()) { case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true; default -> false; }
|
||||
&& !Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
||||
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);
|
||||
return true;
|
||||
changed = true;
|
||||
}
|
||||
return false;
|
||||
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; }
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
final class SoupText {
|
||||
private SoupText() {}
|
||||
static String roman(int level) {
|
||||
if (level < 1 || level > 256) throw new IllegalArgumentException("Potion level out of range: " + level);
|
||||
int[] values = {100, 90, 50, 40, 10, 9, 5, 4, 1};
|
||||
String[] numerals = {"C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (int i = 0; i < values.length; i++) while (level >= values[i]) {
|
||||
text.append(numerals[i]); level -= values[i];
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
# Ровно четыре предмета, по одной единице каждого. Повторы разрешены.
|
||||
# Одна варка дает одну миску: питание и эффекты не размножаются.
|
||||
# Одна варка даёт четыре порции; каждая получает питание и эффекты всего состава.
|
||||
servings-per-brew: 4
|
||||
require-full-water: true
|
||||
# Варка с водоворотом, в секундах (0.5–60). 20 тиков = 1 секунда.
|
||||
brew-seconds: 4.0
|
||||
soup-name: 'Комбинированный суп'
|
||||
# Цвет поверхности — ближайший оттенок терракоты без ресурспака.
|
||||
# Резервный цвет неизвестной еды. Известные продукты имеют собственные цвета,
|
||||
# зелья передают свой RGB. Поверхность супа показывает среднее RGB четырёх ингредиентов.
|
||||
default-color: '#B77A36'
|
||||
# Ограничения предотвращают переполнение при многократной варке супов из супов.
|
||||
max-nutrition: 1000
|
||||
@@ -20,4 +24,5 @@ incompatible: []
|
||||
# nutrition — единицы голода (2 = один значок), saturation — очки насыщения.
|
||||
# Необязательные effects: [{type: 'minecraft:strength', duration: 3600, amplifier: 1}]
|
||||
# duration в тиках; amplifier: 0 = I, 1 = II. Эффекты добавляются к исходным.
|
||||
# Необязательный color: '#D45B37' задаёт цвет уникальной еды для смешивания.
|
||||
custom-ingredients: {}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CauldronAnimationTest {
|
||||
@Test void remainsInsideCauldronAtEveryWaterLevel() {
|
||||
for (int level = 1; level <= 3; level++) for (int tick = 0; tick <= 80; tick++) for (int slot = 0; slot < 4; slot++) {
|
||||
var p = CauldronAnimation.frame(slot, level, tick, tick, 80);
|
||||
assertTrue(p.x() > .125 && p.x() < .875 && p.z() > .125 && p.z() < .875);
|
||||
assertTrue(p.y() >= .26 && p.y() < .375 + .1875 * level);
|
||||
}
|
||||
}
|
||||
@Test void idleIngredientOriginIsSubmergedEnoughToOffsetNativeItemBobbing() {
|
||||
for (int tick = 0; tick < 200; tick++) {
|
||||
var p = CauldronAnimation.frame(0, 3, tick, 0, 0);
|
||||
assertTrue(.9375 - p.y() >= .2699);
|
||||
}
|
||||
}
|
||||
@Test void whirlpoolRotatesShrinksAndSinks() {
|
||||
var start = CauldronAnimation.frame(0, 3, 0, 0, 80);
|
||||
var middle = CauldronAnimation.frame(0, 3, 40, 40, 80);
|
||||
var end = CauldronAnimation.frame(0, 3, 80, 80, 80);
|
||||
assertTrue(Math.hypot(end.x() - .5, end.z() - .5) < Math.hypot(start.x() - .5, start.z() - .5) / 5);
|
||||
assertTrue(end.y() < start.y());
|
||||
assertTrue(Math.atan2(middle.z() - .5, middle.x() - .5) != Math.atan2(start.z() - .5, start.x() - .5));
|
||||
}
|
||||
@Test void initialPositionDoesNotJumpWhenBrewingStarts() {
|
||||
assertEquals(CauldronAnimation.frame(2, 3, 15, 0, 0), CauldronAnimation.frame(2, 3, 15, 0, 80));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SoupTextTest {
|
||||
@Test void formatsPotionLevelsAsRomanNumerals() {
|
||||
assertEquals("I", SoupText.roman(1)); assertEquals("II", SoupText.roman(2));
|
||||
assertEquals("IV", SoupText.roman(4)); assertEquals("IX", SoupText.roman(9));
|
||||
assertEquals("XL", SoupText.roman(40)); assertEquals("XC", SoupText.roman(90));
|
||||
assertEquals("CCLVI", SoupText.roman(256));
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,15 @@ public final class SoupSmokeTest extends JavaPlugin {
|
||||
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<Item> visualItems(Block block) {
|
||||
return world.getNearbyEntities(block.getLocation().add(.5, .5, .5), .5, .5, .5).stream()
|
||||
.filter(e -> e instanceof Item && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual")))
|
||||
.map(e -> (Item) e).toList();
|
||||
}
|
||||
private ItemStack soupInInventory() {
|
||||
return Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(plugin.ingredients()::isCombined).findFirst().orElseThrow();
|
||||
}
|
||||
@@ -113,6 +122,24 @@ public final class SoupSmokeTest extends JavaPlugin {
|
||||
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");
|
||||
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");
|
||||
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");
|
||||
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");
|
||||
@@ -169,6 +196,7 @@ public final class SoupSmokeTest extends JavaPlugin {
|
||||
check(player.getInventory().getItemInMainHand().getType().isAir(), "Adding a fourth ingredient consumes exactly one item");
|
||||
long count = world.getEntities().stream().filter(e -> e instanceof Item && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual"))).count();
|
||||
check(count == 4, "Four real item entities visualize the ingredients");
|
||||
check(visualItems(pot).stream().allMatch(e -> e.getLocation().getY() < pot.getY() + .9375 - .26), "Idle ingredients are partly submerged after accounting for client item bobbing");
|
||||
for (Entity e : world.getEntities()) if (e instanceof Item drop && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual"))) {
|
||||
check(!drop.canPlayerPickup() && !drop.canMobPickup() && !drop.hasGravity() && drop.isUnlimitedLifetime(), "Display ingredient cannot be picked up or expire");
|
||||
}
|
||||
@@ -178,35 +206,79 @@ public final class SoupSmokeTest extends JavaPlugin {
|
||||
plugin.getConfig().set("incompatible", List.of(List.of("material:cooked_beef", "effect:minecraft:strength")));
|
||||
plugin.saveConfig(); plugin.onCommand(Bukkit.getConsoleSender(), plugin.getCommand("soups"), "soups", new String[]{"reload"});
|
||||
click(pot, item(Material.AIR), true, false);
|
||||
check(world.getEntities().stream().noneMatch(e -> e instanceof BlockDisplay), "Incompatible recipe does not create ready soup");
|
||||
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().anyMatch(e -> e instanceof BlockDisplay), "Brew creates colored soup surface");
|
||||
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");
|
||||
Item tracked = visualItems(pot).getFirst(); Location start = tracked.getLocation();
|
||||
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);
|
||||
check(tracked.isValid() && tracked.getLocation().distance(start) > .1, "Same item entity moves along the whirlpool");
|
||||
double radius = Math.hypot(tracked.getLocation().getX() - pot.getX() - .5, tracked.getLocation().getZ() - pot.getZ() - .5);
|
||||
check(radius < .2 && tracked.getLocation().getY() < start.getY(), "Whirlpool pulls ingredients inward and downward");
|
||||
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(world.getEntities().stream().noneMatch(e -> e instanceof Item && e.getPersistentDataContainer().has(new NamespacedKey(plugin, "cauldron_visual"))), "Brew removes ingredient visuals");
|
||||
click(pot, new ItemStack(Material.BOWL, 2), false, false);
|
||||
check(player.getInventory().getItemInMainHand().getAmount() == 1, "Collecting soup consumes one bowl");
|
||||
check(soupInInventory().isSimilar(soup), "Collecting yields exactly the expected recipe");
|
||||
check(pot.getType() == Material.CAULDRON, "Collecting consumes cauldron water");
|
||||
check(pot.getType() == Material.WATER_CAULDRON, "Cauldron retains soup after the first of four portions");
|
||||
for (int i = 0; i < 3; i++) click(pot, item(Material.BOWL), false, false);
|
||||
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() {
|
||||
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");
|
||||
click(pot, item(Material.BOWL), false, false);
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
+20
-2
@@ -50,6 +50,12 @@ PASS: Vanilla soup stack size: SUSPICIOUS_STEW
|
||||
PASS: Example combines 10 hunger points
|
||||
PASS: Example combines 13.2 saturation points
|
||||
PASS: Combined soup stacks to sixteen
|
||||
PASS: 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: Different food colors produce different soup colors
|
||||
PASS: Reusing a combined soup preserves its stored liquid color
|
||||
PASS: Same recipe stacks regardless of ingredient insertion order
|
||||
PASS: Extended night vision preserved
|
||||
PASS: Strength II from splash potion preserved without splash reduction
|
||||
@@ -70,6 +76,7 @@ PASS: Malformed reload retains previous working ingredient configuration
|
||||
PASS: Cancelled protected interaction does not take an ingredient
|
||||
PASS: Adding a fourth ingredient consumes exactly one item
|
||||
PASS: Four real item entities visualize the ingredients
|
||||
PASS: Idle ingredients are partly submerged after accounting for client item bobbing
|
||||
PASS: Display ingredient cannot be picked up or expire
|
||||
PASS: Display ingredient cannot be picked up or expire
|
||||
PASS: Display ingredient cannot be picked up or expire
|
||||
@@ -77,11 +84,22 @@ PASS: Display ingredient cannot be picked up or expire
|
||||
PASS: Empty-hand withdrawal is LIFO
|
||||
PASS: Incompatible recipe does not create ready soup
|
||||
PASS: Rejected recipe retains its ingredients
|
||||
PASS: 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 item entity moves along the whirlpool
|
||||
PASS: Whirlpool pulls ingredients inward and downward
|
||||
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: Collecting consumes cauldron water
|
||||
PASS: Cauldron retains soup after the first of four portions
|
||||
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 86 CHECKS (phase1)
|
||||
PASS: ALL 104 CHECKS (phase1)
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
PASS: Plugin enables on Paper 26.2
|
||||
PASS: Ready cauldron block survives restart
|
||||
PASS: Ready soup keeps stack size and effects across process restart
|
||||
PASS: 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: ALL 5 CHECKS (phase2)
|
||||
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 11 CHECKS (phase2)
|
||||
|
||||
Reference in New Issue
Block a user