diff --git a/README.md b/README.md index 962241d..5c338e8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# AstraContent 0.2.4 +# AstraContent 0.2.5 -Декларативный стартовый контент для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25. -Сборка дистрибутива AstraPlus включает эти определения и ресурсы; на сервере достаточно -двух JAR — AstraPlus и AstraPacks. Отдельный AstraContent JAR больше не нужен: его -оставшийся entrypoint является пустой совместимой оболочкой и ничего не регистрирует. +Контент для Minecraft 26.2, NeoForge 26.2.0.79 и Java 25. +AstraContent 0.2.5 владеет обработчиками дополнительных боеприпасов и их двумя mixin. +Требуется AstraPlus 0.9.11+; AstraPacks обслуживает ресурспак. Без AstraContent новый +AstraPlus не меняет боеприпасы арбалета и не запускает огненный заряд по ПКМ в воздух. На клиент мод устанавливать не нужно. Оформление передаётся обычным ресурспаком. ## Арбалет и огненный заряд @@ -121,10 +121,11 @@ Shift + ПКМ киркой по выбранному торцу снимает ## Установка и разработка -Устанавливается собранный дистрибутив AstraPlus вместе с AstraPacks; старый AstraContent -JAR архивируется при переходе на двухмодовую поставку. Модели, переводы и datapack-ресурсы -этого репозитория — входы воспроизводимой сборки дистрибутива, а не зависимости от -наличия AstraContent в запущенном сервере. Существующие ресурсы, настройки и миры не заменяются. +Устанавливаются AstraPlus 0.9.11+, AstraContent 0.2.5+ и AstraPacks. Прежний Content 0.2.4 +был пустой оболочкой: новую версию ядра нельзя устанавливать вместе с этой оболочкой, +загрузчик отклонит такую пару. Старые JAR следует архивировать, не оставляя дубликатов. +Модели, переводы и рельсы пока остаются входами сборки AstraPlus. Существующие ресурсы, +настройки и миры не заменяются. Это частичное, а не завершённое разделение всех механик. При выключенной стартовой сборке ресурспака выполнить `/astraplus build`. Восемь определений рельсов и рецепт находятся в `src/main/resources/content/astracontent`. @@ -139,11 +140,15 @@ JAR архивируется при переходе на двухмодовую Глобальные правила транспорта и боеприпасов находятся в `src/main/resources/content/policies`: `transport-defaults.json` и `projectile-defaults.json` — реальные настраиваемые политики, соответствующие `*-schema.json` — формы Studio. `*-compatibility.json` сохраняют прежние -ключи миров, идентичности и командные псевдонимы. Настройки публикуются в работающий -generic runtime AstraPlus сразу после проверенного сохранения; в этом репозитории больше -нет Java-реализаций конкретных механик. Движок предоставляет ограниченный набор типизированных -возможностей (нативные снаряды, сцепление вагонеток, отражение транспорта, регулирование -скорости); данные выбирают предметы, поверхности, условия и числовые параметры. +ключи миров, идентичности и командные псевдонимы. Боеприпасы исполняет Java-модуль этого +репозитория; транспорт пока исполняет AstraPlus. Сохранение `astracontent:projectiles` +в Studio проверяет и обновляет именно `config/astracontent-projectiles.json` и текущий +обработчик. При старте и перезапуске существующий файл сохраняется, некорректный файл +не заменяется значениями по умолчанию. Селектор пользовательских предметов использует +публичный `AstraPlusApi.identify`, а не внутренние классы ядра. + +Это настраиваемые правила, не полная реализация обработчика узлами. `_astra.logic` +остаётся дополнительным графом; перенос файлов между модулями этого ограничения не снимает. ```powershell .\gradlew.bat build @@ -153,7 +158,20 @@ generic runtime AstraPlus сразу после проверенного сох Для запуска серверных проверок нужны PowerShell 7 и соседние сборки AstraPlus/AstraPacks. Серверные проверки находятся в src/integrationTest, результаты — только в build. -Они проверяют оба движка вагонеток и сохранение после перезапуска на AstraPlus/AstraPacks -без runtime JAR AstraContent (дополнительно загружается только тестовый мод проверок). +Они проверяют боеприпасы, оба движка вагонеток и сохранение после перезапуска на +AstraPlus/AstraPacks/AstraContent с отдельным тестовым модом. Проверка отсутствия вмешательства +без AstraContent находится в `AstraPlus/src/integrationTest/.../ContentBoundarySmoke.java`. Перед ними нужно собрать соседний дистрибутив AstraPlus. Рабочие миры и конфигурации при проверках не используются. + +Отдельная проверка несовместимого обновления запускает AstraPlus 0.9.11 со старой +оболочкой AstraContent 0.2.4 и требует отказа загрузчика именно по диапазону версии, +до открытия мира. После обновления передайте сохранённый архивный JAR: + +```powershell +.\gradlew.bat compatibilityTest -PoldContentJar="C:/path/to/archive/AstraContent-0.2.4.jar" +``` + +`src/integrationTest/compatibility.ps1` ограничивает время запуска и завершает только +свой тестовый процесс. Библиотеки NeoForge и уже принятую владельцем EULA он читает +из `ServerRoot`, всё остальное создаёт в уникальной папке `build`. diff --git a/build.gradle.kts b/build.gradle.kts index 6e9e18b..ab48bc2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,12 +3,12 @@ plugins { id("net.neoforged.moddev") version "2.0.146" } group = "online.astradev" -version = "0.2.4" +version = "0.2.5" repositories { mavenCentral() } val astraPlusApi = providers.gradleProperty("astraPlusApi") - .orElse("../AstraPlus/build/libs/AstraPlus-0.9.9-api.jar") + .orElse("../AstraPlus/build/libs/AstraPlus-0.9.11-api.jar") val astraPlusRuntime = providers.gradleProperty("astraPlusRuntime") - .orElse("../AstraPlus/build/libs/AstraPlus-0.9.9.jar") + .orElse("../AstraPlus/build/libs/AstraPlus-0.9.11.jar") dependencies { compileOnly(files(astraPlusApi)) testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") @@ -61,3 +61,9 @@ tasks.register("integrationTest") { commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/run.ps1") if (providers.gradleProperty("experimental").isPresent) args("-Experimental") } + +tasks.register("compatibilityTest") { + commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/compatibility.ps1") + providers.gradleProperty("oldContentJar").orNull?.let { args("-OldContentJar", it) } + providers.gradleProperty("astraPlusRuntime").orNull?.let { args("-PlusJar", it) } +} diff --git a/src/integrationTest/compatibility.ps1 b/src/integrationTest/compatibility.ps1 new file mode 100644 index 0000000..9ceaff4 --- /dev/null +++ b/src/integrationTest/compatibility.ps1 @@ -0,0 +1,117 @@ +param( + [string]$ServerRoot = 'C:\Users\ScarPC\Documents\NeoForge Server 26.2', + [string]$PlusJar, + [string]$OldContentJar, + [ValidateRange(10, 180)][int]$TimeoutSeconds = 90 +) + +$ErrorActionPreference = 'Stop' +$project = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path +$runtime = (Resolve-Path -LiteralPath $ServerRoot).Path +$plusRoot = Join-Path (Split-Path $project -Parent) 'AstraPlus' +if (!$PlusJar) { $PlusJar = Join-Path $plusRoot 'build/libs/AstraPlus-0.9.11.jar' } +if (!$OldContentJar) { $OldContentJar = Join-Path $runtime 'mods/AstraContent-0.2.4.jar' } +$plus = (Get-Item -LiteralPath $PlusJar).FullName +$oldContent = (Get-Item -LiteralPath $OldContentJar).FullName +$acceptedEula = Join-Path $runtime 'eula.txt' +if (!(Test-Path -LiteralPath $acceptedEula) -or + !(Select-String -LiteralPath $acceptedEula -Pattern '^eula=true\s*$' -Quiet)) { + throw 'The server owner must have accepted the Minecraft EULA before this test can run.' +} + +# Refuse misleading inputs: this regression is specifically about the old shell mod. +Add-Type -AssemblyName System.IO.Compression.FileSystem +function Assert-ModVersion([string]$Path, [string]$Id, [string]$Version) { + $archive = [IO.Compression.ZipFile]::OpenRead($Path) + try { + $entry = $archive.GetEntry('META-INF/neoforge.mods.toml') + if (!$entry) { throw "Missing mod metadata: $Path" } + $reader = [IO.StreamReader]::new($entry.Open()) + try { $metadata = $reader.ReadToEnd() } finally { $reader.Dispose() } + $pattern = '(?ms)^\[\[mods\]\]\s*modId\s*=\s*"' + [regex]::Escape($Id) + + '"\s*version\s*=\s*"' + [regex]::Escape($Version) + '"' + if ($metadata -notmatch $pattern) { throw "Expected $Id $Version in $Path" } + } finally { $archive.Dispose() } +} +Assert-ModVersion $plus 'astraplus' '0.9.11' +Assert-ModVersion $oldContent 'astracontent' '0.2.4' + +$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 +Copy-Item -LiteralPath $acceptedEula -Destination "$output/eula.txt" +Copy-Item -LiteralPath $plus, $oldContent -Destination "$output/mods" +$libraryRoot = $runtime.Replace('\', '/') +$argsFile = Join-Path $runtime 'libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt' +$lines = (Get-Content -Raw -LiteralPath $argsFile).Replace('libraries/', "$libraryRoot/libraries/") -split "`r?`n" +for ($i = 0; $i -lt $lines.Length; $i++) { + if ($lines[$i].StartsWith('-DlibraryDirectory=')) { $lines[$i] = '"-DlibraryDirectory=' + $libraryRoot + '/libraries"' } + if ($i -gt 0 -and $lines[$i - 1] -eq '-classpath') { $lines[$i] = '"' + $lines[$i] + '"' } +} +$lines | Set-Content -LiteralPath "$output/server-args.txt" +# No fixed ports: even a regression must not collide with another test or the live server. +@' +server-ip=127.0.0.1 +server-port=0 +online-mode=false +level-name=compatibility-world +enable-query=false +enable-rcon=false +max-tick-time=30000 +'@ | Set-Content -LiteralPath "$output/server.properties" +'{"build":{"onStartup":false},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | + Set-Content -LiteralPath "$output/config/astraplus.json" + +$java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java -CommandType Application | Select-Object -First 1).Source } +$start = [Diagnostics.ProcessStartInfo]::new() +$start.FileName = $java +$start.WorkingDirectory = $output +$start.UseShellExecute = $false +$start.CreateNoWindow = $true +$start.RedirectStandardOutput = $true +$start.RedirectStandardError = $true +foreach ($argument in @('-Xmx1G', '@server-args.txt', 'nogui')) { $start.ArgumentList.Add($argument) } +$process = [Diagnostics.Process]::new() +$process.StartInfo = $start +$started = $false +try { + $started = $process.Start() + if (!$started) { throw 'Failed to start the isolated compatibility-test JVM.' } + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + $timer = [Diagnostics.Stopwatch]::StartNew() + while (!$process.WaitForExit(1000)) { + if ($timer.Elapsed.TotalSeconds -ge $TimeoutSeconds) { + $process.Kill($true) + $process.WaitForExit() + $stdout.GetAwaiter().GetResult() | Set-Content -LiteralPath "$output/stdout.log" + $stderr.GetAwaiter().GetResult() | Set-Content -LiteralPath "$output/stderr.log" + throw "Timed out after ${TimeoutSeconds}s; stopped only the test JVM. Evidence: $output" + } + } + $exitCode = $process.ExitCode + $outText = $stdout.GetAwaiter().GetResult() + $errText = $stderr.GetAwaiter().GetResult() + $outText | Set-Content -LiteralPath "$output/stdout.log" + $errText | Set-Content -LiteralPath "$output/stderr.log" + $log = $outText + "`n" + $errText + if ($exitCode -eq 0) { throw "Incompatible mods unexpectedly exited successfully. Evidence: $output" } + $dependencyError = "(?s)Mod ID: 'astracontent', Requested by: 'astraplus', Expected range: '\[0\.2\.5,\)', Actual version: '0\.2\.4'" + $translatedError = '(?is)Mod astraplus only supports astracontent 0\.2\.5 or above\s*Currently,? astracontent is 0\.2\.4' + if ($log -notmatch $dependencyError -and $log -notmatch $translatedError) { + throw "Failure was not the expected AstraPlus -> AstraContent [0.2.5,) / actual 0.2.4 dependency rejection. Evidence: $output" + } + if ((Test-Path -LiteralPath "$output/compatibility-world") -or (Test-Path -LiteralPath "$output/world") -or + $log -match 'Preparing level|Preparing start region|Done \([\d.,]+s\)!') { + throw "Loader opened a world despite incompatible mods. Evidence: $output" + } + $result = "PASS compatibility: AstraPlus 0.9.11 rejects AstraContent 0.2.4 for [0.2.5,), exit=$exitCode, no world opened" + $result | Set-Content -LiteralPath "$output/verification-result.txt" + Write-Output $result + Write-Output "Evidence: $output" +} finally { + if ($started -and !$process.HasExited) { + $process.Kill($true) + $process.WaitForExit() + } + $process.Dispose() +} diff --git a/src/integrationTest/java/online/astradev/content/verification/ContentVerification.java b/src/integrationTest/java/online/astradev/content/verification/ContentVerification.java index d7464dd..539c99c 100644 --- a/src/integrationTest/java/online/astradev/content/verification/ContentVerification.java +++ b/src/integrationTest/java/online/astradev/content/verification/ContentVerification.java @@ -19,11 +19,8 @@ import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.*; import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.projectile.FireworkRocketEntity; -import net.minecraft.world.entity.projectile.arrow.AbstractArrow; import net.minecraft.world.entity.vehicle.minecart.*; import net.minecraft.world.item.*; -import net.minecraft.world.item.component.ChargedProjectiles; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.properties.RailShape; @@ -72,6 +69,7 @@ public final class ContentVerification { AbstractMinecart.useExperimentalMovement(level) == Boolean.getBoolean("astracontent.expectedExperimental"), "requested movement engine enabled"); + ProjectileVerification.run(level); if (Files.exists(Path.of("first-pass.txt"))) { DeclarativeRailVerification.restart(level); var migrated = new BlockPos(10, 100, 90); @@ -110,7 +108,6 @@ public final class ContentVerification { setup(level); bundledResources(); packResponses(level); - ammunition(level); } if (ticks == 129) for (int age = 0; age < 4; age++) previousX[age] = carts.get(age).getX(); @@ -468,92 +465,6 @@ public final class ContentVerification { require(RailSpeed.signal(level, rail) == 11, "maximum of two inputs"); } - private void ammunition(ServerLevel level) { - var player = FakePlayerFactory.getMinecraft(level); - player.setPos(40, 115, 35); - var crossbow = (CrossbowItem) Items.CROSSBOW; - var supported = - List.of( - Items.ENDER_PEARL, - Items.FIRE_CHARGE, - Items.ENDER_EYE, - Items.EGG, - Items.BLUE_EGG, - Items.BROWN_EGG, - Items.SNOWBALL, - Items.WIND_CHARGE, - Items.EXPERIENCE_BOTTLE, - Items.TNT); - for (var ammo : supported) { - var weapon = new ItemStack(Items.CROSSBOW); - var stack = new ItemStack(ammo, 2); - player.setItemInHand(InteractionHand.MAIN_HAND, weapon); - player.setItemInHand(InteractionHand.OFF_HAND, stack); - require(crossbow.getSupportedHeldProjectiles().test(stack), "held ammunition " + ammo); - require( - crossbow.getAllSupportedProjectiles().test(stack), - "inventory ammunition " + ammo); - require( - crossbow.use(level, player, InteractionHand.MAIN_HAND).consumesAction(), - "start loading " + ammo); - crossbow.onUseTick( - level, player, weapon, 72000 - CrossbowItem.getChargeDuration(weapon, player)); - require(CrossbowItem.isCharged(weapon), "loaded " + ammo); - require(stack.getCount() == 1, "one ammo consumed " + ammo); - crossbow.performShooting( - level, player, InteractionHand.MAIN_HAND, weapon, 3.15f, 0, null); - require(!CrossbowItem.isCharged(weapon), "unloaded after shot " + ammo); - require(weapon.getDamageValue() == 1, "durability " + ammo); - player.stopUsingItem(); - } - for (var ammo : List.of(Items.ARROW, Items.FIREWORK_ROCKET)) { - var weapon = new ItemStack(Items.CROSSBOW); - weapon.set( - DataComponents.CHARGED_PROJECTILES, - ChargedProjectiles.ofNonEmpty(List.of(new ItemStack(ammo)))); - crossbow.performShooting( - level, player, InteractionHand.MAIN_HAND, weapon, 3.15f, 0, null); - } - require( - !level.getEntitiesOfClass( - AbstractArrow.class, new AABB(player.blockPosition()).inflate(8)) - .isEmpty(), - "vanilla arrows remain arrows"); - require( - !level.getEntitiesOfClass( - FireworkRocketEntity.class, - new AABB(player.blockPosition()).inflate(8)) - .isEmpty(), - "vanilla fireworks remain fireworks"); - var multi = new ItemStack(Items.CROSSBOW); - multi.enchant( - level.registryAccess() - .lookupOrThrow(net.minecraft.core.registries.Registries.ENCHANTMENT) - .getOrThrow(net.minecraft.world.item.enchantment.Enchantments.MULTISHOT), - 1); - player.setItemInHand(InteractionHand.MAIN_HAND, multi); - player.setItemInHand(InteractionHand.OFF_HAND, new ItemStack(Items.SNOWBALL, 2)); - crossbow.use(level, player, InteractionHand.MAIN_HAND); - crossbow.onUseTick( - level, player, multi, 72000 - CrossbowItem.getChargeDuration(multi, player)); - require( - multi.get(DataComponents.CHARGED_PROJECTILES).itemCopies().size() == 3, - "multishot loads three snowballs"); - require(player.getOffhandItem().getCount() == 1, "multishot consumes one ammo"); - player.stopUsingItem(); - player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.FIRE_CHARGE, 2)); - NeoForge.EVENT_BUS.post( - new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem( - player, InteractionHand.MAIN_HAND)); - require(player.getMainHandItem().getCount() == 1, "right click fire charge consumes one"); - NeoForge.EVENT_BUS.post( - new net.neoforged.neoforge.event.entity.player.PlayerInteractEvent.RightClickItem( - player, InteractionHand.MAIN_HAND)); - require( - player.getMainHandItem().getCount() == 1, - "fire charge cooldown prevents second shot"); - } - private void finish(net.minecraft.server.MinecraftServer server, String text) throws Exception { Files.writeString(Path.of("verification-result.txt"), text); System.out.println(text); diff --git a/src/integrationTest/java/online/astradev/content/verification/ProjectileVerification.java b/src/integrationTest/java/online/astradev/content/verification/ProjectileVerification.java new file mode 100644 index 0000000..8ac6483 --- /dev/null +++ b/src/integrationTest/java/online/astradev/content/verification/ProjectileVerification.java @@ -0,0 +1,271 @@ +package online.astradev.content.verification; + +import com.google.gson.JsonArray; +import com.google.gson.JsonParser; +import com.mojang.authlib.GameProfile; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.entity.projectile.FireworkRocketEntity; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.projectile.arrow.AbstractArrow; +import net.minecraft.world.entity.projectile.hurtingprojectile.SmallFireball; +import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge; +import net.minecraft.world.entity.projectile.throwableitemprojectile.Snowball; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEgg; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnderpearl; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownExperienceBottle; +import net.minecraft.world.item.CrossbowItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.GameType; +import net.minecraft.world.phys.AABB; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.util.FakePlayerFactory; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import online.astradev.plus.api.editor.EditorDefinitions; +import online.astradev.plus.api.AstraPlusApi; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +/** Drives native items and the public editor provider, never AstraPlus implementation classes. */ +final class ProjectileVerification { + private static final CrossbowItem CROSSBOW = (CrossbowItem) Items.CROSSBOW; + private static final String POLICY = "astracontent:projectiles"; + + static void run(ServerLevel level) throws Exception { + var player = FakePlayerFactory.get(level, + new GameProfile(UUID.fromString("8680f9bf-2328-42c2-9e90-1b6616aa6c1e"), "ProjectileVerify")); + player.gameMode.changeGameModeForPlayer(GameType.SURVIVAL); + player.setPos(40, 115, 35); + var provider = EditorDefinitions.find(POLICY).orElseThrow(); + var original = provider.snapshot(); + try { + defaultAmmunition(level, player); + vanillaAmmunition(level, player); + multishot(level, player); + protectedAndNormalUse(level, player); + + var modified = JsonParser.parseString(original.documentJson()).getAsJsonObject(); + var rules = new JsonArray(); + rules.add(JsonParser.parseString(""" + {"selector":{"item":"minecraft:snowball"},"kind":"EGG","crossbow":true} + """)); + rules.add(JsonParser.parseString(""" + {"selector":{"customId":"astracontent:copper_rail"},"kind":"SNOWBALL","crossbow":true} + """)); + rules.addAll(modified.getAsJsonArray("rules")); + modified.add("rules", rules); + for (var value : rules) { + var rule = value.getAsJsonObject(); + if (rule.get("kind").getAsString().equals("TNT_PAYLOAD")) { + rule.getAsJsonObject("parameters").addProperty("fuseTicks", 37); + rule.getAsJsonObject("parameters").addProperty("velocityScale", .5); + } + } + provider.save(modified.toString(), original.revision()); + var reconfigured = loadAndShoot(level, player, Items.SNOWBALL); + require(reconfigured instanceof ThrownEgg, "First matching edited rule wins immediately"); + reconfigured.discard(); + tntPayload(level, player, loadAndShoot(level, player, Items.TNT), 37, .5); + customIdentity(level, player); + + var active = provider.snapshot(); + boolean rejected = false; + try { provider.save("{\"rules\":[{\"selector\":{\"item\":\"minecraft:snowball\"},\"kind\":\"INVALID\"}]}", active.revision()); } + catch (IllegalArgumentException expected) { rejected = true; } + require(rejected && provider.snapshot().equals(active), "Invalid policy preserves the active revision"); + var preserved = loadAndShoot(level, player, Items.SNOWBALL); + require(preserved instanceof ThrownEgg, "Rejected save leaves the live rule active"); + preserved.discard(); + + provider.save("{\"rules\":[]}", provider.snapshot().revision()); + for (var ammo : List.of(Items.SNOWBALL, Items.FIRE_CHARGE, Items.TNT)) { + var stack = new ItemStack(ammo); + require(!CROSSBOW.getSupportedHeldProjectiles().test(stack), "Disabled held ammo " + ammo); + require(!CROSSBOW.getAllSupportedProjectiles().test(stack), "Disabled inventory ammo " + ammo); + } + var before = ids(level, player); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.FIRE_CHARGE, 2)); + player.getCooldowns().removeCooldown(Items.FIRE_CHARGE.builtInRegistryHolder().key().identifier()); + var disabled = new PlayerInteractEvent.RightClickItem(player, InteractionHand.MAIN_HAND); + NeoForge.EVENT_BUS.post(disabled); + require(!disabled.isCanceled() && player.getMainHandItem().getCount() == 2, "Disabled right-click leaves vanilla interaction and stack untouched"); + require(ids(level, player).equals(before), "Disabled rule launches no projectile"); + vanillaAmmunition(level, player); + } finally { + provider.save(original.documentJson(), provider.snapshot().revision()); + player.stopUsingItem(); + } + var restored = loadAndShoot(level, player, Items.SNOWBALL); + require(restored instanceof Snowball && !(restored instanceof ThrownEgg), "Restoring saved policy restores real vanilla snowball launch"); + restored.discard(); + player.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY); + player.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); + System.out.println("PASS projectile content: native ammo, payloads, multishot, protected use, live rule precedence, checked custom identity, invalid-save preservation, disable/restore and vanilla fallback"); + } + + private static void defaultAmmunition(ServerLevel level, ServerPlayer player) { + var types = Map.>of( + Items.ENDER_PEARL, ThrownEnderpearl.class, Items.FIRE_CHARGE, SmallFireball.class, + Items.EGG, ThrownEgg.class, Items.BLUE_EGG, ThrownEgg.class, Items.BROWN_EGG, ThrownEgg.class, + Items.SNOWBALL, Snowball.class, Items.WIND_CHARGE, WindCharge.class, + Items.EXPERIENCE_BOTTLE, ThrownExperienceBottle.class); + types.forEach((item, type) -> { + var shot = loadAndShoot(level, player, item); + require(type.isInstance(shot), "Native projectile type for " + item); + require(shot.getOwner() == player && shot.getDeltaMovement().length() > 1, "Projectile owns its native shooter and launch velocity"); + shot.discard(); + }); + tntPayload(level, player, loadAndShoot(level, player, Items.TNT), 80, 1); + var eyePayload = loadAndShoot(level, player, Items.ENDER_EYE); + var oldDrops = level.getEntitiesOfClass(ItemEntity.class, area(player)).stream().map(Entity::getUUID).collect(Collectors.toSet()); + eyePayload.tick(); + require(eyePayload.isRemoved(), "Eye carrier replaces itself on its first tick"); + var drops = level.getEntitiesOfClass(ItemEntity.class, area(player)).stream() + .filter(item -> !oldDrops.contains(item.getUUID())).toList(); + require(drops.size() == 1 && drops.getFirst().getItem().is(Items.ENDER_EYE) + && drops.getFirst().getItem().getCount() == 1, "No-structure world returns exactly one physical eye payload"); + drops.forEach(Entity::discard); + } + + private static void tntPayload(ServerLevel level, ServerPlayer player, Projectile carrier, int fuse, double scale) { + var velocity = carrier.getDeltaMovement().scale(scale); + var old = level.getEntitiesOfClass(PrimedTnt.class, area(player)).stream().map(Entity::getUUID).collect(Collectors.toSet()); + carrier.tick(); + var payloads = level.getEntitiesOfClass(PrimedTnt.class, area(player)).stream() + .filter(tnt -> !old.contains(tnt.getUUID())).toList(); + require(carrier.isRemoved() && payloads.size() == 1, "TNT carrier becomes exactly one native payload"); + var tnt = payloads.getFirst(); + require(tnt.getFuse() == fuse && tnt.getOwner() == player, "TNT policy fuse and shooter survive launch"); + require(tnt.getDeltaMovement().distanceToSqr(velocity) < 1e-9, "TNT policy controls transferred velocity"); + tnt.discard(); + } + + private static Projectile loadAndShoot(ServerLevel level, ServerPlayer player, Item ammo) { + return loadAndShoot(level, player, new ItemStack(ammo, 2)); + } + + private static Projectile loadAndShoot(ServerLevel level, ServerPlayer player, ItemStack stack) { + var ammo = stack.getItem(); + var weapon = new ItemStack(Items.CROSSBOW); + player.setItemInHand(InteractionHand.MAIN_HAND, weapon); + player.setItemInHand(InteractionHand.OFF_HAND, stack); + require(CROSSBOW.getSupportedHeldProjectiles().test(stack), "Held ammunition " + ammo); + require(CROSSBOW.getAllSupportedProjectiles().test(stack) == (ammo != Items.FIREWORK_ROCKET), + "Inventory ammunition preserves the vanilla held-only firework rule: " + ammo); + load(level, player, weapon); + require(stack.getCount() == 1, "Native loading consumes one ammo " + ammo); + var before = ids(level, player); + CROSSBOW.performShooting(level, player, InteractionHand.MAIN_HAND, weapon, 3.15f, 0, null); + var created = fresh(level, player, before); + require(created.size() == 1, "Exactly one native launch for " + ammo); + require(!CrossbowItem.isCharged(weapon), "Crossbow clears the charged payload " + ammo); + require(weapon.getDamageValue() == (ammo == Items.FIREWORK_ROCKET ? 3 : 1), "Native weapon durability for " + ammo); + return created.getFirst(); + } + + private static void customIdentity(ServerLevel level, ServerPlayer player) { + var api = AstraPlusApi.current().orElseThrow(); + var custom = api.create(Identifier.parse("astracontent:copper_rail"), 2); + require(!custom.isEmpty(), "Existing authored custom item is available through the public API"); + require(!CROSSBOW.getSupportedHeldProjectiles().test(new ItemStack(custom.getItem())), + "Custom selector does not capture the ordinary carrier item"); + var spoofed = new ItemStack(custom.is(Items.DIRT) ? Items.STONE : Items.DIRT); + spoofed.set(DataComponents.CUSTOM_DATA, custom.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY)); + require(!CROSSBOW.getSupportedHeldProjectiles().test(spoofed), "Copied ID on an unrelated carrier cannot select a custom rule"); + var unknown = custom.copy(); + CustomData.update(DataComponents.CUSTOM_DATA, unknown, tag -> tag.putString("astraplus:id", "verification:missing")); + require(!CROSSBOW.getSupportedHeldProjectiles().test(unknown), "Unregistered custom identity cannot select a rule"); + var shot = loadAndShoot(level, player, custom); + require(shot instanceof Snowball, "Custom rule launches its configured native projectile via the public API"); + shot.discard(); + } + + private static void load(ServerLevel level, ServerPlayer player, ItemStack weapon) { + require(CROSSBOW.use(level, player, InteractionHand.MAIN_HAND).consumesAction(), "Native crossbow starts loading"); + CROSSBOW.onUseTick(level, player, weapon, 72000 - CrossbowItem.getChargeDuration(weapon, player)); + require(CrossbowItem.isCharged(weapon), "Native crossbow loads"); + player.stopUsingItem(); + } + + private static void vanillaAmmunition(ServerLevel level, ServerPlayer player) { + var arrow = loadAndShoot(level, player, Items.ARROW); + require(arrow instanceof AbstractArrow, "Ordinary vanilla ammunition remains a native arrow"); + arrow.discard(); + var firework = loadAndShoot(level, player, Items.FIREWORK_ROCKET); + require(firework instanceof FireworkRocketEntity, "Ordinary fireworks retain vanilla factory behavior"); + firework.discard(); + require(!CROSSBOW.getSupportedHeldProjectiles().test(new ItemStack(Items.DIRT)), "Unconfigured ordinary items do not become ammo"); + } + + private static void multishot(ServerLevel level, ServerPlayer player) { + var weapon = new ItemStack(Items.CROSSBOW); + weapon.enchant(level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).getOrThrow(Enchantments.MULTISHOT), 1); + player.setItemInHand(InteractionHand.MAIN_HAND, weapon); + player.setItemInHand(InteractionHand.OFF_HAND, new ItemStack(Items.SNOWBALL, 2)); + load(level, player, weapon); + require(weapon.get(DataComponents.CHARGED_PROJECTILES).itemCopies().size() == 3, "Multishot loads three snowballs"); + require(player.getOffhandItem().getCount() == 1, "Multishot consumes only one ammo"); + var before = ids(level, player); + CROSSBOW.performShooting(level, player, InteractionHand.MAIN_HAND, weapon, 3.15f, 0, null); + var shots = fresh(level, player, before); + require(shots.size() == 3 && shots.stream().allMatch(Snowball.class::isInstance), "Native multishot creates three actual snowballs"); + shots.forEach(Entity::discard); + } + + private static void protectedAndNormalUse(ServerLevel level, ServerPlayer player) { + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.FIRE_CHARGE, 2)); + var gate = new DenyUse(player); + var before = ids(level, player); + NeoForge.EVENT_BUS.register(gate); + try { + var denied = new PlayerInteractEvent.RightClickItem(player, InteractionHand.MAIN_HAND); + NeoForge.EVENT_BUS.post(denied); + require(denied.isCanceled() && player.getMainHandItem().getCount() == 2, "Earlier protection keeps the original ammo"); + require(ids(level, player).equals(before), "Earlier protection prevents projectile creation"); + } finally { NeoForge.EVENT_BUS.unregister(gate); } + var accepted = new PlayerInteractEvent.RightClickItem(player, InteractionHand.MAIN_HAND); + NeoForge.EVENT_BUS.post(accepted); + var shots = fresh(level, player, before); + require(accepted.isCanceled() && player.getMainHandItem().getCount() == 1, "Configured right click consumes one fire charge"); + require(shots.size() == 1 && shots.getFirst() instanceof SmallFireball, "Configured right click launches a native fireball"); + shots.forEach(Entity::discard); + before = ids(level, player); + NeoForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickItem(player, InteractionHand.MAIN_HAND)); + require(player.getMainHandItem().getCount() == 1 && ids(level, player).equals(before), "Cooldown blocks a second launch and second debit"); + } + + public static final class DenyUse { + private final ServerPlayer player; + DenyUse(ServerPlayer player) { this.player = player; } + @SubscribeEvent(priority = EventPriority.HIGHEST) + public void deny(PlayerInteractEvent.RightClickItem event) { + if (event.getEntity() == player) event.setCanceled(true); + } + } + + private static AABB area(ServerPlayer player) { return new AABB(player.blockPosition()).inflate(8); } + private static Set ids(ServerLevel level, ServerPlayer player) { + return level.getEntitiesOfClass(Projectile.class, area(player)).stream().map(Entity::getUUID).collect(Collectors.toSet()); + } + private static List fresh(ServerLevel level, ServerPlayer player, Set before) { + return level.getEntitiesOfClass(Projectile.class, area(player)).stream().filter(shot -> !before.contains(shot.getUUID())).toList(); + } + private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); } +} diff --git a/src/integrationTest/java/online/astradev/content/verification/StarterBundleVerification.java b/src/integrationTest/java/online/astradev/content/verification/StarterBundleVerification.java index 67ae688..56954b1 100644 --- a/src/integrationTest/java/online/astradev/content/verification/StarterBundleVerification.java +++ b/src/integrationTest/java/online/astradev/content/verification/StarterBundleVerification.java @@ -3,7 +3,7 @@ package online.astradev.content.verification; import com.google.gson.JsonParser; import net.neoforged.fml.ModList; import net.neoforged.fml.loading.FMLPaths; -import online.astradev.plus.AstraPlus; +import online.astradev.plus.api.AstraPlusApi; import online.astradev.plus.api.editor.EditorDefinitions; import online.astradev.plus.api.snapshot.SnapshotKind; import online.astradev.plus.api.snapshot.SnapshotSource; @@ -14,21 +14,24 @@ import java.util.Map; import java.util.HashSet; import java.util.stream.Collectors; -/** Runs before gameplay on a fresh distribution; no concrete content mod may be loaded. */ +/** Runs before gameplay with core declarations plus the separately owned projectile content mod. */ final class StarterBundleVerification { static void run() throws Exception { - for (String forbidden : new String[]{"astracontent", "astracauldron", "astraspears"}) + for (String forbidden : new String[]{"astracauldron", "astraspears"}) require(!ModList.get().isLoaded(forbidden), "Concrete mod is not required: " + forbidden); require(ModList.get().isLoaded("astraplus") && ModList.get().isLoaded("astrapacks"), "Two distribution mods loaded"); + require(ModList.get().isLoaded("astracontent"), "Projectile verification loads its real content owner JAR"); var kindMap = Map.of("items", SnapshotKind.ITEM, "blocks", SnapshotKind.BLOCK, "mobs", SnapshotKind.MOB, "skills", SnapshotKind.SKILL, "recipes", SnapshotKind.RECIPE, - "enchantments", SnapshotKind.ENCHANTMENT); + "enchantments", SnapshotKind.ENCHANTMENT, "effects", SnapshotKind.EFFECT, + "mechanics", SnapshotKind.MECHANIC); var documents = Game.snapshot().documents().stream().collect(Collectors.toMap( document -> document.kind() + ":" + document.id(), document -> document)); int installed = 0, editable = 0, modelFiles = 0; - try (var source = AstraPlus.class.getResourceAsStream("/astra-starter/index.json")) { + try (var source = AstraPlusApi.class.getResourceAsStream("/astra-starter/index.json")) { require(source != null, "Distribution embeds a starter manifest"); var manifest = JsonParser.parseString(new String(source.readAllBytes(), StandardCharsets.UTF_8)).getAsJsonObject(); + var expectedProviders = new HashSet(); for (var entry : manifest.getAsJsonArray("files")) { String target = entry.getAsString(); require(Files.isRegularFile(FMLPaths.GAMEDIR.get().resolve(target)), "Bundle target installed: " + target); @@ -39,12 +42,13 @@ final class StarterBundleVerification { var kind = kindMap.get(pieces[3]); require(kind != null, "Every installed content declaration has an editable runtime: " + target); String id = pieces[2] + ":" + pieces[4].substring(0, pieces[4].length() - 5); + if (kind == SnapshotKind.MECHANIC) expectedProviders.add(id); var document = documents.get(kind + ":" + id); require(document != null, "Authored declaration is visible: " + kind + " " + id); require(document.source() == SnapshotSource.FILE && !document.readOnly(), "Authored declaration is editable FILE: " + id); editable++; } - var expectedProviders = new HashSet(); + require(manifest.getAsJsonArray("capabilities").size() == 4, "Four remaining core capability policies"); for (var value : manifest.getAsJsonArray("capabilities")) { var policy = value.getAsJsonObject(); String id = policy.get("id").getAsString(); @@ -53,14 +57,18 @@ final class StarterBundleVerification { var document = documents.get(SnapshotKind.MECHANIC + ":" + id); require(document != null && document.source() == SnapshotSource.FILE && !document.readOnly(), "Live FILE policy is editable: " + id); } - require(expectedProviders.size() == 5, "Five declared capability policies"); + require(!expectedProviders.contains("astracontent:projectiles"), "Core starter no longer owns projectile policy"); require(expectedProviders.contains("astraplus:villager_appearance"), "Native villager appearance is editable policy data"); + expectedProviders.add("astracontent:projectiles"); + var projectile = documents.get(SnapshotKind.MECHANIC + ":astracontent:projectiles"); + require(projectile != null && projectile.source() == SnapshotSource.FILE && !projectile.readOnly(), "Content-owned projectile policy stays editable through the public snapshot"); + require(Files.isRegularFile(FMLPaths.GAMEDIR.get().resolve("config/astracontent-projectiles.json")), "Content-owned projectile FILE is installed"); require(EditorDefinitions.all().stream().map(value -> value.id()).collect(Collectors.toSet()).equals(expectedProviders), "Only the declared live providers are installed"); } - require(installed == 288 && editable == installed, "Exact authored editable content file count: " + installed); - require(modelFiles == 141 && AstraPlus.models().catalog().ids().size() == 141, "All 141 models load without content JARs"); - System.out.println("PASS bare distribution: contentFiles=" + installed + " editableCatalog=" + editable - + " models=" + modelFiles + " mechanics=5; concreteRuntimeMods=0"); + 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"); + System.out.println("PASS modular distribution: contentFiles=" + installed + " editableCatalog=" + editable + + " models=" + modelFiles + " coreMechanics=4; contentProjectileMechanics=1"); } private static void require(boolean condition, String message) { if (!condition) throw new AssertionError(message); } diff --git a/src/integrationTest/run.ps1 b/src/integrationTest/run.ps1 index 466201b..12c8589 100644 --- a/src/integrationTest/run.ps1 +++ b/src/integrationTest/run.ps1 @@ -12,7 +12,11 @@ for($i=0;$i -lt $lines.Length;$i++) { if($i -gt 0 -and $lines[$i-1] -eq '-classpath'){$lines[$i]='"'+$lines[$i]+'"'} } $lines | Set-Content "$output/server-args.txt" -'eula=true' | Set-Content "$output/eula.txt" +$acceptedEula=Join-Path $runtime 'eula.txt' +if (!(Test-Path -LiteralPath $acceptedEula) -or !(Select-String -LiteralPath $acceptedEula -Pattern '^eula=true\s*$' -Quiet)) { + throw 'The server owner must have accepted the Minecraft EULA before integration tests can run.' +} +Copy-Item -LiteralPath $acceptedEula -Destination "$output/eula.txt" @' server-ip=127.0.0.1 server-port=26783 @@ -36,7 +40,7 @@ $packsVersion=[regex]::Match((Get-Content "$packsRoot/build.gradle.kts" -Raw), ' Copy-Item -LiteralPath "$packsRoot/build/libs/AstraPacks-$packsVersion.jar" -Destination "$output/mods" '{"enabled":false}' | Set-Content "$output/config/astrapacks.json" $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-integration-tests.jar" -Destination "$output/mods" +Copy-Item -LiteralPath $plus.FullName,"$project/build/libs/AstraContent-$contentVersion.jar","$project/build/libs/AstraContent-$contentVersion-integration-tests.jar" -Destination "$output/mods" Push-Location $output try { foreach($pass in @('gameplay','restart')) { diff --git a/src/main/java/online/astradev/content/AstraContent.java b/src/main/java/online/astradev/content/AstraContent.java index bd1cfa9..ecf75ee 100644 --- a/src/main/java/online/astradev/content/AstraContent.java +++ b/src/main/java/online/astradev/content/AstraContent.java @@ -1,11 +1,86 @@ package online.astradev.content; +import com.google.gson.JsonParser; + import net.neoforged.api.distmarker.Dist; import net.neoforged.fml.common.Mod; +import net.neoforged.fml.loading.FMLPaths; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.server.ServerStartingEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; +import net.neoforged.neoforge.event.server.ServerStoppingEvent; + +import online.astradev.content.projectile.ProjectileCapabilities; +import online.astradev.plus.api.AstraPlusApi; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; @Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER) public final class AstraContent { + private static final String POLICY_RESOURCES = "/content/policies/projectile-"; + private static final int POLICY_RESOURCE_LIMIT = 512 * 1024; + + private ProjectileCapabilities projectiles; + public AstraContent() { - // Compatibility shell. AstraPlus' assembled starter pack owns declarations and runtime. + NeoForge.EVENT_BUS.addListener(this::start); + NeoForge.EVENT_BUS.addListener(this::stopping); + NeoForge.EVENT_BUS.addListener(this::stopped); + } + + private void start(ServerStartingEvent event) { + if (projectiles != null) throw new IllegalStateException("AstraContent already started"); + // AstraPlus publishes its API during ServerAboutToStartEvent. The FILE definition must + // be registered before ServerStartedEvent exposes the administrator editor. + if (AstraPlusApi.current().isEmpty()) { + throw new IllegalStateException("AstraContent requires the running AstraPlus API"); + } + try { + projectiles = startProjectiles(FMLPaths.GAMEDIR.get()); + projectiles.register(NeoForge.EVENT_BUS); + } catch (IOException | RuntimeException failure) { + close(); + throw new IllegalStateException("Cannot initialize AstraContent projectile policy", failure); + } + } + + static ProjectileCapabilities startProjectiles(Path gameDirectory) throws IOException { + // Keep the existing identity, location and compatibility tags. Packaged documents seed + // missing files only; an administrator's configuration remains authoritative on upgrade. + return ProjectileCapabilities.start( + gameDirectory.resolve("config/astracontent-projectiles.json"), + "astracontent:projectiles", + "Боеприпасы", + resource("defaults"), + resource("schema"), + JsonParser.parseString(resource("compatibility")).getAsJsonObject()); + } + + private static String resource(String kind) throws IOException { + String path = POLICY_RESOURCES + kind + ".json"; + try (var stream = AstraContent.class.getResourceAsStream(path)) { + if (stream == null) throw new IOException("Missing AstraContent policy resource: " + path); + byte[] bytes = stream.readNBytes(POLICY_RESOURCE_LIMIT + 1); + if (bytes.length > POLICY_RESOURCE_LIMIT) { + throw new IOException("AstraContent policy resource exceeds 512 KiB: " + path); + } + return new String(bytes, StandardCharsets.UTF_8); + } + } + + private void stopping(ServerStoppingEvent event) { + close(); + } + + private void stopped(ServerStoppedEvent event) { + close(); + } + + private void close() { + if (projectiles == null) return; + projectiles.close(); + projectiles = null; } } diff --git a/src/main/java/online/astradev/content/mixin/ProjectilePayloadMixin.java b/src/main/java/online/astradev/content/mixin/ProjectilePayloadMixin.java new file mode 100644 index 0000000..37e0192 --- /dev/null +++ b/src/main/java/online/astradev/content/mixin/ProjectilePayloadMixin.java @@ -0,0 +1,24 @@ +package online.astradev.content.mixin; + +import net.minecraft.world.entity.projectile.EyeOfEnder; +import net.minecraft.world.phys.Vec3; + +import online.astradev.content.projectile.ProjectileCapabilities; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(EyeOfEnder.class) +public abstract class ProjectilePayloadMixin { + @Shadow private boolean surviveAfterDeath; + + @Inject(method = "signalTo", at = @At("RETURN")) + private void astracontent$projectilePolicyNoDuplicate(Vec3 target, CallbackInfo callback) { + if (ProjectileCapabilities.suppressesEyeDrop((EyeOfEnder) (Object) this)) { + surviveAfterDeath = false; + } + } +} diff --git a/src/main/java/online/astradev/content/mixin/ProjectilePolicyCrossbowMixin.java b/src/main/java/online/astradev/content/mixin/ProjectilePolicyCrossbowMixin.java new file mode 100644 index 0000000..e40fe63 --- /dev/null +++ b/src/main/java/online/astradev/content/mixin/ProjectilePolicyCrossbowMixin.java @@ -0,0 +1,46 @@ +package online.astradev.content.mixin; + +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.item.CrossbowItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +import online.astradev.content.projectile.ProjectileCapabilities; + +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.CallbackInfoReturnable; + +import java.util.function.Predicate; + +@Mixin(CrossbowItem.class) +public abstract class ProjectilePolicyCrossbowMixin { + @Inject( + method = { + "getSupportedHeldProjectiles()Ljava/util/function/Predicate;", + "getAllSupportedProjectiles()Ljava/util/function/Predicate;" + }, + at = @At("RETURN"), + cancellable = true) + private void astracontent$projectilePolicyAmmo( + CallbackInfoReturnable> callback) { + if (!ProjectileCapabilities.active()) return; + callback.setReturnValue( + callback.getReturnValue().or(ProjectileCapabilities::acceptsCrossbowAmmo)); + } + + @Inject(method = "createProjectile", at = @At("HEAD"), cancellable = true) + private void astracontent$projectilePolicyCreate( + Level level, + LivingEntity owner, + ItemStack weapon, + ItemStack ammo, + boolean critical, + CallbackInfoReturnable callback) { + Projectile projectile = + ProjectileCapabilities.createCrossbowProjectile(level, owner, ammo); + if (projectile != null) callback.setReturnValue(projectile); + } +} diff --git a/src/main/java/online/astradev/content/projectile/PolicyPayloadProjectile.java b/src/main/java/online/astradev/content/projectile/PolicyPayloadProjectile.java new file mode 100644 index 0000000..7cd9c5b --- /dev/null +++ b/src/main/java/online/astradev/content/projectile/PolicyPayloadProjectile.java @@ -0,0 +1,76 @@ +package online.astradev.content.projectile; + +import net.minecraft.core.component.DataComponents; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.item.PrimedTnt; +import net.minecraft.world.entity.projectile.EyeOfEnder; +import net.minecraft.world.entity.projectile.throwableitemprojectile.Snowball; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; + +/** One-tick adapter that replaces itself with a vanilla payload understood by vanilla clients. */ +final class PolicyPayloadProjectile extends Snowball { + private final ProjectilePolicy.ProjectileKind kind; + private final ProjectilePolicy.ProjectileParameters parameters; + + PolicyPayloadProjectile( + Level level, + LivingEntity owner, + ItemStack stack, + ProjectilePolicy.ProjectileKind kind, + ProjectilePolicy.ProjectileParameters parameters) { + super(level, owner, stack); + this.kind = kind; + this.parameters = parameters; + } + + @Override + public void tick() { + if (!(level() instanceof ServerLevel level)) return; + switch (kind) { + case TNT_PAYLOAD -> spawnTnt(level); + case ENDER_EYE_PAYLOAD -> spawnEye(level); + default -> throw new IllegalStateException("Unsupported payload kind: " + kind); + } + discard(); + } + + private void spawnTnt(ServerLevel level) { + var tnt = + new PrimedTnt( + level, + getX(), + getY(), + getZ(), + getOwner() instanceof LivingEntity living ? living : null); + tnt.setFuse(parameters.fuseTicks()); + tnt.setDeltaMovement(getDeltaMovement().scale(parameters.velocityScale())); + level.addFreshEntity(tnt); + } + + private void spawnEye(ServerLevel level) { + var target = + level.findNearestMapStructure( + parameters.structureTag(), + blockPosition(), + parameters.searchRadius(), + parameters.skipKnownStructures()); + ItemStack item = getItem(); + boolean intangible = item.has(DataComponents.INTANGIBLE_PROJECTILE); + if (target != null) { + var eye = new EyeOfEnder(level, getX(), getY(), getZ()); + eye.setItem(item); + if (intangible && parameters.intangiblePreventsDrop()) { + eye.addTag(parameters.noDropTag()); + } + eye.signalTo(Vec3.atLowerCornerOf(target)); + eye.setDeltaMovement(getDeltaMovement().scale(parameters.velocityScale())); + level.addFreshEntity(eye); + } else if (parameters.dropWhenNoTarget() + && !(intangible && parameters.intangiblePreventsDrop())) { + spawnAtLocation(level, item.copyWithCount(1)); + } + } +} diff --git a/src/main/java/online/astradev/content/projectile/ProjectileCapabilities.java b/src/main/java/online/astradev/content/projectile/ProjectileCapabilities.java new file mode 100644 index 0000000..2ec081d --- /dev/null +++ b/src/main/java/online/astradev/content/projectile/ProjectileCapabilities.java @@ -0,0 +1,248 @@ +package online.astradev.content.projectile; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.stats.Stats; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.projectile.EyeOfEnder; +import net.minecraft.world.entity.projectile.Projectile; +import net.minecraft.world.entity.projectile.hurtingprojectile.SmallFireball; +import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge; +import net.minecraft.world.entity.projectile.throwableitemprojectile.Snowball; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEgg; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnderpearl; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownExperienceBottle; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; + +import online.astradev.plus.api.editor.EditorDefinitionProvider; +import online.astradev.plus.api.editor.EditorDefinitions; +import online.astradev.plus.api.editor.FileEditorDefinition; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Objects; + +/** + * AstraContent's data-driven, server-only projectile mechanics. + * + *

The facade is deliberately inactive until {@link #start}; mixins therefore fail closed during + * bootstrap and after shutdown. Concrete item IDs, tags, sounds, and tuning values belong to the + * supplied JSON document, never this runtime. + */ +public final class ProjectileCapabilities implements AutoCloseable { + private static volatile ProjectileCapabilities active; + + private final ProjectilePolicy.Compatibility compatibility; + private final FileEditorDefinition provider; + private volatile ProjectilePolicy policy; + private IEventBus eventBus; + private boolean closed; + + private ProjectileCapabilities( + Path actualFile, + String id, + String name, + String schemaJson, + ProjectilePolicy.Compatibility compatibility) { + this.compatibility = compatibility; + this.provider = + new FileEditorDefinition<>( + actualFile, + id, + name, + schemaJson, + json -> ProjectilePolicy.parse(json, compatibility), + prepared -> policy = prepared); + } + + /** Seeds a missing FILE definition, loads the actual file, and publishes one active runtime. */ + public static synchronized ProjectileCapabilities start( + Path actualFile, + String id, + String name, + String defaultsJson, + String schemaJson, + JsonObject compatibility) + throws IOException { + if (active != null) throw new IllegalStateException("Projectile capabilities already started"); + Objects.requireNonNull(actualFile, "actualFile"); + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(defaultsJson, "defaultsJson"); + Objects.requireNonNull(schemaJson, "schemaJson"); + if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) { + throw new IllegalArgumentException("Invalid projectile mechanic identifier"); + } + if (name.isBlank()) throw new IllegalArgumentException("Projectile mechanic needs a name"); + if (EditorDefinitions.find(id).isPresent()) { + throw new IllegalArgumentException("Mechanic already registered: " + id); + } + JsonParser.parseString(schemaJson).getAsJsonObject(); + var parsedCompatibility = + ProjectilePolicy.Compatibility.parse( + compatibility == null ? new JsonObject() : compatibility.deepCopy()); + ProjectilePolicy.parse(defaultsJson, parsedCompatibility); + var runtime = + new ProjectileCapabilities(actualFile, id, name, schemaJson, parsedCompatibility); + boolean initialized = runtime.provider.initialize(defaultsJson); + if (!initialized) { + runtime.policy = + ProjectilePolicy.parse( + runtime.provider.snapshot().documentJson(), parsedCompatibility); + } + EditorDefinitions.register(runtime.provider); + active = runtime; + return runtime; + } + + /** Registers the right-click hook once; mixins use the same active instance automatically. */ + public synchronized ProjectileCapabilities register(IEventBus bus) { + requireOpen(); + Objects.requireNonNull(bus, "bus"); + if (eventBus == bus) return this; + if (eventBus != null) { + throw new IllegalStateException("Projectile capabilities already use another event bus"); + } + eventBus = bus; + bus.register(this); + return this; + } + + public EditorDefinitionProvider definitionProvider() { + return provider; + } + + public static boolean active() { + return active != null; + } + + /** Called by the crossbow predicate mixin. */ + public static boolean acceptsCrossbowAmmo(ItemStack stack) { + ProjectileCapabilities runtime = active; + return runtime != null && runtime.policy.crossbow(stack) != null; + } + + /** Called by the crossbow projectile factory mixin. Null means vanilla owns this stack. */ + public static Projectile createCrossbowProjectile( + Level level, LivingEntity owner, ItemStack stack) { + ProjectileCapabilities runtime = active; + if (runtime == null) return null; + ProjectilePolicy.Rule rule = runtime.policy.crossbow(stack); + return rule == null ? null : runtime.create(level, owner, stack, rule); + } + + /** Called after EyeOfEnder.signalTo; entity tags persist and keep legacy worlds compatible. */ + public static boolean suppressesEyeDrop(EyeOfEnder eye) { + ProjectileCapabilities runtime = active; + return runtime != null && runtime.compatibility.matches(eye.entityTags()); + } + + @SubscribeEvent + public void rightClick(PlayerInteractEvent.RightClickItem event) { + if (closed || !(event.getLevel() instanceof ServerLevel level)) return; + ItemStack stack = event.getItemStack(); + ProjectilePolicy.Rule rule = policy.rightClick(stack); + if (rule == null) return; + var player = event.getEntity(); + if (player.getCooldowns().isOnCooldown(stack)) return; + Projectile projectile = create(level, player, stack, rule); + if (projectile == null) return; + ProjectilePolicy.RightClick launch = rule.rightClick(); + Projectile.spawnProjectile( + projectile, + level, + stack, + shot -> + shot.shootFromRotation( + player, + player.getXRot(), + player.getYRot(), + 0, + launch.velocity(), + launch.inaccuracy())); + playSound(level, player.blockPosition(), launch.sound()); + if (launch.cooldownTicks() > 0) { + player.getCooldowns().addCooldown(stack, launch.cooldownTicks()); + } + player.awardStat(Stats.ITEM_USED.get(stack.getItem())); + if (launch.consume() > 0) stack.consume(launch.consume(), player); + event.setCanceled(true); + event.setCancellationResult(InteractionResult.SUCCESS); + } + + private Projectile create( + Level level, + LivingEntity owner, + ItemStack stack, + ProjectilePolicy.Rule rule) { + ProjectilePolicy.ProjectileParameters parameters = rule.parameters(); + return switch (rule.kind()) { + case ENDER_PEARL -> new ThrownEnderpearl(level, owner, stack); + case EGG -> new ThrownEgg(level, owner, stack); + case SNOWBALL -> new Snowball(level, owner, stack); + case EXPERIENCE_BOTTLE -> new ThrownExperienceBottle(level, owner, stack); + case SMALL_FIREBALL -> { + var fire = new SmallFireball(level, owner, owner.getLookAngle()); + fire.setPos(owner.getX(), owner.getEyeY() + parameters.eyeOffset(), owner.getZ()); + fire.setItem(stack); + yield fire; + } + case WIND_CHARGE -> { + var wind = + new WindCharge( + level, + owner.getX(), + owner.getEyeY() + parameters.eyeOffset(), + owner.getZ(), + owner.getLookAngle()); + wind.setOwner(owner); + yield wind; + } + case TNT_PAYLOAD, ENDER_EYE_PAYLOAD -> + new PolicyPayloadProjectile(level, owner, stack, rule.kind(), parameters); + }; + } + + private static void playSound( + ServerLevel level, + net.minecraft.core.BlockPos position, + ProjectilePolicy.Sound configured) { + if (configured == null) return; + SoundEvent sound = BuiltInRegistries.SOUND_EVENT.getOptional(configured.id()).orElse(null); + if (sound == null) return; + level.playSound( + null, + position, + sound, + configured.source(), + configured.volume(), + configured.pitch()); + } + + @Override + public synchronized void close() { + if (closed) return; + closed = true; + if (eventBus != null) { + eventBus.unregister(this); + eventBus = null; + } + EditorDefinitions.unregister(provider); + synchronized (ProjectileCapabilities.class) { + if (active == this) active = null; + } + } + + private void requireOpen() { + if (closed) throw new IllegalStateException("Projectile capabilities are closed"); + } +} diff --git a/src/main/java/online/astradev/content/projectile/ProjectilePolicy.java b/src/main/java/online/astradev/content/projectile/ProjectilePolicy.java new file mode 100644 index 0000000..fd23409 --- /dev/null +++ b/src/main/java/online/astradev/content/projectile/ProjectilePolicy.java @@ -0,0 +1,379 @@ +package online.astradev.content.projectile; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundSource; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.levelgen.structure.Structure; + +import online.astradev.plus.api.AstraPlusApi; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** Immutable, validated projectile rules published atomically by the live editor definition. */ +final class ProjectilePolicy { + private static final int MAX_RULES = 256; + + private final List rules; + + private ProjectilePolicy(List rules) { + this.rules = List.copyOf(rules); + } + + static ProjectilePolicy parse(String documentJson, Compatibility compatibility) { + if (documentJson == null || documentJson.isBlank()) { + throw new IllegalArgumentException("Projectile policy must be a JSON object"); + } + JsonObject root; + try { + root = JsonParser.parseString(documentJson).getAsJsonObject(); + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Projectile policy must be a JSON object", failure); + } + JsonArray source = array(root, "rules"); + if (source.size() > MAX_RULES) { + throw new IllegalArgumentException("Projectile policy accepts at most 256 rules"); + } + var rules = new ArrayList(source.size()); + for (int index = 0; index < source.size(); index++) { + JsonObject rule = object(source.get(index), "rules[" + index + "]"); + Selector selector = Selector.parse(object(rule, "selector"), index); + ProjectileKind kind = ProjectileKind.parse(text(rule, "kind")); + boolean crossbow = optionalBoolean(rule, "crossbow", true); + JsonObject parameters = optionalObject(rule, "parameters"); + ProjectileParameters prepared = ProjectileParameters.parse(kind, parameters, compatibility); + RightClick rightClick = rule.has("rightClick") + ? RightClick.parse(object(rule, "rightClick")) + : null; + rules.add(new Rule(selector, kind, prepared, crossbow, rightClick)); + } + return new ProjectilePolicy(rules); + } + + Rule crossbow(ItemStack stack) { + for (Rule rule : rules) { + if (rule.crossbow() && rule.selector().matches(stack)) return rule; + } + return null; + } + + Rule rightClick(ItemStack stack) { + for (Rule rule : rules) { + if (rule.rightClick() != null && rule.selector().matches(stack)) return rule; + } + return null; + } + + List rules() { + return rules; + } + + enum ProjectileKind { + ENDER_PEARL, + EGG, + SNOWBALL, + EXPERIENCE_BOTTLE, + SMALL_FIREBALL, + WIND_CHARGE, + TNT_PAYLOAD, + ENDER_EYE_PAYLOAD; + + static ProjectileKind parse(String value) { + try { + return valueOf(value.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException failure) { + throw new IllegalArgumentException("Unknown projectile kind: " + value, failure); + } + } + } + + record Rule( + Selector selector, + ProjectileKind kind, + ProjectileParameters parameters, + boolean crossbow, + RightClick rightClick) {} + + record Selector( + Set items, Set> tags, Set customIds) { + Selector { + items = Set.copyOf(items); + tags = Set.copyOf(tags); + customIds = Set.copyOf(customIds); + if (items.isEmpty() && tags.isEmpty() && customIds.isEmpty()) { + throw new IllegalArgumentException("Projectile selector must not be empty"); + } + } + + static Selector parse(JsonObject json, int index) { + var items = identifiers(json, "item", "items", "rules[" + index + "].selector"); + var tagIds = identifiers(json, "tag", "tags", "rules[" + index + "].selector"); + var tags = new LinkedHashSet>(); + tagIds.forEach(id -> tags.add(TagKey.create(Registries.ITEM, id))); + var custom = strings(json, "customId", "customIds"); + for (String id : custom) requireNamespaced(id, "custom item identifier"); + return new Selector(items, tags, custom); + } + + boolean matches(ItemStack stack) { + if (stack == null || stack.isEmpty()) return false; + if (items.contains(BuiltInRegistries.ITEM.getKey(stack.getItem()))) return true; + for (TagKey tag : tags) { + if (stack.is(tag)) return true; + } + if (customIds.isEmpty()) return false; + return AstraPlusApi.current() + .flatMap(api -> api.identify(stack)) + .map(id -> customIds.contains(id.toString())) + .orElse(false); + } + } + + record ProjectileParameters( + double eyeOffset, + int fuseTicks, + double velocityScale, + TagKey structureTag, + int searchRadius, + boolean skipKnownStructures, + boolean dropWhenNoTarget, + boolean intangiblePreventsDrop, + String noDropTag) { + static ProjectileParameters parse( + ProjectileKind kind, JsonObject json, Compatibility compatibility) { + double eyeOffset = 0; + int fuseTicks = 0; + double velocityScale = 1; + TagKey structureTag = null; + int searchRadius = 0; + boolean skipKnown = false; + boolean dropWhenMissing = false; + boolean intangiblePreventsDrop = false; + String noDropTag = null; + switch (kind) { + case SMALL_FIREBALL, WIND_CHARGE -> + eyeOffset = number(json, "eyeOffset", -16, 16); + case TNT_PAYLOAD -> { + fuseTicks = integer(json, "fuseTicks", 0, 72000); + velocityScale = number(json, "velocityScale", 0, 16); + } + case ENDER_EYE_PAYLOAD -> { + Identifier tag = identifier(text(json, "structureTag"), "structure tag"); + structureTag = TagKey.create(Registries.STRUCTURE, tag); + searchRadius = integer(json, "searchRadius", 1, 10000); + skipKnown = bool(json, "skipKnownStructures"); + dropWhenMissing = bool(json, "dropWhenNoTarget"); + intangiblePreventsDrop = bool(json, "intangiblePreventsDrop"); + velocityScale = number(json, "velocityScale", 0, 16); + if (intangiblePreventsDrop) { + noDropTag = compatibility.primaryNoDropTag(); + if (noDropTag == null) { + throw new IllegalArgumentException( + "Eye payloads that suppress drops need compatibility.primaryNoDropTag"); + } + } + } + default -> { + // Unknown extension keys remain inert and survive editor round trips. + } + } + return new ProjectileParameters( + eyeOffset, + fuseTicks, + velocityScale, + structureTag, + searchRadius, + skipKnown, + dropWhenMissing, + intangiblePreventsDrop, + noDropTag); + } + } + + record RightClick( + float velocity, + float inaccuracy, + int cooldownTicks, + int consume, + Sound sound) { + static RightClick parse(JsonObject json) { + float velocity = (float) number(json, "velocity", 0.01, 16); + float inaccuracy = (float) number(json, "inaccuracy", 0, 180); + int cooldown = integer(json, "cooldownTicks", 0, 72000); + int consume = integer(json, "consume", 0, 64); + Sound sound = json.has("sound") ? Sound.parse(object(json, "sound")) : null; + return new RightClick(velocity, inaccuracy, cooldown, consume, sound); + } + } + + record Sound(Identifier id, SoundSource source, float volume, float pitch) { + static Sound parse(JsonObject json) { + Identifier id = identifier(text(json, "id"), "sound identifier"); + SoundSource source; + try { + source = SoundSource.valueOf(text(json, "source").toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException failure) { + throw new IllegalArgumentException("Unknown sound source", failure); + } + float volume = (float) number(json, "volume", 0, 16); + float pitch = (float) number(json, "pitch", 0.01, 4); + return new Sound(id, source, volume, pitch); + } + } + + record Compatibility(String primaryNoDropTag, Set noDropTags) { + Compatibility { + noDropTags = Set.copyOf(noDropTags); + } + + static Compatibility parse(JsonObject json) { + String primary = optionalText(json, "primaryNoDropTag"); + if (primary != null) requireNamespaced(primary, "primary no-drop entity tag"); + var aliases = strings(json, null, "noDropTagAliases"); + for (String alias : aliases) requireNamespaced(alias, "no-drop entity tag alias"); + var all = new LinkedHashSet<>(aliases); + if (primary != null) all.add(primary); + return new Compatibility(primary, all); + } + + boolean matches(Set entityTags) { + for (String tag : noDropTags) { + if (entityTags.contains(tag)) return true; + } + return false; + } + } + + private static JsonArray array(JsonObject json, String name) { + if (!json.has(name) || !json.get(name).isJsonArray()) { + throw new IllegalArgumentException("Required array is missing: " + name); + } + return json.getAsJsonArray(name); + } + + private static JsonObject object(JsonObject json, String name) { + if (!json.has(name)) throw new IllegalArgumentException("Required object is missing: " + name); + return object(json.get(name), name); + } + + private static JsonObject object(JsonElement value, String name) { + if (value == null || !value.isJsonObject()) { + throw new IllegalArgumentException("Expected object: " + name); + } + return value.getAsJsonObject(); + } + + private static JsonObject optionalObject(JsonObject json, String name) { + return json.has(name) ? object(json, name) : new JsonObject(); + } + + private static String text(JsonObject json, String name) { + String value = optionalText(json, name); + if (value == null) throw new IllegalArgumentException("Required text is missing: " + name); + return value; + } + + private static String optionalText(JsonObject json, String name) { + if (!json.has(name) + || !json.get(name).isJsonPrimitive() + || !json.getAsJsonPrimitive(name).isString()) { + return null; + } + String value = json.get(name).getAsString().trim(); + return value.isEmpty() ? null : value; + } + + private static boolean bool(JsonObject json, String name) { + if (!json.has(name) + || !json.get(name).isJsonPrimitive() + || !json.getAsJsonPrimitive(name).isBoolean()) { + throw new IllegalArgumentException("Required boolean is missing: " + name); + } + return json.get(name).getAsBoolean(); + } + + private static boolean optionalBoolean(JsonObject json, String name, boolean fallback) { + if (!json.has(name)) return fallback; + return bool(json, name); + } + + private static double number(JsonObject json, String name, double minimum, double maximum) { + if (!json.has(name) + || !json.get(name).isJsonPrimitive() + || !json.getAsJsonPrimitive(name).isNumber()) { + throw new IllegalArgumentException("Required number is missing: " + name); + } + double value = json.get(name).getAsDouble(); + if (!Double.isFinite(value) || value < minimum || value > maximum) { + throw new IllegalArgumentException( + "Number " + name + " must be between " + minimum + " and " + maximum); + } + return value; + } + + private static int integer(JsonObject json, String name, int minimum, int maximum) { + double value = number(json, name, minimum, maximum); + if (value != Math.rint(value)) { + throw new IllegalArgumentException("Number must be an integer: " + name); + } + return (int) value; + } + + private static Set identifiers( + JsonObject json, String singular, String plural, String description) { + var values = strings(json, singular, plural); + var result = new LinkedHashSet(); + for (String value : values) result.add(identifier(value, description)); + return result; + } + + private static Set strings(JsonObject json, String singular, String plural) { + var result = new LinkedHashSet(); + if (singular != null && json.has(singular)) { + String value = text(json, singular); + result.add(value); + } + if (plural != null && json.has(plural)) { + JsonArray values = array(json, plural); + for (JsonElement element : values) { + if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException("Expected text entries in " + plural); + } + String value = element.getAsString().trim(); + if (value.isEmpty()) throw new IllegalArgumentException("Blank entry in " + plural); + result.add(value); + } + } + if (result.size() > MAX_RULES) { + throw new IllegalArgumentException("Selector lists accept at most 256 entries"); + } + return result; + } + + private static Identifier identifier(String value, String description) { + requireNamespaced(value, description); + try { + return Identifier.parse(value); + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Invalid " + description + ": " + value, failure); + } + } + + private static void requireNamespaced(String value, String description) { + if (value == null || !value.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) { + throw new IllegalArgumentException("Invalid " + description + ": " + value); + } + } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index 2829223..c3ba249 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -21,6 +21,6 @@ side="SERVER" [[dependencies.astracontent]] modId="astraplus" type="required" -versionRange="[0.9.9,0.10)" +versionRange="[0.9.11,0.10)" ordering="AFTER" side="SERVER" diff --git a/src/main/resources/astracontent.mixins.json b/src/main/resources/astracontent.mixins.json index 27354b8..d3aff19 100644 --- a/src/main/resources/astracontent.mixins.json +++ b/src/main/resources/astracontent.mixins.json @@ -2,6 +2,9 @@ "required": true, "package": "online.astradev.content.mixin", "compatibilityLevel": "JAVA_25", - "mixins": [], + "mixins": [ + "ProjectilePolicyCrossbowMixin", + "ProjectilePayloadMixin" + ], "injectors": {"defaultRequire": 1} } diff --git a/src/test/java/online/astradev/content/AstraContentTest.java b/src/test/java/online/astradev/content/AstraContentTest.java new file mode 100644 index 0000000..839fc97 --- /dev/null +++ b/src/test/java/online/astradev/content/AstraContentTest.java @@ -0,0 +1,78 @@ +package online.astradev.content; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.gson.JsonParser; + +import online.astradev.content.projectile.ProjectileCapabilities; +import online.astradev.plus.api.editor.EditorDefinitions; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +class AstraContentTest { + @TempDir Path directory; + private ProjectileCapabilities runtime; + + @AfterEach + void closeRuntime() { + if (runtime != null) runtime.close(); + } + + @Test + void ownsTheExistingProjectileFileAndEditorIdentityWithPackagedSchema() throws Exception { + runtime = AstraContent.startProjectiles(directory); + var provider = EditorDefinitions.find("astracontent:projectiles").orElseThrow(); + assertEquals(runtime.definitionProvider(), provider); + assertEquals("Боеприпасы", provider.name()); + assertEquals(resource("defaults"), provider.snapshot().documentJson()); + assertEquals(resource("schema"), provider.schemaJson()); + assertEquals( + provider.snapshot().documentJson(), + Files.readString(directory.resolve("config/astracontent-projectiles.json"))); + assertEquals( + 8, + JsonParser.parseString(provider.snapshot().documentJson()) + .getAsJsonObject().getAsJsonArray("rules").size()); + + String disabled = "{\"rules\":[],\"administratorNote\":\"keep this extension\"}"; + provider.save(disabled, provider.snapshot().revision()); + assertEquals(disabled, Files.readString(directory.resolve("config/astracontent-projectiles.json"))); + runtime.close(); + runtime = null; + assertFalse(ProjectileCapabilities.active()); + assertTrue(EditorDefinitions.find("astracontent:projectiles").isEmpty()); + + runtime = AstraContent.startProjectiles(directory); + assertEquals(disabled, runtime.definitionProvider().snapshot().documentJson()); + assertEquals(resource("schema"), runtime.definitionProvider().schemaJson()); + } + + @Test + void doesNotOverwriteInvalidExistingConfigurationOrPublishAnActiveRuntime() throws Exception { + Path configuration = directory.resolve("config/astracontent-projectiles.json"); + Files.createDirectories(configuration.getParent()); + String invalid = "{\"rules\":[{\"kind\":\"SNOWBALL\"}]}"; + Files.writeString(configuration, invalid); + + assertThrows(IllegalArgumentException.class, () -> AstraContent.startProjectiles(directory)); + assertEquals(invalid, Files.readString(configuration)); + assertFalse(ProjectileCapabilities.active()); + assertTrue(EditorDefinitions.find("astracontent:projectiles").isEmpty()); + } + + private static String resource(String kind) throws Exception { + try (var input = AstraContent.class.getResourceAsStream("/content/policies/projectile-" + kind + ".json")) { + if (input == null) throw new AssertionError("Missing packaged projectile " + kind); + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + } +} diff --git a/src/test/java/online/astradev/content/projectile/ProjectileCapabilitiesTest.java b/src/test/java/online/astradev/content/projectile/ProjectileCapabilitiesTest.java new file mode 100644 index 0000000..737c2ee --- /dev/null +++ b/src/test/java/online/astradev/content/projectile/ProjectileCapabilitiesTest.java @@ -0,0 +1,111 @@ +package online.astradev.content.projectile; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.gson.JsonObject; + +import online.astradev.plus.api.editor.EditorDefinitions; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; + +class ProjectileCapabilitiesTest { + @TempDir Path directory; + + private ProjectileCapabilities runtime; + + @AfterEach + void closeRuntime() { + if (runtime != null) runtime.close(); + } + + @Test + void seedsRegistersAndPublishesValidatedLiveFileEdits() throws Exception { + Path file = directory.resolve("config/projectiles.json"); + String defaults = + "{\"rules\":[{\"selector\":{\"item\":\"minecraft:snowball\"},\"kind\":\"SNOWBALL\"}]}"; + runtime = + ProjectileCapabilities.start( + file, + "test:projectiles", + "Test projectiles", + defaults, + "{\"fields\":[]}", + new JsonObject()); + + assertTrue(ProjectileCapabilities.active()); + assertEquals(defaults, Files.readString(file)); + var provider = EditorDefinitions.find("test:projectiles").orElseThrow(); + assertEquals(runtime.definitionProvider(), provider); + + String changed = + "{\"rules\":[{\"selector\":{\"customId\":\"test:ammo\"},\"kind\":\"ENDER_PEARL\"}]}"; + provider.save(changed, provider.snapshot().revision()); + assertEquals(changed, provider.snapshot().documentJson()); + assertThrows( + IllegalArgumentException.class, + () -> provider.save("{\"rules\":[{}]}", provider.snapshot().revision())); + assertEquals(changed, provider.snapshot().documentJson()); + + runtime.close(); + runtime = null; + assertFalse(ProjectileCapabilities.active()); + assertTrue(EditorDefinitions.find("test:projectiles").isEmpty()); + } + + @Test + void existingAdministratorFileWinsOverPackagedDefaults() throws Exception { + Path file = directory.resolve("config/projectiles.json"); + Files.createDirectories(file.getParent()); + String existing = "{\"rules\":[]}"; + Files.writeString(file, existing); + + runtime = + ProjectileCapabilities.start( + file, + "test:existing_projectiles", + "Existing projectiles", + "{\"rules\":[{\"selector\":{\"item\":\"minecraft:tnt\"},\"kind\":\"TNT_PAYLOAD\",\"parameters\":{\"fuseTicks\":80,\"velocityScale\":1}}]}", + "{\"fields\":[]}", + new JsonObject()); + + assertEquals(existing, Files.readString(file)); + assertEquals(existing, runtime.definitionProvider().snapshot().documentJson()); + } + + @Test + void rejectsInvalidMetadataAndPackagedDefaultsBeforeCreatingAFile() { + Path invalidId = directory.resolve("config/invalid-id.json"); + assertThrows( + IllegalArgumentException.class, + () -> + ProjectileCapabilities.start( + invalidId, + "not-an-id", + "Invalid", + "{\"rules\":[]}", + "{\"fields\":[]}", + new JsonObject())); + assertFalse(Files.exists(invalidId)); + + Path invalidDefaults = directory.resolve("config/invalid-defaults.json"); + assertThrows( + IllegalArgumentException.class, + () -> + ProjectileCapabilities.start( + invalidDefaults, + "test:invalid_defaults", + "Invalid defaults", + "{\"rules\":[{}]}", + "{\"fields\":[]}", + new JsonObject())); + assertFalse(Files.exists(invalidDefaults)); + } +} diff --git a/src/test/java/online/astradev/content/projectile/ProjectilePolicyTest.java b/src/test/java/online/astradev/content/projectile/ProjectilePolicyTest.java new file mode 100644 index 0000000..cd79015 --- /dev/null +++ b/src/test/java/online/astradev/content/projectile/ProjectilePolicyTest.java @@ -0,0 +1,156 @@ +package online.astradev.content.projectile; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.gson.JsonParser; + +import net.minecraft.resources.Identifier; + +import org.junit.jupiter.api.Test; + +class ProjectilePolicyTest { + @Test + void parsesConcreteTagAndCustomSelectorsWithTypedParameters() { + var compatibility = + ProjectilePolicy.Compatibility.parse( + JsonParser.parseString( + """ + { + "primaryNoDropTag": "legacy:no_drop", + "noDropTagAliases": ["legacy:older_no_drop"] + } + """) + .getAsJsonObject()); + var policy = + ProjectilePolicy.parse( + """ + { + "rules": [ + { + "selector": { + "items": ["minecraft:snowball"], + "tags": ["minecraft:eggs"], + "customIds": ["test:custom_ammo"] + }, + "kind": "SMALL_FIREBALL", + "crossbow": false, + "parameters": {"eyeOffset": -0.15}, + "rightClick": { + "velocity": 1.5, + "inaccuracy": 1, + "cooldownTicks": 10, + "consume": 1, + "sound": { + "id": "minecraft:item.firecharge.use", + "source": "players", + "volume": 1, + "pitch": 1 + } + } + }, + { + "selector": {"item": "minecraft:ender_eye"}, + "kind": "ENDER_EYE_PAYLOAD", + "parameters": { + "structureTag": "minecraft:eye_of_ender_located", + "searchRadius": 100, + "skipKnownStructures": false, + "dropWhenNoTarget": true, + "intangiblePreventsDrop": true, + "velocityScale": 1 + } + } + ] + } + """, + compatibility); + + assertEquals(2, policy.rules().size()); + var launch = policy.rules().getFirst(); + assertFalse(launch.crossbow()); + assertEquals( + Identifier.parse("minecraft:snowball"), launch.selector().items().iterator().next()); + assertEquals("test:custom_ammo", launch.selector().customIds().iterator().next()); + assertEquals(-0.15, launch.parameters().eyeOffset()); + assertEquals(10, launch.rightClick().cooldownTicks()); + assertEquals("minecraft:item.firecharge.use", launch.rightClick().sound().id().toString()); + + var eye = policy.rules().get(1).parameters(); + assertEquals(100, eye.searchRadius()); + assertTrue(eye.intangiblePreventsDrop()); + assertEquals("legacy:no_drop", eye.noDropTag()); + assertTrue(compatibility.matches(java.util.Set.of("legacy:older_no_drop"))); + } + + @Test + void allowsAnEmptyPolicyToDisableTheCapability() { + var policy = ProjectilePolicy.parse("{\"rules\":[]}", compatibility()); + assertTrue(policy.rules().isEmpty()); + } + + @Test + void rejectsAmbiguousOrUnsafeDocuments() { + assertThrows( + IllegalArgumentException.class, + () -> + ProjectilePolicy.parse( + "{\"rules\":[{\"selector\":{},\"kind\":\"SNOWBALL\"}]}", + compatibility())); + assertThrows( + IllegalArgumentException.class, + () -> + ProjectilePolicy.parse( + "{\"rules\":[{\"selector\":{\"item\":\"snowball\"},\"kind\":\"SNOWBALL\"}]}", + compatibility())); + assertThrows( + IllegalArgumentException.class, + () -> + ProjectilePolicy.parse( + """ + {"rules":[{ + "selector":{"item":"minecraft:tnt"}, + "kind":"TNT_PAYLOAD", + "parameters":{"fuseTicks":1.5,"velocityScale":1} + }]} + """, + compatibility())); + assertThrows( + IllegalArgumentException.class, + () -> + ProjectilePolicy.parse( + """ + {"rules":[{ + "selector":{"item":"minecraft:ender_eye"}, + "kind":"ENDER_EYE_PAYLOAD", + "parameters":{ + "structureTag":"minecraft:eye_of_ender_located", + "searchRadius":100, + "skipKnownStructures":false, + "dropWhenNoTarget":true, + "intangiblePreventsDrop":true, + "velocityScale":1 + } + }]} + """, + compatibility())); + } + + @Test + void ordinaryProjectilesHaveNoPayloadOnlySettings() { + var policy = + ProjectilePolicy.parse( + "{\"rules\":[{\"selector\":{\"item\":\"minecraft:snowball\"},\"kind\":\"SNOWBALL\"}]}", + compatibility()); + var parameters = policy.rules().getFirst().parameters(); + assertNull(parameters.structureTag()); + assertEquals(1, parameters.velocityScale()); + } + + private static ProjectilePolicy.Compatibility compatibility() { + return ProjectilePolicy.Compatibility.parse(JsonParser.parseString("{}").getAsJsonObject()); + } +}