Own item trap runtime with safe lifecycle and upgrade regression tests

This commit is contained in:
2026-09-24 22:25:12 +03:00
parent c9a4e9d643
commit 0ab34eef48
26 changed files with 1486 additions and 53 deletions
+59 -25
View File
@@ -1,10 +1,11 @@
# AstraContent 0.2.6 # AstraContent 0.2.7
Контент для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25. Контент для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25.
AstraContent владеет обработчиками дополнительных боеприпасов и транспорта: скоростью AstraContent владеет обработчиками дополнительных боеприпасов, предметных ловушек и
вагонеток, сцепками, отскоком от слизи и совместимостью старых рельсов. Здесь находятся транспорта: скоростью вагонеток, сцепками, отскоком от слизи и совместимостью старых рельсов.
два mixin боеприпасов и семь перенесённых mixin транспорта; новых точек вмешательства Здесь находятся два mixin боеприпасов, семь транспорта и два ловушек; новых точек
при переносе не добавлено. Требуется AstraPlus 0.9.13+; AstraPacks обслуживает ресурспак. вмешательства при переносе не добавлено. Требуется AstraPlus 0.9.14+;
AstraPacks обслуживает ресурспак.
Без AstraContent ядро не подключает эти конкретные обработчики, даже если их настройки Без AstraContent ядро не подключает эти конкретные обработчики, даже если их настройки
остались на диске. Общий API декларативных свойств блоков остаётся в AstraPlus. остались на диске. Общий API декларативных свойств блоков остаётся в AstraPlus.
На клиент мод устанавливать не нужно. Оформление передаётся обычным ресурспаком. На клиент мод устанавливать не нужно. Оформление передаётся обычным ресурспаком.
@@ -106,6 +107,24 @@ Shift + ПКМ киркой по выбранному торцу снимает
по соответствующей оси, для управляемой игроком лодки отправляется ванильный пакет скорости. по соответствующей оси, для управляемой игроком лодки отправляется ванильный пакет скорости.
Последующее трение и ускорение рельсами остаются штатными. Последующее трение и ускорение рельсами остаются штатными.
## Предметные ловушки
Копьё в центральной ячейке раздатчика (слот 4) выдвигается по редстоун-сигналу после
ванильной задержки; без питания втягивается. По умолчанию копьё не расходуется,
остальные слоты не используются. Урон наносится один раз по каждой цели при выдвижении,
а не при удержании или втягивании. Стены ограничивают ход; выгрузка и остановка удаляют
временное отображение, не предмет из раздатчика. Поддерживаются все шесть направлений,
замена предмета при работе и отмена активации/урона через публичные события.
Политика `astraspears:trap_policy` редактирует прежний `config/astraspears.json`.
Сохранены тег `astraspears:spear_display` и публичный
`online.astradev.plus.api.event.ItemTrapActivateEvent`. Геометрия, слот, разрешённые
предметы, цели, урон и расход задаются настройками. При `enabled=false` обработчик
не перехватывает выдачу: раздатчик работает по ванильным правилам. Без AstraContent
старый файл настроек также не включает ловушки. AstraSpears 0.2.1 не нужен для их
работы и остаётся только совместимым маркером. Подробности правил — в
[README AstraSpears](../AstraSpears/README.md).
## Совместимость с ванильным клиентом ## Совместимость с ванильным клиентом
В мире стоят настоящие `minecraft:powered_rail`. Поэтому установка, соединения, В мире стоят настоящие `minecraft:powered_rail`. Поэтому установка, соединения,
@@ -124,8 +143,8 @@ Shift + ПКМ киркой по выбранному торцу снимает
## Установка и разработка ## Установка и разработка
Устанавливаются AstraPlus 0.9.13+, AstraContent 0.2.6+ и AstraPacks. В Content 0.2.5 ещё Устанавливаются AstraPlus 0.9.14+, AstraContent 0.2.7+ и AstraPacks. В Content 0.2.6 ещё
не было обработчиков транспорта: новое ядро отклоняет прежнюю версию, а не запускает не было обработчиков ловушек: новое ядро отклоняет прежнюю версию, а не запускает
мир с отсутствующей механикой. Ядро и модуль обновляются вместе. Старые JAR следует мир с отсутствующей механикой. Ядро и модуль обновляются вместе. Старые JAR следует
архивировать, не оставляя дубликатов. архивировать, не оставляя дубликатов.
Модели, переводы и рельсы пока остаются входами сборки AstraPlus. Существующие ресурсы, Модели, переводы и рельсы пока остаются входами сборки AstraPlus. Существующие ресурсы,
@@ -141,13 +160,14 @@ Shift + ПКМ киркой по выбранному торцу снимает
Старый формат идентичности рельсов читается при загрузке чанка и переводится в общий реестр; Старый формат идентичности рельсов читается при загрузке чанка и переводится в общий реестр;
уже сохранённая новая идентичность имеет приоритет. Идентификаторы всех восьми вариантов сохранены. уже сохранённая новая идентичность имеет приоритет. Идентификаторы всех восьми вариантов сохранены.
Глобальные правила транспорта и боеприпасов находятся в `src/main/resources/content/policies`: Глобальные правила транспорта, боеприпасов и ловушек находятся в `src/main/resources/content/policies`:
`transport-defaults.json` и `projectile-defaults.json` — реальные настраиваемые политики, `transport-defaults.json`, `projectile-defaults.json` и `trap-defaults.json` — настраиваемые политики,
соответствующие `*-schema.json` — формы Studio. `*-compatibility.json` сохраняют прежние соответствующие `*-schema.json` — формы Studio. `*-compatibility.json` сохраняют прежние
ключи миров, идентичности и командные псевдонимы. Обе политики исполняет Java-модуль этого ключи миров, идентичности и командные псевдонимы. Все три политики исполняет Java-модуль этого
репозитория. Сохранение `astracontent:projectiles` и `astracontent:transport` в Studio репозитория. Сохранение `astracontent:projectiles`, `astracontent:transport` и `astraspears:trap_policy` в Studio
обновляет соответственно `config/astracontent-projectiles.json` и обновляет соответственно `config/astracontent-projectiles.json`,
`config/astracontent-transport.json`, а также текущий обработчик. Существующие файлы `config/astracontent-transport.json` и `config/astraspears.json`, а также текущий обработчик.
Существующие файлы
не заменяются значениями по умолчанию. Селектор боеприпасов использует публичный не заменяются значениями по умолчанию. Селектор боеприпасов использует публичный
`AstraPlusApi.identify`, а не внутренние классы ядра. `AstraPlusApi.identify`, а не внутренние классы ядра.
@@ -170,27 +190,41 @@ Shift + ПКМ киркой по выбранному торцу снимает
Для запуска серверных проверок нужны PowerShell 7 и соседние сборки AstraPlus/AstraPacks. Для запуска серверных проверок нужны PowerShell 7 и соседние сборки AstraPlus/AstraPacks.
Серверные проверки находятся в src/integrationTest, результаты — только в build. Серверные проверки находятся в src/integrationTest, результаты — только в build.
Они проверяют боеприпасы, оба движка вагонеток и сохранение после перезапуска на Они проверяют боеприпасы, оба движка вагонеток, ловушки и сохранение после перезапуска на
AstraPlus/AstraPacks/AstraContent с отдельным тестовым модом. Проверка отсутствия вмешательства AstraPlus/AstraPacks/AstraContent с отдельным тестовым модом. Проверка отсутствия вмешательства
без AstraContent находится в `AstraPlus/src/integrationTest/.../ContentBoundarySmoke.java`. без AstraContent находится в `AstraPlus/src/integrationTest/.../ContentBoundarySmoke.java`.
Перед ними нужно собрать соседний дистрибутив AstraPlus. Рабочие миры и конфигурации Перед ними нужно собрать соседний дистрибутив AstraPlus. Рабочие миры и конфигурации
при проверках не используются. при проверках не используются.
Проверка состава стартового набора рассчитана на AstraPlus 0.9.13: две оставшиеся Проверка состава стартового набора рассчитана на AstraPlus 0.9.14: одна политика ядра
политики ядра и две политики AstraContent, без модуля котлов. (оформление жителей) и три политики AstraContent, без модуля котлов.
`TrapVerification` переносит игровые сценарии прежней проверки AstraSpears: направления,
материалы, урон и его отмену, задержку, препятствия, импульсы, работу инвентаря,
ванильные исключения и восстановление отображения. Дополнительно проверяются отказ
некорректного сохранения без изменения файла/ревизии, `enabled=false`, единственный
поставщик настроек и очистка при остановке.
Для `upgradeFrom` укажите успешный старый прогон из `build/verification-*`, созданный Для проверки переноса создайте изолированный исходный мир со старыми исполнителями:
с AstraPlus 0.9.12 и AstraContent 0.2.5. Проверяются реальные версии старых JAR и
результаты обеих фаз. Мир, конфигурации и контрольные объекты копируются в новый
каталог `build`; исходный прогон не изменяется. Проверяется загрузка старых вагонеток
и сцепок новым модулем, а не только перезапуск одной версии. Рабочий мир и каталоги
со ссылками для этого режима не принимаются.
Отдельная проверка несовместимого обновления запускает AstraPlus 0.9.13 со старым ```powershell
AstraContent 0.2.5 и требует отказа загрузчика именно по диапазону версии, .\gradlew.bat integrationTest -PlegacyTrapBaseline -PastraPlusRuntime="C:/path/to/archive/AstraPlus-0.9.13.jar" -PcontentRuntime="C:/path/to/archive/AstraContent-0.2.6.jar"
.\gradlew.bat integrationTest -PupgradeFrom="build/verification-YYYYMMDD-HHMMSS"
```
`legacyTrapBaseline` требует именно AstraPlus 0.9.13 и AstraContent 0.2.6 и несовместим
с экспериментальным режимом или `upgradeFrom`. Для `upgradeFrom` укажите созданный
успешный прогон из `build/verification-*`, содержащий `trap-first-pass.txt` и результаты
обеих фаз. Проверяются реальные версии старых JAR. Мир, конфигурации и контрольные
объекты копируются в новый каталог `build`; исходный прогон не изменяется.
Проверяется загрузка старых вагонеток
и сцепок, а также инвентаря и отображения ловушки новым модулем, а не только перезапуск
одной версии. Рабочий мир и каталоги со ссылками для этого режима не принимаются.
Отдельная проверка несовместимого обновления запускает AstraPlus 0.9.14 со старым
AstraContent 0.2.6 и требует отказа загрузчика именно по диапазону `[0.2.7,)`,
до открытия мира. После обновления передайте сохранённый архивный JAR: до открытия мира. После обновления передайте сохранённый архивный JAR:
```powershell ```powershell
.\gradlew.bat compatibilityTest -PoldContentJar="C:/path/to/archive/AstraContent-0.2.5.jar" .\gradlew.bat compatibilityTest -PoldContentJar="C:/path/to/archive/AstraContent-0.2.6.jar"
``` ```
`src/integrationTest/compatibility.ps1` ограничивает время запуска и завершает только `src/integrationTest/compatibility.ps1` ограничивает время запуска и завершает только
+7 -3
View File
@@ -3,12 +3,12 @@ plugins {
id("net.neoforged.moddev") version "2.0.146" id("net.neoforged.moddev") version "2.0.146"
} }
group = "online.astradev" group = "online.astradev"
version = "0.2.6" version = "0.2.7"
repositories { mavenCentral() } repositories { mavenCentral() }
val astraPlusApi = providers.gradleProperty("astraPlusApi") val astraPlusApi = providers.gradleProperty("astraPlusApi")
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.13-api.jar") .orElse("../AstraPlus/build/libs/AstraPlus-0.9.14-api.jar")
val astraPlusRuntime = providers.gradleProperty("astraPlusRuntime") val astraPlusRuntime = providers.gradleProperty("astraPlusRuntime")
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.13.jar") .orElse("../AstraPlus/build/libs/AstraPlus-0.9.14.jar")
dependencies { dependencies {
compileOnly(files(astraPlusApi)) compileOnly(files(astraPlusApi))
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
@@ -53,6 +53,8 @@ val integrationTest = sourceSets.create("integrationTest") {
tasks.register<Jar>("integrationTestJar") { tasks.register<Jar>("integrationTestJar") {
from(integrationTest.output) from(integrationTest.output)
from("src/main/resources") { include("content/astracontent/legacy-rails.json") } from("src/main/resources") { include("content/astracontent/legacy-rails.json") }
// The old-runtime baseline uses these as test inputs before the module owns them.
from("src/main/resources") { include("content/policies/trap-*.json") }
archiveClassifier.set("integration-tests") archiveClassifier.set("integration-tests")
} }
@@ -62,6 +64,8 @@ tasks.register<Exec>("integrationTest") {
if (providers.gradleProperty("experimental").isPresent) args("-Experimental") if (providers.gradleProperty("experimental").isPresent) args("-Experimental")
providers.gradleProperty("upgradeFrom").orNull?.let { args("-UpgradeFrom", it) } providers.gradleProperty("upgradeFrom").orNull?.let { args("-UpgradeFrom", it) }
providers.gradleProperty("astraPlusRuntime").orNull?.let { args("-PlusJar", it) } providers.gradleProperty("astraPlusRuntime").orNull?.let { args("-PlusJar", it) }
providers.gradleProperty("contentRuntime").orNull?.let { args("-ContentJar", it) }
if (providers.gradleProperty("legacyTrapBaseline").isPresent) args("-LegacyTrapBaseline")
} }
tasks.register<Exec>("compatibilityTest") { tasks.register<Exec>("compatibilityTest") {
+9 -9
View File
@@ -9,8 +9,8 @@ $ErrorActionPreference = 'Stop'
$project = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path $project = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path
$runtime = (Resolve-Path -LiteralPath $ServerRoot).Path $runtime = (Resolve-Path -LiteralPath $ServerRoot).Path
$plusRoot = Join-Path (Split-Path $project -Parent) 'AstraPlus' $plusRoot = Join-Path (Split-Path $project -Parent) 'AstraPlus'
if (!$PlusJar) { $PlusJar = Join-Path $plusRoot 'build/libs/AstraPlus-0.9.13.jar' } if (!$PlusJar) { $PlusJar = Join-Path $plusRoot 'build/libs/AstraPlus-0.9.14.jar' }
if (!$OldContentJar) { $OldContentJar = Join-Path $runtime 'mods/AstraContent-0.2.5.jar' } if (!$OldContentJar) { $OldContentJar = Join-Path $runtime 'mods/AstraContent-0.2.6.jar' }
$plus = (Get-Item -LiteralPath $PlusJar).FullName $plus = (Get-Item -LiteralPath $PlusJar).FullName
$oldContent = (Get-Item -LiteralPath $OldContentJar).FullName $oldContent = (Get-Item -LiteralPath $OldContentJar).FullName
$acceptedEula = Join-Path $runtime 'eula.txt' $acceptedEula = Join-Path $runtime 'eula.txt'
@@ -19,7 +19,7 @@ if (!(Test-Path -LiteralPath $acceptedEula) -or
throw 'The server owner must have accepted the Minecraft EULA before this test can run.' throw 'The server owner must have accepted the Minecraft EULA before this test can run.'
} }
# Refuse misleading inputs: this regression targets the version before transport moved here. # Refuse misleading inputs: this regression targets the version before traps moved here.
Add-Type -AssemblyName System.IO.Compression.FileSystem Add-Type -AssemblyName System.IO.Compression.FileSystem
function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) { function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) {
$archive = [IO.Compression.ZipFile]::OpenRead($Path) $archive = [IO.Compression.ZipFile]::OpenRead($Path)
@@ -33,8 +33,8 @@ function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) {
if ($metadata -notmatch $pattern) { throw "Expected $Id $Version in $Path" } if ($metadata -notmatch $pattern) { throw "Expected $Id $Version in $Path" }
} finally { $archive.Dispose() } } finally { $archive.Dispose() }
} }
Assert-ModVersion $plus 'astraplus' '0.9.13' Assert-ModVersion $plus 'astraplus' '0.9.14'
Assert-ModVersion $oldContent 'astracontent' '0.2.5' Assert-ModVersion $oldContent 'astracontent' '0.2.6'
$output = Join-Path $project ('build/compatibility-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) $output = Join-Path $project ('build/compatibility-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8))
New-Item -ItemType Directory -Path "$output/mods", "$output/config" | Out-Null New-Item -ItemType Directory -Path "$output/mods", "$output/config" | Out-Null
@@ -95,16 +95,16 @@ try {
$errText | Set-Content -LiteralPath "$output/stderr.log" $errText | Set-Content -LiteralPath "$output/stderr.log"
$log = $outText + "`n" + $errText $log = $outText + "`n" + $errText
if ($exitCode -eq 0) { throw "Incompatible mods unexpectedly exited successfully. Evidence: $output" } if ($exitCode -eq 0) { throw "Incompatible mods unexpectedly exited successfully. Evidence: $output" }
$dependencyError = "(?s)Mod ID: 'astracontent', Requested by: 'astraplus', Expected range: '\[0\.2\.6,\)', Actual version: '0\.2\.5'" $dependencyError = "(?s)Mod ID: 'astracontent', Requested by: 'astraplus', Expected range: '\[0\.2\.7,\)', Actual version: '0\.2\.6'"
$translatedError = '(?is)Mod astraplus only supports astracontent 0\.2\.6 or above\s*Currently,? astracontent is 0\.2\.5' $translatedError = '(?is)Mod astraplus only supports astracontent 0\.2\.7 or above\s*Currently,? astracontent is 0\.2\.6'
if ($log -notmatch $dependencyError -and $log -notmatch $translatedError) { if ($log -notmatch $dependencyError -and $log -notmatch $translatedError) {
throw "Failure was not the expected AstraPlus -> AstraContent [0.2.6,) / actual 0.2.5 dependency rejection. Evidence: $output" throw "Failure was not the expected AstraPlus -> AstraContent [0.2.7,) / actual 0.2.6 dependency rejection. Evidence: $output"
} }
if ((Test-Path -LiteralPath "$output/compatibility-world") -or (Test-Path -LiteralPath "$output/world") -or if ((Test-Path -LiteralPath "$output/compatibility-world") -or (Test-Path -LiteralPath "$output/world") -or
$log -match 'Preparing level|Preparing start region|Done \([\d.,]+s\)!') { $log -match 'Preparing level|Preparing start region|Done \([\d.,]+s\)!') {
throw "Loader opened a world despite incompatible mods. Evidence: $output" throw "Loader opened a world despite incompatible mods. Evidence: $output"
} }
$result = "PASS compatibility: AstraPlus 0.9.13 rejects AstraContent 0.2.5 for [0.2.6,), exit=$exitCode, no world opened" $result = "PASS compatibility: AstraPlus 0.9.14 rejects AstraContent 0.2.6 for [0.2.7,), exit=$exitCode, no world opened"
$result | Set-Content -LiteralPath "$output/verification-result.txt" $result | Set-Content -LiteralPath "$output/verification-result.txt"
Write-Output $result Write-Output $result
Write-Output "Evidence: $output" Write-Output "Evidence: $output"
@@ -46,11 +46,14 @@ public final class ContentVerification {
private final List<AbstractMinecart> carts = new ArrayList<>(); private final List<AbstractMinecart> carts = new ArrayList<>();
private boolean done; private boolean done;
private final double[] previousX = new double[4]; private final double[] previousX = new double[4];
private final TrapVerification traps;
public ContentVerification() { public ContentVerification() {
if (!Boolean.getBoolean("astracontent.verify")) if (!Boolean.getBoolean("astracontent.verify"))
throw new IllegalStateException("Isolated test server only"); throw new IllegalStateException("Isolated test server only");
TransportBoundaryVerification.register(); TransportBoundaryVerification.register();
traps = new TrapVerification();
if (!Boolean.getBoolean("astracontent.trapBaseline")) TrapLifecycleVerification.register();
NeoForge.EVENT_BUS.addListener(this::tick); NeoForge.EVENT_BUS.addListener(this::tick);
} }
@@ -65,14 +68,16 @@ public final class ContentVerification {
.performPrefixedCommand( .performPrefixedCommand(
server.createCommandSourceStack(), "forceload add 0 0 159 95"); server.createCommandSourceStack(), "forceload add 0 0 159 95");
if (ticks == 20) { if (ticks == 20) {
StarterBundleVerification.run(); if (!Boolean.getBoolean("astracontent.trapBaseline")) StarterBundleVerification.run();
TransportBoundaryVerification.run(level); TransportBoundaryVerification.run(level);
traps.boundary(level);
require( require(
AbstractMinecart.useExperimentalMovement(level) AbstractMinecart.useExperimentalMovement(level)
== Boolean.getBoolean("astracontent.expectedExperimental"), == Boolean.getBoolean("astracontent.expectedExperimental"),
"requested movement engine enabled"); "requested movement engine enabled");
ProjectileVerification.run(level); ProjectileVerification.run(level);
if (Files.exists(Path.of("first-pass.txt"))) { if (Files.exists(Path.of("first-pass.txt"))) {
traps.restart(level);
DeclarativeRailVerification.restart(level); DeclarativeRailVerification.restart(level);
var migrated = new BlockPos(10, 100, 90); var migrated = new BlockPos(10, 100, 90);
require( require(
@@ -111,6 +116,7 @@ public final class ContentVerification {
bundledResources(); bundledResources();
packResponses(level); packResponses(level);
} }
traps.tick(level, ticks, Files.exists(Path.of("first-pass.txt")));
if (ticks == 129) if (ticks == 129)
for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX(); for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX();
if (ticks == 130) { if (ticks == 130) {
@@ -48,7 +48,7 @@ final class StarterBundleVerification {
require(document.source() == SnapshotSource.FILE && !document.readOnly(), "Authored declaration is editable FILE: " + id); require(document.source() == SnapshotSource.FILE && !document.readOnly(), "Authored declaration is editable FILE: " + id);
editable++; editable++;
} }
require(manifest.getAsJsonArray("capabilities").size() == 2, "Two remaining core capability policies; transport, projectiles and cauldrons belong to their optional modules"); require(manifest.getAsJsonArray("capabilities").size() == 1, "Only villager appearance remains a core policy; traps, transport, projectiles and cauldrons belong to their modules");
for (var value : manifest.getAsJsonArray("capabilities")) { for (var value : manifest.getAsJsonArray("capabilities")) {
var policy = value.getAsJsonObject(); var policy = value.getAsJsonObject();
String id = policy.get("id").getAsString(); String id = policy.get("id").getAsString();
@@ -60,6 +60,12 @@ final class StarterBundleVerification {
require(!expectedProviders.contains("astracontent:projectiles"), "Core starter no longer owns projectile policy"); require(!expectedProviders.contains("astracontent:projectiles"), "Core starter no longer owns projectile policy");
require(!expectedProviders.contains("astracontent:transport"), "Core starter no longer owns transport policy"); require(!expectedProviders.contains("astracontent:transport"), "Core starter no longer owns transport policy");
require(expectedProviders.contains("astraplus:villager_appearance"), "Native villager appearance is editable policy data"); require(expectedProviders.contains("astraplus:villager_appearance"), "Native villager appearance is editable policy data");
require(!expectedProviders.contains("astraspears:trap_policy"), "Core starter no longer owns trap policy");
expectedProviders.add("astraspears:trap_policy");
var trapDocument = documents.get(SnapshotKind.MECHANIC + ":astraspears:trap_policy");
require(trapDocument != null && trapDocument.source() == SnapshotSource.FILE && !trapDocument.readOnly(),
"Content-owned trap policy preserves its editable identity");
require(Files.isRegularFile(FMLPaths.GAMEDIR.get().resolve("config/astraspears.json")), "Trap policy preserves its original file");
for (String capability : new String[]{"projectiles", "transport"}) { for (String capability : new String[]{"projectiles", "transport"}) {
String id = "astracontent:" + capability; String id = "astracontent:" + capability;
expectedProviders.add(id); expectedProviders.add(id);
@@ -72,7 +78,7 @@ final class StarterBundleVerification {
require(installed == 186 && editable == installed, "Exact authored editable content file count: " + installed); require(installed == 186 && editable == installed, "Exact authored editable content file count: " + installed);
require(modelFiles == 142 && documents.values().stream().filter(document -> document.kind() == SnapshotKind.MODEL).count() == 142, "All 142 authored models appear in the public runtime snapshot"); require(modelFiles == 142 && documents.values().stream().filter(document -> document.kind() == SnapshotKind.MODEL).count() == 142, "All 142 authored models appear in the public runtime snapshot");
System.out.println("PASS modular distribution: contentFiles=" + installed + " editableCatalog=" + editable System.out.println("PASS modular distribution: contentFiles=" + installed + " editableCatalog=" + editable
+ " models=" + modelFiles + " coreMechanics=2; contentProjectileAndTransportMechanics=2"); + " models=" + modelFiles + " coreMechanics=1; contentProjectileTransportTrapMechanics=3");
} }
private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); } private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); }
@@ -0,0 +1,164 @@
package online.astradev.content.verification;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.entity.Display;
import net.minecraft.world.phys.AABB;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import online.astradev.content.trap.ItemTrapCapabilities;
import online.astradev.plus.api.editor.EditorDefinitionProvider;
import online.astradev.plus.api.editor.EditorDefinitions;
/** Exercises failed startup and a second lifecycle only after normal gameplay has shut down. */
final class TrapLifecycleVerification {
private static final String POLICY_ID = "astraspears:trap_policy";
private static final String DISPLAY_TAG = "astraspears:spear_display";
private TrapLifecycleVerification() {}
static void register() {
if (Boolean.getBoolean("astracontent.trapBaseline")) return;
if (!Boolean.getBoolean("astracontent.verify")) {
throw new IllegalStateException("Trap lifecycle verification requires an isolated test server");
}
NeoForge.EVENT_BUS.addListener(EventPriority.LOW, TrapLifecycleVerification::stopping);
}
private static void stopping(ServerStoppingEvent event) {
try {
verify(event.getServer());
System.out.println("PASS traps lifecycle: failed starts remain inactive, foreign provider retained,"
+ " valid restart and idempotent close, administrator configuration unchanged");
} catch (Throwable failure) {
try {
Files.writeString(Path.of("verification-result.txt"), "FAIL trap lifecycle: " + failure);
} catch (IOException recordingFailure) {
failure.addSuppressed(recordingFailure);
}
throw new IllegalStateException("Trap lifecycle verification failed", failure);
}
}
private static void verify(MinecraftServer server) throws IOException {
require(!ItemTrapCapabilities.active(), "Normal module shutdown must precede this test");
require(EditorDefinitions.find(POLICY_ID).isEmpty(), "Normal shutdown releases the trap provider");
Path game = FMLPaths.GAMEDIR.get().toAbsolutePath().normalize();
require(game.getParent() != null && game.getParent().getFileName().toString().equals("build")
&& game.getFileName().toString().matches("verification-\\d{8}-\\d{6}(?:-[a-f0-9]+)?"),
"Lifecycle fixtures must remain inside the isolated build verification directory");
Path administratorConfig = game.resolve("config/astraspears.json");
byte[] administratorBytes = Files.readAllBytes(administratorConfig);
Path fixture = Files.createTempDirectory(game, "trap-lifecycle-");
Path validFile = fixture.resolve("valid.json");
String defaults = resource("defaults");
String schema = resource("schema");
JsonObject compatibility = JsonParser.parseString(resource("compatibility")).getAsJsonObject();
String validDocument = defaults + "\n\n";
Files.writeString(validFile, validDocument, StandardCharsets.UTF_8);
EditorDefinitionProvider foreign = new ForeignProvider();
EditorDefinitions.register(foreign);
try {
Path missingFile = fixture.resolve("must-not-be-created.json");
boolean missingRejected = false;
try { start(server, missingFile, defaults, schema, compatibility); }
catch (IllegalArgumentException expected) { missingRejected = true; }
require(missingRejected && !Files.exists(missingFile),
"A duplicate owner cannot seed a new configuration before failing");
boolean rejected = false;
try {
start(server, validFile, defaults, schema, compatibility);
} catch (IllegalArgumentException expected) {
require(expected.getMessage().contains("Mechanic already registered"),
"The duplicate-owner failure must come from provider registration");
rejected = true;
}
require(rejected, "A foreign provider must prevent trap startup");
require(!ItemTrapCapabilities.active(), "Duplicate registration must not publish a trap runtime");
require(EditorDefinitions.find(POLICY_ID).orElseThrow() == foreign,
"Failed startup must retain the foreign provider");
ItemTrapCapabilities.close();
require(EditorDefinitions.find(POLICY_ID).orElseThrow() == foreign,
"Closing a failed startup must not unregister a foreign owner");
} finally {
EditorDefinitions.unregister(foreign);
}
require(Files.readString(validFile, StandardCharsets.UTF_8).equals(validDocument),
"Duplicate startup must preserve the existing test configuration byte for byte");
Path invalidFile = fixture.resolve("invalid-damage-type.json");
var invalid = JsonParser.parseString(defaults).getAsJsonObject();
invalid.addProperty("damageType", "verification:missing_trap_damage_type");
String invalidDocument = invalid + "\n";
Files.writeString(invalidFile, invalidDocument, StandardCharsets.UTF_8);
boolean invalidRejected = false;
try {
start(server, invalidFile, defaults, schema, compatibility);
} catch (RuntimeException expected) {
require(expected.toString().contains("verification:missing_trap_damage_type"),
"The invalid-start failure must identify the missing damage registry entry");
invalidRejected = true;
}
require(invalidRejected, "Unknown damage types must prevent startup");
require(!ItemTrapCapabilities.active(), "Invalid policy must not publish a trap runtime");
require(EditorDefinitions.find(POLICY_ID).isEmpty(), "Invalid policy must not publish an editor provider");
require(Files.readString(invalidFile, StandardCharsets.UTF_8).equals(invalidDocument),
"Validation failure must preserve the invalid file for administrator correction");
start(server, validFile, defaults, schema, compatibility);
try {
require(ItemTrapCapabilities.active(), "A valid startup must succeed after both failed attempts");
require(EditorDefinitions.find(POLICY_ID).isPresent(), "The restarted runtime owns its editor provider");
} finally {
ItemTrapCapabilities.close();
}
ItemTrapCapabilities.close();
require(!ItemTrapCapabilities.active(), "Repeated close must leave callbacks disabled");
require(EditorDefinitions.find(POLICY_ID).isEmpty(), "Repeated close must leave no editor provider");
for (var level : server.getAllLevels()) {
require(level.getEntitiesOfClass(Display.ItemDisplay.class, new AABB(0, 116, 0, 130, 125, 32),
entity -> entity.entityTags().contains(DISPLAY_TAG)).isEmpty(),
"Lifecycle restart must not resurrect any gameplay-fixture trap display");
}
require(Arrays.equals(administratorBytes, Files.readAllBytes(administratorConfig)),
"Lifecycle tests must never modify the actual gameplay policy configuration");
}
private static void start(MinecraftServer server, Path file, String defaults, String schema,
JsonObject compatibility) throws IOException {
ItemTrapCapabilities.start(server, file, POLICY_ID, "Lifecycle verification", defaults, schema, compatibility);
}
private static String resource(String kind) throws IOException {
String path = "/content/policies/trap-" + kind + ".json";
try (var stream = TrapLifecycleVerification.class.getResourceAsStream(path)) {
if (stream == null) throw new IOException("Missing lifecycle fixture resource: " + path);
byte[] bytes = stream.readNBytes(512 * 1024 + 1);
if (bytes.length > 512 * 1024) throw new IOException("Oversized lifecycle fixture resource: " + path);
return new String(bytes, StandardCharsets.UTF_8);
}
}
private static void require(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
private static final class ForeignProvider implements EditorDefinitionProvider {
@Override public String id() { return POLICY_ID; }
@Override public String name() { return "Foreign trap owner"; }
@Override public String schemaJson() { return "{\"fields\":[]}"; }
@Override public Snapshot snapshot() { return new Snapshot("{}", "0".repeat(64)); }
@Override public void save(String documentJson, String expectedRevision) {
throw new UnsupportedOperationException("The lifecycle test must never save through the foreign provider");
}
}
}
@@ -0,0 +1,378 @@
package online.astradev.content.verification;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.Display;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.level.block.entity.DispenserBlockEntity;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.entity.living.LivingIncomingDamageEvent;
import net.neoforged.neoforge.event.level.LevelEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
import online.astradev.content.AstraContent;
import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.editor.EditorDefinitions;
/**
* Trap gameplay in the same isolated world and tick loop as transport verification.
* Uses only the public API so the identical test can create a baseline with the former core owner.
*/
final class TrapVerification {
private static final String POLICY_ID = "astraspears:trap_policy";
private static final String DISPLAY_TAG = "astraspears:spear_display";
private static final boolean BASELINE = Boolean.getBoolean("astracontent.trapBaseline");
private static final BlockPos SAVED = new BlockPos(8, 120, 8);
private static final BlockPos CUSTOM = new BlockPos(8, 120, 24);
private static final BlockPos BLOCKED = new BlockPos(24, 120, 24);
private static final BlockPos DROPPER = new BlockPos(40, 120, 24);
private static final BlockPos OFFCENTER = new BlockPos(56, 120, 24);
private static final BlockPos INSERT = new BlockPos(72, 120, 24);
private static final BlockPos SHORT = new BlockPos(88, 120, 24);
private static final BlockPos CANCEL = new BlockPos(104, 120, 24);
private static final BlockPos DISABLED = new BlockPos(120, 120, 24);
private static final BlockPos UNCANCELLED = new BlockPos(136, 120, 24);
private final List<BlockPos> traps = new ArrayList<>();
private final Map<UUID, List<Float>> hits = new HashMap<>();
private final List<Mob> victims = new ArrayList<>();
private final List<Vec3> victimPositions = new ArrayList<>();
private final Path config;
private final byte[] existingConfig;
private boolean levelLoaded;
private boolean providerBeforeWorldLoad = true;
private boolean finished;
private ItemStack custom;
private Mob uncancelledVictim;
private Vec3 uncancelledPosition;
private float uncancelledInitialHealth;
TrapVerification() {
try {
config = FMLPaths.GAMEDIR.get().resolve("config/astraspears.json");
if (!Files.exists(config)) {
Files.createDirectories(config.getParent());
try (var source = TrapVerification.class.getResourceAsStream("/content/policies/trap-defaults.json")) {
if (source == null) throw new IOException("Missing trap verification defaults");
var document = JsonParser.parseString(new String(source.readAllBytes(), StandardCharsets.UTF_8)).getAsJsonObject();
document.addProperty("verificationExtension", "must survive owner migration");
Files.writeString(config, document + "\n\n", StandardCharsets.UTF_8);
}
}
existingConfig = Files.readAllBytes(config);
} catch (IOException failure) {
throw new IllegalStateException("Cannot prepare isolated trap verification", failure);
}
NeoForge.EVENT_BUS.addListener(this::damage);
NeoForge.EVENT_BUS.addListener((online.astradev.plus.api.event.ItemTrapActivateEvent event) -> {
if (event.pos().equals(CANCEL)) event.setCanceled(true);
});
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::levelLoad);
// The historical core closes at LOWEST too, whose tie order depends on mod construction.
// Observe that baseline after ServerStopped; require the new owner to close before saving.
if (BASELINE) NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST,
(ServerStoppedEvent event) -> verifyShutdown(event.getServer()));
else NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST,
(ServerStoppingEvent event) -> verifyShutdown(event.getServer()));
}
private void levelLoad(LevelEvent.Load event) {
if (!(event.getLevel() instanceof ServerLevel)) return;
levelLoaded = true;
providerBeforeWorldLoad &= EditorDefinitions.find(POLICY_ID).isPresent();
}
void boundary(ServerLevel level) throws Exception {
require(levelLoaded && providerBeforeWorldLoad, "trap policy is active before chunks load");
require(Arrays.equals(existingConfig, Files.readAllBytes(config)),
"trap startup preserves existing configuration byte for byte");
require(EditorDefinitions.all().stream().filter(provider -> provider.id().equals(POLICY_ID)).count() == 1,
"one live editable trap provider retains the compatibility identity");
Class<?> owner = BASELINE ? AstraPlusApi.class : AstraContent.class;
String expected = BASELINE ? "online.astradev.plus.capability.trap." : "online.astradev.content.trap.";
String absent = BASELINE ? "online.astradev.content.trap." : "online.astradev.plus.capability.trap.";
for (String name : List.of("ItemTrapCapabilities", "ItemTrapConfig", "ItemTrapDisplay",
"ItemTrapGeometry", "ItemTrapItems", "ItemTrapSettings", "ItemTraps")) {
var runtime = Class.forName(expected + name, false, TrapVerification.class.getClassLoader());
require(runtime.getProtectionDomain().getCodeSource().getLocation()
.equals(owner.getProtectionDomain().getCodeSource().getLocation()),
"trap runtime belongs to " + (BASELINE ? "former core" : "content") + ": " + name);
try {
Class.forName(absent + name, false, TrapVerification.class.getClassLoader());
throw new AssertionError("Duplicate trap implementation: " + absent + name);
} catch (ClassNotFoundException correct) { }
}
for (String mixin : List.of("ItemTrapInventoryMixin", "ItemTrapDispenserMixin")) {
require(mixins(owner, BASELINE ? "/astraplus.mixins.json" : "/astracontent.mixins.json").contains(mixin),
"trap hook belongs to the active owner: " + mixin);
require(!mixins(BASELINE ? AstraContent.class : AstraPlusApi.class,
BASELINE ? "/astracontent.mixins.json" : "/astraplus.mixins.json").contains(mixin),
"trap hook is absent from the other owner: " + mixin);
}
var provider = EditorDefinitions.find(POLICY_ID).orElseThrow();
var original = provider.snapshot();
var invalid = JsonParser.parseString(original.documentJson()).getAsJsonObject();
invalid.addProperty("reach", -1);
try {
provider.save(invalid.toString(), original.revision());
throw new AssertionError("Invalid trap reach was accepted");
} catch (IllegalArgumentException rejected) { }
require(provider.snapshot().revision().equals(original.revision())
&& Arrays.equals(existingConfig, Files.readAllBytes(config)),
"invalid trap edits leave file and live revision unchanged");
}
private static Set<String> mixins(Class<?> owner, String path) throws IOException {
try (var stream = owner.getResourceAsStream(path)) {
if (stream == null) throw new IOException("Missing mixin declaration " + path);
var json = JsonParser.parseString(new String(stream.readAllBytes(), StandardCharsets.UTF_8)).getAsJsonObject();
var names = new HashSet<String>();
json.getAsJsonArray("mixins").forEach(value -> names.add(value.getAsString()));
return names;
}
}
private void verifyDisabledPolicy(ServerLevel level) throws IOException {
var provider = EditorDefinitions.find(POLICY_ID).orElseThrow();
var snapshot = provider.snapshot();
var disabled = JsonParser.parseString(snapshot.documentJson()).getAsJsonObject();
disabled.addProperty("enabled", false);
provider.save(disabled.toString(), snapshot.revision());
require(!provider.snapshot().revision().equals(snapshot.revision()), "trap edit publishes a new revision");
place(level, DISABLED, Direction.EAST, new ItemStack(Items.DIAMOND_SPEAR), false);
power(level, DISABLED, true);
}
private void restoreSettings() throws IOException {
var provider = EditorDefinitions.find(POLICY_ID).orElseThrow();
provider.save(new String(existingConfig, StandardCharsets.UTF_8), provider.snapshot().revision());
}
private void damage(LivingIncomingDamageEvent event) {
if (hits.containsKey(event.getEntity().getUUID())) {
if (event.getSource().is(net.minecraft.world.damagesource.DamageTypes.SPEAR))
hits.get(event.getEntity().getUUID()).add(event.getAmount());
event.setCanceled(true);
}
}
void tick(ServerLevel level, int ticks, boolean restart) throws Exception {
if (finished || restart) return;
for (int i = 0; i < victims.size(); i++) {
victims.get(i).setPos(victimPositions.get(i));
victims.get(i).setDeltaMovement(Vec3.ZERO);
}
if (uncancelledVictim != null) {
uncancelledVictim.setPos(uncancelledPosition);
uncancelledVictim.setDeltaMovement(Vec3.ZERO);
}
if (ticks == 30) {
setup(level);
verifyDisabledPolicy(level);
}
if (ticks == 37) {
require(center(level, DISABLED).isEmpty() && displays(level, DISABLED).isEmpty(),
"disabled policy leaves native spear dispensing intact");
restoreSettings();
}
if (ticks == 40) {
for (var pos : traps) power(level, pos, true);
for (var pos : List.of(CUSTOM, BLOCKED, DROPPER, OFFCENTER, INSERT, SHORT, CANCEL)) power(level, pos, true);
power(level, UNCANCELLED, true);
}
if (ticks == 42) {
require(displays(level, SAVED).isEmpty(), "vanilla four tick delay");
power(level, SHORT, false);
}
if (ticks == 50) {
require(displays(level, UNCANCELLED).size() == 1
&& Math.abs(uncancelledVictim.getHealth() - (uncancelledInitialHealth - 1)) < .001,
"uncancelled wooden spear applies one point of native damage to an unarmored cow");
double[] damage = {1, 2, 2, 3, 1, 4, 5};
for (int i = 0; i < traps.size(); i++) {
var pos = traps.get(i);
require(displays(level, pos).size() == 1, "one display for direction/material " + i);
require(!center(level, pos).isEmpty(), "spear preserved " + i);
var dispenser = (DispenserBlockEntity) level.getBlockEntity(pos);
require(dispenser.getItem(0).getCount() == 8 && dispenser.getItem(1).is(Items.WATER_BUCKET), "other slots preserved " + i);
var recorded = hits.get(victims.get(i).getUUID());
require(recorded.size() == 1 && Math.abs(recorded.getFirst() - damage[i]) < 0.001,
"one outward hit and vanilla damage " + i + ": " + recorded);
require(victims.get(i).getHealth() == victims.get(i).getMaxHealth(), "damage cancellation " + i);
}
require(displays(level, BLOCKED).isEmpty(), "solid obstacle blocks display");
require(displays(level, CANCEL).isEmpty() && !center(level, CANCEL).isEmpty(), "activation cancellation preserves spear");
require(displays(level, SHORT).isEmpty(), "short pulse does not extend");
require(center(level, DROPPER).isEmpty() && displays(level, DROPPER).isEmpty(), "dropper is vanilla");
require(((DispenserBlockEntity) level.getBlockEntity(OFFCENTER)).getItem(0).isEmpty(), "off-center spear dispenses");
var display = displays(level, CUSTOM).getFirst();
require(ItemStack.isSameItemSameComponents(custom, display.getSlot(0).get()), "AstraPlus display preserves components");
require(hits.get(victims.getLast().getUUID()).equals(List.of(10f)), "AstraPlus configured attack damage");
((DispenserBlockEntity) level.getBlockEntity(INSERT)).setItem(4, new ItemStack(Items.IRON_SPEAR));
level.getBlockEntity(INSERT).setChanged();
}
if (ticks == 65) {
require(Math.abs(uncancelledVictim.getHealth() - (uncancelledInitialHealth - 1)) < .001,
"held spear does not repeat successful damage after hurt immunity expires");
require(displays(level, INSERT).size() == 1, "inventory insertion while powered");
for (var victim : victims) require(hits.get(victim.getUUID()).size() == 1, "held spear never repeats damage");
for (var pos : traps) power(level, pos, false);
power(level, CUSTOM, false);
}
if (ticks == 75) {
for (var pos : traps) require(displays(level, pos).isEmpty(), "retraction removes display");
for (var victim : victims) require(hits.get(victim.getUUID()).size() == 1, "no damage on retraction");
for (var pos : traps) power(level, pos, true);
power(level, CUSTOM, true);
}
if (ticks == 90) {
for (var victim : victims) require(hits.get(victim.getUUID()).size() == 2, "new pulse rearms hit");
((DispenserBlockEntity) level.getBlockEntity(CUSTOM)).setItem(4, new ItemStack(Items.NETHERITE_SPEAR));
level.getBlockEntity(CUSTOM).setChanged();
level.setBlock(BLOCKED.relative(Direction.EAST), Blocks.AIR.defaultBlockState(), 3);
((DispenserBlockEntity) level.getBlockEntity(INSERT)).setItem(4, ItemStack.EMPTY);
level.getBlockEntity(INSERT).setChanged();
}
if (ticks == 100) {
require(displays(level, CUSTOM).getFirst().getSlot(0).get().is(Items.NETHERITE_SPEAR), "live item replacement");
require(displays(level, INSERT).isEmpty(), "item removal retracts");
require(displays(level, BLOCKED).size() == 1, "obstruction removal extends");
level.setBlock(CUSTOM, Blocks.AIR.defaultBlockState(), 3);
}
if (ticks == 110) {
require(displays(level, CUSTOM).isEmpty(), "block removal cleans display");
for (var victim : victims) victim.discard();
uncancelledVictim.discard();
power(level, UNCANCELLED, false);
level.setBlock(UNCANCELLED, Blocks.AIR.defaultBlockState(), 3);
require(Arrays.equals(existingConfig, Files.readAllBytes(config)),
"live policy test restores exact administrator configuration bytes");
Files.writeString(Path.of("trap-first-pass.txt"), "PASS trap gameplay\n");
finished = true;
System.out.println("PASS traps gameplay: 7 materials, 6 directions, components, native damage,"
+ " cancellation, power delay, inventory, disabled mode, obstacles and cleanup");
}
}
private void setup(ServerLevel level) throws Exception {
var api = AstraPlusApi.current().orElseThrow();
var id = Identifier.parse("verification:spear");
var definition = JsonParser.parseString("""
{"name":"Test spear","material":"minecraft:diamond_spear","texture":"verification:item/spear",
"components":{"minecraft:enchantment_glint_override":true,"minecraft:attribute_modifiers":[
{"type":"minecraft:attack_damage","id":"verification:damage","amount":9,"operation":"add_value","slot":"mainhand"}]}}
""").getAsJsonObject();
api.save(id, api.find(id).map(d -> d.revision()).orElse(AstraPlusApi.NEW_REVISION), definition);
custom = api.create(id, 1);
require(!custom.isEmpty(), "public API creates custom spear for runtime recognition");
Item[] items = {Items.WOODEN_SPEAR, Items.STONE_SPEAR, Items.COPPER_SPEAR, Items.IRON_SPEAR,
Items.GOLDEN_SPEAR, Items.DIAMOND_SPEAR, Items.NETHERITE_SPEAR};
Direction[] faces = {Direction.EAST, Direction.WEST, Direction.UP, Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.EAST};
for (int i = 0; i < items.length; i++) {
var pos = new BlockPos(8 + i * 12, 120, 8);
traps.add(pos);
place(level, pos, faces[i], new ItemStack(items[i]), false);
var dispenser = (DispenserBlockEntity) level.getBlockEntity(pos);
dispenser.setItem(0, new ItemStack(Items.TNT, 8));
dispenser.setItem(1, new ItemStack(Items.WATER_BUCKET));
victim(level, pos, faces[i]);
}
place(level, CUSTOM, Direction.EAST, custom, false);
victim(level, CUSTOM, Direction.EAST);
place(level, BLOCKED, Direction.EAST, new ItemStack(Items.DIAMOND_SPEAR), false);
level.setBlock(BLOCKED.east(), Blocks.STONE.defaultBlockState(), 3);
place(level, DROPPER, Direction.EAST, new ItemStack(Items.DIAMOND_SPEAR), true);
place(level, OFFCENTER, Direction.EAST, ItemStack.EMPTY, false);
((DispenserBlockEntity) level.getBlockEntity(OFFCENTER)).setItem(0, new ItemStack(Items.DIAMOND_SPEAR));
place(level, INSERT, Direction.EAST, ItemStack.EMPTY, false);
place(level, SHORT, Direction.EAST, new ItemStack(Items.DIAMOND_SPEAR), false);
place(level, CANCEL, Direction.EAST, new ItemStack(Items.DIAMOND_SPEAR), false);
place(level, UNCANCELLED, Direction.EAST, new ItemStack(Items.WOODEN_SPEAR), false);
uncancelledVictim = Objects.requireNonNull(EntityTypes.COW.create(level, EntitySpawnReason.COMMAND));
uncancelledVictim.setNoAi(true);
uncancelledVictim.setNoGravity(true);
uncancelledPosition = Vec3.atCenterOf(UNCANCELLED).add(.95, -.5, 0);
uncancelledVictim.setPos(uncancelledPosition);
uncancelledInitialHealth = uncancelledVictim.getHealth();
require(uncancelledVictim.getArmorValue() == 0 && level.addFreshEntity(uncancelledVictim),
"uncancelled damage target is an unarmored native cow");
// Do not add this victim to hits: the damage listener cancels only tracked victims.
}
private void victim(ServerLevel level, BlockPos pos, Direction face) {
var victim = EntityTypes.HUSK.create(level, EntitySpawnReason.COMMAND);
victim.setNoAi(true);
victim.setNoGravity(true);
Vec3 target = Vec3.atCenterOf(pos).add(face.getStepX() * 0.95, face.getStepY() * 0.95 - 0.5, face.getStepZ() * 0.95);
victim.setPos(target);
level.addFreshEntity(victim);
victims.add(victim);
victimPositions.add(target);
hits.put(victim.getUUID(), new ArrayList<>());
}
private static void place(ServerLevel level, BlockPos pos, Direction face, ItemStack item, boolean dropper) {
level.setBlock(pos, (dropper ? Blocks.DROPPER : Blocks.DISPENSER).defaultBlockState().setValue(DispenserBlock.FACING, face), 3);
((DispenserBlockEntity) level.getBlockEntity(pos)).setItem(4, item.copy());
level.getBlockEntity(pos).setChanged();
}
private static void power(ServerLevel level, BlockPos pos, boolean on) {
// Power from the west unless the spear points west; then use the north face.
var face = level.getBlockState(pos).getValue(DispenserBlock.FACING);
var powerPos = pos.relative(face == Direction.WEST ? Direction.NORTH : Direction.WEST);
level.setBlock(powerPos, (on ? Blocks.REDSTONE_BLOCK : Blocks.AIR).defaultBlockState(), 3);
}
private static ItemStack center(ServerLevel level, BlockPos pos) { return ((DispenserBlockEntity) level.getBlockEntity(pos)).getItem(4); }
private static List<Display.ItemDisplay> displays(ServerLevel level, BlockPos pos) {
return level.getEntitiesOfClass(Display.ItemDisplay.class, new AABB(pos).inflate(3), e -> e.entityTags().contains(DISPLAY_TAG));
}
private static void require(boolean success, String message) {
if (!success) throw new AssertionError(message);
System.out.println("PASS " + message);
}
void restart(ServerLevel level) throws Exception {
require(Files.isRegularFile(Path.of("trap-first-pass.txt")), "trap fixture was saved by a gameplay pass");
require(center(level, SAVED).is(Items.WOODEN_SPEAR), "saved trap inventory survives owner upgrade/restart");
require(displays(level, SAVED).size() == 1, "one powered trap display restored on restart");
require(!displays(level, SAVED).getFirst().shouldBeSaved(), "restored trap display remains transient");
require(Arrays.equals(existingConfig, Files.readAllBytes(config)),
"trap restart leaves existing configuration unchanged");
System.out.println("PASS traps restart: saved inventory, powered restoration, single transient display");
}
private void verifyShutdown(MinecraftServer server) {
try {
require(EditorDefinitions.find(POLICY_ID).isEmpty(), "trap provider unregisters on shutdown");
require(server.overworld().getEntitiesOfClass(Display.ItemDisplay.class,
new AABB(0, 116, 0, 130, 125, 32),
entity -> entity.entityTags().contains(DISPLAY_TAG)).isEmpty(),
BASELINE ? "former core removes transient displays by shutdown completion"
: "trap shutdown removes transient displays before save");
require(Arrays.equals(existingConfig, Files.readAllBytes(config)),
"trap shutdown preserves administrator configuration");
System.out.println("PASS traps shutdown: provider removed, displays cleaned, configuration unchanged");
} catch (Throwable failure) {
failure.printStackTrace();
try { Files.writeString(Path.of("verification-result.txt"), "FAIL trap shutdown: " + failure); }
catch (IOException recordingFailure) { failure.addSuppressed(recordingFailure); }
throw new IllegalStateException("Trap shutdown verification failed", failure);
}
}
}
+29 -9
View File
@@ -2,10 +2,16 @@ param(
[string]$ServerRoot='C:\Users\ScarPC\Documents\NeoForge Server 26.2', [string]$ServerRoot='C:\Users\ScarPC\Documents\NeoForge Server 26.2',
[switch]$Experimental, [switch]$Experimental,
[string]$PlusJar, [string]$PlusJar,
[string]$UpgradeFrom [string]$UpgradeFrom,
[string]$ContentJar,
[switch]$LegacyTrapBaseline
) )
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$project=(Resolve-Path "$PSScriptRoot/../..").Path $project=(Resolve-Path "$PSScriptRoot/../..").Path
if ($LegacyTrapBaseline -and ($UpgradeFrom -or $Experimental -or !$PlusJar -or !$ContentJar)) {
throw 'LegacyTrapBaseline requires explicit old PlusJar/ContentJar and cannot be combined with UpgradeFrom or Experimental.'
}
if ($ContentJar -and !$LegacyTrapBaseline) { throw 'ContentJar override is restricted to the validated old-runtime baseline.' }
function Assert-PlainTree([string]$Root) { function Assert-PlainTree([string]$Root) {
$pending = [Collections.Generic.Stack[string]]::new() $pending = [Collections.Generic.Stack[string]]::new()
@@ -42,6 +48,11 @@ function Assert-OldMod([string]$Jar, [string]$Id, [string]$Version) {
} }
$upgradeSource = $null $upgradeSource = $null
if ($LegacyTrapBaseline) {
Add-Type -AssemblyName System.IO.Compression.FileSystem
Assert-OldMod $PlusJar 'astraplus' '0.9.13'
Assert-OldMod $ContentJar 'astracontent' '0.2.6'
}
if ($UpgradeFrom) { if ($UpgradeFrom) {
if ($Experimental) { throw 'UpgradeFrom uses an existing stable world; do not combine it with Experimental.' } if ($Experimental) { throw 'UpgradeFrom uses an existing stable world; do not combine it with Experimental.' }
$buildRoot = [IO.Path]::GetFullPath((Join-Path $project 'build')) $buildRoot = [IO.Path]::GetFullPath((Join-Path $project 'build'))
@@ -73,7 +84,7 @@ if ($UpgradeFrom) {
throw "Missing upgrade fixture directory: $directory" throw "Missing upgrade fixture directory: $directory"
} }
} }
foreach ($file in @('saved-cart.txt', 'saved-train.txt')) { foreach ($file in @('saved-cart.txt', 'saved-train.txt', 'trap-first-pass.txt')) {
if (!(Test-Path -LiteralPath (Join-Path $upgradeSource $file) -PathType Leaf)) { if (!(Test-Path -LiteralPath (Join-Path $upgradeSource $file) -PathType Leaf)) {
throw "Missing upgrade fixture: $file" throw "Missing upgrade fixture: $file"
} }
@@ -88,8 +99,8 @@ if ($UpgradeFrom) {
throw 'Upgrade fixture must keep the administrator editor and pack web services disabled.' throw 'Upgrade fixture must keep the administrator editor and pack web services disabled.'
} }
Add-Type -AssemblyName System.IO.Compression.FileSystem Add-Type -AssemblyName System.IO.Compression.FileSystem
Assert-OldMod (Join-Path $upgradeSource 'mods/AstraPlus-0.9.12.jar') 'astraplus' '0.9.12' Assert-OldMod (Join-Path $upgradeSource 'mods/AstraPlus-0.9.13.jar') 'astraplus' '0.9.13'
Assert-OldMod (Join-Path $upgradeSource 'mods/AstraContent-0.2.5.jar') 'astracontent' '0.2.5' Assert-OldMod (Join-Path $upgradeSource 'mods/AstraContent-0.2.6.jar') 'astracontent' '0.2.6'
} }
$java = 'java' $java = 'java'
@@ -97,10 +108,10 @@ if ($env:JAVA_HOME) { $java = Join-Path $env:JAVA_HOME 'bin/java.exe' }
$output=Join-Path $project ('build/verification-'+(Get-Date -Format 'yyyyMMdd-HHmmss')+'-'+[guid]::NewGuid().ToString('N').Substring(0,8)) $output=Join-Path $project ('build/verification-'+(Get-Date -Format 'yyyyMMdd-HHmmss')+'-'+[guid]::NewGuid().ToString('N').Substring(0,8))
New-Item -ItemType Directory -Path "$output/mods" | Out-Null New-Item -ItemType Directory -Path "$output/mods" | Out-Null
if ($upgradeSource) { if ($upgradeSource) {
foreach ($name in @('world', 'config', 'astraplus', 'first-pass.txt', 'saved-cart.txt', 'saved-train.txt')) { foreach ($name in @('world', 'config', 'astraplus', 'first-pass.txt', 'saved-cart.txt', 'saved-train.txt', 'trap-first-pass.txt')) {
Copy-Item -LiteralPath (Join-Path $upgradeSource $name) -Destination $output -Recurse Copy-Item -LiteralPath (Join-Path $upgradeSource $name) -Destination $output -Recurse
} }
"Read-only source: $upgradeSource`nOld versions: AstraPlus 0.9.12 + AstraContent 0.2.5" | "Read-only source: $upgradeSource`nOld versions: AstraPlus 0.9.13 + AstraContent 0.2.6" |
Set-Content -LiteralPath "$output/upgrade-source.txt" Set-Content -LiteralPath "$output/upgrade-source.txt"
} else { } else {
New-Item -ItemType Directory -Path "$output/config" | Out-Null New-Item -ItemType Directory -Path "$output/config" | Out-Null
@@ -142,17 +153,26 @@ $packsVersion=[regex]::Match((Get-Content "$packsRoot/build.gradle.kts" -Raw), '
Copy-Item -LiteralPath "$packsRoot/build/libs/AstraPacks-$packsVersion.jar" -Destination "$output/mods" Copy-Item -LiteralPath "$packsRoot/build/libs/AstraPacks-$packsVersion.jar" -Destination "$output/mods"
if (!$upgradeSource) { '{"enabled":false}' | Set-Content "$output/config/astrapacks.json" } if (!$upgradeSource) { '{"enabled":false}' | Set-Content "$output/config/astrapacks.json" }
$contentVersion=[regex]::Match((Get-Content "$project/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value $contentVersion=[regex]::Match((Get-Content "$project/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value
Copy-Item -LiteralPath $plus.FullName,"$project/build/libs/AstraContent-$contentVersion.jar","$project/build/libs/AstraContent-$contentVersion-integration-tests.jar" -Destination "$output/mods" $contentArtifact=Get-Item -LiteralPath $(if ($ContentJar) { $ContentJar } else { "$project/build/libs/AstraContent-$contentVersion.jar" })
Copy-Item -LiteralPath $plus.FullName,$contentArtifact.FullName,"$project/build/libs/AstraContent-$contentVersion-integration-tests.jar" -Destination "$output/mods"
Push-Location $output Push-Location $output
try { try {
$passes = if ($upgradeSource) { @('restart') } else { @('gameplay','restart') } $passes = if ($upgradeSource) { @('restart') } else { @('gameplay','restart') }
foreach($pass in $passes) { foreach($pass in $passes) {
& $java '-Xmx2G' '-Dastracontent.verify=true' "-Dastracontent.expectedExperimental=$($Experimental.IsPresent.ToString().ToLowerInvariant())" '@server-args.txt' nogui *> "$pass.log" & $java '-Xmx2G' '-Dastracontent.verify=true' "-Dastracontent.trapBaseline=$($LegacyTrapBaseline.IsPresent.ToString().ToLowerInvariant())" "-Dastracontent.expectedExperimental=$($Experimental.IsPresent.ToString().ToLowerInvariant())" '@server-args.txt' nogui *> "$pass.log"
if($LASTEXITCODE -ne 0){throw "Server failed: $output/$pass.log"} if($LASTEXITCODE -ne 0){throw "Server failed: $output/$pass.log"}
if(Select-String -Quiet -LiteralPath "$pass.log" -Pattern 'Exception stopping the server|Encountered an unexpected exception|Failed to save chunk|Mixin apply failed'){throw "Server lifecycle failed: $output/$pass.log"} if(Select-String -Quiet -LiteralPath "$pass.log" -Pattern 'Exception stopping the server|Encountered an unexpected exception|Failed to save chunk|Mixin apply failed'){throw "Server lifecycle failed: $output/$pass.log"}
if(!(Select-String -Quiet -LiteralPath "$pass.log" -SimpleMatch 'PASS transport shutdown: editor removed, vanilla speed restored, serialization retained for final save')) { if(!(Select-String -Quiet -LiteralPath "$pass.log" -SimpleMatch 'PASS transport shutdown: editor removed, vanilla speed restored, serialization retained for final save')) {
throw "Transport shutdown contract was not verified: $output/$pass.log" throw "Transport shutdown contract was not verified: $output/$pass.log"
} }
foreach ($trapMarker in @(("PASS traps " + $pass + ":"), 'PASS traps shutdown:')) {
if (!(Select-String -Quiet -LiteralPath "$pass.log" -SimpleMatch $trapMarker)) {
throw "Trap contract was not verified ($trapMarker): $output/$pass.log"
}
}
if (!$LegacyTrapBaseline -and !(Select-String -Quiet -LiteralPath "$pass.log" -SimpleMatch 'PASS traps lifecycle:')) {
throw "Trap startup failure/recovery contract was not verified: $output/$pass.log"
}
$result=Get-Content -Raw verification-result.txt $result=Get-Content -Raw verification-result.txt
if(!$result.StartsWith("PASS $pass")){throw "Verification failed: $result ($output/$pass.log)"} if(!$result.StartsWith("PASS $pass")){throw "Verification failed: $result ($output/$pass.log)"}
Copy-Item verification-result.txt "$pass-result.txt" Copy-Item verification-result.txt "$pass-result.txt"
@@ -160,7 +180,7 @@ try {
} }
}finally{Pop-Location} }finally{Pop-Location}
if ($upgradeSource) { if ($upgradeSource) {
$result = "PASS upgrade: old AstraPlus 0.9.12 + AstraContent 0.2.5 world loaded with AstraPlus $plusVersion + AstraContent $contentVersion; source unchanged" $result = "PASS upgrade: old AstraPlus 0.9.13 + AstraContent 0.2.6 world loaded with AstraPlus $plusVersion + AstraContent $contentVersion; source unchanged"
$result | Set-Content -LiteralPath "$output/upgrade-result.txt" $result | Set-Content -LiteralPath "$output/upgrade-result.txt"
Write-Output $result Write-Output $result
} }
@@ -15,6 +15,7 @@ import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import online.astradev.content.projectile.ProjectileCapabilities; import online.astradev.content.projectile.ProjectileCapabilities;
import online.astradev.content.transport.TransportCapabilities; import online.astradev.content.transport.TransportCapabilities;
import online.astradev.content.trap.ItemTrapCapabilities;
import online.astradev.plus.api.AstraPlusApi; import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.RailBehavior; import online.astradev.plus.api.RailBehavior;
@@ -42,6 +43,7 @@ public final class AstraContent {
throw new IllegalStateException("Cannot declare AstraContent transport compatibility", failure); throw new IllegalStateException("Cannot declare AstraContent transport compatibility", failure);
} }
TransportCapabilities.register(NeoForge.EVENT_BUS); TransportCapabilities.register(NeoForge.EVENT_BUS);
ItemTrapCapabilities.register(NeoForge.EVENT_BUS);
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::aboutToStart); NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::aboutToStart);
NeoForge.EVENT_BUS.addListener(this::start); NeoForge.EVENT_BUS.addListener(this::start);
NeoForge.EVENT_BUS.addListener(this::stopping); NeoForge.EVENT_BUS.addListener(this::stopping);
@@ -62,9 +64,16 @@ public final class AstraContent {
resource("transport", "defaults"), resource("transport", "schema"), transportCompatibility); resource("transport", "defaults"), resource("transport", "schema"), transportCompatibility);
railSpeedRuntime = RailBehavior.registerSpeedRuntime("astracontent:transport"); railSpeedRuntime = RailBehavior.registerSpeedRuntime("astracontent:transport");
transportStarted = true; transportStarted = true;
// Existing dispensers are discovered by ChunkEvent.Load; register their runtime
// before levels load, while retaining the old configuration and display identity.
ItemTrapCapabilities.start(event.getServer(),
FMLPaths.GAMEDIR.get().resolve("config/astraspears.json"),
"astraspears:trap_policy", "Предметные ловушки",
resource("trap", "defaults"), resource("trap", "schema"),
JsonParser.parseString(resource("trap", "compatibility")).getAsJsonObject());
} catch (IOException | RuntimeException failure) { } catch (IOException | RuntimeException failure) {
close(); close();
throw new IllegalStateException("Cannot initialize AstraContent transport policy", failure); throw new IllegalStateException("Cannot initialize AstraContent early gameplay policies", failure);
} }
} }
@@ -117,6 +126,7 @@ public final class AstraContent {
} }
private void close() { private void close() {
ItemTrapCapabilities.close();
if (projectiles != null) { if (projectiles != null) {
projectiles.close(); projectiles.close();
projectiles = null; projectiles = null;
@@ -0,0 +1,19 @@
package online.astradev.content.mixin;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.level.block.state.BlockState;
import online.astradev.content.trap.ItemTrapCapabilities;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(DispenserBlock.class)
abstract class ItemTrapDispenserMixin {
@Inject(method = "dispenseFrom", at = @At("HEAD"), cancellable = true)
private void astraspears$dispense(ServerLevel level, BlockState state, BlockPos pos, CallbackInfo ci) {
if (ItemTrapCapabilities.dispense(level, pos)) ci.cancel();
}
}
@@ -0,0 +1,22 @@
package online.astradev.content.mixin;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.DispenserBlockEntity;
import net.minecraft.world.level.block.entity.DropperBlockEntity;
import online.astradev.content.trap.ItemTrapCapabilities;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BlockEntity.class)
abstract class ItemTrapInventoryMixin {
@Inject(method = "setChanged()V", at = @At("TAIL"))
private void astraspears$inventoryChanged(CallbackInfo ci) {
Object self = this;
if (self instanceof DispenserBlockEntity dispenser && !(self instanceof DropperBlockEntity)
&& dispenser.getLevel() instanceof ServerLevel level)
ItemTrapCapabilities.changed(level, dispenser.getBlockPos());
}
}
@@ -0,0 +1,82 @@
package online.astradev.content.trap;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.nio.file.Path;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
import net.neoforged.neoforge.event.level.ChunkEvent;
import net.neoforged.neoforge.event.level.LevelEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import online.astradev.plus.api.editor.EditorDefinitions;
/** Native inventory, power, collision and item-animation adapter for authored trap policies. */
public final class ItemTrapCapabilities {
private static ItemTraps traps;
private static ItemTrapSettings settings;
private static String displayTag;
private ItemTrapCapabilities() {}
public static void register(IEventBus bus) {
bus.addListener(ItemTrapCapabilities::tick);
bus.addListener(ItemTrapCapabilities::load);
bus.addListener(ItemTrapCapabilities::unload);
bus.addListener(ItemTrapCapabilities::unloadLevel);
bus.addListener(ItemTrapCapabilities::join);
}
public static void start(net.minecraft.server.MinecraftServer server, Path file, String id, String name, String defaults, String schema,
JsonObject compatibility) throws IOException {
if (settings != null) throw new IllegalStateException("Trap capability is already active");
if (EditorDefinitions.find(id).isPresent()) {
throw new IllegalArgumentException("Mechanic already registered: " + id);
}
String nextDisplayTag = compatibility.get("displayTag").getAsString();
if (!nextDisplayTag.matches("[a-z0-9_.-]+:[a-z0-9_/.-]+")) throw new IOException("Invalid display identity");
var nextSettings = new ItemTrapSettings(file, id, name, defaults, schema, config -> {
var key = net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.DAMAGE_TYPE,
net.minecraft.resources.Identifier.parse(config.damageType()));
server.registryAccess().lookupOrThrow(net.minecraft.core.registries.Registries.DAMAGE_TYPE).getOrThrow(key);
return config;
});
var nextTraps = new ItemTraps(nextSettings::current);
// Publish the runtime only after validation and ownership registration succeed.
// A duplicate provider or invalid file must not leave callbacks partly active.
EditorDefinitions.register(nextSettings.definition());
settings = nextSettings;
displayTag = nextDisplayTag;
traps = nextTraps;
}
public static void close() {
var previousSettings = settings;
var previousTraps = traps;
// Stop callbacks before discarding displays; inventory contents remain untouched.
traps = null;
settings = null;
displayTag = null;
if (previousSettings != null) EditorDefinitions.unregister(previousSettings.definition());
if (previousTraps != null) previousTraps.close();
}
public static boolean active() { return traps != null; }
static String displayTag() { return displayTag; }
public static ItemTrapConfig config() { return settings == null ? ItemTrapConfig.defaults() : settings.current(); }
public static boolean dispense(ServerLevel level, BlockPos pos) { return traps != null && traps.dispense(level, pos); }
public static void changed(ServerLevel level, BlockPos pos) { if (traps != null) traps.refreshLater(level, pos); }
private static void tick(ServerTickEvent.Post event) { if (traps != null) traps.tick(); }
private static void load(ChunkEvent.Load event) {
if (traps != null && event.getLevel() instanceof ServerLevel level) traps.scanLater(level, event.getChunk().getPos());
}
private static void unload(ChunkEvent.Unload event) {
if (traps != null && event.getLevel() instanceof ServerLevel level) traps.unload(level, event.getChunk().getPos());
}
private static void unloadLevel(LevelEvent.Unload event) {
if (traps != null && event.getLevel() instanceof ServerLevel level) traps.unload(level, null);
}
private static void join(EntityJoinLevelEvent event) {
if (displayTag != null && event.loadedFromDisk() && event.getEntity().entityTags().contains(displayTag)) event.setCanceled(true);
}
}
@@ -0,0 +1,100 @@
package online.astradev.content.trap;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public record ItemTrapConfig(double reach, double hitRadius, int animationTicks,
boolean enabled, int slot, boolean damagePlayers, boolean damageMobs,
double damageMultiplier, int durabilityPerHit, boolean breakOnUse,
java.util.List<String> allowedSpears, java.util.Map<String, Double> damageOverrides,
double insertionDepth, double modelLength, double modelRoll, double modelYaw,
String damageType, java.util.List<String> excludedEntityTypes) {
private static final com.google.gson.Gson JSON = new GsonBuilder().setPrettyPrinting().create();
private static final int RESOURCE_LIMIT = 512 * 1024;
private static final JsonObject DEFAULT_DOCUMENT = resource("trap-defaults.json");
private static final ItemTrapConfig DEFAULT_CONFIG = JSON.fromJson(DEFAULT_DOCUMENT, ItemTrapConfig.class);
public ItemTrapConfig(double reach, double hitRadius, int animationTicks) {
this(reach, hitRadius, animationTicks, DEFAULT_CONFIG.enabled(), DEFAULT_CONFIG.slot(),
DEFAULT_CONFIG.damagePlayers(), DEFAULT_CONFIG.damageMobs(), DEFAULT_CONFIG.damageMultiplier(),
DEFAULT_CONFIG.durabilityPerHit(), DEFAULT_CONFIG.breakOnUse(),
DEFAULT_CONFIG.allowedSpears(), DEFAULT_CONFIG.damageOverrides(),
DEFAULT_CONFIG.insertionDepth(), DEFAULT_CONFIG.modelLength(), DEFAULT_CONFIG.modelRoll(),
DEFAULT_CONFIG.modelYaw(), DEFAULT_CONFIG.damageType(), DEFAULT_CONFIG.excludedEntityTypes());
}
public ItemTrapConfig {
if (!Double.isFinite(reach) || reach < 0.25 || reach > 4
|| !Double.isFinite(hitRadius) || hitRadius < 0.05 || hitRadius > 0.5
|| animationTicks < 1 || animationTicks > 20)
throw new IllegalArgumentException("reach: 0.25..4; hitRadius: 0.05..0.5; animationTicks: 1..20");
if (slot < 0 || slot > 8 || !Double.isFinite(damageMultiplier) || damageMultiplier < 0 || damageMultiplier > 1000
|| durabilityPerHit < 0 || durabilityPerHit > 10000 || allowedSpears == null || damageOverrides == null)
throw new IllegalArgumentException("Invalid spear policy");
allowedSpears = java.util.List.copyOf(allowedSpears);
damageOverrides = java.util.Map.copyOf(damageOverrides);
if (!Double.isFinite(insertionDepth) || insertionDepth < 0 || insertionDepth > 4
|| !Double.isFinite(modelLength) || modelLength <= 0 || modelLength > 32
|| !Double.isFinite(modelRoll) || Math.abs(modelRoll) > 360
|| !Double.isFinite(modelYaw) || Math.abs(modelYaw) > 360 || excludedEntityTypes == null)
throw new IllegalArgumentException("Invalid trap geometry");
identifier(damageType);
excludedEntityTypes = java.util.List.copyOf(excludedEntityTypes);
excludedEntityTypes.forEach(ItemTrapConfig::identifier);
for (String id : allowedSpears) identifier(id);
for (var entry : damageOverrides.entrySet()) {
identifier(entry.getKey());
if (!Double.isFinite(entry.getValue()) || entry.getValue() < 0 || entry.getValue() > 1000000)
throw new IllegalArgumentException("Invalid damage: " + entry.getKey());
}
}
private static void identifier(String id) {
if (id == null || !id.matches("[a-z0-9_.-]+:[a-z0-9/._-]+")) throw new IllegalArgumentException("Invalid item id: " + id);
}
public static ItemTrapConfig defaults() { return DEFAULT_CONFIG; }
static String defaultsJson() { return JSON.toJson(DEFAULT_DOCUMENT); }
static JsonObject resource(String name) {
if (!name.equals("trap-defaults.json") && !name.equals("trap-schema.json")) {
throw new IllegalArgumentException("Unknown trap policy resource: " + name);
}
String path = "/content/policies/" + name;
try (var stream = ItemTrapConfig.class.getResourceAsStream(path)) {
if (stream == null) throw new IOException("Missing AstraContent trap resource: " + path);
byte[] bytes = stream.readNBytes(RESOURCE_LIMIT + 1);
if (bytes.length > RESOURCE_LIMIT) throw new IOException("Trap policy resource exceeds 512 KiB: " + path);
return JsonParser.parseString(new String(bytes, StandardCharsets.UTF_8)).getAsJsonObject();
} catch (IOException | RuntimeException failure) {
throw new IllegalStateException("Cannot read AstraContent trap resource: " + path, failure);
}
}
public static ItemTrapConfig parse(String document) {
try {
var value = JsonParser.parseString(document);
if (!value.isJsonObject()) throw new IllegalArgumentException("Настройки копий должны быть JSON-объектом.");
var json = DEFAULT_DOCUMENT.deepCopy();
value.getAsJsonObject().entrySet().forEach(entry -> json.add(entry.getKey(), entry.getValue()));
return JSON.fromJson(json, ItemTrapConfig.class);
} catch (RuntimeException error) {
if (error instanceof IllegalArgumentException invalid) throw invalid;
throw new IllegalArgumentException("Некорректные настройки ловушек: проверьте диапазоны и идентификаторы.", error);
}
}
public static ItemTrapConfig load(Path file) throws IOException {
if (!Files.exists(file)) {
Files.createDirectories(file.getParent());
Files.writeString(file, defaultsJson() + "\n");
}
try {
var result = parse(Files.readString(file));
if (result == null) throw new IllegalArgumentException("Empty config");
return result;
} catch (RuntimeException e) { throw new IOException("Invalid " + file, e); }
}
}
@@ -0,0 +1,19 @@
package online.astradev.content.trap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Display;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.level.storage.ValueOutput;
final class ItemTrapDisplay extends Display.ItemDisplay {
ItemTrapDisplay(ServerLevel level) {
super(EntityTypes.ITEM_DISPLAY, level);
setNoGravity(true);
setInvulnerable(true);
setTransformationInterpolationDuration(1);
setPosRotInterpolationDuration(1);
addTag(ItemTrapCapabilities.displayTag());
}
@Override public boolean shouldBeSaved() { return false; }
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
}
@@ -0,0 +1,42 @@
package online.astradev.content.trap;
import net.minecraft.core.Direction;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
public final class ItemTrapGeometry {
private ItemTrapGeometry() {}
static boolean needsRedraw(double drawnLength, double length,
ItemTrapConfig drawnConfig, ItemTrapConfig currentConfig) {
return Math.abs(drawnLength - length) > 0.0001
|| !java.util.Objects.equals(drawnConfig, currentConfig);
}
public static double modelCenterOffset(double exposedLength) {
return modelCenterOffset(exposedLength, ItemTrapConfig.defaults());
}
public static double modelCenterOffset(double exposedLength, ItemTrapConfig config) {
return (exposedLength - config.insertionDepth()) / 2;
}
public static AABB bounds(Vec3 mouth, Vec3 direction, double length, double radius) {
return new AABB(mouth, mouth.add(direction.scale(length))).inflate(
direction.x == 0 ? radius : 0,
direction.y == 0 ? radius : 0,
direction.z == 0 ? radius : 0);
}
public static Matrix4f model(Direction face, double length) {
return model(face, length, ItemTrapConfig.defaults());
}
public static Matrix4f model(Direction face, double length, ItemTrapConfig config) {
Vector3f direction = new Vector3f(face.getStepX(), face.getStepY(), face.getStepZ());
Quaternionf facing = new Quaternionf().rotationTo(new Vector3f(0, 1, 0), direction);
// NONE uses the diagonal spear_in_hand sprite. Cancel the renderer's appended Y rotation.
float scale = (float) ((length + config.insertionDepth()) / config.modelLength());
return new Matrix4f().rotate(facing).scale(scale)
.rotateZ((float) Math.toRadians(config.modelRoll())).rotateY((float) Math.toRadians(config.modelYaw()));
}
}
@@ -0,0 +1,35 @@
package online.astradev.content.trap;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.component.DataComponents;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import online.astradev.plus.api.AstraPlusApi;
public final class ItemTrapItems {
public boolean isSpear(ItemStack stack) {
return isSpear(stack, ItemTrapCapabilities.config());
}
public boolean isSpear(ItemStack stack, ItemTrapConfig config) {
if (stack.isEmpty()) return false;
// Resolve through the public catalog on every refresh, including after AstraPlus reload.
var custom = AstraPlusApi.current().flatMap(api -> api.find(stack));
String material = BuiltInRegistries.ITEM.getKey(stack.getItem()).toString();
return config.allowedSpears().contains(material)
|| custom.map(definition -> config.allowedSpears().contains(definition.id().toString())).orElse(false);
}
public double damage(ItemStack stack) {
// AttributeInstance applies all three operations in vanilla order, independent of JSON order.
var attribute = new AttributeInstance(Attributes.ATTACK_DAMAGE, ignored -> {});
attribute.setBaseValue(1);
stack.getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY)
.forEach(EquipmentSlot.MAINHAND, (type, modifier) -> {
if (type.equals(Attributes.ATTACK_DAMAGE)) attribute.addOrUpdateTransientModifier(modifier);
});
double result = attribute.getValue();
return Double.isFinite(result) ? Math.max(0, result) : 0;
}
}
@@ -0,0 +1,45 @@
package online.astradev.content.trap;
import java.io.IOException;
import java.nio.file.Path;
import online.astradev.plus.api.editor.FileEditorDefinition;
/** One live configuration source shared by the editor, recognition and every trap step. */
final class ItemTrapSettings {
private ItemTrapConfig current;
private final FileEditorDefinition<ItemTrapConfig> definition;
ItemTrapSettings(Path file) throws IOException {
this(file, "test:item_trap", "Ловушка", ItemTrapConfig.defaultsJson(), schema());
}
ItemTrapSettings(Path file, String id, String name, String defaults, String schema) throws IOException {
this(file, id, name, defaults, schema, java.util.function.UnaryOperator.identity());
}
ItemTrapSettings(Path file, String id, String name, String defaults, String schema,
java.util.function.UnaryOperator<ItemTrapConfig> validate) throws IOException {
definition = new FileEditorDefinition<>(file, id, name,
schemaWithDefaults(schema, defaults), json -> validate.apply(ItemTrapConfig.parse(json)), value -> current = value);
definition.initialize(defaults);
current = validate.apply(ItemTrapConfig.parse(definition.snapshot().documentJson()));
}
ItemTrapConfig current() { return current; }
FileEditorDefinition<ItemTrapConfig> definition() { return definition; }
static String schema() {
return schemaWithDefaults(ItemTrapConfig.resource("trap-schema.json").toString(), ItemTrapConfig.defaultsJson());
}
private static String schemaWithDefaults(String declaration, String document) {
var schema = com.google.gson.JsonParser.parseString(declaration).getAsJsonObject();
var defaults = com.google.gson.JsonParser.parseString(document).getAsJsonObject();
for (var entry : schema.getAsJsonArray("fields")) {
var field = entry.getAsJsonObject();
field.add("default", defaults.get(field.get("path").getAsString()).deepCopy());
}
return schema.toString();
}
}
@@ -0,0 +1,222 @@
package online.astradev.content.trap;
import com.mojang.math.Transformation;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.Registries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.damagesource.DamageTypes;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.decoration.ArmorStand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.level.block.entity.DispenserBlockEntity;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import org.slf4j.LoggerFactory;
import net.neoforged.neoforge.common.NeoForge;
import online.astradev.plus.api.event.ItemTrapActivateEvent;
final class ItemTraps implements AutoCloseable {
private final java.util.function.Supplier<ItemTrapConfig> configuration;
private final ItemTrapItems types = new ItemTrapItems();
private final Map<Key, Trap> active = new LinkedHashMap<>();
private final Set<Key> refresh = new LinkedHashSet<>();
private final Set<ChunkKey> scans = new LinkedHashSet<>();
ItemTraps(ItemTrapConfig config) { this(() -> config); }
ItemTraps(java.util.function.Supplier<ItemTrapConfig> configuration) { this.configuration = configuration; }
private ItemTrapConfig config() { return configuration.get(); }
boolean dispense(ServerLevel level, BlockPos pos) {
if (!config().enabled()) return false;
ItemStack spear = centralSpear(level, pos);
if (spear.isEmpty()) return false;
activate(new Key(level, pos.immutable()), spear);
return true; // Before random slot selection, including buckets, armor and TNT.
}
private ItemStack centralSpear(ServerLevel level, BlockPos pos) {
if (!level.hasChunkAt(pos) || !level.getBlockState(pos).is(Blocks.DISPENSER)) return ItemStack.EMPTY;
if (!(level.getBlockEntity(pos) instanceof DispenserBlockEntity dispenser)) return ItemStack.EMPTY;
if (!config().enabled()) return ItemStack.EMPTY;
ItemStack item = dispenser.getItem(config().slot());
return types.isSpear(item, config()) ? item : ItemStack.EMPTY;
}
private String itemId(ItemStack item) {
return online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.find(item))
.map(definition -> definition.id().toString())
.orElseGet(() -> net.minecraft.core.registries.BuiltInRegistries.ITEM.getKey(item.getItem()).toString());
}
private boolean powered(Key key) {
// Signal queries also inspect horizontal neighbor chunks; never load them for a trap.
for (Direction side : Direction.values()) {
if (!key.level.hasChunkAt(key.pos.relative(side))
|| !key.level.hasChunkAt(key.pos.above().relative(side))) return false;
}
return key.level.hasNeighborSignal(key.pos) || key.level.hasNeighborSignal(key.pos.above());
}
private void activate(Key key, ItemStack spear) {
if (spear.isEmpty() || !powered(key) || active.containsKey(key)) return;
var event = new ItemTrapActivateEvent(key.level, key.pos, spear);
if (NeoForge.EVENT_BUS.post(event).isCanceled()) return;
// Protection callbacks may change the inventory or remove the dispenser.
var current = centralSpear(key.level, key.pos);
if (ItemStack.isSameItemSameComponents(current, spear) && powered(key))
active.put(key, new Trap(key, current));
}
void refreshLater(ServerLevel level, BlockPos pos) { refresh.add(new Key(level, pos.immutable())); }
void scanLater(ServerLevel level, ChunkPos pos) { scans.add(new ChunkKey(level, pos)); }
void unload(ServerLevel level, ChunkPos pos) {
for (var key : new ArrayList<>(active.keySet()))
if (key.level == level && (pos == null || new ChunkPos(key.pos.getX() >> 4, key.pos.getZ() >> 4).equals(pos))) remove(key);
refresh.removeIf(key -> key.level == level && (pos == null || new ChunkPos(key.pos.getX() >> 4, key.pos.getZ() >> 4).equals(pos)));
scans.removeIf(key -> key.level == level && (pos == null || key.pos.equals(pos)));
}
void tick() {
var pendingScans = new ArrayList<>(scans);
scans.clear();
for (var key : pendingScans) {
var chunk = key.level.getChunkSource().getChunkNow(key.pos.x(), key.pos.z());
if (chunk != null)
for (var entity : chunk.getBlockEntities().values())
if (entity instanceof DispenserBlockEntity) refreshLater(key.level, entity.getBlockPos());
}
var pending = new ArrayList<>(refresh);
refresh.clear();
for (var key : pending) {
if (!key.level.getBlockTicks().hasScheduledTick(key.pos, Blocks.DISPENSER))
activate(key, centralSpear(key.level, key.pos));
}
for (Trap trap : new ArrayList<>(active.values())) {
if (active.get(trap.key) != trap) continue;
try { if (!trap.step()) remove(trap.key); }
catch (RuntimeException error) {
remove(trap.key);
LoggerFactory.getLogger("ItemTrapCapabilities").warn("Removed failed spear trap {}", trap.key, error);
}
}
}
private void remove(Key key) {
Trap trap = active.remove(key);
if (trap != null && trap.display != null) trap.display.discard();
}
@Override public void close() {
for (Key key : new ArrayList<>(active.keySet())) remove(key);
refresh.clear();
scans.clear();
}
private record Key(ServerLevel level, BlockPos pos) {}
private record ChunkKey(ServerLevel level, ChunkPos pos) {}
private final class Trap {
final Key key;
final Direction face;
final Vec3 direction, mouth;
final Set<UUID> hitThisStroke = new HashSet<>();
boolean wasExtended;
ItemStack spear;
ItemTrapDisplay display;
ItemTrapConfig drawnConfig;
double length, drawnLength = -1;
Trap(Key key, ItemStack spear) {
this.key = key;
face = key.level.getBlockState(key.pos).getValue(DispenserBlock.FACING);
direction = new Vec3(face.getStepX(), face.getStepY(), face.getStepZ());
mouth = Vec3.atCenterOf(key.pos).add(direction.scale(0.501));
this.spear = spear.copyWithCount(1);
}
boolean step() {
var level = key.level;
if (!level.hasChunkAt(key.pos)) return false;
var state = level.getBlockState(key.pos);
if (!state.is(Blocks.DISPENSER) || state.getValue(DispenserBlock.FACING) != face) return false;
ItemStack current = centralSpear(level, key.pos);
boolean extended = !current.isEmpty() && powered(key);
if (extended && !wasExtended) hitThisStroke.clear();
wasExtended = extended;
if (!current.isEmpty() && !ItemStack.isSameItemSameComponents(current, spear)) {
spear = current.copyWithCount(1);
if (display != null) display.getSlot(0).set(spear.copy());
}
double available = unobstructedLength();
double target = extended ? available : 0;
double step = config().reach() / config().animationTicks();
double previous = length;
length = target > length ? Math.min(target, length + step) : Math.max(target, length - step);
length = Math.min(length, available);
if (length < 0.001) {
if (display != null) { display.discard(); display = null; drawnLength = -1; }
return extended;
}
ItemTrapConfig visualConfig = config();
if (display == null || display.isRemoved()) {
display = new ItemTrapDisplay(level);
display.getSlot(0).set(spear.copy());
draw(visualConfig);
if (!level.addFreshEntity(display) || active.get(key) != this) {
display.discard();
return false;
}
} else if (ItemTrapGeometry.needsRedraw(drawnLength, length, drawnConfig, visualConfig)) {
draw(visualConfig);
}
if (extended && length > previous + 0.00001) hurt();
return true;
}
void draw(ItemTrapConfig visualConfig) {
display.setPos(mouth.add(direction.scale(ItemTrapGeometry.modelCenterOffset(length, visualConfig))));
display.setTransformationInterpolationDelay(0);
display.setTransformation(new Transformation(ItemTrapGeometry.model(face, length, visualConfig)));
drawnLength = length;
drawnConfig = visualConfig;
}
double unobstructedLength() {
var level = key.level;
var box = ItemTrapGeometry.bounds(mouth, direction, config().reach(), config().hitRadius());
for (int x = Mth.floor(box.minX) >> 4; x <= Mth.floor(box.maxX) >> 4; x++)
for (int z = Mth.floor(box.minZ) >> 4; z <= Mth.floor(box.maxZ) >> 4; z++)
if (level.getChunkSource().getChunkNow(x, z) == null) return 0;
double limit = config().reach();
if (face == Direction.UP) limit = Math.min(limit, level.getMaxY() + 1 - mouth.y);
if (face == Direction.DOWN) limit = Math.min(limit, mouth.y - level.getMinY());
if (limit <= 0) return 0;
var hit = level.clip(new ClipContext(mouth, mouth.add(direction.scale(limit)),
ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, net.minecraft.world.phys.shapes.CollisionContext.empty()));
return hit.getType() == HitResult.Type.MISS ? limit : Math.max(0, mouth.distanceTo(hit.getLocation()) - 0.01);
}
void hurt() {
var level = key.level;
var box = ItemTrapGeometry.bounds(mouth, direction, length, config().hitRadius());
var source = new DamageSource(level.registryAccess().lookupOrThrow(Registries.DAMAGE_TYPE)
.getOrThrow(net.minecraft.resources.ResourceKey.create(Registries.DAMAGE_TYPE,
net.minecraft.resources.Identifier.parse(config().damageType()))), mouth);
for (var victim : level.getEntitiesOfClass(LivingEntity.class, box)) {
if (config().excludedEntityTypes().contains(net.minecraft.core.registries.BuiltInRegistries.ENTITY_TYPE.getKey(victim.getType()).toString())
|| !victim.isAlive() || victim.isRemoved()
|| victim.isInvulnerable() || hitThisStroke.contains(victim.getUUID())) continue;
if (victim instanceof Player player && (player.isCreative() || player.isSpectator())) continue;
hitThisStroke.add(victim.getUUID());
if (victim instanceof Player ? !config().damagePlayers() : !config().damageMobs()) continue;
double damage = config().damageOverrides().getOrDefault(itemId(spear), types.damage(spear)) * config().damageMultiplier();
if (victim.hurtServer(level, source, (float) damage)) {
var current = centralSpear(level, key.pos);
if (!current.isEmpty() && ItemStack.isSameItemSameComponents(current, spear)) {
if (config().breakOnUse()) current.shrink(1);
else if (config().durabilityPerHit() > 0) current.hurtAndBreak(config().durabilityPerHit(), level, null, item -> {});
if (level.getBlockEntity(key.pos) instanceof DispenserBlockEntity dispenser) dispenser.setChanged();
if (current.isEmpty()) return;
spear = current.copyWithCount(1);
if (display != null) display.getSlot(0).set(spear.copy());
}
}
if (active.get(key) != this) return;
}
}
}
}
@@ -5,7 +5,7 @@ license="All Rights Reserved"
modId="astracontent" modId="astracontent"
version="${version}" version="${version}"
displayName="AstraContent" displayName="AstraContent"
description='''Server-only ammunition, copper rails, minecart trains and transport policies. Vanilla clients supported.''' description='''Server-only ammunition, item traps, copper rails, minecart trains and transport policies. Vanilla clients supported.'''
[[mixins]] [[mixins]]
config="astracontent.mixins.json" config="astracontent.mixins.json"
[[dependencies.astracontent]] [[dependencies.astracontent]]
@@ -21,6 +21,6 @@ side="SERVER"
[[dependencies.astracontent]] [[dependencies.astracontent]]
modId="astraplus" modId="astraplus"
type="required" type="required"
versionRange="[0.9.13,0.10)" versionRange="[0.9.14,0.10)"
ordering="AFTER" ordering="AFTER"
side="SERVER" side="SERVER"
+3 -1
View File
@@ -11,7 +11,9 @@
"TransportExperimentalCartMixin", "TransportExperimentalCartMixin",
"TransportTrainCartMixin", "TransportTrainCartMixin",
"TransportSlimeCollisionMixin", "TransportSlimeCollisionMixin",
"TransportBoatPacketMixin" "TransportBoatPacketMixin",
"ItemTrapInventoryMixin",
"ItemTrapDispenserMixin"
], ],
"injectors": {"defaultRequire": 1} "injectors": {"defaultRequire": 1}
} }
@@ -0,0 +1,3 @@
{
"displayTag": "astraspears:spear_display"
}
@@ -0,0 +1,23 @@
{
"reach": 1.0,
"hitRadius": 0.12,
"animationTicks": 4,
"enabled": true,
"slot": 4,
"damagePlayers": true,
"damageMobs": true,
"damageMultiplier": 1.0,
"durabilityPerHit": 0,
"breakOnUse": false,
"allowedSpears": [
"minecraft:wooden_spear", "minecraft:stone_spear", "minecraft:copper_spear",
"minecraft:iron_spear", "minecraft:golden_spear", "minecraft:diamond_spear", "minecraft:netherite_spear"
],
"damageOverrides": {},
"insertionDepth": 0.95,
"modelLength": 1.4142135623730951,
"modelRoll": -45,
"modelYaw": -180,
"damageType": "minecraft:spear",
"excludedEntityTypes": ["minecraft:armor_stand"]
}
@@ -0,0 +1,23 @@
{
"description": "Действующие правила копейных ловушек. Изменения применяются при следующих взаимодействиях и шагах активных ловушек, без перезапуска сервера.",
"fields": [
{"path":"enabled","label":"Ловушки включены","type":"boolean","group":"Активация"},
{"path":"slot","label":"Слот раздатчика (с нуля)","type":"integer","min":0,"max":8,"group":"Активация"},
{"path":"allowedSpears","label":"Разрешённые предметы","type":"strings","group":"Активация","description":"Ванильные материалы или идентификаторы AstraPlus, например minecraft:iron_spear и my_mod:ruby_spear. Модель должна соответствовать геометрии копья."},
{"path":"reach","label":"Длина удара, блоки","type":"number","min":0.25,"max":4,"group":"Движение"},
{"path":"hitRadius","label":"Радиус попадания, блоки","type":"number","min":0.05,"max":0.5,"group":"Движение"},
{"path":"animationTicks","label":"Время выдвижения и втягивания, тики","type":"integer","min":1,"max":20,"group":"Движение"},
{"path":"damagePlayers","label":"Урон игрокам","type":"boolean","group":"Урон"},
{"path":"damageMobs","label":"Урон мобам","type":"boolean","group":"Урон"},
{"path":"damageMultiplier","label":"Множитель урона","type":"number","min":0,"max":1000,"group":"Урон"},
{"path":"damageOverrides","label":"Урон отдельных предметов","type":"object","group":"Урон","editor":{"kind":"map","keyType":"identifier","valueType":"number","keyLabel":"ID предмета","valueLabel":"Базовый урон","min":0,"max":1000000},"description":"Базовый урон предмета от 0 до 1000000. Затем применяется общий множитель."},
{"path":"durabilityPerHit","label":"Расход прочности за успешное попадание","type":"integer","min":0,"max":10000,"group":"Расход предмета"},
{"path":"breakOnUse","label":"Расходовать предмет при успешном попадании","type":"boolean","group":"Расход предмета","description":"При включении предмет расходуется вместо уменьшения прочности."},
{"path":"insertionDepth","label":"Глубина внутри раздатчика, блоки","type":"number","min":0,"max":4,"group":"Модель"},
{"path":"modelLength","label":"Исходная длина модели, блоки","type":"number","min":0.001,"max":32,"group":"Модель"},
{"path":"modelRoll","label":"Наклон модели, градусы","type":"number","min":-360,"max":360,"group":"Модель"},
{"path":"modelYaw","label":"Поворот модели, градусы","type":"number","min":-360,"max":360,"group":"Модель"},
{"path":"damageType","label":"Тип урона","type":"string","group":"Урон"},
{"path":"excludedEntityTypes","label":"Существа без урона от ловушки","type":"strings","group":"Урон"}
]
}
@@ -0,0 +1,45 @@
package online.astradev.content.trap;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ItemTrapConfigTest {
@Test void readsOnlyOwnedPolicyResources() {
assertEquals(1, ItemTrapConfig.resource("trap-defaults.json").get("reach").getAsDouble());
assertTrue(ItemTrapConfig.resource("trap-schema.json").has("fields"));
assertThrows(IllegalArgumentException.class, () -> ItemTrapConfig.resource("../trap-defaults.json"));
assertThrows(IllegalArgumentException.class, () -> ItemTrapConfig.resource("transport-defaults.json"));
}
@Test void loadsPoliciesAndRejectsInvalidDamage() throws Exception {
var file = directory.resolve("policy.json");
Files.writeString(file, """
{"enabled":false,"allowedSpears":["astraplus:test"],"damageOverrides":{"astraplus:test":7.5},"durabilityPerHit":2,"breakOnUse":true}
""");
var policy = ItemTrapConfig.load(file);
assertFalse(policy.enabled());
assertEquals(7.5, policy.damageOverrides().get("astraplus:test"));
assertEquals(2, policy.durabilityPerHit());
assertTrue(policy.breakOnUse());
assertEquals(4, policy.slot());
Files.writeString(file, "{\"damageOverrides\":{\"minecraft:iron_spear\":-1}}");
assertThrows(java.io.IOException.class, () -> ItemTrapConfig.load(file));
}
@TempDir Path directory;
@Test void createsDefaultsAndPreservesExistingSettings() throws Exception {
var file = directory.resolve("astraspears.json");
assertEquals(new ItemTrapConfig(1, 0.12, 4), ItemTrapConfig.load(file));
Files.writeString(file, "{\"reach\":2.5,\"hitRadius\":0.2,\"animationTicks\":8}");
assertEquals(new ItemTrapConfig(2.5, 0.2, 8), ItemTrapConfig.load(file));
}
@Test void rejectsInvalidConfigurationWithoutOverwritingIt() throws Exception {
var file = directory.resolve("astraspears.json");
String invalid = "{\"reach\":100,\"hitRadius\":0.1,\"animationTicks\":4}";
Files.writeString(file, invalid);
assertThrows(java.io.IOException.class, () -> ItemTrapConfig.load(file));
assertEquals(invalid, Files.readString(file));
assertThrows(IllegalArgumentException.class, () -> new ItemTrapConfig(Double.NaN, 0.1, 4));
}
}
@@ -0,0 +1,70 @@
package online.astradev.content.trap;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.core.Direction;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.junit.jupiter.api.Test;
class ItemTrapGeometryTest {
@Test
void liveGeometryEditRedrawsAStationaryExtendedTrap() {
var original = ItemTrapConfig.defaults();
var rotated = ItemTrapConfig.parse("{\"modelYaw\":-90}");
assertFalse(ItemTrapGeometry.needsRedraw(1, 1, original, original));
assertTrue(ItemTrapGeometry.needsRedraw(1, 1, original, rotated));
assertTrue(ItemTrapGeometry.needsRedraw(1, 0.5, original, original));
}
@Test
void shaftAndTipAlignWithAllSixDispenserFaces() {
for (Direction face :
new Direction[] {
Direction.UP,
Direction.DOWN,
Direction.NORTH,
Direction.SOUTH,
Direction.EAST,
Direction.WEST
}) {
// Include the rotation the actual Minecraft ItemDisplayRenderer appends. The old
// test inspected only the server matrix, so it passed while the item rendered sideways.
var direction = new Vector3f(face.getStepX(), face.getStepY(), face.getStepZ());
for (double length : new double[] {0.01, 0.25, 0.5, 0.75, 1}) {
var center = new Vector3f(direction).mul((float) ItemTrapGeometry.modelCenterOffset(length));
var transform = new Matrix4f().translation(center)
.mul(ItemTrapGeometry.model(face, length)).rotateY((float) Math.PI);
Vector3f tip = transform.transformPosition(new Vector3f(-0.5f, 0.5f, 0));
Vector3f tail = transform.transformPosition(new Vector3f(0.5f, -0.5f, 0));
assertEquals(0, tip.distance(new Vector3f(direction).mul((float) length)), 0.00001);
assertEquals(0, tail.distance(new Vector3f(direction).mul(-0.95f)), 0.00001);
assertTrue(tail.dot(direction) > -1, "Tail must not exit the back of the block");
}
}
}
@Test
void damageVolumeNeverExtendsBehindMouthOrBeyondTip() {
Vec3 mouth = new Vec3(3.5, 100, -4.5);
for (Direction face :
new Direction[] {
Direction.UP,
Direction.DOWN,
Direction.NORTH,
Direction.SOUTH,
Direction.EAST,
Direction.WEST
}) {
var dir = new Vec3(face.getStepX(), face.getStepY(), face.getStepZ());
var box = ItemTrapGeometry.bounds(mouth, dir, 1, 0.12);
assertTrue(box.contains(mouth.add(dir.scale(0.5))));
assertFalse(box.contains(mouth.add(dir.scale(-0.01))));
assertFalse(box.contains(mouth.add(dir.scale(1.01))));
Vec3 sideways = dir.x == 0 ? new Vec3(1, 0, 0) : new Vec3(0, 0, 1);
assertFalse(box.contains(mouth.add(dir).add(sideways.scale(0.13))));
}
}
}
@@ -0,0 +1,59 @@
package online.astradev.content.trap;
import static org.junit.jupiter.api.Assertions.*;
import com.google.gson.JsonParser;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import online.astradev.plus.api.editor.FileEditorDefinition;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ItemTrapSettingsTest {
@TempDir Path directory;
@Test
void publishesAuthoredTrapPolicyAndPreservesNativeFileExtensions() throws Exception {
var file = directory.resolve("astraspears.json");
Files.writeString(file, "{\"reach\":1,\"extension\":{\"keep\":true}}");
var settings = new ItemTrapSettings(file);
var live = (java.util.function.Supplier<ItemTrapConfig>) settings::current;
var before = settings.definition().snapshot();
var next = JsonParser.parseString(before.documentJson()).getAsJsonObject();
next.addProperty("reach", 2.5);
next.addProperty("damageMultiplier", 3);
next.addProperty("durabilityPerHit", 2);
next.addProperty("damagePlayers", false);
next.add("allowedSpears", JsonParser.parseString("[\"test:aloe\"]"));
settings.definition().save(next.toString(), before.revision());
assertEquals(2.5, live.get().reach(), "trap supplier immediately observes the authored policy");
assertEquals(3, live.get().damageMultiplier());
assertEquals(2, live.get().durabilityPerHit());
assertFalse(live.get().damagePlayers());
assertEquals(java.util.List.of("test:aloe"), live.get().allowedSpears());
assertTrue(JsonParser.parseString(Files.readString(file)).getAsJsonObject().getAsJsonObject("extension").get("keep").getAsBoolean());
var current = settings.current();
assertThrows(FileEditorDefinition.Conflict.class,
() -> settings.definition().save("{}", before.revision()));
next.addProperty("reach", -1);
assertThrows(RuntimeException.class,
() -> settings.definition().save(next.toString(), settings.definition().snapshot().revision()));
assertSame(current, settings.current());
assertEquals(2.5, ItemTrapConfig.load(file).reach());
}
@Test
void allNativeSettingsHaveTypedSchemaAndResourceDefaults() throws Exception {
var settings = new ItemTrapSettings(directory.resolve("new/astraspears.json"));
assertEquals(new ItemTrapConfig(1, .12, 4), settings.current());
var covered = new HashSet<String>();
for (var entry : JsonParser.parseString(ItemTrapSettings.schema()).getAsJsonObject().getAsJsonArray("fields")) {
var field = entry.getAsJsonObject();
assertTrue(field.has("default"));
assertTrue(covered.add(field.get("path").getAsString()));
}
for (var field : ItemTrapConfig.class.getRecordComponents()) assertTrue(covered.remove(field.getName()), field.getName());
assertTrue(covered.isEmpty());
}
}