Simplify ingredient handling and remove generated verification files
This commit is contained in:
@@ -1,27 +0,0 @@
|
||||
# AstraCauldron — серверный мод NeoForge
|
||||
|
||||
Проект переименован из AstraSoups. По запросу пользователя здесь используется
|
||||
Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+, без Paper и ItemsAdder.
|
||||
Эти правила установки заменяют родительские указания о Paper.
|
||||
|
||||
- Рабочий сервер: `C:\Users\ScarPC\Documents\NeoForge Server 26.2`.
|
||||
- После изменений кода/ресурсов собрать и проверить мод, установить основной JAR прямо в `mods`.
|
||||
- Старые JAR именно AstraCauldron (или прежнего AstraSoups) переносить в уникальный
|
||||
`old-mods/YYYYMMDD-HHMMSS/` с сохранением имени. Не оставлять две версии в `mods`.
|
||||
- Сравнивать SHA-256 установленного файла и сборки. При блокировке файла сообщить,
|
||||
не использовать отложенные установки. Конфигурации, данные и миры не заменять.
|
||||
- AstraPlus 0.9.x — обязательная зависимость. Публичные интерфейсы `CauldronApi` и
|
||||
`ColoredWaterApi` принадлежат AstraPlus; мод котлов использует их для преобразования
|
||||
предметов и отображения жидкости. Не дублировать здесь модель/рендер цветной воды.
|
||||
- В AstraCauldron живут игровые взаимодействия, расход предметов, варка и сохранение котлов.
|
||||
RegisteredRecipes обслуживает Java/файловые рецепты AstraPlus: источник жидкости,
|
||||
точный уровень, зажжённый обычный/душевный костёр снизу, расход и цвет остатка воды.
|
||||
Сохранение жидкости должно завершаться до расхода ингредиента и выдачи результата.
|
||||
- Клиенту достаточно ванильного Minecraft и серверного ресурспака. Не регистрировать
|
||||
клиентские предметы/блоки и обязательные сетевые каналы.
|
||||
- Проверки с игровым миром запускать только в отдельном каталоге `build` и с флагом
|
||||
`-Dastracauldron.isolatedVerification=true`; проверочный JAR никогда не устанавливать на рабочий сервер.
|
||||
- Проверить diff и создать коммит задачи. Push только по запросу.
|
||||
- Не коммитить build, .gradle, JAR сборки, логи, миры и резервные копии;
|
||||
`gradle/wrapper/gradle-wrapper.jar` — часть системы сборки.
|
||||
- В итоге сообщать установку, архив старого JAR, коммиты и ограничения проверок.
|
||||
@@ -1,40 +0,0 @@
|
||||
# Настройки котлов
|
||||
|
||||
Файл: `config/astracauldron.json`. Применение через `/astracauldron reload` или перезапуск. Отсутствующие поля сохраняют значения по умолчанию. Существующий файл не перезаписывается при обновлении JAR.
|
||||
|
||||
| Поля | Значения по умолчанию | Назначение |
|
||||
|---|---|---|
|
||||
| soupsEnabled | true | Разрешить начало новых супов; готовые и сохранённые котлы остаются доступны |
|
||||
| dyeWater, dyeArmor, dyeBlocks | true | Отдельно окрашивание воды, брони, шерсти/ковров |
|
||||
| storePotions, tipArrows | true | Добавление зелий и обработка стрел; забирать старые жидкости можно при отключении |
|
||||
| ingredientCount | 4 | 1–4 ингредиента; при уменьшении можно вернуть лишние пустой рукой |
|
||||
| servingsPerBrew | 4 | 1–16 порций |
|
||||
| requireFullWater, requireHeat | true | Полная вода и обязательный нагрев |
|
||||
| brewSeconds | 4 | Варка, 0.5–60 секунд |
|
||||
| inheritEffects, alwaysEdible, returnBowl | true | Эффекты ингредиентов, еда при полном голоде, возврат миски |
|
||||
| consumeSeconds | 1.6 | Употребление, 0.05–60 секунд |
|
||||
| soupStackSize | 16 | Размер стопки супов, 1–64 |
|
||||
| normalizeVanillaSoups | true | Применять размер стопки также к ванильным супам |
|
||||
| particles, ingredientDisplays, sounds, messages | true | Частицы, предметы в котле, звуки и сообщения |
|
||||
| soundVolume | 0.8 | Громкость, 0–4 |
|
||||
| messageOverrides | {} | Замена полного исходного текста сообщения на свой текст |
|
||||
| soupName | Комбинированный суп | Имя приготовленного супа |
|
||||
| defaultColor | #B77A36 | Цвет ингредиентов без собственной палитры |
|
||||
| maxNutrition, maxSaturation | 1000 | Верхние пределы питания и насыщения |
|
||||
| blockedIngredients, incompatible, customIngredients | [], [], {} | Запрещённые ингредиенты, пары несовместимости и собственные определения |
|
||||
|
||||
Пример:
|
||||
|
||||
```json
|
||||
{
|
||||
"ingredientCount": 2,
|
||||
"servingsPerBrew": 6,
|
||||
"requireHeat": false,
|
||||
"tipArrows": false,
|
||||
"inheritEffects": false,
|
||||
"particles": false,
|
||||
"soundVolume": 0.4
|
||||
}
|
||||
```
|
||||
|
||||
Состав и свойства уже приготовленного супа сохраняются. Изменение рецептурных параметров действует на следующую варку. Формат котла по-прежнему использует три уровня жидкости и до четырёх видимых ингредиентов. Сообщения с числами заменяются по полному тексту, включая число; `messages: false` отключает их все. Ошибка сохранения всегда отменяет действие независимо от показа сообщения.
|
||||
@@ -1,7 +1,7 @@
|
||||
# AstraCauldron
|
||||
|
||||
Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
|
||||
Переименован и перенесён из AstraSoups. Требуется **AstraPlus 0.9.x**.
|
||||
Требуется **AstraPlus 0.9.x**.
|
||||
Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks.
|
||||
|
||||
## Режимы котла
|
||||
@@ -24,7 +24,7 @@
|
||||
Котёл с супом остаётся под управлением механики супов. Время варки супа не меняется.
|
||||
|
||||
Пример Java-регистрации и контракт находятся в соседнем AstraPlus:
|
||||
`examples/WorkshopContent.java`, `docs/content-api.md`.
|
||||
[примеры AstraPlus](../AstraPlus/src/examples/example), [контракт API](../AstraPlus/README.md).
|
||||
|
||||
| Действие | Результат |
|
||||
| --- | --- |
|
||||
@@ -119,7 +119,7 @@
|
||||
**AstraPlus** содержит `CauldronApi` (смешивание красителей, окрашивание брони, нормализация
|
||||
зелий и преобразование стрел) и `ColoredWaterApi` (отображение поверхности). Эти интерфейсы
|
||||
не расходуют предметы и не сохраняют игровые котлы. Другие моды могут использовать их
|
||||
без AstraCauldron. Пример API: `AstraPlus/docs/api.md`.
|
||||
без AstraCauldron. Пример API: [AstraPlus](../AstraPlus/README.md).
|
||||
|
||||
**AstraCauldron** обрабатывает действия игроков, рассчитывает игровой расход, сохраняет
|
||||
содержимое и вызывает API. Имена и модель комбинированного супа остаются отдельными ресурсами
|
||||
@@ -155,22 +155,35 @@ Minecraft и мода не является общей транзакцией с
|
||||
другими модами действия уважаются. Внешняя замена блока очищает состояние при проверке.
|
||||
|
||||
```powershell
|
||||
# Сначала собрать AstraPlus с API-артефактом.
|
||||
.\gradlew.bat test assemble verificationJar
|
||||
.\gradlew.bat build
|
||||
.\gradlew.bat integrationTest
|
||||
```
|
||||
|
||||
Сборка использует `../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 установленного файла.
|
||||
Перед сборкой нужен JAR соседнего AstraPlus; серверные тесты запускаются через PowerShell 7. Серверные тесты из src/integrationTest
|
||||
используют отдельные миры в build и проверяют игровой процесс и сохранение после
|
||||
перезапуска. На рабочий сервер устанавливается только основной JAR из build/libs.
|
||||
|
||||
При запуске модель миски экспортируется в
|
||||
`astraplus/resources/assets/astradev_soups`; AstraPlus добавляет свою модель жидкости и
|
||||
собирает ZIP. Неизменённая однотонная модель из версий 0.2.0–0.2.3 обновляется автоматически;
|
||||
пользовательские модели сохраняются. При наличии AstraPacks используется его экспорт/доставка. Для ручной
|
||||
пересборки: `/astraplus build`.
|
||||
## Настройки
|
||||
|
||||
Bukkit-YAML, UUID миров Paper и данные ItemsAdder автоматически не импортируются:
|
||||
Paper-сервер остаётся нетронутым. Git-история AstraSoups сохранена в переименованном репозитории.
|
||||
Проверочный сервер и методика: [VERIFICATION.md](VERIFICATION.md).
|
||||
Файл config/astracauldron.json применяется через `/astracauldron reload`.
|
||||
Отсутствующие поля получают значения по умолчанию; существующий файл не перезаписывается.
|
||||
|
||||
| Настройка | По умолчанию | Назначение |
|
||||
|---|---|---|
|
||||
| ingredientCount / servingsPerBrew | 4 / 4 | Ингредиенты (1–4) и порции (1–16) |
|
||||
| requireFullWater / requireHeat | true / true | Полный котёл и нагрев |
|
||||
| brewSeconds / consumeSeconds | 4 / 1.6 | Варка и употребление |
|
||||
| soupStackSize | 16 | Размер стопки (1–64) |
|
||||
| soupsEnabled | true | Разрешить новые супы |
|
||||
| dyeWater / dyeArmor / dyeBlocks | true | Окрашивание воды, брони и блоков |
|
||||
| storePotions / tipArrows | true | Хранение зелий и обработка стрел |
|
||||
| inheritEffects / alwaysEdible / returnBowl | true | Эффекты, еда при полном голоде, возврат миски |
|
||||
| normalizeVanillaSoups | true | Размер стопки ванильных супов |
|
||||
| particles / ingredientDisplays / sounds / messages | true | Отображение и обратная связь |
|
||||
| soundVolume | 0.8 | Громкость (0–4) |
|
||||
| maxNutrition / maxSaturation | 1000 | Пределы питания |
|
||||
| blockedIngredients / incompatible / customIngredients | пустые | Запреты, несовместимость, свои ингредиенты |
|
||||
| messageOverrides | {} | Замена полного текста сообщений |
|
||||
| soupName / defaultColor | Комбинированный суп / #B77A36 | Имя и цвет |
|
||||
|
||||
Свойства готового супа сохраняются. Новые настройки рецептуры действуют на следующую варку.
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
# Проверки AstraCauldron
|
||||
|
||||
## Градиент миски супа — 11 сентября 2026, версия 0.2.4
|
||||
|
||||
- `gradlew.bat --offline test assemble` — успешно, 19 тестов без ошибок.
|
||||
- Проверены экспорт модели, повторный запуск без перезаписи, обновление исходной
|
||||
однотонной модели с LF/CRLF и сохранение пользовательской модификации.
|
||||
- Декодеры `ClientItem.CODEC` и `CuboidModel` Minecraft 26.2 приняли модели из
|
||||
проверочного ZIP, содержащего ресурсы нового JAR.
|
||||
- Используются три нейтральных оттенка ванильных текстур: `#FFFFFF`, `#EAEAEA`,
|
||||
`#D8D8D8`, умножаемые на прежний RGB супа. Проверка в игровом клиенте не проводилась.
|
||||
- AstraCauldron-0.2.4.jar установлен непосредственно в `mods` рабочего NeoForge-сервера.
|
||||
SHA-256 сборки и установленного файла:
|
||||
`ED66C33A153DFA6089D99C62F8A864F279C3ABC9CF8D88EEF6AD4F8D6CF6D48E`.
|
||||
- Прежний JAR сохранён в
|
||||
`C:/Users/ScarPC/Documents/NeoForge Server 26.2/old-mods/20260911-181130/AstraCauldron-0.2.3.jar`.
|
||||
Для загрузки нужен перезапуск сервера; штатная модель обновится до сборки ресурспака.
|
||||
|
||||
## AstraCauldron 0.2.0 и AstraPlus 0.5.1
|
||||
|
||||
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: оба определения предметов и обе геометрии (миска/жидкость).
|
||||
|
||||
Проверены нативные питание и употребление супа с возвратом миски из стака, эффекты зелий
|
||||
и еды, порядок рецепта, размеры стаков, ингредиенты AstraPlus и сохранение их регистрации
|
||||
при редактировании определения, отказ некорректной конфигурации и откат при ошибке записи.
|
||||
|
||||
Общий API AstraPlus проверен отдельно от рецепта супа: создание воды, смена RGB/высоты
|
||||
без новой сущности, защита владельца, восстановление удалённого отображения, отсутствие
|
||||
принудительной загрузки чанков, очистка и валидация параметров. Модели воды входят
|
||||
в ZIP самого AstraPlus; ресурсы миски экспортируются AstraCauldron до сборки ZIP.
|
||||
|
||||
Проверены шесть окрашиваемых видов брони (четыре кожаные части, кожаная конская, волчья),
|
||||
сохранение имён и прочности, смешивание красителей, отказ неокрашиваемой брони, неизменность
|
||||
входного предмета при вызове API. Обычные/взрывные/туманные бутылочки принимаются;
|
||||
разные зелья отклоняются без потери. Проверены возврат стекла, выдача обычной бутылочки,
|
||||
пачки стрел 17/32/64 и частичное преобразование при нехватке жидкости, нативный множитель
|
||||
длительности стрел. Чистая вода всех трёх типов бутылочек наполняет обычный водяной котёл.
|
||||
|
||||
После перезапуска сохранены сырые ингредиенты, готовые порции, незавершённая варка,
|
||||
зелье и цветная вода. API-визуализация восстановлена без дубликатов; последняя порция
|
||||
удаляет содержимое и поверхность. Проверки используют FakePlayer и настоящие события
|
||||
NeoForge. Проверочный JAR явно требует `-Dastracauldron.isolatedVerification=true`.
|
||||
|
||||
## Повторение
|
||||
|
||||
Сначала собрать AstraPlus, затем AstraCauldron:
|
||||
|
||||
```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'
|
||||
```
|
||||
|
||||
`verify-server.ps1` создаёт уникальный каталог, запускает оба прогона и оставляет их
|
||||
логи/мир в build. Он читает только библиотеки установленного NeoForge. На рабочий
|
||||
сервер проверочный JAR не устанавливать. Лимит памяти теста — 1 ГБ.
|
||||
|
||||
## Установка
|
||||
|
||||
Оба основных JAR установлены непосредственно в
|
||||
`C:/Users/ScarPC/Documents/NeoForge Server 26.2/mods`, SHA-256 совпали со сборками:
|
||||
|
||||
- AstraPlus-0.5.1.jar: `C47953465AFCE4A5DEA64E9F44F48D9E4D18160156477A12CC7465E662C51B16`.
|
||||
- AstraCauldron-0.2.0.jar: `0F5149CAE4BD32D09D37A30155CC445650C639084D8B37C32509F525ECD6A7F5`.
|
||||
|
||||
Старый 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.
|
||||
|
||||
После финальной нормализации окончаний строк JAR повторно установлен; промежуточная
|
||||
сборка AstraCauldron этой задачи сохранена в "old-mods/20260908-194159/".
|
||||
Побайтово проверено: все классы совпадают с протестированной сборкой; различаются
|
||||
только окончания строк и пустые строки в конце трёх файлов ресурсов.
|
||||
+11
-6
@@ -3,10 +3,10 @@ plugins {
|
||||
id("net.neoforged.moddev") version "2.0.146"
|
||||
}
|
||||
group = "online.astradev"
|
||||
version = "0.3.2"
|
||||
version = "0.3.3"
|
||||
repositories { mavenCentral() }
|
||||
val astraPlusApi = providers.gradleProperty("astraPlusApi")
|
||||
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.0.jar")
|
||||
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.1.jar")
|
||||
dependencies {
|
||||
compileOnly(files(astraPlusApi))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
@@ -33,11 +33,16 @@ sourceSets.test {
|
||||
compileClasspath += sourceSets.main.get().compileClasspath
|
||||
runtimeClasspath += sourceSets.main.get().compileClasspath
|
||||
}
|
||||
val verification = sourceSets.create("verification") {
|
||||
val integrationTest = sourceSets.create("integrationTest") {
|
||||
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>("integrationTestJar") {
|
||||
from(integrationTest.output)
|
||||
archiveClassifier.set("integration-tests")
|
||||
}
|
||||
|
||||
tasks.register<Exec>("integrationTest") {
|
||||
dependsOn("build", "integrationTestJar")
|
||||
commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/run.ps1")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,713 @@
|
||||
package online.astradev.cauldron.verification;
|
||||
|
||||
import com.google.gson.*;
|
||||
|
||||
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.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.cauldron.*;
|
||||
import online.astradev.plus.api.*;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* 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).soup().isEmpty(),
|
||||
"cannot brew without campfire; ingredients preserved");
|
||||
level.setBlock(
|
||||
READY.below(),
|
||||
Blocks.CAMPFIRE
|
||||
.defaultBlockState()
|
||||
.setValue(net.minecraft.world.level.block.CampfireBlock.LIT, false),
|
||||
3);
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(
|
||||
AstraCauldron.pots().get(level, READY).soup().isEmpty(),
|
||||
"unlit campfire cannot start soup");
|
||||
level.setBlock(READY.below(), Blocks.CAMPFIRE.defaultBlockState(), 3);
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(
|
||||
AstraCauldron.pots().get(level, READY).brewTicks() > 0,
|
||||
"four ingredients start timed brew");
|
||||
level.setBlock(READY.below(), Blocks.AIR.defaultBlockState(), 3);
|
||||
for (int i = 0; i < 100; i++) AstraCauldron.pots().tick();
|
||||
require(
|
||||
AstraCauldron.pots().get(level, READY).brewTicks() > 0,
|
||||
"removing fire pauses cooking beyond full duration");
|
||||
level.setBlock(READY.below(), Blocks.SOUL_CAMPFIRE.defaultBlockState(), 3);
|
||||
require(
|
||||
online.astradev.cauldron.CauldronHeat.heated(level, READY),
|
||||
"soul campfire resumes heating");
|
||||
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);
|
||||
level.setBlock(BREW.below(), Blocks.CAMPFIRE.defaultBlockState(), 3);
|
||||
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();
|
||||
checkDyedBlocks(level, api);
|
||||
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 void checkDyedBlocks(ServerLevel level, online.astradev.plus.api.CauldronApi api)
|
||||
throws Exception {
|
||||
var pos = new BlockPos(30, 100, 8);
|
||||
for (var family : List.of(Items.WOOL, Items.CARPET)) {
|
||||
for (var color : DyeColor.values()) {
|
||||
var source = family.pick(color == DyeColor.WHITE ? DyeColor.BLACK : DyeColor.WHITE);
|
||||
int rgb =
|
||||
api.mixDye(OptionalInt.empty(), new ItemStack(Items.DYE.pick(color)))
|
||||
.orElseThrow();
|
||||
var named = new ItemStack(source, 64);
|
||||
named.set(
|
||||
DataComponents.CUSTOM_NAME,
|
||||
net.minecraft.network.chat.Component.literal("Keep textile name"));
|
||||
var batch = api.dyeBlocks(named, rgb, 3).orElseThrow();
|
||||
require(
|
||||
batch.result().is(family.pick(color))
|
||||
&& batch.result().getCount() == 64
|
||||
&& batch.result()
|
||||
.getHoverName()
|
||||
.getString()
|
||||
.equals("Keep textile name")
|
||||
&& named.is(source)
|
||||
&& named.getCount() == 64,
|
||||
"textile palette and metadata: " + family.pick(color));
|
||||
}
|
||||
for (int water = 1; water <= 3; water++)
|
||||
for (int count : new int[] {1, 16, 17, 32, 33, 64}) {
|
||||
AstraCauldron.liquids().breakPot(level, pos);
|
||||
level.setBlock(
|
||||
pos,
|
||||
Blocks.WATER_CAULDRON
|
||||
.defaultBlockState()
|
||||
.setValue(LayeredCauldronBlock.LEVEL, water),
|
||||
3);
|
||||
player.getInventory().clearContent();
|
||||
use(pos, new ItemStack(Items.DYE.pick(DyeColor.RED)));
|
||||
use(pos, new ItemStack(family.pick(DyeColor.WHITE), count));
|
||||
int converted = Math.min(count, water == 3 ? 64 : water * 16);
|
||||
int cost = converted <= 16 ? 1 : converted <= 32 ? 2 : 3;
|
||||
var remaining = AstraCauldron.liquids().get(level, pos);
|
||||
require(
|
||||
player.getInventory().countItem(family.pick(DyeColor.RED)) == converted
|
||||
&& player.getInventory().countItem(family.pick(DyeColor.WHITE))
|
||||
== count - converted
|
||||
&& (remaining == null
|
||||
? water == cost
|
||||
: remaining.levels() == water - cost),
|
||||
"textile batch/inventory/water: "
|
||||
+ family.pick(DyeColor.WHITE)
|
||||
+ " count="
|
||||
+ count
|
||||
+ " levels="
|
||||
+ water);
|
||||
}
|
||||
}
|
||||
int red =
|
||||
api.mixDye(OptionalInt.empty(), new ItemStack(Items.DYE.pick(DyeColor.RED)))
|
||||
.orElseThrow();
|
||||
require(
|
||||
api.dyeBlocks(new ItemStack(Items.WOOL.pick(DyeColor.RED)), red, 3).isEmpty()
|
||||
&& api.dyeBlocks(new ItemStack(Items.STONE), red, 3).isEmpty(),
|
||||
"matching colors and unsupported blocks rejected");
|
||||
AstraCauldron.liquids().breakPot(level, pos);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,15 @@ param(
|
||||
[string]$PlusDirectory = ''
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repo = Split-Path $PSScriptRoot -Parent
|
||||
if ($Java -eq 'java' -and $env:JAVA_HOME) { $Java = Join-Path $env:JAVA_HOME 'bin/java.exe' }
|
||||
$repo = (Resolve-Path "$PSScriptRoot/../..").Path
|
||||
$plus = Join-Path (Split-Path $repo -Parent) 'AstraPlus'
|
||||
if ($PlusDirectory) { $plus = (Resolve-Path -LiteralPath $PlusDirectory).Path }
|
||||
$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
|
||||
$plusVersion = [regex]::Match((Get-Content "$plus/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
|
||||
$cauldronVersion = [regex]::Match((Get-Content "$repo/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
|
||||
foreach ($jar in @("$plus/build/libs/AstraPlus-$plusVersion.jar", "$repo/build/libs/AstraCauldron-$cauldronVersion.jar", "$repo/build/libs/AstraCauldron-$cauldronVersion-verification.jar")) {
|
||||
foreach ($jar in @("$plus/build/libs/AstraPlus-$plusVersion.jar", "$repo/build/libs/AstraCauldron-$cauldronVersion.jar", "$repo/build/libs/AstraCauldron-$cauldronVersion-integration-tests.jar")) {
|
||||
Copy-Item -LiteralPath $jar -Destination (Join-Path $run 'mods')
|
||||
}
|
||||
$serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/')
|
||||
@@ -95,9 +95,9 @@ public final class AstraCauldron {
|
||||
}
|
||||
|
||||
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)));
|
||||
if (!(level instanceof ServerLevel serverLevel)) return false;
|
||||
if (pots != null && pots.contains(serverLevel, pos)) return true;
|
||||
return liquids != null && liquids.contains(serverLevel, pos);
|
||||
}
|
||||
|
||||
private void interact(PlayerInteractEvent.RightClickBlock event) {
|
||||
@@ -105,31 +105,26 @@ public final class AstraCauldron {
|
||||
|| event.isCanceled()
|
||||
|| event.getUseBlock() == TriState.FALSE
|
||||
|| event.getUseItem() == TriState.FALSE) return;
|
||||
if (event.getEntity() instanceof ServerPlayer player
|
||||
&& RegisteredRecipes.interact(player, event.getPos(), event.getHand())) {
|
||||
event.setCanceled(true);
|
||||
event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
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);
|
||||
}
|
||||
if (!(event.getEntity() instanceof ServerPlayer player)) return;
|
||||
var pos = event.getPos();
|
||||
var hand = event.getHand();
|
||||
boolean handled = RegisteredRecipes.interact(player, pos, hand);
|
||||
if (!handled && !pots.contains(player.level(), pos) && liquids != null)
|
||||
handled = liquids.interact(player, pos, hand);
|
||||
if (!handled) handled = pots.interact(player, pos, hand);
|
||||
if (!handled) return;
|
||||
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);
|
||||
}
|
||||
if (event.isCanceled() || pots == null) return;
|
||||
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||
boolean removed = pots.breakPot(level, event.getPos());
|
||||
if (removed && liquids != null) removed = liquids.breakPot(level, event.getPos());
|
||||
if (removed) return;
|
||||
event.setCanceled(true);
|
||||
event.setNotifyClient(true);
|
||||
}
|
||||
|
||||
private void explosion(ExplosionEvent.Detonate event) {
|
||||
@@ -141,11 +136,11 @@ public final class AstraCauldron {
|
||||
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);
|
||||
if (resolver == null || !resolver.resolve()) return;
|
||||
boolean movesCauldron = resolver.getToPush().stream().anyMatch(pos -> occupied(level, pos));
|
||||
boolean breaksCauldron =
|
||||
resolver.getToDestroy().stream().anyMatch(pos -> occupied(level, pos));
|
||||
if (movesCauldron || breaksCauldron) event.setCanceled(true);
|
||||
}
|
||||
|
||||
private void unload(ChunkEvent.Unload event) {
|
||||
@@ -193,7 +188,7 @@ public final class AstraCauldron {
|
||||
() ->
|
||||
Component.literal(
|
||||
"AstraCauldron: настройки"
|
||||
+ " применены."),
|
||||
+ " применены."),
|
||||
true);
|
||||
return 1;
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -11,25 +11,49 @@ import net.minecraft.world.level.block.LayeredCauldronBlock;
|
||||
/** Uses the existing campfire ticker; no scanning worlds or spawning persistent effects. */
|
||||
public final class CauldronHeat {
|
||||
private CauldronHeat() {}
|
||||
|
||||
public static boolean heated(LevelReader level, BlockPos cauldron) {
|
||||
var below = cauldron.below();
|
||||
if (!level.hasChunkAt(below)) return false;
|
||||
var state = level.getBlockState(below);
|
||||
return state.getBlock() instanceof CampfireBlock && state.getValue(CampfireBlock.LIT);
|
||||
}
|
||||
|
||||
public static void tick(ServerLevel level, BlockPos campfire) {
|
||||
if (!AstraCauldron.config().particles) return;
|
||||
var pos = campfire.above();
|
||||
if ((level.getGameTime() + pos.asLong()) % 10 != 0 || !heated(level, pos)) return;
|
||||
var state = level.getBlockState(pos);
|
||||
double surface;
|
||||
if (state.is(Blocks.WATER_CAULDRON)) surface = .375 + .1875 * state.getValue(LayeredCauldronBlock.LEVEL);
|
||||
if (state.is(Blocks.WATER_CAULDRON))
|
||||
surface = .375 + .1875 * state.getValue(LayeredCauldronBlock.LEVEL);
|
||||
else {
|
||||
var pot = AstraCauldron.pots() == null ? null : AstraCauldron.pots().get(level, pos);
|
||||
if (!state.is(Blocks.CAULDRON) || pot == null || pot.soup().isEmpty() || pot.brewTicks() > 0) return;
|
||||
if (!state.is(Blocks.CAULDRON)
|
||||
|| pot == null
|
||||
|| pot.soup().isEmpty()
|
||||
|| pot.brewTicks() > 0) return;
|
||||
surface = CauldronAnimation.liquidHeight(pot.servings(), pot.capacity());
|
||||
}
|
||||
level.sendParticles(ParticleTypes.BUBBLE_POP, pos.getX() + .5, pos.getY() + surface + .01, pos.getZ() + .5, 4, .18, .015, .18, 0);
|
||||
level.sendParticles(ParticleTypes.SPLASH, pos.getX() + .5, pos.getY() + surface + .02, pos.getZ() + .5, 2, .16, 0, .16, 0);
|
||||
level.sendParticles(
|
||||
ParticleTypes.BUBBLE_POP,
|
||||
pos.getX() + .5,
|
||||
pos.getY() + surface + .01,
|
||||
pos.getZ() + .5,
|
||||
4,
|
||||
.18,
|
||||
.015,
|
||||
.18,
|
||||
0);
|
||||
level.sendParticles(
|
||||
ParticleTypes.SPLASH,
|
||||
pos.getX() + .5,
|
||||
pos.getY() + surface + .02,
|
||||
pos.getZ() + .5,
|
||||
2,
|
||||
.16,
|
||||
0,
|
||||
.16,
|
||||
0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,12 @@ public final class CombinationRules {
|
||||
List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
|
||||
return rejection(ingredients, blocked, pairs, 4);
|
||||
}
|
||||
public static String rejection(List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs, int count) {
|
||||
|
||||
public static String rejection(
|
||||
List<Set<String>> ingredients,
|
||||
List<String> blocked,
|
||||
List<List<String>> pairs,
|
||||
int count) {
|
||||
if (ingredients.size() != count) return "Нужно ровно " + count + " ингредиента.";
|
||||
for (Set<String> tags : ingredients) {
|
||||
for (String selector : blocked) {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
|
||||
|
||||
|
||||
final class IngredientColors {
|
||||
private IngredientColors() {}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
@@ -12,21 +11,37 @@ 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;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
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) {}
|
||||
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);
|
||||
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);
|
||||
@@ -38,18 +53,28 @@ public final class Ingredients {
|
||||
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);
|
||||
String plusId = plus.map(value -> value.id().toString()).orElse(null);
|
||||
Custom match = findCustom(stack, plusId);
|
||||
var food = stack.get(DataComponents.FOOD);
|
||||
boolean potion = stack.is(Items.POTION) || stack.is(Items.SPLASH_POTION) || stack.is(Items.LINGERING_POTION);
|
||||
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();
|
||||
int nutrition = 0;
|
||||
float saturation = 0;
|
||||
if (food != null) {
|
||||
nutrition = food.nutrition();
|
||||
saturation = food.saturation();
|
||||
} else if (cake) {
|
||||
nutrition = 14;
|
||||
saturation = 2.8f;
|
||||
}
|
||||
var effects = new ArrayList<ConsumeEffect>();
|
||||
var consumable = stack.get(DataComponents.CONSUMABLE);
|
||||
if (consumable != null) effects.addAll(consumable.onConsumeEffects());
|
||||
@@ -59,13 +84,21 @@ public final class Ingredients {
|
||||
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));
|
||||
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()));
|
||||
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");
|
||||
@@ -74,91 +107,199 @@ public final class Ingredients {
|
||||
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));
|
||||
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()));
|
||||
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);
|
||||
}
|
||||
|
||||
private Custom findCustom(ItemStack stack, String plusId) {
|
||||
ItemStack normalized = null;
|
||||
for (var ingredient : custom) {
|
||||
String expected = ingredient.definition.astraPlusId;
|
||||
if (expected != null) {
|
||||
if (expected.equals(plusId)) return ingredient;
|
||||
continue;
|
||||
}
|
||||
if (normalized == null) normalized = normalizedCopy(stack);
|
||||
if (ItemStack.isSameItemSameComponents(ingredient.sample, normalized))
|
||||
return ingredient;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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, config.ingredientCount);
|
||||
String error =
|
||||
CombinationRules.rejection(
|
||||
data.stream().map(Ingredient::tags).toList(),
|
||||
config.blockedIngredients,
|
||||
config.incompatible,
|
||||
config.ingredientCount);
|
||||
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 "В супе слишком много эффектов.";
|
||||
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();
|
||||
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();
|
||||
List<ConsumeEffect> effects = config.inheritEffects ? data.stream().flatMap(i -> i.effects.stream()).toList() : List.of();
|
||||
List<ConsumeEffect> effects =
|
||||
config.inheritEffects
|
||||
? data.stream().flatMap(i -> i.effects.stream()).toList()
|
||||
: List.of();
|
||||
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, config.alwaysEdible));
|
||||
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, config.alwaysEdible));
|
||||
var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE));
|
||||
soup.set(DataComponents.CONSUMABLE, new Consumable(config.consumeSeconds, base.animation(), base.sound(), config.particles && base.hasConsumeParticles(), effects));
|
||||
if (config.returnBowl) soup.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
|
||||
soup.set(
|
||||
DataComponents.CONSUMABLE,
|
||||
new Consumable(
|
||||
config.consumeSeconds,
|
||||
base.animation(),
|
||||
base.sound(),
|
||||
config.particles && base.hasConsumeParticles(),
|
||||
effects));
|
||||
if (config.returnBowl)
|
||||
soup.set(
|
||||
DataComponents.USE_REMAINDER,
|
||||
new UseRemainder(
|
||||
ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
|
||||
else soup.remove(DataComponents.USE_REMAINDER);
|
||||
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; }
|
||||
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);
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
if (isCombined(stack) || AstraCauldron.config().normalizeVanillaSoups) stack.set(DataComponents.MAX_STACK_SIZE, AstraCauldron.config().soupStackSize);
|
||||
if (!(stack.is(Items.MUSHROOM_STEW)
|
||||
|| stack.is(Items.RABBIT_STEW)
|
||||
|| stack.is(Items.BEETROOT_SOUP)
|
||||
|| stack.is(Items.SUSPICIOUS_STEW))) return;
|
||||
if (isCombined(stack) || AstraCauldron.config().normalizeVanillaSoups)
|
||||
stack.set(DataComponents.MAX_STACK_SIZE, AstraCauldron.config().soupStackSize);
|
||||
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));
|
||||
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())));
|
||||
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));
|
||||
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));
|
||||
if (effect instanceof ApplyStatusEffectsConsumeEffect apply) {
|
||||
for (var instance : apply.effects())
|
||||
lines.add(effectLine(instance, apply.probability()));
|
||||
continue;
|
||||
}
|
||||
String description =
|
||||
switch (effect) {
|
||||
case TeleportRandomlyConsumeEffect ignored -> "Случайная телепортация";
|
||||
case ClearAllStatusEffectsConsumeEffect ignored -> "Снятие всех эффектов";
|
||||
case RemoveStatusEffectsConsumeEffect ignored -> "Снятие эффектов";
|
||||
default -> "Звук при употреблении";
|
||||
};
|
||||
lines.add(line(description, ChatFormatting.GRAY));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static Component effectLine(MobEffectInstance effect, float probability) {
|
||||
String duration = "∞";
|
||||
if (!effect.isInfiniteDuration())
|
||||
duration =
|
||||
String.format(
|
||||
Locale.ROOT,
|
||||
"%d:%02d",
|
||||
effect.getDuration() / 1200,
|
||||
effect.getDuration() / 20 % 60);
|
||||
String details = " " + SoupText.roman(effect.getAmplifier() + 1) + " (" + duration + ")";
|
||||
if (probability < 1) details += " " + Math.round(probability * 100) + "%";
|
||||
return Component.translatable(effect.getDescriptionId())
|
||||
.append(details)
|
||||
.withStyle(style -> style.withColor(ChatFormatting.AQUA).withItalic(false));
|
||||
}
|
||||
|
||||
private static Component line(String text, ChatFormatting color) {
|
||||
return Component.literal(text).withStyle(s -> s.withColor(color).withItalic(false));
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ public final class LiquidPots implements AutoCloseable {
|
||||
say(
|
||||
player,
|
||||
"Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно"
|
||||
+ " смешивать.");
|
||||
+ " смешивать.");
|
||||
return true;
|
||||
}
|
||||
if (AstraCauldron.config().storePotions
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import com.google.gson.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
@@ -36,6 +37,7 @@ public final class SoupConfig {
|
||||
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;
|
||||
@@ -44,55 +46,95 @@ public final class SoupConfig {
|
||||
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();
|
||||
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 (ingredientCount < 1 || ingredientCount > 4 || soupStackSize < 1 || soupStackSize > 64 || !Float.isFinite(consumeSeconds) || consumeSeconds < .05 || consumeSeconds > 60)
|
||||
if (ingredientCount < 1
|
||||
|| ingredientCount > 4
|
||||
|| soupStackSize < 1
|
||||
|| soupStackSize > 64
|
||||
|| !Float.isFinite(consumeSeconds)
|
||||
|| consumeSeconds < .05
|
||||
|| consumeSeconds > 60)
|
||||
throw new IllegalArgumentException("Invalid ingredients/consumption settings");
|
||||
if (!Float.isFinite(soundVolume) || soundVolume < 0 || soundVolume > 4 || messageOverrides == null
|
||||
|| messageOverrides.containsValue(null)) throw new IllegalArgumentException("Invalid sound/messages");
|
||||
if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds)
|
||||
|| brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0
|
||||
|| !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank())
|
||||
if (!Float.isFinite(soundVolume)
|
||||
|| soundVolume < 0
|
||||
|| soundVolume > 4
|
||||
|| messageOverrides == null
|
||||
|| messageOverrides.containsValue(null))
|
||||
throw new IllegalArgumentException("Invalid sound/messages");
|
||||
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 нужны пары");
|
||||
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)
|
||||
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("Некорректный эффект");
|
||||
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_:./-]+"))
|
||||
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");
|
||||
if (s == null || !s.matches("#[0-9a-fA-F]{6}"))
|
||||
throw new IllegalArgumentException("Цвет: #RRGGBB");
|
||||
return Integer.parseInt(s.substring(1), 16);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,19 +3,18 @@ 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);
|
||||
@@ -27,12 +26,28 @@ final class SoupDisplay extends Display.ItemDisplay {
|
||||
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)));
|
||||
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;
|
||||
}
|
||||
@Override public boolean shouldBeSaved() { return false; }
|
||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
||||
}
|
||||
|
||||
@@ -2,28 +2,47 @@ 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;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
|
||||
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); }
|
||||
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();
|
||||
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();
|
||||
return ItemStack.CODEC
|
||||
.parse(RegistryOps.create(JsonOps.INSTANCE, registries), json)
|
||||
.getOrThrow();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
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;
|
||||
@@ -15,21 +13,40 @@ 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;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
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()); }
|
||||
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); }
|
||||
|
||||
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;
|
||||
@@ -41,32 +58,59 @@ public final class SoupPots implements AutoCloseable {
|
||||
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.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 SoupConfig config() { return config; }
|
||||
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 Ingredients ingredients() {
|
||||
return ingredients;
|
||||
}
|
||||
|
||||
public SoupConfig config() {
|
||||
return config;
|
||||
}
|
||||
|
||||
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 и предмет в руке");
|
||||
|
||||
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()));
|
||||
// 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());
|
||||
else
|
||||
custom.item =
|
||||
SoupFiles.encode(
|
||||
Ingredients.normalizedCopy(player.getMainHandItem()),
|
||||
server.registryAccess());
|
||||
custom.nutrition = nutrition;
|
||||
custom.saturation = saturation;
|
||||
next.customIngredients.put(id, custom);
|
||||
@@ -75,57 +119,108 @@ public final class SoupPots implements AutoCloseable {
|
||||
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");
|
||||
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 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());
|
||||
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);
|
||||
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.isEmpty() : !p.items.isEmpty())))
|
||||
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.isEmpty() : !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); }
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
var level = player.level();
|
||||
var pos = Position.at(level, blockPos);
|
||||
var pot = pots.get(pos);
|
||||
if (player.isSpectator()) return false;
|
||||
if (!config.soupsEnabled && pot == null) return false;
|
||||
if (hand != InteractionHand.MAIN_HAND) return pot != null;
|
||||
@@ -135,117 +230,282 @@ public final class SoupPots implements AutoCloseable {
|
||||
if (pot == null && ingredients.read(held) == null) return false;
|
||||
if (pot == null) {
|
||||
if (config.requireFullWater && state.getValue(LayeredCauldronBlock.LEVEL) != 3) {
|
||||
say(player, "Сначала наполните котёл водой доверху."); return true;
|
||||
say(player, "Сначала наполните котёл водой доверху.");
|
||||
return true;
|
||||
}
|
||||
pot = Pot.raw(List.of());
|
||||
}
|
||||
if (pot.brewing()) { say(player, (!config.requireHeat || CauldronHeat.heated(level, blockPos)) ? "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с." : "Варка приостановлена. Зажгите костёр под котлом."); return true; }
|
||||
if (pot.brewing()) {
|
||||
say(
|
||||
player,
|
||||
(!config.requireHeat || CauldronHeat.heated(level, blockPos))
|
||||
? "Суп варится… Осталось: "
|
||||
+ 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);
|
||||
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;
|
||||
say(
|
||||
player,
|
||||
left == 0
|
||||
? "Последняя порция собрана. Котёл пуст."
|
||||
: "Осталось порций: " + left + ".");
|
||||
return true;
|
||||
}
|
||||
if (pot.items.size() >= config.ingredientCount && (player.isShiftKeyDown() || !held.isEmpty())) {
|
||||
if (config.requireHeat && !CauldronHeat.heated(level, blockPos)) { say(player, "Для варки нужен горящий костёр прямо под котлом."); return true; }
|
||||
if (pot.items.size() >= config.ingredientCount
|
||||
&& (player.isShiftKeyDown() || !held.isEmpty())) {
|
||||
if (config.requireHeat && !CauldronHeat.heated(level, blockPos)) {
|
||||
say(player, "Для варки нужен горящий костёр прямо под котлом.");
|
||||
return true;
|
||||
}
|
||||
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 (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() + "/" + config.ingredientCount + "."); 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()
|
||||
+ "/"
|
||||
+ config.ingredientCount
|
||||
+ ".");
|
||||
return true;
|
||||
}
|
||||
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/" + config.ingredientCount + "."); 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() + "/" + config.ingredientCount + "." + (items.size() == config.ingredientCount ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
|
||||
if (ingredients.read(held) == null) {
|
||||
say(
|
||||
player,
|
||||
"Добавьте еду или зелье. В котле: "
|
||||
+ pot.items.size()
|
||||
+ "/"
|
||||
+ config.ingredientCount
|
||||
+ ".");
|
||||
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()
|
||||
+ "/"
|
||||
+ config.ingredientCount
|
||||
+ "."
|
||||
+ (items.size() == config.ingredientCount
|
||||
? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний."
|
||||
: ""));
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean breakPot(ServerLevel level, BlockPos blockPos) {
|
||||
var pos = Position.at(level, blockPos); var old = pots.get(pos);
|
||||
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());
|
||||
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; }
|
||||
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;
|
||||
}
|
||||
boolean heated = !config.requireHeat || CauldronHeat.heated(level, pos.pos);
|
||||
if (pot.brewing() && heated) {
|
||||
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))) {
|
||||
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);
|
||||
if (config.particles) level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01);
|
||||
if (config.particles)
|
||||
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 (config.ingredientDisplays && 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) + (heated ? 2 : 0), pot.brewTicks);
|
||||
for (int i = 0; i < displays.size(); i++)
|
||||
displays.get(i)
|
||||
.ingredient(
|
||||
i,
|
||||
water,
|
||||
ticks + 2,
|
||||
elapsed.getOrDefault(pos, 0) + (heated ? 2 : 0),
|
||||
pot.brewTicks);
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
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)));
|
||||
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;
|
||||
}
|
||||
if (!config.ingredientDisplays) {
|
||||
removeVisuals(pos);
|
||||
return;
|
||||
}
|
||||
if (!config.ingredientDisplays) { removeVisuals(pos); return; }
|
||||
var existing = visuals.get(pos);
|
||||
if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { removeVisuals(pos); existing = null; }
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
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)));
|
||||
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() {
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
||||
water.removeAll(WATER_OWNER);
|
||||
}
|
||||
private void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { if (config.sounds) level.playSound(null, pos, sound, SoundSource.BLOCKS, config.soundVolume, 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) { var config = AstraCauldron.config(); if (config.messages) player.sendSystemMessage(Component.literal(config.messageOverrides.getOrDefault(text, text)).withStyle(ChatFormatting.GOLD), true); }
|
||||
private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||
|
||||
private void sound(ServerLevel level, BlockPos pos, SoundEvent sound) {
|
||||
if (config.sounds)
|
||||
level.playSound(null, pos, sound, SoundSource.BLOCKS, config.soundVolume, 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) {
|
||||
var config = AstraCauldron.config();
|
||||
if (config.messages)
|
||||
player.sendSystemMessage(
|
||||
Component.literal(config.messageOverrides.getOrDefault(text, text))
|
||||
.withStyle(ChatFormatting.GOLD),
|
||||
true);
|
||||
}
|
||||
|
||||
private static void saveError(ServerPlayer player) {
|
||||
say(player, "Не удалось сохранить котёл. Обратитесь к администратору.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,61 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
/** Export before AstraPlus's startup pack build; upgrade only known, unmodified defaults. */
|
||||
final class SoupResources {
|
||||
// Bundled flat-colour model in 0.2.0–0.2.3, with normalized newlines and outer whitespace.
|
||||
private static final String FLAT_MODEL_SHA256 =
|
||||
"51b5c2b0561ec815e5ddaff5654ce04fffa0995fc3e5972323f385d58842cd2c";
|
||||
|
||||
private SoupResources() {}
|
||||
|
||||
static void install(Path root) throws IOException {
|
||||
for (String name : List.of("items/combined_soup.json",
|
||||
"models/item/soup_liquid.json")) {
|
||||
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());
|
||||
boolean exists = Files.exists(target, LinkOption.NOFOLLOW_LINKS);
|
||||
if (exists && !(name.equals("models/item/soup_liquid.json") && isFlatDefault(target))) continue;
|
||||
try (var input = SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
|
||||
if (exists && !(name.equals("models/item/soup_liquid.json") && isFlatDefault(target)))
|
||||
continue;
|
||||
try (var input =
|
||||
SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
|
||||
if (input == null) throw new IOException("Missing resource " + relative);
|
||||
if (!exists) Files.copy(input, target);
|
||||
else {
|
||||
Path temp = Files.createTempFile(target.getParent(), "soup-model-", ".tmp");
|
||||
try {
|
||||
Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
Files.move(
|
||||
temp,
|
||||
target,
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
Files.deleteIfExists(temp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isFlatDefault(Path path) throws IOException {
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 8192) return false;
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 8192)
|
||||
return false;
|
||||
String model = Files.readString(path, UTF_8).replace("\r\n", "\n").trim();
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
|
||||
.digest(model.getBytes(UTF_8))).equals(FLAT_MODEL_SHA256);
|
||||
} catch (NoSuchAlgorithmException impossible) { throw new AssertionError(impossible); }
|
||||
return HexFormat.of()
|
||||
.formatHex(MessageDigest.getInstance("SHA-256").digest(model.getBytes(UTF_8)))
|
||||
.equals(FLAT_MODEL_SHA256);
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new AssertionError(impossible);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.item.crafting.*;
|
||||
import net.minecraft.world.level.block.entity.CampfireBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
@@ -13,8 +14,13 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
@Mixin(CampfireBlockEntity.class)
|
||||
public abstract class CampfireHeatMixin {
|
||||
@Inject(method = "cookTick", at = @At("TAIL"))
|
||||
private static void astracauldron$heat(ServerLevel level, BlockPos pos, BlockState state, CampfireBlockEntity entity,
|
||||
RecipeManager.CachedCheck<SingleRecipeInput, CampfireCookingRecipe> recipes, CallbackInfo ci) {
|
||||
private static void astracauldron$heat(
|
||||
ServerLevel level,
|
||||
BlockPos pos,
|
||||
BlockState state,
|
||||
CampfireBlockEntity entity,
|
||||
RecipeManager.CachedCheck<SingleRecipeInput, CampfireCookingRecipe> recipes,
|
||||
CallbackInfo ci) {
|
||||
online.astradev.cauldron.CauldronHeat.tick(level, pos);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ 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;
|
||||
@@ -15,11 +17,18 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
@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) {
|
||||
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) {
|
||||
private void soups$drip(
|
||||
BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) {
|
||||
if (AstraCauldron.occupied(level, pos)) ci.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ 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;
|
||||
|
||||
@@ -4,6 +4,7 @@ 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;
|
||||
@@ -11,16 +12,21 @@ 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) {
|
||||
@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" -> {
|
||||
var config = online.astradev.cauldron.AstraCauldron.config();
|
||||
if (config.normalizeVanillaSoups) components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize);
|
||||
if (config.normalizeVanillaSoups)
|
||||
components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize);
|
||||
}
|
||||
default -> { }
|
||||
default -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ConfigurationPolicyTest {
|
||||
@TempDir Path root;
|
||||
@Test void oldConfigKeepsDefaultsAndNewFieldsAreValidated() throws Exception {
|
||||
|
||||
@Test
|
||||
void oldConfigKeepsDefaultsAndNewFieldsAreValidated() throws Exception {
|
||||
Path file = root.resolve("cauldron.json");
|
||||
Files.writeString(file, "{\"servingsPerBrew\":2,\"ingredientCount\":2,\"requireHeat\":false,\"soupStackSize\":8}");
|
||||
Files.writeString(
|
||||
file,
|
||||
"{\"servingsPerBrew\":2,\"ingredientCount\":2,\"requireHeat\":false,\"soupStackSize\":8}");
|
||||
var config = SoupConfig.load(file);
|
||||
assertEquals(2, config.servingsPerBrew);
|
||||
assertEquals(2, config.ingredientCount);
|
||||
@@ -20,11 +26,19 @@ class ConfigurationPolicyTest {
|
||||
config.ingredientCount = 5;
|
||||
assertThrows(IllegalArgumentException.class, config::validate);
|
||||
}
|
||||
@Test void ingredientCountStillChecksForbiddenCombinations() {
|
||||
|
||||
@Test
|
||||
void ingredientCountStillChecksForbiddenCombinations() {
|
||||
var ingredients = List.of(Set.of("material:carrot"), Set.of("material:potato"));
|
||||
assertNull(CombinationRules.rejection(ingredients, List.of(), List.of(), 2));
|
||||
assertNotNull(CombinationRules.rejection(ingredients, List.of("material:carrot"), List.of(), 2));
|
||||
assertNotNull(CombinationRules.rejection(ingredients, List.of(), List.of(List.of("material:carrot", "material:potato")), 2));
|
||||
assertNotNull(
|
||||
CombinationRules.rejection(ingredients, List.of("material:carrot"), List.of(), 2));
|
||||
assertNotNull(
|
||||
CombinationRules.rejection(
|
||||
ingredients,
|
||||
List.of(),
|
||||
List.of(List.of("material:carrot", "material:potato")),
|
||||
2));
|
||||
assertNotNull(CombinationRules.rejection(ingredients, List.of(), List.of(), 3));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
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 {
|
||||
|
||||
@Test
|
||||
void writesDefaultsAndRejectsInvalidFileWithoutReplacingIt() throws Exception {
|
||||
Path path = root.resolve("config.json");
|
||||
assertEquals(4, SoupConfig.load(path).servingsPerBrew);
|
||||
String broken = "{\"brewSeconds\":0}";
|
||||
@@ -16,7 +20,9 @@ class SoupConfigTest {
|
||||
assertThrows(IllegalArgumentException.class, () -> SoupConfig.load(path));
|
||||
assertEquals(broken, Files.readString(path));
|
||||
}
|
||||
@Test void validatesSelectorsAndDistinctCustomIdentityModes() {
|
||||
|
||||
@Test
|
||||
void validatesSelectorsAndDistinctCustomIdentityModes() {
|
||||
var c = new SoupConfig();
|
||||
c.blockedIngredients = List.of("astraplus:foods:chili");
|
||||
c.validate();
|
||||
@@ -24,15 +30,22 @@ class SoupConfigTest {
|
||||
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.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;
|
||||
|
||||
@Test
|
||||
void rejectsNonfiniteNutritionAndInvalidColors() {
|
||||
var c = new SoupConfig();
|
||||
c.maxSaturation = Float.NaN;
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
c.maxSaturation = 1000; c.defaultColor = "#1234567";
|
||||
c.maxSaturation = 1000;
|
||||
c.defaultColor = "#1234567";
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,37 @@
|
||||
package online.astradev.cauldron;
|
||||
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.nio.file.*;
|
||||
|
||||
class SoupResourcesTest {
|
||||
@TempDir Path root;
|
||||
private static final String MODEL = "assets/astradev_soups/models/item/soup_liquid.json";
|
||||
|
||||
@Test void exportsBundledResourcesAndCanRunAgain() throws Exception {
|
||||
@Test
|
||||
void exportsBundledResourcesAndCanRunAgain() throws Exception {
|
||||
SoupResources.install(root);
|
||||
assertArrayEquals(bundled(), Files.readAllBytes(target()));
|
||||
var modified = Files.getLastModifiedTime(target());
|
||||
SoupResources.install(root);
|
||||
assertEquals(modified, Files.getLastModifiedTime(target()));
|
||||
assertTrue(Files.exists(root.resolve("astraplus/resources/assets/astradev_soups/items/combined_soup.json")));
|
||||
assertTrue(
|
||||
Files.exists(
|
||||
root.resolve(
|
||||
"astraplus/resources/assets/astradev_soups/items/combined_soup.json")));
|
||||
}
|
||||
|
||||
@Test void upgradesFlatDefaultWithEitherLineEnding() throws Exception {
|
||||
@Test
|
||||
void upgradesFlatDefaultWithEitherLineEnding() throws Exception {
|
||||
try (var input = getClass().getResourceAsStream("/legacy/soup_liquid.json")) {
|
||||
String legacy = new String(input.readAllBytes(), UTF_8).replace("\r\n", "\n");
|
||||
Files.createDirectories(target().getParent());
|
||||
for (String ending : new String[]{"\n", "\r\n"}) {
|
||||
for (String ending : new String[] {"\n", "\r\n"}) {
|
||||
Files.writeString(target(), legacy.replace("\n", ending));
|
||||
SoupResources.install(root);
|
||||
assertArrayEquals(bundled(), Files.readAllBytes(target()));
|
||||
@@ -31,9 +39,12 @@ class SoupResourcesTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void preservesAdministratorCustomizationOfOldModel() throws Exception {
|
||||
@Test
|
||||
void preservesAdministratorCustomizationOfOldModel() throws Exception {
|
||||
try (var input = getClass().getResourceAsStream("/legacy/soup_liquid.json")) {
|
||||
String custom = new String(input.readAllBytes(), UTF_8).replace("minecraft:item/bone_meal", "custom:item/soup");
|
||||
String custom =
|
||||
new String(input.readAllBytes(), UTF_8)
|
||||
.replace("minecraft:item/bone_meal", "custom:item/soup");
|
||||
Files.createDirectories(target().getParent());
|
||||
Files.writeString(target(), custom);
|
||||
SoupResources.install(root);
|
||||
@@ -41,8 +52,13 @@ class SoupResourcesTest {
|
||||
}
|
||||
}
|
||||
|
||||
private Path target() { return root.resolve("astraplus/resources").resolve(MODEL); }
|
||||
private Path target() {
|
||||
return root.resolve("astraplus/resources").resolve(MODEL);
|
||||
}
|
||||
|
||||
private byte[] bundled() throws Exception {
|
||||
try (var input = getClass().getResourceAsStream("/astra-resources/" + MODEL)) { return input.readAllBytes(); }
|
||||
try (var input = getClass().getResourceAsStream("/astra-resources/" + MODEL)) {
|
||||
return input.readAllBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
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).soup().isEmpty(), "cannot brew without campfire; ingredients preserved");
|
||||
level.setBlock(READY.below(), Blocks.CAMPFIRE.defaultBlockState().setValue(net.minecraft.world.level.block.CampfireBlock.LIT, false), 3);
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(AstraCauldron.pots().get(level, READY).soup().isEmpty(), "unlit campfire cannot start soup");
|
||||
level.setBlock(READY.below(), Blocks.CAMPFIRE.defaultBlockState(), 3);
|
||||
use(READY, new ItemStack(Items.BOWL));
|
||||
require(AstraCauldron.pots().get(level, READY).brewTicks() > 0, "four ingredients start timed brew");
|
||||
level.setBlock(READY.below(), Blocks.AIR.defaultBlockState(), 3);
|
||||
for (int i = 0; i < 100; i++) AstraCauldron.pots().tick();
|
||||
require(AstraCauldron.pots().get(level, READY).brewTicks() > 0, "removing fire pauses cooking beyond full duration");
|
||||
level.setBlock(READY.below(), Blocks.SOUL_CAMPFIRE.defaultBlockState(), 3);
|
||||
require(online.astradev.cauldron.CauldronHeat.heated(level, READY), "soul campfire resumes heating");
|
||||
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); level.setBlock(BREW.below(), Blocks.CAMPFIRE.defaultBlockState(), 3);
|
||||
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();
|
||||
checkDyedBlocks(level, api);
|
||||
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 void checkDyedBlocks(ServerLevel level, online.astradev.plus.api.CauldronApi api) throws Exception {
|
||||
var pos = new BlockPos(30,100,8);
|
||||
for (var family : List.of(Items.WOOL, Items.CARPET)) {
|
||||
for (var color : DyeColor.values()) {
|
||||
var source = family.pick(color == DyeColor.WHITE ? DyeColor.BLACK : DyeColor.WHITE);
|
||||
int rgb = api.mixDye(OptionalInt.empty(), new ItemStack(Items.DYE.pick(color))).orElseThrow();
|
||||
var named = new ItemStack(source,64);
|
||||
named.set(DataComponents.CUSTOM_NAME,net.minecraft.network.chat.Component.literal("Keep textile name"));
|
||||
var batch = api.dyeBlocks(named,rgb,3).orElseThrow();
|
||||
require(batch.result().is(family.pick(color)) && batch.result().getCount()==64
|
||||
&& batch.result().getHoverName().getString().equals("Keep textile name")
|
||||
&& named.is(source) && named.getCount()==64,"textile palette and metadata: " + family.pick(color));
|
||||
}
|
||||
for (int water = 1; water <= 3; water++) for (int count : new int[]{1,16,17,32,33,64}) {
|
||||
AstraCauldron.liquids().breakPot(level,pos);
|
||||
level.setBlock(pos,Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,water),3);
|
||||
player.getInventory().clearContent(); use(pos,new ItemStack(Items.DYE.pick(DyeColor.RED)));
|
||||
use(pos,new ItemStack(family.pick(DyeColor.WHITE),count));
|
||||
int converted = Math.min(count,water==3 ? 64 : water*16);
|
||||
int cost = converted<=16 ? 1 : converted<=32 ? 2 : 3;
|
||||
var remaining = AstraCauldron.liquids().get(level,pos);
|
||||
require(player.getInventory().countItem(family.pick(DyeColor.RED))==converted
|
||||
&& player.getInventory().countItem(family.pick(DyeColor.WHITE))==count-converted
|
||||
&& (remaining==null ? water==cost : remaining.levels()==water-cost),
|
||||
"textile batch/inventory/water: " + family.pick(DyeColor.WHITE) + " count=" + count + " levels=" + water);
|
||||
}
|
||||
}
|
||||
int red = api.mixDye(OptionalInt.empty(),new ItemStack(Items.DYE.pick(DyeColor.RED))).orElseThrow();
|
||||
require(api.dyeBlocks(new ItemStack(Items.WOOL.pick(DyeColor.RED)),red,3).isEmpty()
|
||||
&& api.dyeBlocks(new ItemStack(Items.STONE),red,3).isEmpty(),"matching colors and unsupported blocks rejected");
|
||||
AstraCauldron.liquids().breakPot(level,pos);
|
||||
}
|
||||
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); }
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import net.minecraft.client.renderer.item.ClientItem;
|
||||
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();
|
||||
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,23 +0,0 @@
|
||||
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 {
|
||||
"$MinecraftDirectory/libraries/" + $_.downloads.artifact.path
|
||||
} | Where-Object { Test-Path -LiteralPath $_ }
|
||||
)
|
||||
New-Item -ItemType Directory -Force -Path "$repo/build" | Out-Null
|
||||
$arguments = @(
|
||||
'--class-path', ('"' + (($classpath -join ';').Replace('\', '/')) + '"'),
|
||||
('"' + "$PSScriptRoot/CheckSoupModels.java".Replace('\', '/') + '"'),
|
||||
('"' + $ResourcePack.Replace('\', '/') + '"')
|
||||
)
|
||||
$argumentFile = "$repo/build/check-models.args"
|
||||
Set-Content -Encoding utf8 -LiteralPath $argumentFile -Value $arguments
|
||||
& java "@$argumentFile"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Minecraft model validation failed' }
|
||||
@@ -1,86 +0,0 @@
|
||||
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,10 +0,0 @@
|
||||
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