Compare commits

...

5 Commits

98 changed files with 8968 additions and 1 deletions
+17
View File
@@ -0,0 +1,17 @@
# Mossling neutral pipeline creature
Mossling is an original, non-distributable-gameplay test creature used to prove the Blockbench/Hytale asset roundtrip before Pokémon production assets are built.
## Source concept
- `mossling-turnaround.png`
- SHA-256: `516aa9c22ed586a748d90be3638c3cb26e12fc4086be3d3c9aac58a2e6543390`
- Generated with OpenAI ImageGen on 2026-08-15.
## Generation prompt
> Create a professional 3D modeling turnaround concept sheet for an original small fantasy creature called Mossling, intended solely as a neutral Hytale/Blockbench asset-pipeline test. Design: friendly squat quadruped, jade-blue skin, darker geometric freckles, broad wedge-shaped head, leaf-shaped ears, amber eyes, short sturdy legs, and a faceted moss-covered crystal bud on its back. Make it clearly original and not based on any existing franchise character. Translate it into a Hytale-compatible blocky low-poly aesthetic using cubes and simple planar shapes, chunky readable silhouette, 64 pixels per model unit texture logic, and animation-friendly joint separation. Show front, left side, rear, top, and three-quarter views on a clean neutral light gray background, consistent proportions and colors across all views, no logos and no game screenshot. Include a compact color palette strip and subtle bone/socket guide overlays for root, body, head, four legs, ears, and back crystal. High clarity, production reference sheet, orthographic views, no dramatic lighting.
## Production gate
The Blockbench source, texture, model, animations, previews and validator report must be generated from a deterministic asset recipe. This concept image is reference material, not the exported in-game model.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

+97
View File
@@ -0,0 +1,97 @@
import org.gradle.api.GradleException
import org.gradle.api.tasks.testing.Test
import dev.projectcapture.buildlogic.VerifyFanProjectPolicy
plugins {
base
}
group = "dev.projectcapture"
version = "0.1.0"
allprojects {
group = rootProject.group
version = rootProject.version
repositories {
mavenCentral()
maven {
name = "hytaleRelease"
url = uri("https://maven.hytale.com/release")
mavenContent { releasesOnly() }
}
}
}
subprojects {
plugins.withId("java") {
extensions.configure<JavaPluginExtension> {
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
withSourcesJar()
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(25)
options.compilerArgs.addAll(listOf("-Xlint:all", "-parameters"))
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
testLogging {
events("failed", "skipped")
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
}
}
}
}
val verifyFanProjectPolicy = tasks.register<VerifyFanProjectPolicy>("verifyFanProjectPolicy") {
group = "verification"
description = "Verifies the public, non-commercial and unofficial fan-project safeguards."
projectRoot.set(layout.projectDirectory)
}
tasks.named("check") {
dependsOn(
verifyFanProjectPolicy,
":engine:check",
":content-pokemon:check",
":content-tools:check",
":hytale-adapter:check",
)
}
tasks.register("fanBuild") {
group = "build"
description = "Builds and verifies the unofficial non-commercial fan mod."
dependsOn("check", ":hytale-adapter:fanModJar")
}
val releaseReviewFile = layout.projectDirectory.file("release-review.json").asFile
tasks.register("publish") {
group = "release"
description = "Guarded public publishing entry point; no upload is performed by this task."
doFirst {
if (!releaseReviewFile.isFile || !releaseReviewFile.readText().contains("\"approved\": true")) {
throw GradleException(
"Release review is missing. Copy release-review.example.json to release-review.json, " +
"complete the Hytale and third-party-rights review, then set approved to true."
)
}
}
}
tasks.register("release") {
group = "release"
description = "Guarded release entry point; requires a current manual policy review."
doFirst {
if (!releaseReviewFile.isFile || !releaseReviewFile.readText().contains("\"approved\": true")) {
throw GradleException(
"Release review is missing. Copy release-review.example.json to release-review.json, " +
"complete the Hytale and third-party-rights review, then set approved to true."
)
}
}
}
@@ -0,0 +1,48 @@
package dev.projectcapture.buildlogic;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
public abstract class VerifyFanProjectPolicy extends DefaultTask {
@Internal
public abstract DirectoryProperty getProjectRoot();
@TaskAction
public void verify() throws IOException {
File root = getProjectRoot().get().getAsFile();
List<String> requiredFiles = List.of(
"LICENSE",
"THIRD_PARTY_NOTICE.md",
"fan-project-metadata.json",
"docs/UNOFFICIAL_FAN_PROJECT_POLICY.md"
);
List<String> missing = requiredFiles.stream()
.filter(path -> !root.toPath().resolve(path).toFile().isFile())
.toList();
if (!missing.isEmpty()) {
throw new GradleException("Missing fan-project safeguards: " + String.join(", ", missing));
}
String metadata = Files.readString(root.toPath().resolve("fan-project-metadata.json"));
List<String> requiredFlags = List.of(
"\"unofficial\": true",
"\"nonCommercial\": true",
"\"containsPokemonFanContent\": true",
"\"bundlesHytaleGameFiles\": false"
);
List<String> absentFlags = requiredFlags.stream()
.filter(flag -> !metadata.contains(flag))
.toList();
if (!absentFlags.isEmpty()) {
throw new GradleException("Invalid fan-project metadata; missing: " + String.join(", ", absentFlags));
}
}
}
+7
View File
@@ -0,0 +1,7 @@
# Unofficial fan-content catalog
`content-pokemon` contains the openly inspectable, non-commercial and unofficial twelve-form fanmod catalog. Every document and content entry is explicitly marked with `unofficialFanContent: true`.
The catalog intentionally contains no copied game files and no generated binary assets. Asset records with `status: "PLANNED"` are deterministic production specifications and safe relative target paths, not claims that an asset already exists.
Validation is performed by `:content-tools:validateFanContent`. The catalog also records `nonCommercial: true` and `rightsReviewRequired: true`; these declarations must be preserved by any distribution workflow. This module does not configure a publisher, remote or upload target.
+31
View File
@@ -0,0 +1,31 @@
plugins {
`java-library`
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
tasks.register("verifyNoBinaryAssets") {
group = "verification"
description = "Rejects copied or generated binary assets from the metadata-only fan-content catalog."
inputs.files(fileTree("src/main/resources") {
include(
"**/*.jar", "**/*.zip", "**/*.class", "**/*.png", "**/*.jpg", "**/*.jpeg",
"**/*.ogg", "**/*.wav", "**/*.mp3", "**/*.bbmodel", "**/*.blockymodel", "**/*.blockyanim"
)
})
doLast {
check(inputs.files.isEmpty) {
"content-pokemon may contain metadata only; binary/generated files found: " +
inputs.files.files.joinToString { it.path }
}
}
}
tasks.named("check") {
dependsOn("verifyNoBinaryAssets")
}
@@ -0,0 +1,78 @@
{
"schemaVersion": 1,
"unofficialFanContent": true,
"items": [
{
"id": "projectcapture:bulbasaur-assets", "speciesId": "projectcapture:bulbasaur", "status": "PLANNED", "seed": 1001,
"bodyPlan": "QUADRUPED_SMALL", "palette": ["#68B878", "#78C8B0", "#405060", "#D85868"], "sockets": ["head", "back", "tail"],
"source": "assets/fan/bulbasaur/source/bulbasaur.bbmodel", "model": "assets/fan/bulbasaur/models/bulbasaur.blockymodel", "texture": "assets/fan/bulbasaur/textures/bulbasaur.png", "recipe": "assets/fan/bulbasaur/recipes/bulbasaur.asset.json",
"animations": { "idle": "assets/fan/bulbasaur/animations/bulbasaur_idle.blockyanim", "walk": "assets/fan/bulbasaur/animations/bulbasaur_walk.blockyanim", "attack": "assets/fan/bulbasaur/animations/bulbasaur_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:ivysaur-assets", "speciesId": "projectcapture:ivysaur", "status": "PLANNED", "seed": 1002,
"bodyPlan": "QUADRUPED_MEDIUM", "palette": ["#58A890", "#78C8B0", "#405060", "#D85878"], "sockets": ["head", "back", "tail"],
"source": "assets/fan/ivysaur/source/ivysaur.bbmodel", "model": "assets/fan/ivysaur/models/ivysaur.blockymodel", "texture": "assets/fan/ivysaur/textures/ivysaur.png", "recipe": "assets/fan/ivysaur/recipes/ivysaur.asset.json",
"animations": { "idle": "assets/fan/ivysaur/animations/ivysaur_idle.blockyanim", "walk": "assets/fan/ivysaur/animations/ivysaur_walk.blockyanim", "attack": "assets/fan/ivysaur/animations/ivysaur_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:venusaur-assets", "speciesId": "projectcapture:venusaur", "status": "PLANNED", "seed": 1003,
"bodyPlan": "QUADRUPED_LARGE", "palette": ["#489878", "#68B8A0", "#384858", "#D85868"], "sockets": ["head", "back", "tail"],
"source": "assets/fan/venusaur/source/venusaur.bbmodel", "model": "assets/fan/venusaur/models/venusaur.blockymodel", "texture": "assets/fan/venusaur/textures/venusaur.png", "recipe": "assets/fan/venusaur/recipes/venusaur.asset.json",
"animations": { "idle": "assets/fan/venusaur/animations/venusaur_idle.blockyanim", "walk": "assets/fan/venusaur/animations/venusaur_walk.blockyanim", "attack": "assets/fan/venusaur/animations/venusaur_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:charmander-assets", "speciesId": "projectcapture:charmander", "status": "PLANNED", "seed": 1004,
"bodyPlan": "BIPED_SMALL_TAILED", "palette": ["#E89048", "#F0C070", "#405060", "#F05838"], "sockets": ["head", "back", "tail", "hand_left", "hand_right"],
"source": "assets/fan/charmander/source/charmander.bbmodel", "model": "assets/fan/charmander/models/charmander.blockymodel", "texture": "assets/fan/charmander/textures/charmander.png", "recipe": "assets/fan/charmander/recipes/charmander.asset.json",
"animations": { "idle": "assets/fan/charmander/animations/charmander_idle.blockyanim", "walk": "assets/fan/charmander/animations/charmander_walk.blockyanim", "attack": "assets/fan/charmander/animations/charmander_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:charmeleon-assets", "speciesId": "projectcapture:charmeleon", "status": "PLANNED", "seed": 1005,
"bodyPlan": "BIPED_MEDIUM_TAILED", "palette": ["#D86848", "#F0B860", "#384858", "#F05030"], "sockets": ["head", "back", "tail", "hand_left", "hand_right"],
"source": "assets/fan/charmeleon/source/charmeleon.bbmodel", "model": "assets/fan/charmeleon/models/charmeleon.blockymodel", "texture": "assets/fan/charmeleon/textures/charmeleon.png", "recipe": "assets/fan/charmeleon/recipes/charmeleon.asset.json",
"animations": { "idle": "assets/fan/charmeleon/animations/charmeleon_idle.blockyanim", "walk": "assets/fan/charmeleon/animations/charmeleon_walk.blockyanim", "attack": "assets/fan/charmeleon/animations/charmeleon_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:charizard-assets", "speciesId": "projectcapture:charizard", "status": "PLANNED", "seed": 1006,
"bodyPlan": "BIPED_LARGE_WINGED", "palette": ["#D87048", "#F0B858", "#385070", "#F05028"], "sockets": ["head", "back", "tail", "wing_left", "wing_right", "hand_left", "hand_right"],
"source": "assets/fan/charizard/source/charizard.bbmodel", "model": "assets/fan/charizard/models/charizard.blockymodel", "texture": "assets/fan/charizard/textures/charizard.png", "recipe": "assets/fan/charizard/recipes/charizard.asset.json",
"animations": { "idle": "assets/fan/charizard/animations/charizard_idle.blockyanim", "walk": "assets/fan/charizard/animations/charizard_walk.blockyanim", "attack": "assets/fan/charizard/animations/charizard_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:squirtle-assets", "speciesId": "projectcapture:squirtle", "status": "PLANNED", "seed": 1007,
"bodyPlan": "BIPED_SMALL_SHELLED", "palette": ["#58A8C8", "#E8D098", "#987048", "#405060"], "sockets": ["head", "back", "tail", "hand_left", "hand_right"],
"source": "assets/fan/squirtle/source/squirtle.bbmodel", "model": "assets/fan/squirtle/models/squirtle.blockymodel", "texture": "assets/fan/squirtle/textures/squirtle.png", "recipe": "assets/fan/squirtle/recipes/squirtle.asset.json",
"animations": { "idle": "assets/fan/squirtle/animations/squirtle_idle.blockyanim", "walk": "assets/fan/squirtle/animations/squirtle_walk.blockyanim", "attack": "assets/fan/squirtle/animations/squirtle_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:wartortle-assets", "speciesId": "projectcapture:wartortle", "status": "PLANNED", "seed": 1008,
"bodyPlan": "BIPED_MEDIUM_SHELLED", "palette": ["#5088C0", "#E8D8B0", "#887058", "#405078"], "sockets": ["head", "back", "tail", "hand_left", "hand_right"],
"source": "assets/fan/wartortle/source/wartortle.bbmodel", "model": "assets/fan/wartortle/models/wartortle.blockymodel", "texture": "assets/fan/wartortle/textures/wartortle.png", "recipe": "assets/fan/wartortle/recipes/wartortle.asset.json",
"animations": { "idle": "assets/fan/wartortle/animations/wartortle_idle.blockyanim", "walk": "assets/fan/wartortle/animations/wartortle_walk.blockyanim", "attack": "assets/fan/wartortle/animations/wartortle_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:blastoise-assets", "speciesId": "projectcapture:blastoise", "status": "PLANNED", "seed": 1009,
"bodyPlan": "BIPED_LARGE_SHELLED", "palette": ["#3878B0", "#E8D8B0", "#786048", "#384868"], "sockets": ["head", "back", "tail", "cannon_left", "cannon_right", "hand_left", "hand_right"],
"source": "assets/fan/blastoise/source/blastoise.bbmodel", "model": "assets/fan/blastoise/models/blastoise.blockymodel", "texture": "assets/fan/blastoise/textures/blastoise.png", "recipe": "assets/fan/blastoise/recipes/blastoise.asset.json",
"animations": { "idle": "assets/fan/blastoise/animations/blastoise_idle.blockyanim", "walk": "assets/fan/blastoise/animations/blastoise_walk.blockyanim", "attack": "assets/fan/blastoise/animations/blastoise_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:pikachu-assets", "speciesId": "projectcapture:pikachu", "status": "PLANNED", "seed": 1025,
"bodyPlan": "BIPED_SMALL_TAILED", "palette": ["#F0D848", "#A06838", "#E85048", "#384050"], "sockets": ["head", "back", "tail", "hand_left", "hand_right"],
"source": "assets/fan/pikachu/source/pikachu.bbmodel", "model": "assets/fan/pikachu/models/pikachu.blockymodel", "texture": "assets/fan/pikachu/textures/pikachu.png", "recipe": "assets/fan/pikachu/recipes/pikachu.asset.json",
"animations": { "idle": "assets/fan/pikachu/animations/pikachu_idle.blockyanim", "walk": "assets/fan/pikachu/animations/pikachu_walk.blockyanim", "attack": "assets/fan/pikachu/animations/pikachu_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:raichu-assets", "speciesId": "projectcapture:raichu", "status": "PLANNED", "seed": 1026,
"bodyPlan": "BIPED_MEDIUM_TAILED", "palette": ["#D89040", "#F0D078", "#886040", "#384050"], "sockets": ["head", "back", "tail", "hand_left", "hand_right"],
"source": "assets/fan/raichu/source/raichu.bbmodel", "model": "assets/fan/raichu/models/raichu.blockymodel", "texture": "assets/fan/raichu/textures/raichu.png", "recipe": "assets/fan/raichu/recipes/raichu.asset.json",
"animations": { "idle": "assets/fan/raichu/animations/raichu_idle.blockyanim", "walk": "assets/fan/raichu/animations/raichu_walk.blockyanim", "attack": "assets/fan/raichu/animations/raichu_attack.blockyanim" }, "unofficialFanContent": true
},
{
"id": "projectcapture:ditto-assets", "speciesId": "projectcapture:ditto", "status": "PLANNED", "seed": 1132,
"bodyPlan": "AMORPHOUS_SMALL", "palette": ["#A878C8", "#D0A8E0", "#405060", "#F0E8F0"], "sockets": ["core", "surface"],
"source": "assets/fan/ditto/source/ditto.bbmodel", "model": "assets/fan/ditto/models/ditto.blockymodel", "texture": "assets/fan/ditto/textures/ditto.png", "recipe": "assets/fan/ditto/recipes/ditto.asset.json",
"animations": { "idle": "assets/fan/ditto/animations/ditto_idle.blockyanim", "walk": "assets/fan/ditto/animations/ditto_walk.blockyanim", "attack": "assets/fan/ditto/animations/ditto_attack.blockyanim" }, "unofficialFanContent": true
}
]
}
@@ -0,0 +1,31 @@
{
"schemaVersion": 1,
"contentSetId": "projectcapture:twelve-form-fan-slice",
"contentProfile": "UNOFFICIAL_TWELVE_FORM_SLICE",
"unofficialFanContent": true,
"publicationStatus": "UNOFFICIAL_FAN_CONTENT",
"nonCommercial": true,
"rightsReviewRequired": true,
"gameplay": {
"minimumLevel": 1,
"maximumLevel": 100,
"maximumPartySize": 6,
"visibleCompanionLimit": 1,
"commandedMoveSlots": 3,
"starterGrantEnabled": false
},
"expectedSpeciesIds": [
"projectcapture:bulbasaur",
"projectcapture:ivysaur",
"projectcapture:venusaur",
"projectcapture:charmander",
"projectcapture:charmeleon",
"projectcapture:charizard",
"projectcapture:squirtle",
"projectcapture:wartortle",
"projectcapture:blastoise",
"projectcapture:pikachu",
"projectcapture:raichu",
"projectcapture:ditto"
]
}
@@ -0,0 +1,23 @@
{
"schemaVersion": 1,
"unofficialFanContent": true,
"items": [
{ "schemaVersion": 1, "id": "projectcapture:tackle", "displayName": "Tackle", "type": "NORMAL", "category": "PHYSICAL", "power": 28, "accuracy": 0.95, "priority": 0, "role": "BASIC", "cooldownSeconds": 1.4, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:guard-stance", "displayName": "Guard Stance", "type": "NORMAL", "category": "STATUS", "power": 0, "accuracy": 1.0, "priority": 1, "role": "COMMAND", "cooldownSeconds": 9.0, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:leafy-burst", "displayName": "Leafy Burst", "type": "GRASS", "category": "SPECIAL", "power": 42, "accuracy": 0.90, "priority": 0, "role": "COMMAND", "cooldownSeconds": 5.0, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:spore-veil", "displayName": "Spore Veil", "type": "GRASS", "category": "SPECIAL", "power": 18, "accuracy": 0.92, "priority": 0, "role": "COMMAND", "cooldownSeconds": 8.0, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:seed-pulse", "displayName": "Seed Pulse", "type": "GRASS", "category": "SPECIAL", "power": 58, "accuracy": 0.88, "priority": 0, "role": "COMMAND", "cooldownSeconds": 7.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:ember-dart", "displayName": "Ember Dart", "type": "FIRE", "category": "SPECIAL", "power": 31, "accuracy": 0.95, "priority": 0, "role": "BASIC", "cooldownSeconds": 1.6, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:heat-wave", "displayName": "Heat Wave", "type": "FIRE", "category": "SPECIAL", "power": 52, "accuracy": 0.85, "priority": 0, "role": "COMMAND", "cooldownSeconds": 6.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:flame-guard", "displayName": "Flame Guard", "type": "FIRE", "category": "STATUS", "power": 0, "accuracy": 1.0, "priority": 1, "role": "COMMAND", "cooldownSeconds": 9.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:sky-dive", "displayName": "Sky Dive", "type": "FLYING", "category": "PHYSICAL", "power": 64, "accuracy": 0.85, "priority": 0, "role": "COMMAND", "cooldownSeconds": 8.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:water-jet", "displayName": "Water Jet", "type": "WATER", "category": "SPECIAL", "power": 30, "accuracy": 0.95, "priority": 0, "role": "BASIC", "cooldownSeconds": 1.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:shell-guard", "displayName": "Shell Guard", "type": "WATER", "category": "STATUS", "power": 0, "accuracy": 1.0, "priority": 1, "role": "COMMAND", "cooldownSeconds": 8.0, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:mist-surge", "displayName": "Mist Surge", "type": "WATER", "category": "SPECIAL", "power": 49, "accuracy": 0.90, "priority": 0, "role": "COMMAND", "cooldownSeconds": 6.0, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:static-spark", "displayName": "Static Spark", "type": "ELECTRIC", "category": "SPECIAL", "power": 33, "accuracy": 0.95, "priority": 0, "role": "BASIC", "cooldownSeconds": 1.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:quick-step", "displayName": "Quick Step", "type": "NORMAL", "category": "PHYSICAL", "power": 24, "accuracy": 0.98, "priority": 1, "role": "COMMAND", "cooldownSeconds": 3.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:thunder-arc", "displayName": "Thunder Arc", "type": "ELECTRIC", "category": "SPECIAL", "power": 61, "accuracy": 0.88, "priority": 0, "role": "COMMAND", "cooldownSeconds": 7.0, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:morph-strike", "displayName": "Morph Strike", "type": "NORMAL", "category": "PHYSICAL", "power": 26, "accuracy": 0.95, "priority": 0, "role": "BASIC", "cooldownSeconds": 1.5, "unofficialFanContent": true },
{ "schemaVersion": 1, "id": "projectcapture:mirror-form", "displayName": "Mirror Form", "type": "NORMAL", "category": "STATUS", "power": 0, "accuracy": 1.0, "priority": 0, "role": "COMMAND", "cooldownSeconds": 12.0, "unofficialFanContent": true }
]
}
@@ -0,0 +1,42 @@
{
"schemaVersion": 1,
"unofficialFanContent": true,
"items": [
{
"id": "projectcapture:basic-capture-capsule", "category": "CAPTURE_DEVICE", "unlockedByDefault": true,
"output": { "itemId": "projectcapture:capture-capsule", "quantity": 4 },
"ingredients": [
{ "itemId": "hytale:copper_ingot", "quantity": 1 },
{ "itemId": "hytale:plant_fiber", "quantity": 2 }
],
"unofficialFanContent": true
},
{
"id": "projectcapture:breeding-habitat", "category": "HABITAT", "unlockedByDefault": false,
"output": { "itemId": "projectcapture:breeding-habitat", "quantity": 1 },
"ingredients": [
{ "itemId": "hytale:wood_plank", "quantity": 12 },
{ "itemId": "hytale:iron_ingot", "quantity": 4 }
],
"unofficialFanContent": true
},
{
"id": "projectcapture:gene-analyzer", "category": "ANALYSIS_TOOL", "unlockedByDefault": false,
"output": { "itemId": "projectcapture:gene-analyzer", "quantity": 1 },
"ingredients": [
{ "itemId": "hytale:iron_ingot", "quantity": 6 },
{ "itemId": "hytale:crystal_shard", "quantity": 2 }
],
"unofficialFanContent": true
},
{
"id": "projectcapture:thunder-core", "category": "EVOLUTION_CATALYST", "unlockedByDefault": false,
"output": { "itemId": "projectcapture:thunder-core", "quantity": 1 },
"ingredients": [
{ "itemId": "hytale:crystal_shard", "quantity": 4 },
{ "itemId": "hytale:copper_ingot", "quantity": 3 }
],
"unofficialFanContent": true
}
]
}
@@ -0,0 +1,18 @@
{
"schemaVersion": 1,
"unofficialFanContent": true,
"items": [
{ "id": "projectcapture:spawn-bulbasaur", "speciesId": "projectcapture:bulbasaur", "biomes": ["FOREST", "MEADOW"], "time": "DAY", "rarityWeight": 36, "minimumLevel": 3, "maximumLevel": 15, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-ivysaur", "speciesId": "projectcapture:ivysaur", "biomes": ["FOREST", "JUNGLE"], "time": "ANY", "rarityWeight": 12, "minimumLevel": 16, "maximumLevel": 34, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-venusaur", "speciesId": "projectcapture:venusaur", "biomes": ["JUNGLE"], "time": "DAY", "rarityWeight": 2, "minimumLevel": 34, "maximumLevel": 60, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-charmander", "speciesId": "projectcapture:charmander", "biomes": ["VOLCANIC", "BADLANDS"], "time": "DAY", "rarityWeight": 34, "minimumLevel": 3, "maximumLevel": 15, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-charmeleon", "speciesId": "projectcapture:charmeleon", "biomes": ["VOLCANIC", "BADLANDS"], "time": "ANY", "rarityWeight": 11, "minimumLevel": 16, "maximumLevel": 38, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-charizard", "speciesId": "projectcapture:charizard", "biomes": ["VOLCANIC", "MOUNTAINS"], "time": "DAY", "rarityWeight": 2, "minimumLevel": 38, "maximumLevel": 64, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-squirtle", "speciesId": "projectcapture:squirtle", "biomes": ["COAST", "RIVER"], "time": "DAY", "rarityWeight": 38, "minimumLevel": 3, "maximumLevel": 15, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-wartortle", "speciesId": "projectcapture:wartortle", "biomes": ["COAST", "SWAMP"], "time": "ANY", "rarityWeight": 12, "minimumLevel": 16, "maximumLevel": 38, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-blastoise", "speciesId": "projectcapture:blastoise", "biomes": ["COAST", "DEEP_WATER"], "time": "ANY", "rarityWeight": 2, "minimumLevel": 38, "maximumLevel": 64, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-pikachu", "speciesId": "projectcapture:pikachu", "biomes": ["FOREST", "MEADOW"], "time": "ANY", "rarityWeight": 24, "minimumLevel": 5, "maximumLevel": 30, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-raichu", "speciesId": "projectcapture:raichu", "biomes": ["HIGHLANDS", "STORM_FIELDS"], "time": "ANY", "rarityWeight": 4, "minimumLevel": 28, "maximumLevel": 58, "unofficialFanContent": true },
{ "id": "projectcapture:spawn-ditto", "speciesId": "projectcapture:ditto", "biomes": ["MEADOW", "CAVES", "SWAMP"], "time": "NIGHT", "rarityWeight": 6, "minimumLevel": 10, "maximumLevel": 50, "unofficialFanContent": true }
]
}
@@ -0,0 +1,85 @@
{
"schemaVersion": 1,
"unofficialFanContent": true,
"items": [
{
"schemaVersion": 1, "id": "projectcapture:bulbasaur", "displayName": "Bulbasaur", "catalogNumber": 1, "form": "BASE", "types": ["GRASS", "POISON"],
"rarity": "UNCOMMON", "captureRate": 199, "baseStats": { "vitality": 45, "power": 42, "guard": 44, "agility": 40 },
"basicMoveId": "projectcapture:tackle", "commandMoveIds": ["projectcapture:leafy-burst", "projectcapture:spore-veil", "projectcapture:guard-stance"],
"evolution": { "method": "LEVEL", "targetSpeciesId": "projectcapture:ivysaur", "minimumLevel": 16 },
"assetId": "projectcapture:bulbasaur-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:ivysaur", "displayName": "Ivysaur", "catalogNumber": 2, "form": "STAGE_1", "types": ["GRASS", "POISON"],
"rarity": "RARE", "captureRate": 148, "baseStats": { "vitality": 60, "power": 58, "guard": 60, "agility": 54 },
"basicMoveId": "projectcapture:tackle", "commandMoveIds": ["projectcapture:leafy-burst", "projectcapture:seed-pulse", "projectcapture:spore-veil"],
"evolution": { "method": "LEVEL", "targetSpeciesId": "projectcapture:venusaur", "minimumLevel": 32 },
"assetId": "projectcapture:ivysaur-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:venusaur", "displayName": "Venusaur", "catalogNumber": 3, "form": "STAGE_2", "types": ["GRASS", "POISON"],
"rarity": "EPIC", "captureRate": 71, "baseStats": { "vitality": 82, "power": 80, "guard": 84, "agility": 68 },
"basicMoveId": "projectcapture:tackle", "commandMoveIds": ["projectcapture:seed-pulse", "projectcapture:spore-veil", "projectcapture:guard-stance"],
"assetId": "projectcapture:venusaur-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:charmander", "displayName": "Charmander", "catalogNumber": 4, "form": "BASE", "types": ["FIRE"],
"rarity": "UNCOMMON", "captureRate": 194, "baseStats": { "vitality": 39, "power": 50, "guard": 38, "agility": 56 },
"basicMoveId": "projectcapture:ember-dart", "commandMoveIds": ["projectcapture:heat-wave", "projectcapture:quick-step", "projectcapture:flame-guard"],
"evolution": { "method": "LEVEL", "targetSpeciesId": "projectcapture:charmeleon", "minimumLevel": 16 },
"assetId": "projectcapture:charmander-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:charmeleon", "displayName": "Charmeleon", "catalogNumber": 5, "form": "STAGE_1", "types": ["FIRE"],
"rarity": "RARE", "captureRate": 140, "baseStats": { "vitality": 58, "power": 66, "guard": 54, "agility": 70 },
"basicMoveId": "projectcapture:ember-dart", "commandMoveIds": ["projectcapture:heat-wave", "projectcapture:quick-step", "projectcapture:flame-guard"],
"evolution": { "method": "LEVEL", "targetSpeciesId": "projectcapture:charizard", "minimumLevel": 36 },
"assetId": "projectcapture:charmeleon-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:charizard", "displayName": "Charizard", "catalogNumber": 6, "form": "STAGE_2", "types": ["FIRE", "FLYING"],
"rarity": "EPIC", "captureRate": 61, "baseStats": { "vitality": 78, "power": 88, "guard": 72, "agility": 96 },
"basicMoveId": "projectcapture:ember-dart", "commandMoveIds": ["projectcapture:heat-wave", "projectcapture:sky-dive", "projectcapture:flame-guard"],
"assetId": "projectcapture:charizard-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:squirtle", "displayName": "Squirtle", "catalogNumber": 7, "form": "BASE", "types": ["WATER"],
"rarity": "UNCOMMON", "captureRate": 196, "baseStats": { "vitality": 44, "power": 40, "guard": 64, "agility": 38 },
"basicMoveId": "projectcapture:water-jet", "commandMoveIds": ["projectcapture:shell-guard", "projectcapture:mist-surge", "projectcapture:quick-step"],
"evolution": { "method": "LEVEL", "targetSpeciesId": "projectcapture:wartortle", "minimumLevel": 16 },
"assetId": "projectcapture:squirtle-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:wartortle", "displayName": "Wartortle", "catalogNumber": 8, "form": "STAGE_1", "types": ["WATER"],
"rarity": "RARE", "captureRate": 145, "baseStats": { "vitality": 59, "power": 54, "guard": 78, "agility": 52 },
"basicMoveId": "projectcapture:water-jet", "commandMoveIds": ["projectcapture:shell-guard", "projectcapture:mist-surge", "projectcapture:guard-stance"],
"evolution": { "method": "LEVEL", "targetSpeciesId": "projectcapture:blastoise", "minimumLevel": 36 },
"assetId": "projectcapture:wartortle-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:blastoise", "displayName": "Blastoise", "catalogNumber": 9, "form": "STAGE_2", "types": ["WATER"],
"rarity": "EPIC", "captureRate": 64, "baseStats": { "vitality": 80, "power": 76, "guard": 102, "agility": 66 },
"basicMoveId": "projectcapture:water-jet", "commandMoveIds": ["projectcapture:shell-guard", "projectcapture:mist-surge", "projectcapture:guard-stance"],
"assetId": "projectcapture:blastoise-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:pikachu", "displayName": "Pikachu", "catalogNumber": 25, "form": "BASE", "types": ["ELECTRIC"],
"rarity": "UNCOMMON", "captureRate": 179, "baseStats": { "vitality": 36, "power": 54, "guard": 34, "agility": 92 },
"basicMoveId": "projectcapture:static-spark", "commandMoveIds": ["projectcapture:thunder-arc", "projectcapture:quick-step", "projectcapture:guard-stance"],
"evolution": { "method": "ITEM", "targetSpeciesId": "projectcapture:raichu", "itemId": "projectcapture:thunder-core" },
"assetId": "projectcapture:pikachu-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:raichu", "displayName": "Raichu", "catalogNumber": 26, "form": "STAGE_1", "types": ["ELECTRIC"],
"rarity": "RARE", "captureRate": 99, "baseStats": { "vitality": 60, "power": 84, "guard": 56, "agility": 108 },
"basicMoveId": "projectcapture:static-spark", "commandMoveIds": ["projectcapture:thunder-arc", "projectcapture:quick-step", "projectcapture:guard-stance"],
"assetId": "projectcapture:raichu-assets", "unofficialFanContent": true
},
{
"schemaVersion": 1, "id": "projectcapture:ditto", "displayName": "Ditto", "catalogNumber": 132, "form": "SINGLE", "types": ["NORMAL"],
"rarity": "RARE", "captureRate": 122, "baseStats": { "vitality": 48, "power": 48, "guard": 48, "agility": 48 },
"basicMoveId": "projectcapture:morph-strike", "commandMoveIds": ["projectcapture:mirror-form", "projectcapture:guard-stance", "projectcapture:quick-step"],
"assetId": "projectcapture:ditto-assets", "unofficialFanContent": true
}
]
}
+10
View File
@@ -0,0 +1,10 @@
# Content tools
`content-tools` is a Java 25 command-line validator for the ProjectCapture metadata catalogs.
Commands:
- `validate <content-root>` checks schema versions, stable IDs, references, evolution graphs, level and party metadata, spawn coverage, recipes and safe asset paths.
- `digest <content-root>` prints a deterministic SHA-256 digest for reproducible review records.
The catalog must declare itself unofficial, non-commercial and subject to rights review. No Gradle publishing plugin, repository or upload target is configured here.
+47
View File
@@ -0,0 +1,47 @@
plugins {
java
application
}
repositories {
mavenCentral()
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
dependencies {
implementation("com.fasterxml.jackson.core:jackson-databind:2.20.0")
testImplementation(project(":engine"))
testImplementation(platform("org.junit:junit-bom:5.13.4"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
application {
mainClass = "dev.projectcapture.contenttools.ContentTool"
}
val fanContentRoot = rootProject.layout.projectDirectory
.dir("content-pokemon/src/main/resources/projectcapture/content/v1")
tasks.test {
useJUnitPlatform()
systemProperty("projectCapture.contentRoot", fanContentRoot.asFile.absolutePath)
}
tasks.register<JavaExec>("validateFanContent") {
group = "verification"
description = "Validates the unofficial, non-commercial fan-content catalog."
classpath = sourceSets.main.get().runtimeClasspath
mainClass = application.mainClass
args("validate", fanContentRoot.asFile.absolutePath)
}
tasks.named("check") {
dependsOn("validateFanContent")
}
@@ -0,0 +1,112 @@
package dev.projectcapture.contenttools;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class ContentBundle {
public static final int CURRENT_SCHEMA_VERSION = 1;
public static final List<String> REQUIRED_DOCUMENTS = List.of(
"manifest.json",
"moves.json",
"species.json",
"spawn-rules.json",
"recipes.json",
"assets.json"
);
private static final ObjectMapper JSON = new ObjectMapper()
.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
private final Path root;
private final Map<String, JsonNode> documents;
private ContentBundle(Path root, Map<String, JsonNode> documents) {
this.root = root;
this.documents = Map.copyOf(documents);
}
public static ContentBundle load(Path requestedRoot) throws IOException {
Path root = requestedRoot.toAbsolutePath().normalize();
if (!Files.isDirectory(root)) {
throw new IOException("Content root is not a directory: " + root);
}
Map<String, JsonNode> documents = new LinkedHashMap<>();
for (String name : REQUIRED_DOCUMENTS) {
Path document = root.resolve(name).normalize();
if (!document.startsWith(root)) {
throw new IOException("Document escaped content root: " + name);
}
if (!Files.isRegularFile(document)) {
throw new IOException("Required content document is missing: " + document);
}
JsonNode parsed = JSON.readTree(document.toFile());
if (parsed == null || !parsed.isObject()) {
throw new IOException("Content document must contain one JSON object: " + document);
}
documents.put(name, parsed);
}
return new ContentBundle(root, documents);
}
public Path root() {
return root;
}
public JsonNode document(String name) {
JsonNode node = documents.get(name);
if (node == null) {
throw new IllegalArgumentException("Unknown content document: " + name);
}
return node;
}
public Map<String, JsonNode> documents() {
return documents;
}
public String digest() {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
REQUIRED_DOCUMENTS.stream().sorted().forEach(name -> {
try {
digest.update(name.getBytes(StandardCharsets.UTF_8));
digest.update((byte) 0);
digest.update(Files.readAllBytes(root.resolve(name)));
digest.update((byte) 0);
} catch (IOException exception) {
throw new DigestReadException(exception);
}
});
return "sha256:" + HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is unavailable", exception);
} catch (DigestReadException exception) {
throw new IllegalStateException("Could not calculate content digest", exception.getCause());
}
}
static ObjectMapper json() {
return JSON;
}
private static final class DigestReadException extends RuntimeException {
private static final long serialVersionUID = 1L;
private DigestReadException(IOException cause) {
super(cause);
}
}
}
@@ -0,0 +1,67 @@
package dev.projectcapture.contenttools;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;
public final class ContentTool {
private ContentTool() {}
public static void main(String[] args) {
int exitCode = run(args, System.out, System.err);
if (exitCode != 0) {
System.exit(exitCode);
}
}
static int run(String[] args, PrintStream out, PrintStream err) {
if (args.length != 2) {
printUsage(err);
return 64;
}
Path contentRoot = Path.of(args[1]).toAbsolutePath().normalize();
return switch (args[0]) {
case "validate" -> validate(contentRoot, out, err);
case "digest" -> digest(contentRoot, out, err);
default -> {
err.println("Unknown command: " + args[0]);
printUsage(err);
yield 64;
}
};
}
private static int validate(Path contentRoot, PrintStream out, PrintStream err) {
ValidationReport report = new ContentValidator().validate(contentRoot);
if (!report.isValid()) {
err.println("Content validation failed with " + report.issues().size() + " issue(s):");
report.issues().forEach(issue -> err.println("- " + issue));
return 2;
}
out.println("Content validation passed: " + contentRoot);
return 0;
}
private static int digest(Path contentRoot, PrintStream out, PrintStream err) {
ValidationReport report = new ContentValidator().validate(contentRoot);
if (!report.isValid()) {
err.println("Digest refused because content validation failed:");
report.issues().forEach(issue -> err.println("- " + issue));
return 2;
}
try {
out.println(ContentBundle.load(contentRoot).digest());
return 0;
} catch (IOException | RuntimeException exception) {
err.println("Could not calculate digest: " + exception.getMessage());
return 2;
}
}
private static void printUsage(PrintStream stream) {
stream.println("Usage:");
stream.println(" content-tools validate <content-root>");
stream.println(" content-tools digest <content-root>");
}
}
@@ -0,0 +1,701 @@
package dev.projectcapture.contenttools;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
public final class ContentValidator {
private static final Pattern STABLE_ID = Pattern.compile("^[a-z][a-z0-9_-]*:[a-z0-9][a-z0-9_-]*$");
private static final Pattern HEX_COLOR = Pattern.compile("^#[0-9A-Fa-f]{6}$");
static final Set<String> ENGINE_ELEMENT_TYPES = Set.of(
"NORMAL", "GRASS", "POISON", "FIRE", "FLYING", "WATER", "ELECTRIC", "PSYCHIC",
"GROUND", "ROCK", "ICE", "BUG", "FIGHTING", "GHOST", "DRAGON"
);
static final Set<String> ENGINE_RARITIES = Set.of("COMMON", "UNCOMMON", "RARE", "EPIC", "LEGENDARY");
static final Set<String> ENGINE_MOVE_CATEGORIES = Set.of("PHYSICAL", "SPECIAL", "STATUS");
static final Set<String> UNOFFICIAL_SLICE_SPECIES = Set.of(
"projectcapture:bulbasaur",
"projectcapture:ivysaur",
"projectcapture:venusaur",
"projectcapture:charmander",
"projectcapture:charmeleon",
"projectcapture:charizard",
"projectcapture:squirtle",
"projectcapture:wartortle",
"projectcapture:blastoise",
"projectcapture:pikachu",
"projectcapture:raichu",
"projectcapture:ditto"
);
public ValidationReport validate(Path root) {
ValidationReport report = new ValidationReport();
try {
report.addAll(validate(ContentBundle.load(root)));
} catch (IOException | RuntimeException exception) {
report.add("CONTENT_LOAD", root.toString(), exception.getMessage());
}
return report;
}
public ValidationReport validate(ContentBundle bundle) {
ValidationReport report = new ValidationReport();
bundle.documents().forEach((name, document) -> validateDocumentHeader(name, document, report));
JsonNode manifest = bundle.document("manifest.json");
Set<String> expectedSpecies = validateManifest(manifest, report);
Map<String, String> moveRoles = validateMoves(bundle.document("moves.json"), report);
Set<String> producedItems = validateRecipes(bundle.document("recipes.json"), report);
AssetIndex assets = validateAssets(bundle.document("assets.json"), report);
SpeciesIndex species = validateSpecies(
bundle.document("species.json"), moveRoles, producedItems, assets, report
);
if (!species.ids.equals(expectedSpecies)) {
Set<String> missing = new LinkedHashSet<>(expectedSpecies);
missing.removeAll(species.ids);
Set<String> unexpected = new LinkedHashSet<>(species.ids);
unexpected.removeAll(expectedSpecies);
report.add(
"SPECIES_SET",
"species.json.items",
"Species must exactly match manifest.expectedSpeciesIds; missing=" + missing + ", unexpected=" + unexpected
);
}
if ("UNOFFICIAL_TWELVE_FORM_SLICE".equals(text(manifest, "contentProfile"))
&& !expectedSpecies.equals(UNOFFICIAL_SLICE_SPECIES)) {
report.add(
"UNOFFICIAL_SLICE",
"manifest.json.expectedSpeciesIds",
"The unofficial twelve-form profile must contain exactly the selected twelve development forms"
);
}
validateEvolutionGraph(species.evolutionTargets, report);
validateAssetCoverage(species.ids, assets, report);
validateSpawns(bundle.document("spawn-rules.json"), species.ids, report);
return report;
}
private void validateDocumentHeader(String name, JsonNode document, ValidationReport report) {
if (document.path("schemaVersion").asInt(-1) != ContentBundle.CURRENT_SCHEMA_VERSION) {
report.add(
"SCHEMA_VERSION",
name + ".schemaVersion",
"Expected schemaVersion " + ContentBundle.CURRENT_SCHEMA_VERSION
);
}
if (!document.path("unofficialFanContent").isBoolean() || !document.path("unofficialFanContent").asBoolean()) {
report.add(
"FAN_CONTENT_MARKER",
name + ".unofficialFanContent",
"Fan-content documents must be explicitly marked unofficialFanContent=true"
);
}
}
private Set<String> validateManifest(JsonNode manifest, ValidationReport report) {
requireId(manifest, "contentSetId", "manifest.json.contentSetId", report);
requireText(manifest, "contentProfile", "manifest.json.contentProfile", report);
if (!"UNOFFICIAL_FAN_CONTENT".equals(text(manifest, "publicationStatus"))) {
report.add(
"PUBLICATION_STATUS",
"manifest.json.publicationStatus",
"Fan-content catalog must declare UNOFFICIAL_FAN_CONTENT"
);
}
if (!manifest.path("nonCommercial").asBoolean(false)) {
report.add("NON_COMMERCIAL", "manifest.json.nonCommercial", "Fan-content catalog must remain non-commercial");
}
if (!manifest.path("rightsReviewRequired").asBoolean(false)) {
report.add(
"RIGHTS_REVIEW",
"manifest.json.rightsReviewRequired",
"Fan-content catalog must require an explicit rights review"
);
}
JsonNode gameplay = manifest.path("gameplay");
requireExactInt(gameplay, "minimumLevel", 1, "manifest.json.gameplay", report);
requireExactInt(gameplay, "maximumLevel", 100, "manifest.json.gameplay", report);
requireExactInt(gameplay, "maximumPartySize", 6, "manifest.json.gameplay", report);
requireExactInt(gameplay, "visibleCompanionLimit", 1, "manifest.json.gameplay", report);
requireExactInt(gameplay, "commandedMoveSlots", 3, "manifest.json.gameplay", report);
if (!gameplay.path("starterGrantEnabled").isBoolean() || gameplay.path("starterGrantEnabled").asBoolean()) {
report.add(
"STARTER_POLICY",
"manifest.json.gameplay.starterGrantEnabled",
"The slice grants no starter; only capture-device crafting is unlocked"
);
}
Set<String> expected = new LinkedHashSet<>();
JsonNode list = manifest.path("expectedSpeciesIds");
if (!list.isArray() || list.isEmpty()) {
report.add("EXPECTED_SPECIES", "manifest.json.expectedSpeciesIds", "Expected species list must be non-empty");
return expected;
}
for (int index = 0; index < list.size(); index++) {
String location = "manifest.json.expectedSpeciesIds[" + index + "]";
String id = list.path(index).asText("");
validateIdValue(id, location, report);
if (!expected.add(id)) {
report.add("DUPLICATE_ID", location, "Duplicate expected species ID: " + id);
}
}
return expected;
}
private Map<String, String> validateMoves(JsonNode document, ValidationReport report) {
Map<String, String> roles = new LinkedHashMap<>();
ArrayNode items = requireItems(document, "moves.json", report);
for (int index = 0; index < items.size(); index++) {
JsonNode move = items.path(index);
String location = "moves.json.items[" + index + "]";
requireUnofficialItem(move, location, report);
String id = requireId(move, "id", location + ".id", report);
if (!id.isEmpty() && roles.containsKey(id)) {
report.add("DUPLICATE_ID", location + ".id", "Duplicate move ID: " + id);
}
requireCurrentSchema(move, location, report);
rejectLegacyField(move, "name", location, report);
rejectLegacyField(move, "element", location, report);
requireText(move, "displayName", location + ".displayName", report);
requireEnum(move, "type", ENGINE_ELEMENT_TYPES, location, report);
String category = requireEnum(move, "category", ENGINE_MOVE_CATEGORIES, location, report);
int power = requireIntegerRange(move, "power", 0, 250, location, report);
requireNumberRange(move, "accuracy", 0.0, 1.0, location, report);
requireIntegerRange(move, "priority", -7, 7, location, report);
String role = requireEnum(move, "role", Set.of("BASIC", "COMMAND"), location, report);
requireNumberRange(move, "cooldownSeconds", 0.1, 120, location, report);
if (!category.isEmpty() && !"STATUS".equals(category) && power == 0) {
report.add(
"MOVE_POWER_CATEGORY",
location + ".power",
"Engine damaging moves must have positive power"
);
}
if (!id.isEmpty()) {
roles.putIfAbsent(id, role);
}
}
if (roles.isEmpty()) {
report.add("MOVE_EMPTY", "moves.json.items", "At least one move is required");
}
return roles;
}
private Set<String> validateRecipes(JsonNode document, ValidationReport report) {
Set<String> ids = new HashSet<>();
Set<String> outputs = new LinkedHashSet<>();
boolean unlockedCaptureDevice = false;
ArrayNode items = requireItems(document, "recipes.json", report);
for (int index = 0; index < items.size(); index++) {
JsonNode recipe = items.path(index);
String location = "recipes.json.items[" + index + "]";
requireUnofficialItem(recipe, location, report);
String id = requireId(recipe, "id", location + ".id", report);
if (!id.isEmpty() && !ids.add(id)) {
report.add("DUPLICATE_ID", location + ".id", "Duplicate recipe ID: " + id);
}
String category = requireText(recipe, "category", location + ".category", report);
JsonNode output = recipe.path("output");
String outputId = requireId(output, "itemId", location + ".output.itemId", report);
requireIntegerRange(output, "quantity", 1, 999, location + ".output", report);
if (!outputId.isEmpty()) {
outputs.add(outputId);
}
JsonNode ingredients = recipe.path("ingredients");
if (!ingredients.isArray() || ingredients.isEmpty()) {
report.add("RECIPE_INGREDIENTS", location + ".ingredients", "Recipe ingredients must be non-empty");
} else {
for (int ingredientIndex = 0; ingredientIndex < ingredients.size(); ingredientIndex++) {
JsonNode ingredient = ingredients.path(ingredientIndex);
String ingredientLocation = location + ".ingredients[" + ingredientIndex + "]";
requireId(ingredient, "itemId", ingredientLocation + ".itemId", report);
requireIntegerRange(ingredient, "quantity", 1, 999, ingredientLocation, report);
}
}
if ("CAPTURE_DEVICE".equals(category) && recipe.path("unlockedByDefault").asBoolean(false)) {
unlockedCaptureDevice = true;
}
}
if (!unlockedCaptureDevice) {
report.add(
"CAPTURE_RECIPE",
"recipes.json.items",
"At least one capture-device recipe must be unlocked by default"
);
}
return outputs;
}
private AssetIndex validateAssets(JsonNode document, ValidationReport report) {
Set<String> ids = new LinkedHashSet<>();
Map<String, String> speciesByAsset = new LinkedHashMap<>();
Map<String, Integer> countBySpecies = new HashMap<>();
ArrayNode items = requireItems(document, "assets.json", report);
for (int index = 0; index < items.size(); index++) {
JsonNode asset = items.path(index);
String location = "assets.json.items[" + index + "]";
requireUnofficialItem(asset, location, report);
String id = requireId(asset, "id", location + ".id", report);
String speciesId = requireId(asset, "speciesId", location + ".speciesId", report);
if (!id.isEmpty() && !ids.add(id)) {
report.add("DUPLICATE_ID", location + ".id", "Duplicate asset ID: " + id);
}
if (!id.isEmpty()) {
speciesByAsset.putIfAbsent(id, speciesId);
}
if (!speciesId.isEmpty()) {
countBySpecies.merge(speciesId, 1, Integer::sum);
}
requireEnum(asset, "status", Set.of("PLANNED", "READY"), location, report);
requireIntegerRange(asset, "seed", 0, Integer.MAX_VALUE, location, report);
requireText(asset, "bodyPlan", location + ".bodyPlan", report);
requireNonEmptyTextArray(asset.path("sockets"), location + ".sockets", report);
JsonNode palette = asset.path("palette");
if (!palette.isArray() || palette.size() < 2) {
report.add("ASSET_PALETTE", location + ".palette", "Asset palette needs at least two colors");
} else {
for (int paletteIndex = 0; paletteIndex < palette.size(); paletteIndex++) {
if (!HEX_COLOR.matcher(palette.path(paletteIndex).asText("")).matches()) {
report.add("ASSET_PALETTE", location + ".palette[" + paletteIndex + "]", "Expected #RRGGBB");
}
}
}
validateAssetPath(asset, "source", ".bbmodel", location, report);
validateAssetPath(asset, "model", ".blockymodel", location, report);
validateAssetPath(asset, "texture", ".png", location, report);
validateAssetPath(asset, "recipe", ".asset.json", location, report);
JsonNode animations = asset.path("animations");
if (!animations.isObject()) {
report.add("ASSET_ANIMATIONS", location + ".animations", "Animations must be an object");
} else {
for (String animation : List.of("idle", "walk", "attack")) {
validateAssetPath(animations, animation, ".blockyanim", location + ".animations", report);
}
}
}
return new AssetIndex(ids, speciesByAsset, countBySpecies);
}
private SpeciesIndex validateSpecies(
JsonNode document,
Map<String, String> moveRoles,
Set<String> producedItems,
AssetIndex assets,
ValidationReport report
) {
Set<String> ids = new LinkedHashSet<>();
Set<Integer> catalogNumbers = new HashSet<>();
Map<String, String> evolutionTargets = new LinkedHashMap<>();
List<PendingSpeciesReferences> pending = new ArrayList<>();
ArrayNode items = requireItems(document, "species.json", report);
for (int index = 0; index < items.size(); index++) {
JsonNode species = items.path(index);
String location = "species.json.items[" + index + "]";
requireUnofficialItem(species, location, report);
String id = requireId(species, "id", location + ".id", report);
if (!id.isEmpty() && !ids.add(id)) {
report.add("DUPLICATE_ID", location + ".id", "Duplicate species ID: " + id);
}
requireCurrentSchema(species, location, report);
requireText(species, "displayName", location + ".displayName", report);
int catalogNumber = requireIntegerRange(species, "catalogNumber", 1, 9999, location, report);
if (catalogNumber >= 0 && !catalogNumbers.add(catalogNumber)) {
report.add("DUPLICATE_CATALOG_NUMBER", location + ".catalogNumber", "Duplicate catalog number: " + catalogNumber);
}
requireEnum(species, "form", Set.of("BASE", "STAGE_1", "STAGE_2", "SINGLE"), location, report);
rejectLegacyField(species, "elements", location, report);
rejectLegacyField(species, "captureDifficulty", location, report);
requireEnumArray(species.path("types"), ENGINE_ELEMENT_TYPES, 1, 2, location + ".types", report);
requireEnum(species, "rarity", ENGINE_RARITIES, location, report);
requireIntegerRange(species, "captureRate", 1, 255, location, report);
JsonNode stats = species.path("baseStats");
for (String stat : List.of("vitality", "power", "guard", "agility")) {
requireIntegerRange(stats, stat, 1, 255, location + ".baseStats", report);
}
String basicMove = requireId(species, "basicMoveId", location + ".basicMoveId", report);
if (!basicMove.isEmpty() && !moveRoles.containsKey(basicMove)) {
report.add("UNKNOWN_MOVE", location + ".basicMoveId", "Unknown move: " + basicMove);
} else if (!basicMove.isEmpty() && !"BASIC".equals(moveRoles.get(basicMove))) {
report.add("MOVE_ROLE", location + ".basicMoveId", "Basic move must have role BASIC");
}
List<String> commandMoves = validateCommandMoves(species.path("commandMoveIds"), moveRoles, location, report);
if (commandMoves.contains(basicMove)) {
report.add("MOVE_ROLE", location + ".commandMoveIds", "Basic move cannot also occupy a command slot");
}
String assetId = requireId(species, "assetId", location + ".assetId", report);
if (!assetId.isEmpty() && !assets.ids.contains(assetId)) {
report.add("UNKNOWN_ASSET", location + ".assetId", "Unknown asset record: " + assetId);
}
JsonNode evolution = species.path("evolution");
String target = "";
if (!evolution.isMissingNode() && !evolution.isNull()) {
if (!evolution.isObject()) {
report.add("EVOLUTION_SHAPE", location + ".evolution", "Evolution must be an object");
} else {
String method = requireEnum(evolution, "method", Set.of("LEVEL", "ITEM"), location + ".evolution", report);
target = requireId(evolution, "targetSpeciesId", location + ".evolution.targetSpeciesId", report);
if ("LEVEL".equals(method)) {
requireIntegerRange(evolution, "minimumLevel", 2, 100, location + ".evolution", report);
} else if ("ITEM".equals(method)) {
String itemId = requireId(evolution, "itemId", location + ".evolution.itemId", report);
if (!itemId.isEmpty() && !producedItems.contains(itemId)) {
report.add("UNKNOWN_EVOLUTION_ITEM", location + ".evolution.itemId", "No recipe produces " + itemId);
}
}
if (!id.isEmpty() && !target.isEmpty()) {
evolutionTargets.put(id, target);
}
}
}
pending.add(new PendingSpeciesReferences(location, id, target, assetId));
}
for (PendingSpeciesReferences reference : pending) {
if (!reference.target.isEmpty() && !ids.contains(reference.target)) {
report.add("UNKNOWN_EVOLUTION_TARGET", reference.location + ".evolution.targetSpeciesId", "Unknown species: " + reference.target);
}
if (!reference.assetId.isEmpty()) {
String assetSpecies = assets.speciesByAsset.get(reference.assetId);
if (assetSpecies != null && !assetSpecies.equals(reference.id)) {
report.add("ASSET_SPECIES_MISMATCH", reference.location + ".assetId", "Asset belongs to " + assetSpecies);
}
}
}
return new SpeciesIndex(ids, evolutionTargets);
}
private List<String> validateCommandMoves(
JsonNode moves,
Map<String, String> moveRoles,
String location,
ValidationReport report
) {
List<String> result = new ArrayList<>();
if (!moves.isArray() || moves.size() != 3) {
report.add("COMMAND_SLOTS", location + ".commandMoveIds", "Exactly three commanded moves are required");
return result;
}
Set<String> unique = new HashSet<>();
for (int index = 0; index < moves.size(); index++) {
String move = moves.path(index).asText("");
String moveLocation = location + ".commandMoveIds[" + index + "]";
validateIdValue(move, moveLocation, report);
if (!unique.add(move)) {
report.add("DUPLICATE_COMMAND_MOVE", moveLocation, "Command moves must be unique");
}
if (!moveRoles.containsKey(move)) {
report.add("UNKNOWN_MOVE", moveLocation, "Unknown move: " + move);
} else if (!"COMMAND".equals(moveRoles.get(move))) {
report.add("MOVE_ROLE", moveLocation, "Command move must have role COMMAND");
}
result.add(move);
}
return result;
}
private void validateEvolutionGraph(Map<String, String> targets, ValidationReport report) {
Map<String, Integer> state = new HashMap<>();
for (String species : targets.keySet()) {
visitEvolution(species, targets, state, new ArrayList<>(), report);
}
}
private void visitEvolution(
String species,
Map<String, String> targets,
Map<String, Integer> state,
List<String> path,
ValidationReport report
) {
int currentState = state.getOrDefault(species, 0);
if (currentState == 2) {
return;
}
if (currentState == 1) {
path.add(species);
report.add("EVOLUTION_CYCLE", "species.json", "Evolution cycle: " + String.join(" -> ", path));
return;
}
state.put(species, 1);
path.add(species);
String target = targets.get(species);
if (target != null) {
visitEvolution(target, targets, state, new ArrayList<>(path), report);
}
state.put(species, 2);
}
private void validateAssetCoverage(Set<String> species, AssetIndex assets, ValidationReport report) {
for (String speciesId : species) {
int count = assets.countBySpecies.getOrDefault(speciesId, 0);
if (count != 1) {
report.add("ASSET_COVERAGE", "assets.json.items", speciesId + " must have exactly one asset record; found " + count);
}
}
for (String assetSpecies : assets.countBySpecies.keySet()) {
if (!species.contains(assetSpecies)) {
report.add("UNKNOWN_ASSET_SPECIES", "assets.json.items", "Asset references unknown species: " + assetSpecies);
}
}
}
private void validateSpawns(JsonNode document, Set<String> species, ValidationReport report) {
Set<String> ids = new HashSet<>();
Map<String, Integer> countBySpecies = new HashMap<>();
ArrayNode items = requireItems(document, "spawn-rules.json", report);
for (int index = 0; index < items.size(); index++) {
JsonNode spawn = items.path(index);
String location = "spawn-rules.json.items[" + index + "]";
requireUnofficialItem(spawn, location, report);
String id = requireId(spawn, "id", location + ".id", report);
if (!id.isEmpty() && !ids.add(id)) {
report.add("DUPLICATE_ID", location + ".id", "Duplicate spawn ID: " + id);
}
String speciesId = requireId(spawn, "speciesId", location + ".speciesId", report);
if (!speciesId.isEmpty() && !species.contains(speciesId)) {
report.add("UNKNOWN_SPAWN_SPECIES", location + ".speciesId", "Unknown species: " + speciesId);
}
countBySpecies.merge(speciesId, 1, Integer::sum);
requireNonEmptyTextArray(spawn.path("biomes"), location + ".biomes", report);
requireEnum(spawn, "time", Set.of("DAY", "NIGHT", "ANY"), location, report);
requireIntegerRange(spawn, "rarityWeight", 1, 100, location, report);
int minimum = requireIntegerRange(spawn, "minimumLevel", 1, 100, location, report);
int maximum = requireIntegerRange(spawn, "maximumLevel", 1, 100, location, report);
if (minimum >= 0 && maximum >= 0 && minimum > maximum) {
report.add("SPAWN_LEVEL_RANGE", location, "minimumLevel must not exceed maximumLevel");
}
}
for (String speciesId : species) {
if (countBySpecies.getOrDefault(speciesId, 0) < 1) {
report.add("SPAWN_COVERAGE", "spawn-rules.json.items", "No spawn rule for " + speciesId);
}
}
}
private void validateAssetPath(
JsonNode node,
String field,
String extension,
String location,
ValidationReport report
) {
String value = requireText(node, field, location + "." + field, report);
if (value.isEmpty()) {
return;
}
if (value.contains("\\") || value.contains("://") || value.matches("^[A-Za-z]:.*")) {
report.add("ASSET_PATH", location + "." + field, "Asset path must be a portable relative path");
return;
}
try {
Path path = Path.of(value);
String normalized = path.normalize().toString().replace('\\', '/');
if (path.isAbsolute() || !normalized.equals(value) || value.contains("../") || !value.startsWith("assets/fan/")) {
report.add("ASSET_PATH", location + "." + field, "Asset path must stay below assets/fan without traversal");
}
} catch (InvalidPathException exception) {
report.add("ASSET_PATH", location + "." + field, "Invalid asset path: " + exception.getMessage());
}
if (!value.endsWith(extension)) {
report.add("ASSET_EXTENSION", location + "." + field, "Expected extension " + extension);
}
}
private ArrayNode requireItems(JsonNode document, String name, ValidationReport report) {
JsonNode items = document.path("items");
if (!items.isArray()) {
report.add("ITEMS_SHAPE", name + ".items", "Expected an array");
return ContentBundle.json().createArrayNode();
}
return (ArrayNode) items;
}
private void requireUnofficialItem(JsonNode item, String location, ValidationReport report) {
if (!item.path("unofficialFanContent").isBoolean() || !item.path("unofficialFanContent").asBoolean()) {
report.add("FAN_CONTENT_MARKER", location + ".unofficialFanContent", "Fan-content entries must be explicitly marked");
}
}
private String requireId(JsonNode node, String field, String location, ValidationReport report) {
String value = requireText(node, field, location, report);
if (!value.isEmpty()) {
validateIdValue(value, location, report);
}
return value;
}
private void validateIdValue(String value, String location, ValidationReport report) {
if (!STABLE_ID.matcher(value).matches()) {
report.add("INVALID_ID", location, "Expected lowercase namespace:value stable ID");
}
}
private String requireText(JsonNode node, String field, String location, ValidationReport report) {
JsonNode value = node.path(field);
if (!value.isTextual() || value.asText().isBlank()) {
report.add("REQUIRED_TEXT", location, "Expected non-blank text");
return "";
}
return value.asText();
}
private String requireEnum(JsonNode node, String field, Set<String> allowed, String location, ValidationReport report) {
String value = requireText(node, field, location + "." + field, report);
if (!value.isEmpty() && !allowed.contains(value)) {
report.add("ENUM_VALUE", location + "." + field, "Expected one of " + allowed + ", got " + value);
}
return value;
}
private int requireIntegerRange(
JsonNode node,
String field,
int minimum,
int maximum,
String location,
ValidationReport report
) {
JsonNode value = node.path(field);
if (!value.isIntegralNumber() || !value.canConvertToInt()) {
report.add("INTEGER_VALUE", location + "." + field, "Expected an integer");
return -1;
}
int number = value.asInt();
if (number < minimum || number > maximum) {
report.add("INTEGER_RANGE", location + "." + field, "Expected " + minimum + ".." + maximum);
}
return number;
}
private void requireNumberRange(
JsonNode node,
String field,
double minimum,
double maximum,
String location,
ValidationReport report
) {
JsonNode value = node.path(field);
if (!value.isNumber()) {
report.add("NUMBER_VALUE", location + "." + field, "Expected a number");
return;
}
double number = value.asDouble();
if (!Double.isFinite(number) || number < minimum || number > maximum) {
report.add("NUMBER_RANGE", location + "." + field, "Expected " + minimum + ".." + maximum);
}
}
private void requireExactInt(JsonNode node, String field, int expected, String location, ValidationReport report) {
JsonNode value = node.path(field);
if (!value.isIntegralNumber() || value.asInt() != expected) {
report.add("GAMEPLAY_METADATA", location + "." + field, "Expected " + expected);
}
}
private void requireCurrentSchema(JsonNode node, String location, ValidationReport report) {
JsonNode version = node.path("schemaVersion");
if (!version.isIntegralNumber() || version.asInt() != ContentBundle.CURRENT_SCHEMA_VERSION) {
report.add(
"SCHEMA_VERSION",
location + ".schemaVersion",
"Expected engine-compatible schemaVersion " + ContentBundle.CURRENT_SCHEMA_VERSION
);
}
}
private void rejectLegacyField(JsonNode node, String field, String location, ValidationReport report) {
if (node.has(field)) {
report.add(
"LEGACY_FIELD",
location + "." + field,
"Legacy field is not allowed in the engine-aligned schema"
);
}
}
private void requireEnumArray(
JsonNode node,
Set<String> allowed,
int minimumSize,
int maximumSize,
String location,
ValidationReport report
) {
requireNonEmptyTextArray(node, location, report);
if (!node.isArray()) {
return;
}
if (node.size() < minimumSize || node.size() > maximumSize) {
report.add(
"ARRAY_SIZE",
location,
"Expected " + minimumSize + ".." + maximumSize + " values"
);
}
for (int index = 0; index < node.size(); index++) {
JsonNode value = node.path(index);
if (value.isTextual() && !allowed.contains(value.asText())) {
report.add(
"ENUM_VALUE",
location + "[" + index + "]",
"Expected one of " + allowed + ", got " + value.asText()
);
}
}
}
private void requireNonEmptyTextArray(JsonNode node, String location, ValidationReport report) {
if (!node.isArray() || node.isEmpty()) {
report.add("TEXT_ARRAY", location, "Expected a non-empty text array");
return;
}
Set<String> values = new HashSet<>();
for (int index = 0; index < node.size(); index++) {
JsonNode value = node.path(index);
if (!value.isTextual() || value.asText().isBlank()) {
report.add("TEXT_ARRAY", location + "[" + index + "]", "Expected non-blank text");
} else if (!values.add(value.asText())) {
report.add("TEXT_ARRAY_DUPLICATE", location + "[" + index + "]", "Duplicate value: " + value.asText());
}
}
}
private static String text(JsonNode node, String field) {
return node.path(field).isTextual() ? node.path(field).asText() : "";
}
private record AssetIndex(
Set<String> ids,
Map<String, String> speciesByAsset,
Map<String, Integer> countBySpecies
) {}
private record SpeciesIndex(Set<String> ids, Map<String, String> evolutionTargets) {}
private record PendingSpeciesReferences(String location, String id, String target, String assetId) {}
}
@@ -0,0 +1,8 @@
package dev.projectcapture.contenttools;
public record ValidationIssue(String code, String location, String message) {
@Override
public String toString() {
return code + " at " + location + ": " + message;
}
}
@@ -0,0 +1,29 @@
package dev.projectcapture.contenttools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class ValidationReport {
private final List<ValidationIssue> issues = new ArrayList<>();
public void add(String code, String location, String message) {
issues.add(new ValidationIssue(code, location, message));
}
public void addAll(ValidationReport other) {
issues.addAll(other.issues);
}
public boolean isValid() {
return issues.isEmpty();
}
public List<ValidationIssue> issues() {
return Collections.unmodifiableList(issues);
}
public boolean containsCode(String code) {
return issues.stream().anyMatch(issue -> issue.code().equals(code));
}
}
@@ -0,0 +1,43 @@
package dev.projectcapture.contenttools;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ContentToolTest {
@Test
void validateCommandSucceedsForCatalog() {
Path root = Path.of(System.getProperty("projectCapture.contentRoot"));
ByteArrayOutputStream standardOut = new ByteArrayOutputStream();
ByteArrayOutputStream standardError = new ByteArrayOutputStream();
int exitCode = ContentTool.run(
new String[] { "validate", root.toString() },
new PrintStream(standardOut, true, StandardCharsets.UTF_8),
new PrintStream(standardError, true, StandardCharsets.UTF_8)
);
assertEquals(0, exitCode, standardError::toString);
assertTrue(standardOut.toString(StandardCharsets.UTF_8).contains("Content validation passed"));
}
@Test
void unknownCommandReturnsUsageError() {
ByteArrayOutputStream error = new ByteArrayOutputStream();
int exitCode = ContentTool.run(
new String[] { "publish", "." },
new PrintStream(new ByteArrayOutputStream()),
new PrintStream(error)
);
assertEquals(64, exitCode);
assertTrue(error.toString(StandardCharsets.UTF_8).contains("Unknown command"));
}
}
@@ -0,0 +1,247 @@
package dev.projectcapture.contenttools;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import dev.projectcapture.engine.model.ElementType;
import dev.projectcapture.engine.model.MoveDefinition;
import dev.projectcapture.engine.model.SpeciesDefinition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ContentValidatorTest {
@TempDir
Path temporaryDirectory;
private Path contentRoot;
@BeforeEach
void copyRealCatalog() throws IOException {
Path source = Path.of(System.getProperty("projectCapture.contentRoot"));
contentRoot = temporaryDirectory.resolve("content");
Files.createDirectories(contentRoot);
for (String document : ContentBundle.REQUIRED_DOCUMENTS) {
Files.copy(source.resolve(document), contentRoot.resolve(document));
}
}
@Test
void realTwelveFormCatalogPasses() throws IOException {
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.isValid(), () -> report.issues().toString());
JsonNode species = ContentBundle.load(contentRoot).document("species.json").path("items");
Set<String> ids = java.util.stream.StreamSupport.stream(species.spliterator(), false)
.map(item -> item.path("id").asText())
.collect(Collectors.toSet());
assertEquals(12, ids.size());
assertEquals(ContentValidator.UNOFFICIAL_SLICE_SPECIES, ids);
}
@Test
void allTwelveSpeciesUseEngineElementRarityAndCaptureSchema() throws IOException {
JsonNode species = ContentBundle.load(contentRoot).document("species.json").path("items");
assertEquals(12, species.size());
for (JsonNode definition : species) {
assertEquals(SpeciesDefinition.CURRENT_SCHEMA_VERSION, definition.path("schemaVersion").asInt());
assertTrue(definition.path("types").size() >= 1 && definition.path("types").size() <= 2);
for (JsonNode type : definition.path("types")) {
ElementType.valueOf(type.asText());
}
SpeciesDefinition.Rarity.valueOf(definition.path("rarity").asText());
assertTrue(definition.path("captureRate").asInt() >= 1);
assertTrue(definition.path("captureRate").asInt() <= 255);
assertFalse(definition.has("elements"));
assertFalse(definition.has("captureDifficulty"));
}
}
@Test
void allMovesConstructAsEngineMoveDefinitions() throws IOException {
JsonNode moves = ContentBundle.load(contentRoot).document("moves.json").path("items");
for (JsonNode move : moves) {
new MoveDefinition(
move.path("schemaVersion").asInt(),
move.path("id").asText(),
move.path("displayName").asText(),
ElementType.valueOf(move.path("type").asText()),
MoveDefinition.Category.valueOf(move.path("category").asText()),
move.path("power").asInt(),
move.path("accuracy").asDouble(),
move.path("priority").asInt()
);
assertFalse(move.has("name"));
assertFalse(move.has("element"));
}
}
@Test
void rejectsWrongSchemaAndDuplicateIds() throws IOException {
ObjectNode moves = object("moves.json");
moves.put("schemaVersion", 99);
ArrayNode items = (ArrayNode) moves.path("items");
items.add(items.path(0).deepCopy());
write("moves.json", moves);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("SCHEMA_VERSION"));
assertTrue(report.containsCode("DUPLICATE_ID"));
}
@Test
void rejectsNonEngineSpeciesEnumsAndCaptureRate() throws IOException {
ObjectNode species = object("species.json");
ObjectNode first = (ObjectNode) species.path("items").path(0);
((ArrayNode) first.path("types")).set(0, ContentBundle.json().getNodeFactory().textNode("TOXIN"));
first.put("rarity", "MYTHIC");
first.put("captureRate", 0);
write("species.json", species);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("ENUM_VALUE"));
assertTrue(report.containsCode("INTEGER_RANGE"));
}
@Test
void rejectsNonEngineMoveCombatFields() throws IOException {
ObjectNode moves = object("moves.json");
ObjectNode first = (ObjectNode) moves.path("items").path(0);
first.put("type", "AIR");
first.put("category", "SPECIAL");
first.put("power", 0);
first.put("accuracy", 1.1);
first.put("priority", 8);
write("moves.json", moves);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("ENUM_VALUE"));
assertTrue(report.containsCode("MOVE_POWER_CATEGORY"));
assertTrue(report.containsCode("NUMBER_RANGE"));
assertTrue(report.containsCode("INTEGER_RANGE"));
}
@Test
void rejectsUnknownMoveEvolutionAndAssetReferences() throws IOException {
ObjectNode species = object("species.json");
ObjectNode first = (ObjectNode) species.path("items").path(0);
first.put("basicMoveId", "projectcapture:missing-move");
first.put("assetId", "projectcapture:missing-assets");
((ObjectNode) first.path("evolution")).put("targetSpeciesId", "projectcapture:missing-species");
write("species.json", species);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("UNKNOWN_MOVE"));
assertTrue(report.containsCode("UNKNOWN_ASSET"));
assertTrue(report.containsCode("UNKNOWN_EVOLUTION_TARGET"));
}
@Test
void rejectsEvolutionCycles() throws IOException {
ObjectNode species = object("species.json");
ObjectNode venusaur = findItem(species, "projectcapture:venusaur");
ObjectNode evolution = venusaur.putObject("evolution");
evolution.put("method", "LEVEL");
evolution.put("targetSpeciesId", "projectcapture:bulbasaur");
evolution.put("minimumLevel", 80);
write("species.json", species);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("EVOLUTION_CYCLE"));
}
@Test
void rejectsUnsafeAssetPathsAndMissingAnimationSlots() throws IOException {
ObjectNode assets = object("assets.json");
ObjectNode first = (ObjectNode) assets.path("items").path(0);
first.put("model", "../../outside.blockymodel");
((ObjectNode) first.path("animations")).remove("attack");
write("assets.json", assets);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("ASSET_PATH"));
assertTrue(report.containsCode("REQUIRED_TEXT"));
}
@Test
void rejectsPartyLevelAndRightsMetadataDrift() throws IOException {
ObjectNode manifest = object("manifest.json");
ObjectNode gameplay = (ObjectNode) manifest.path("gameplay");
gameplay.put("minimumLevel", 0);
gameplay.put("maximumLevel", 101);
gameplay.put("maximumPartySize", 7);
gameplay.put("visibleCompanionLimit", 2);
gameplay.put("commandedMoveSlots", 4);
gameplay.put("starterGrantEnabled", true);
manifest.put("nonCommercial", false);
manifest.put("rightsReviewRequired", false);
write("manifest.json", manifest);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("GAMEPLAY_METADATA"));
assertTrue(report.containsCode("STARTER_POLICY"));
assertTrue(report.containsCode("NON_COMMERCIAL"));
assertTrue(report.containsCode("RIGHTS_REVIEW"));
}
@Test
void rejectsMissingSpawnCoverage() throws IOException {
ObjectNode spawns = object("spawn-rules.json");
((ArrayNode) spawns.path("items")).remove(0);
write("spawn-rules.json", spawns);
ValidationReport report = new ContentValidator().validate(contentRoot);
assertTrue(report.containsCode("SPAWN_COVERAGE"));
}
@Test
void digestIsStableAndChangesWithContent() throws IOException {
String first = ContentBundle.load(contentRoot).digest();
String second = ContentBundle.load(contentRoot).digest();
assertEquals(first, second);
ObjectNode recipes = object("recipes.json");
findItem(recipes, "projectcapture:basic-capture-capsule").put("unlockedByDefault", false);
write("recipes.json", recipes);
String changed = ContentBundle.load(contentRoot).digest();
assertFalse(first.equals(changed));
}
private ObjectNode object(String name) throws IOException {
return (ObjectNode) ContentBundle.json().readTree(contentRoot.resolve(name).toFile());
}
private void write(String name, JsonNode node) throws IOException {
ContentBundle.json().writerWithDefaultPrettyPrinter().writeValue(contentRoot.resolve(name).toFile(), node);
}
private static ObjectNode findItem(ObjectNode document, String id) {
for (JsonNode item : document.path("items")) {
if (id.equals(item.path("id").asText())) {
return (ObjectNode) item;
}
}
throw new IllegalArgumentException("Missing test fixture item: " + id);
}
}
+4
View File
@@ -0,0 +1,4 @@
/dist/
/.work/
/*.env
/*.token
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+19
View File
@@ -0,0 +1,19 @@
# Third-party notice and license boundary
The hardened Blockbench MCP development tool is a modified build of
[`jasonjgardner/blockbench-mcp-plugin`](https://github.com/jasonjgardner/blockbench-mcp-plugin),
pinned to version 1.6.1 / commit
`6b069e308fdfc9b0a1c15bc924ca78150815f143`.
Upstream and the modified build are licensed under **GPL-3.0-only**. The full
license text is stored in `LICENSES/GPL-3.0-only.txt`. Changes made by
ProjectCapture are represented by the patch in `patches/` and are clearly
marked as a hardened ProjectCapture variant.
The official Hytale Models plugin is a separate GPL-3.0 program and is pinned
by repository commit and distribution checksum in `upstream.lock.json`.
These Blockbench plugins are development tools. They are not embedded in, linked
into, or distributed as part of the Hytale runtime mod. Any redistribution of a
generated plugin artifact must include the corresponding source/pinned patchset,
this notice, and the GPL license.
+76
View File
@@ -0,0 +1,76 @@
# ProjectCapture Blockbench MCP
Diese Werkzeugkette erzeugt aus dem exakt gepinnten Blockbench-MCP-Upstream
einen gehärteten, reproduzierbaren Entwicklungs-Build. Sie installiert nichts
automatisch in Blockbench oder Codex und speichert keine Geheimnisse im
Repository.
## Sicherheitsprofil
- Serverbindung ausschließlich an `127.0.0.1`.
- Jede HTTP-, Health- und MCP-Anfrage benötigt einen Bearer-Token aus
`PROJECTCAPTURE_BLOCKBENCH_TOKEN` (mindestens 32 Zeichen).
- Alle Dateiimporte und -exporte liegen unter dem absoluten Verzeichnis aus
`PROJECTCAPTURE_ASSET_ROOT`; absolute Pfade, `..`, falsche Dateiendungen,
Symlink-Eltern und Symlink-Ziele werden abgewiesen.
- Die Werkzeugregistrierung ist fail-closed. `risky_eval`, frei wählbare
Blockbench-Actions, Klicksimulation, URL-Importe, beliebige Exporte und
App-Screenshots werden nicht über MCP registriert.
- Netzwerkgeladene MCP-Prompts sind im gehärteten Build entfernt.
- Codex erhält zusätzlich eine explizite Werkzeug-Allowlist aus
`examples/codex-config.toml`.
## Reproduzierbarer Ablauf
Voraussetzungen sind `git`, `pnpm` und ein POSIX-Shell-Umfeld. Bun wird über
`pnpm dlx bun@1.3.14` exakt gepinnt und nur im Paketmanager-Cache verwendet.
```sh
./scripts/test.sh
./scripts/build.sh
./scripts/stage-hytale-plugin.sh
```
`test.sh` klont Commit `6b069e3…` in ein temporäres Verzeichnis, prüft den
Patch-Hash, wendet den Patch an und führt die automatisierten Tests aus.
`build.sh` wiederholt diese Prüfung, baut anschließend das Plugin und legt nur
reviewbare Artefakte plus SHA-256-Datei in `dist/` ab.
`stage-hytale-plugin.sh` holt ausschließlich den gepinnten offiziellen
Hytale-Plugin-Commit und prüft dessen bereits veröffentlichtes Distributionsfile
gegen den Lock-Hash.
## Lokale Laufzeitwerte
Der gehärtete Build startet absichtlich nicht, solange beide Variablen fehlen:
```sh
export PROJECTCAPTURE_BLOCKBENCH_TOKEN='<zufälliger Token, nicht committen>'
export PROJECTCAPTURE_ASSET_ROOT='/absoluter/Pfad/zu/ProjectCapture/devtools/blockbench-assets'
```
Mit `scripts/create-local-env.sh AUSGABEDATEI ASSET_ROOT` kann außerhalb des
Repositories eine Datei mit Modus `0600` erzeugt werden. Das Skript verweigert
Ausgaben innerhalb dieses Git-Arbeitsbaums. Die Datei wird nicht automatisch
geladen und nicht in Codex eingetragen.
## Review und Installation
Nach erfolgreichem Review kopiert
`scripts/install-reviewed.sh --i-reviewed-gpl ZIELVERZEICHNIS` die beiden
geprüften JavaScript-Dateien in ein ausdrücklich angegebenes Verzeichnis. Das
Skript verändert keine Codex-Konfiguration. Die Vorlage
`examples/codex-config.toml` muss separat und mit
`bearer_token_env_var` übernommen werden; ein Tokenwert gehört nie in TOML.
## Hytale-Werkzeuge
Der Patch ergänzt sichere Werkzeuge für Capability-Probe, Hytale-Projekterzeugung,
Validierung, PNG-Import/-Export, `.bbmodel`, `.blockymodel`, `.blockyanim` und
Attachments. Gruppen-Defaults, Texturflags, Datenpunkte von Keyframes,
asynchrones Codec-Kompilieren sowie Quad-Normalen/-Flächen und Flat-Shading sind
korrigiert.
Der statische Build und die automatisierten Tests ersetzen nicht das Live-Gate:
Nach Installation müssen Blockbench 5.0.7 und Hytale Models 0.9.1 gemeinsam ein
neutrales Testwesen öffnen, speichern, neu laden und in alle drei Formate
exportieren. Erst danach gilt das Asset-Gate als bestanden.
@@ -0,0 +1,69 @@
# Review-Vorlage: keinen Tokenwert in diese Datei schreiben.
[mcp_servers.blockbench]
url = "http://127.0.0.1:3000/bb-mcp"
bearer_token_env_var = "PROJECTCAPTURE_BLOCKBENCH_TOKEN"
enabled = true
required = false
startup_timeout_sec = 20
tool_timeout_sec = 120
default_tools_approval_mode = "writes"
enabled_tools = [
"hytale_capability_probe",
"create_hytale_project",
"hytale_validate_project",
"get_project_info",
"add_group",
"list_outline",
"place_cube",
"modify_cube",
"remove_element",
"duplicate_element",
"rename_element",
"find_elements_by_criteria",
"get_selection",
"create_texture",
"apply_texture",
"list_textures",
"get_texture",
"activate_texture",
"paint_fill_tool",
"draw_shape_tool",
"gradient_tool",
"paint_with_brush",
"hytale_import_texture_png",
"hytale_save_texture_png",
"create_animation",
"manage_keyframes",
"bone_rigging",
"hytale_create_visibility_keyframe",
"hytale_set_animation_loop",
"hytale_get_format_info",
"hytale_set_cube_properties",
"hytale_get_cube_properties",
"hytale_create_quad",
"hytale_list_attachments",
"hytale_set_attachment_piece",
"hytale_list_attachment_pieces",
"hytale_set_cube_stretch",
"hytale_get_cube_stretch",
"hytale_create_attachment",
"hytale_save_bbmodel",
"hytale_export_blockymodel",
"hytale_export_blockyanim",
"capture_screenshot",
"set_camera_angle",
"undo",
"redo",
"get_undo_stack",
"save_checkpoint",
]
disabled_tools = [
"risky_eval",
"trigger_action",
"emulate_clicks",
"import_geojson",
"import_texture_set",
"save_material_config",
"export_model",
"capture_app_screenshot",
]
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"
require_command git
require_command pnpm
stage_parent="$(make_stage_parent)"
trap 'safe_remove_stage "${stage_parent}"' EXIT
source_dir="${stage_parent}/source"
prepare_source "${source_dir}"
run_bun install --cwd "${source_dir}" --frozen-lockfile
run_bun test --cwd "${source_dir}"
run_bun run --cwd "${source_dir}" build
output_dir="${TOOL_ROOT}/dist"
mkdir -p -- "${output_dir}"
cp -- "${source_dir}/dist/mcp.js" "${output_dir}/mcp-projectcapture-1.6.1.js"
cp -- "${source_dir}/dist/icon.svg" "${output_dir}/mcp-icon.svg"
cp -- "${source_dir}/dist/about.md" "${output_dir}/mcp-about.md"
bundle_hash="$(sha256_file "${output_dir}/mcp-projectcapture-1.6.1.js")"
write_dist_checksums "${output_dir}"
printf 'Gehärtetes Build erstellt: %s\nSHA-256: %s\n' \
"${output_dir}/mcp-projectcapture-1.6.1.js" "${bundle_hash}"
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"
require_command git
if [[ "$#" -ne 2 ]]; then
printf 'Verwendung: %s AUSGABEDATEI ABSOLUTER_ASSET_ROOT\n' "$0" >&2
exit 2
fi
output="$1"
asset_root="$2"
output_parent="$(CDPATH= cd -- "$(dirname -- "${output}")" && pwd -P)" || {
printf 'Das Ausgabeverzeichnis muss bereits existieren.\n' >&2
exit 1
}
output="${output_parent}/$(basename -- "${output}")"
project_root="$(git -C "${TOOL_ROOT}" rev-parse --show-toplevel)"
project_root="$(CDPATH= cd -- "${project_root}" && pwd -P)"
case "${output}" in
"${project_root}"|"${project_root}"/*)
printf 'Die Secret-Datei darf nicht im Repository liegen.\n' >&2
exit 1
;;
esac
[[ "${asset_root}" == /* ]] || {
printf 'Asset-Root muss absolut sein.\n' >&2
exit 1
}
[[ ! -e "${output}" ]] || {
printf 'Ausgabedatei existiert bereits; sie wird nicht überschrieben.\n' >&2
exit 1
}
if command -v openssl >/dev/null 2>&1; then
token="$(openssl rand -base64 48 | tr -d '\n')"
else
printf 'openssl wird zur sicheren Token-Erzeugung benötigt.\n' >&2
exit 1
fi
printf 'PROJECTCAPTURE_BLOCKBENCH_TOKEN=%q\nPROJECTCAPTURE_ASSET_ROOT=%q\n' \
"${token}" "${asset_root}" > "${output}"
chmod 0600 "${output}"
printf 'Lokale Environment-Datei erstellt (Token wird nicht ausgegeben): %s\n' "${output}"
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"
if [[ "$#" -ne 2 || "$1" != "--i-reviewed-gpl" ]]; then
printf 'Verwendung: %s --i-reviewed-gpl EXPLIZITES_PLUGIN_ZIELVERZEICHNIS\n' "$0" >&2
exit 2
fi
destination="$2"
[[ -d "${destination}" && ! -L "${destination}" ]] || {
printf 'Ziel muss ein vorhandenes echtes Verzeichnis sein: %s\n' "${destination}" >&2
exit 1
}
mcp_source="${TOOL_ROOT}/dist/mcp-projectcapture-1.6.1.js"
hytale_source="${TOOL_ROOT}/dist/hytale_plugin-0.9.1.js"
[[ -f "${mcp_source}" && ! -L "${mcp_source}" ]] || {
printf 'MCP-Build fehlt; zuerst scripts/build.sh ausführen.\n' >&2
exit 1
}
[[ -f "${hytale_source}" && ! -L "${hytale_source}" ]] || {
printf 'Hytale-Plugin fehlt; zuerst scripts/stage-hytale-plugin.sh ausführen.\n' >&2
exit 1
}
# Bestehende Dateien werden absichtlich nicht überschrieben. Review/Backup ist
# Sache des aufrufenden Installationsschritts.
for target in "${destination}/mcp.js" "${destination}/hytale_plugin.js"; do
[[ ! -e "${target}" ]] || {
printf 'Zieldatei existiert bereits; Installation abgebrochen: %s\n' "${target}" >&2
exit 1
}
done
cp -- "${mcp_source}" "${destination}/mcp.js"
cp -- "${hytale_source}" "${destination}/hytale_plugin.js"
printf 'Geprüfte Plugins installiert. Codex-Konfiguration wurde nicht verändert.\n'
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env bash
set -euo pipefail
TOOL_ROOT="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)"
MCP_REPOSITORY="https://github.com/jasonjgardner/blockbench-mcp-plugin.git"
MCP_COMMIT="6b069e308fdfc9b0a1c15bc924ca78150815f143"
MCP_PATCH="${TOOL_ROOT}/patches/0001-projectcapture-hardening.patch"
MCP_PATCH_SHA256="9de0b3767e96db7a68ef4c7082d7c76bf140b4932fc9550ad6e99d9a24a048c3"
BUN_VERSION="1.3.14"
require_command() {
command -v "$1" >/dev/null 2>&1 || {
printf 'Fehlendes Werkzeug: %s\n' "$1" >&2
exit 1
}
}
sha256_file() {
if command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$1" | awk '{print $1}'
elif command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | awk '{print $1}'
else
printf 'Weder shasum noch sha256sum ist verfügbar.\n' >&2
exit 1
fi
}
verify_patch() {
local actual
actual="$(sha256_file "${MCP_PATCH}")"
if [[ "${actual}" != "${MCP_PATCH_SHA256}" ]]; then
printf 'Patch-Hash stimmt nicht: erwartet %s, erhalten %s\n' \
"${MCP_PATCH_SHA256}" "${actual}" >&2
exit 1
fi
}
prepare_source() {
local destination="$1"
if [[ -z "${destination}" || -e "${destination}" ]]; then
printf 'Temporäres Ziel muss neu und nicht vorhanden sein: %s\n' "${destination}" >&2
exit 1
fi
verify_patch
git clone --quiet --filter=blob:none --no-checkout "${MCP_REPOSITORY}" "${destination}"
git -C "${destination}" checkout --quiet --detach "${MCP_COMMIT}"
local resolved
resolved="$(git -C "${destination}" rev-parse HEAD)"
if [[ "${resolved}" != "${MCP_COMMIT}" ]]; then
printf 'Upstream-Commit stimmt nicht: %s\n' "${resolved}" >&2
exit 1
fi
git -C "${destination}" apply --check "${MCP_PATCH}"
git -C "${destination}" apply "${MCP_PATCH}"
git -C "${destination}" diff --check
}
make_stage_parent() {
mktemp -d "${TMPDIR:-/tmp}/projectcapture-blockbench-mcp.XXXXXX"
}
safe_remove_stage() {
local stage="$1"
local leaf
leaf="$(basename -- "${stage}")"
if [[ -d "${stage}" && ! -L "${stage}" && "${leaf}" == projectcapture-blockbench-mcp.* ]]; then
rm -rf -- "${stage}"
else
printf 'Unsicheres temporäres Löschziel wurde nicht entfernt: %s\n' "${stage}" >&2
fi
}
run_bun() {
pnpm dlx "bun@${BUN_VERSION}" "$@"
}
write_dist_checksums() {
local output_dir="$1"
local checksum_file="${output_dir}/SHA256SUMS"
local temporary_file="${checksum_file}.tmp.$$"
local artifact
: > "${temporary_file}"
for artifact in \
hytale_plugin-0.9.1.js \
mcp-about.md \
mcp-icon.svg \
mcp-projectcapture-1.6.1.js; do
if [[ -f "${output_dir}/${artifact}" && ! -L "${output_dir}/${artifact}" ]]; then
printf '%s %s\n' "$(sha256_file "${output_dir}/${artifact}")" "${artifact}" \
>> "${temporary_file}"
fi
done
mv -- "${temporary_file}" "${checksum_file}"
}
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"
require_command git
repository="https://github.com/JannisX11/hytale-blockbench-plugin.git"
commit="82dc58d19949c802f60f31c24fcb063a6b12fb07"
expected_sha="ce1b0a6a3ad2f36b073b96a71a416261e43f089f4c02799b180b71c9e3f849f3"
stage_parent="$(make_stage_parent)"
trap 'safe_remove_stage "${stage_parent}"' EXIT
source_dir="${stage_parent}/hytale-plugin"
git clone --quiet --filter=blob:none --no-checkout "${repository}" "${source_dir}"
git -C "${source_dir}" checkout --quiet --detach "${commit}"
[[ "$(git -C "${source_dir}" rev-parse HEAD)" == "${commit}" ]] || exit 1
artifact="${source_dir}/dist/hytale_plugin.js"
actual_sha="$(sha256_file "${artifact}")"
if [[ "${actual_sha}" != "${expected_sha}" ]]; then
printf 'Hytale-Plugin-Hash stimmt nicht.\n' >&2
exit 1
fi
output_dir="${TOOL_ROOT}/dist"
mkdir -p -- "${output_dir}"
cp -- "${artifact}" "${output_dir}/hytale_plugin-0.9.1.js"
write_dist_checksums "${output_dir}"
printf 'Offizielles Hytale-Plugin geprüft und bereitgestellt: %s\n' \
"${output_dir}/hytale_plugin-0.9.1.js"
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"
require_command git
require_command pnpm
stage_parent="$(make_stage_parent)"
trap 'safe_remove_stage "${stage_parent}"' EXIT
source_dir="${stage_parent}/source"
prepare_source "${source_dir}"
run_bun install --cwd "${source_dir}" --frozen-lockfile
run_bun test --cwd "${source_dir}"
run_bun run --cwd "${source_dir}" build
bundle="${source_dir}/dist/mcp.js"
[[ -f "${bundle}" ]] || {
printf 'Build-Artefakt fehlt: %s\n' "${bundle}" >&2
exit 1
}
for forbidden_network_marker in 'https://cdn.jsdelivr.net' 'fetch('; do
if grep -Fq "${forbidden_network_marker}" "${bundle}"; then
printf 'Unerwarteter Netzwerkmarker im Build: %s\n' "${forbidden_network_marker}" >&2
exit 1
fi
done
printf 'Blockbench-MCP: Tests und Build erfolgreich.\n'
@@ -0,0 +1,29 @@
{
"schemaVersion": 1,
"blockbench": {
"version": "5.0.7"
},
"mcp": {
"repository": "https://github.com/jasonjgardner/blockbench-mcp-plugin.git",
"version": "1.6.1",
"commit": "6b069e308fdfc9b0a1c15bc924ca78150815f143",
"license": "GPL-3.0-only"
},
"hytalePlugin": {
"repository": "https://github.com/JannisX11/hytale-blockbench-plugin.git",
"version": "0.9.1",
"commit": "82dc58d19949c802f60f31c24fcb063a6b12fb07",
"distSha256": "ce1b0a6a3ad2f36b073b96a71a416261e43f089f4c02799b180b71c9e3f849f3",
"license": "GPL-3.0"
},
"toolchain": {
"bun": "1.3.14",
"packageManager": "pnpm"
},
"patches": [
{
"path": "patches/0001-projectcapture-hardening.patch",
"sha256": "9de0b3767e96db7a68ef4c7082d7c76bf140b4932fc9550ad6e99d9a24a048c3"
}
]
}
+1 -1
View File
@@ -10,7 +10,7 @@ Die technische Basis ist Hytale Stable 0.5.9, Java 25 und Gradle 9.6.1. Das Java
- `engine`: Hytale-unabhängige Fang-, Kampf-, Level-, Evolutions-, Zucht-, Genetik-, Handels- und Duelllogik.
- `hytale-adapter`: Plugin-Lifecycle, Events, ECS, NPCs, Persistenz, UI, Kamera und Weltintegration.
- `content-private`: vorläufiger Modulname für Spezies-, Attacken-, Spawn-, Rezept- und Asset-Daten; nach dem Foundation-Gate wird er zu `content-pokemon` migriert.
- `content-pokemon`: Spezies-, Attacken-, Spawn-, Rezept- und Asset-Daten für den inoffiziellen Fancontent.
- `content-tools`: Schema-, Content-, Asset- und Veröffentlichungsvalidatoren.
Die offizielle Abhängigkeit `com.hypixel.hytale:Server:0.5.9` wird exakt gepinnt. Server-JARs, `Assets.zip`, extrahierte Hytale-Basisassets und Geheimnisse werden nie eingecheckt. Hytale-API-Aufrufe bleiben im Adapter, damit spätere API-Versionen austauschbar sind.
+33
View File
@@ -0,0 +1,33 @@
plugins {
`java-library`
}
group = "dev.projectcapture"
version = "0.1.0-SNAPSHOT"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
withSourcesJar()
}
repositories {
mavenCentral()
}
dependencies {
testImplementation(platform("org.junit:junit-bom:5.11.4"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release = 25
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}
@@ -0,0 +1,39 @@
package dev.projectcapture.engine.model;
public record BaseStats(
int health,
int attack,
int defence,
int specialAttack,
int specialDefence,
int speed
) {
public BaseStats {
Checks.range(health, 1, 255, "health");
Checks.range(attack, 1, 255, "attack");
Checks.range(defence, 1, 255, "defence");
Checks.range(specialAttack, 1, 255, "specialAttack");
Checks.range(specialDefence, 1, 255, "specialDefence");
Checks.range(speed, 1, 255, "speed");
}
public int healthAtLevel(int level) {
Checks.range(level, 1, 100, "level");
return ((2 * health * level) / 100) + level + 10;
}
public int attackAtLevel(int level) {
Checks.range(level, 1, 100, "level");
return ((2 * attack * level) / 100) + 5;
}
public int defenceAtLevel(int level) {
Checks.range(level, 1, 100, "level");
return ((2 * defence * level) / 100) + 5;
}
public int speedAtLevel(int level) {
Checks.range(level, 1, 100, "level");
return ((2 * speed * level) / 100) + 5;
}
}
@@ -0,0 +1,27 @@
package dev.projectcapture.engine.model;
import java.util.UUID;
public record BattleEvent(
UUID actorCreatureId,
UUID targetCreatureId,
String moveId,
boolean automaticBasicAttack,
boolean hit,
int damage,
int targetHealthRemaining
) {
public BattleEvent {
actorCreatureId = Checks.notNull(actorCreatureId, "actorCreatureId");
targetCreatureId = Checks.notNull(targetCreatureId, "targetCreatureId");
if (actorCreatureId.equals(targetCreatureId)) {
throw new IllegalArgumentException("battle actor and target must differ");
}
moveId = Checks.namespacedId(moveId, "moveId");
Checks.range(damage, 0, 100_000, "damage");
Checks.range(targetHealthRemaining, 0, 100_000, "targetHealthRemaining");
if (!hit && damage != 0) {
throw new IllegalArgumentException("missed attacks cannot deal damage");
}
}
}
@@ -0,0 +1,44 @@
package dev.projectcapture.engine.model;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
public record BattleParticipant(
UUID creatureId,
UUID ownerId,
String speciesId,
int level,
int currentHealth,
int maximumHealth,
int attack,
int defence,
int speed,
String basicMoveId,
List<String> commandMoveIds
) {
public BattleParticipant {
creatureId = Checks.notNull(creatureId, "creatureId");
ownerId = Checks.notNull(ownerId, "ownerId");
speciesId = Checks.namespacedId(speciesId, "speciesId");
Checks.range(level, 1, 100, "level");
Checks.range(maximumHealth, 1, 100_000, "maximumHealth");
Checks.range(currentHealth, 0, maximumHealth, "currentHealth");
Checks.range(attack, 1, 100_000, "attack");
Checks.range(defence, 1, 100_000, "defence");
Checks.range(speed, 1, 100_000, "speed");
basicMoveId = Checks.namespacedId(basicMoveId, "basicMoveId");
Checks.noNulls(commandMoveIds, "commandMoveIds");
commandMoveIds = commandMoveIds.stream()
.map(move -> Checks.namespacedId(move, "commandMoveId"))
.toList();
if (commandMoveIds.size() != 3 || new HashSet<>(commandMoveIds).size() != 3
|| commandMoveIds.contains(basicMoveId)) {
throw new IllegalArgumentException("battle participant requires exactly three unique command moves");
}
}
public boolean isFainted() {
return currentHealth == 0;
}
}
@@ -0,0 +1,64 @@
package dev.projectcapture.engine.model;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
public record BattleState(
int schemaVersion,
UUID id,
BattleParticipant participantOne,
BattleParticipant participantTwo,
long turn,
Status status,
Optional<UUID> winnerCreatureId,
List<BattleEvent> lastTurnEvents
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public enum Status {
ACTIVE,
COMPLETED,
CANCELLED
}
public BattleState {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported battle schema version: " + schemaVersion);
}
id = Checks.notNull(id, "id");
participantOne = Checks.notNull(participantOne, "participantOne");
participantTwo = Checks.notNull(participantTwo, "participantTwo");
if (participantOne.creatureId().equals(participantTwo.creatureId())) {
throw new IllegalArgumentException("battle participants must be different creatures");
}
Checks.nonNegative(turn, "turn");
status = Checks.notNull(status, "status");
winnerCreatureId = Checks.optional(winnerCreatureId, "winnerCreatureId");
var creatureIds = Set.of(participantOne.creatureId(), participantTwo.creatureId());
if (winnerCreatureId.isPresent() && !creatureIds.contains(winnerCreatureId.orElseThrow())) {
throw new IllegalArgumentException("winner must participate in the battle");
}
if (status == Status.COMPLETED && winnerCreatureId.isEmpty()) {
throw new IllegalArgumentException("completed battle requires a winner");
}
if (status != Status.COMPLETED && winnerCreatureId.isPresent()) {
throw new IllegalArgumentException("only completed battle may have a winner");
}
if (status == Status.ACTIVE && (participantOne.isFainted() || participantTwo.isFainted())) {
throw new IllegalArgumentException("active battle cannot contain a fainted participant");
}
if (status == Status.COMPLETED) {
boolean exactlyOneFainted = participantOne.isFainted() ^ participantTwo.isFainted();
UUID survivingCreatureId = participantOne.isFainted()
? participantTwo.creatureId()
: participantOne.creatureId();
if (!exactlyOneFainted || !winnerCreatureId.orElseThrow().equals(survivingCreatureId)) {
throw new IllegalArgumentException("completed battle winner must be the sole surviving creature");
}
}
Checks.noNulls(lastTurnEvents, "lastTurnEvents");
lastTurnEvents = List.copyOf(lastTurnEvents);
}
}
@@ -0,0 +1,40 @@
package dev.projectcapture.engine.model;
public record CaptureContext(
int captureRate,
SpeciesDefinition.Rarity rarity,
int level,
int currentHealth,
int maximumHealth,
double deviceMultiplier,
StatusCondition statusCondition
) {
public enum StatusCondition {
NONE(1.0),
POISONED(1.15),
BURNED(1.15),
PARALYSED(1.35),
ASLEEP(1.75),
FROZEN(1.75);
private final double captureMultiplier;
StatusCondition(double captureMultiplier) {
this.captureMultiplier = captureMultiplier;
}
public double captureMultiplier() {
return captureMultiplier;
}
}
public CaptureContext {
Checks.range(captureRate, 1, 255, "captureRate");
rarity = Checks.notNull(rarity, "rarity");
Checks.range(level, 1, 100, "level");
Checks.range(maximumHealth, 1, 100_000, "maximumHealth");
Checks.range(currentHealth, 1, maximumHealth, "currentHealth");
Checks.range(deviceMultiplier, 0.01, 100.0, "deviceMultiplier");
statusCondition = Checks.notNull(statusCondition, "statusCondition");
}
}
@@ -0,0 +1,75 @@
package dev.projectcapture.engine.model;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
final class Checks {
private static final Pattern NAMESPACED_ID =
Pattern.compile("[a-z0-9][a-z0-9_.-]*:[a-z0-9][a-z0-9_./-]*");
private Checks() {
}
static <T> T notNull(T value, String name) {
return Objects.requireNonNull(value, name + " must not be null");
}
static String text(String value, String name) {
notNull(value, name);
var result = value.strip();
if (result.isEmpty()) {
throw new IllegalArgumentException(name + " must not be blank");
}
return result;
}
static String namespacedId(String value, String name) {
var result = text(value, name);
if (!NAMESPACED_ID.matcher(result).matches()) {
throw new IllegalArgumentException(name + " must be a lower-case namespaced id: " + result);
}
return result;
}
static int range(int value, int min, int max, String name) {
if (value < min || value > max) {
throw new IllegalArgumentException(name + " must be between " + min + " and " + max);
}
return value;
}
static long nonNegative(long value, String name) {
if (value < 0) {
throw new IllegalArgumentException(name + " must not be negative");
}
return value;
}
static double range(double value, double min, double max, String name) {
if (!Double.isFinite(value) || value < min || value > max) {
throw new IllegalArgumentException(name + " must be between " + min + " and " + max);
}
return value;
}
static <T> void noNulls(Collection<T> values, String name) {
notNull(values, name);
if (values.stream().anyMatch(Objects::isNull)) {
throw new IllegalArgumentException(name + " must not contain null values");
}
}
static <K, V> void noNulls(Map<K, V> values, String name) {
notNull(values, name);
if (values.entrySet().stream().anyMatch(entry -> entry.getKey() == null || entry.getValue() == null)) {
throw new IllegalArgumentException(name + " must not contain null keys or values");
}
}
static <T> Optional<T> optional(Optional<T> value, String name) {
return notNull(value, name);
}
}
@@ -0,0 +1,33 @@
package dev.projectcapture.engine.model;
import java.time.Instant;
import java.util.UUID;
public record CreatureEgg(
int schemaVersion,
UUID id,
UUID ownerId,
String speciesId,
UUID parentOneId,
UUID parentTwoId,
Genome genome,
Instant createdAt
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public CreatureEgg {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported egg schema version: " + schemaVersion);
}
id = Checks.notNull(id, "id");
ownerId = Checks.notNull(ownerId, "ownerId");
speciesId = Checks.namespacedId(speciesId, "speciesId");
parentOneId = Checks.notNull(parentOneId, "parentOneId");
parentTwoId = Checks.notNull(parentTwoId, "parentTwoId");
if (parentOneId.equals(parentTwoId)) {
throw new IllegalArgumentException("egg parents must be different creatures");
}
genome = Checks.notNull(genome, "genome");
createdAt = Checks.notNull(createdAt, "createdAt");
}
}
@@ -0,0 +1,57 @@
package dev.projectcapture.engine.model;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public record CreatureInstance(
int schemaVersion,
UUID id,
String speciesId,
Optional<String> nickname,
Optional<UUID> ownerId,
int level,
long experience,
int currentHealth,
Genome genome,
String basicMoveId,
List<String> commandMoveIds,
Instant createdAt,
long revision
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public CreatureInstance {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported creature schema version: " + schemaVersion);
}
id = Checks.notNull(id, "id");
speciesId = Checks.namespacedId(speciesId, "speciesId");
nickname = Checks.optional(nickname, "nickname").map(name -> Checks.text(name, "nickname"));
if (nickname.map(String::length).orElse(0) > 32) {
throw new IllegalArgumentException("nickname must contain at most 32 characters");
}
ownerId = Checks.optional(ownerId, "ownerId");
Checks.range(level, 1, 100, "level");
Checks.nonNegative(experience, "experience");
Checks.range(currentHealth, 0, 100_000, "currentHealth");
genome = Checks.notNull(genome, "genome");
basicMoveId = Checks.namespacedId(basicMoveId, "basicMoveId");
Checks.noNulls(commandMoveIds, "commandMoveIds");
commandMoveIds = commandMoveIds.stream()
.map(move -> Checks.namespacedId(move, "commandMoveId"))
.toList();
if (commandMoveIds.size() != 3 || new HashSet<>(commandMoveIds).size() != 3
|| commandMoveIds.contains(basicMoveId)) {
throw new IllegalArgumentException("commandMoveIds must contain exactly three unique non-basic moves");
}
createdAt = Checks.notNull(createdAt, "createdAt");
Checks.nonNegative(revision, "revision");
}
public boolean isFainted() {
return currentHealth == 0;
}
}
@@ -0,0 +1,21 @@
package dev.projectcapture.engine.model;
public record DuelRules(
boolean playerWeaponsDisabled,
boolean naturalLevels,
double zoneRadius
) {
public DuelRules {
if (!playerWeaponsDisabled) {
throw new IllegalArgumentException("player weapons must be disabled in creature duels");
}
if (!naturalLevels) {
throw new IllegalArgumentException("creature duels must use natural levels");
}
Checks.range(zoneRadius, 4.0, 256.0, "zoneRadius");
}
public static DuelRules defaults() {
return new DuelRules(true, true, 32.0);
}
}
@@ -0,0 +1,72 @@
package dev.projectcapture.engine.model;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
public record DuelSession(
int schemaVersion,
UUID id,
UUID challengerId,
UUID opponentId,
DuelRules rules,
Set<UUID> acceptedBy,
Status status,
Optional<UUID> winnerId,
Optional<String> completionReason,
long revision
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public enum Status {
REQUESTED,
ACTIVE,
COMPLETED,
CANCELLED
}
public DuelSession {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported duel schema version: " + schemaVersion);
}
id = Checks.notNull(id, "id");
challengerId = Checks.notNull(challengerId, "challengerId");
opponentId = Checks.notNull(opponentId, "opponentId");
if (challengerId.equals(opponentId)) {
throw new IllegalArgumentException("duel players must be different");
}
rules = Checks.notNull(rules, "rules");
Checks.noNulls(acceptedBy, "acceptedBy");
acceptedBy = Set.copyOf(acceptedBy);
var participants = Set.of(challengerId, opponentId);
if (!participants.containsAll(acceptedBy)) {
throw new IllegalArgumentException("only duel participants may accept");
}
status = Checks.notNull(status, "status");
winnerId = Checks.optional(winnerId, "winnerId");
completionReason = Checks.optional(completionReason, "completionReason")
.map(reason -> Checks.text(reason, "completionReason"));
if (winnerId.isPresent() && !participants.contains(winnerId.orElseThrow())) {
throw new IllegalArgumentException("winner must be a duel participant");
}
if (status == Status.ACTIVE && !acceptedBy.equals(participants)) {
throw new IllegalArgumentException("active duel requires both acceptances");
}
if (status == Status.REQUESTED && acceptedBy.equals(participants)) {
throw new IllegalArgumentException("fully accepted duel must be active");
}
if (status == Status.COMPLETED && (winnerId.isEmpty() || completionReason.isEmpty())) {
throw new IllegalArgumentException("completed duel requires winner and reason");
}
if (status != Status.COMPLETED && winnerId.isPresent()) {
throw new IllegalArgumentException("only completed duel may have a winner");
}
if (status == Status.CANCELLED && completionReason.isEmpty()) {
throw new IllegalArgumentException("cancelled duel requires a reason");
}
if ((status == Status.REQUESTED || status == Status.ACTIVE) && completionReason.isPresent()) {
throw new IllegalArgumentException("non-terminal duel cannot have a completion reason");
}
Checks.nonNegative(revision, "revision");
}
}
@@ -0,0 +1,19 @@
package dev.projectcapture.engine.model;
public enum ElementType {
NORMAL,
GRASS,
POISON,
FIRE,
FLYING,
WATER,
ELECTRIC,
PSYCHIC,
GROUND,
ROCK,
ICE,
BUG,
FIGHTING,
GHOST,
DRAGON
}
@@ -0,0 +1,21 @@
package dev.projectcapture.engine.model;
import java.util.Optional;
public record EvolutionRule(
String targetSpeciesId,
int minimumLevel,
Optional<String> requiredItemId
) {
public EvolutionRule {
targetSpeciesId = Checks.namespacedId(targetSpeciesId, "targetSpeciesId");
Checks.range(minimumLevel, 1, 100, "minimumLevel");
requiredItemId = Checks.optional(requiredItemId, "requiredItemId")
.map(id -> Checks.namespacedId(id, "requiredItemId"));
}
public boolean isEligible(int level, java.util.Set<String> availableItemIds) {
Checks.notNull(availableItemIds, "availableItemIds");
return level >= minimumLevel && requiredItemId.map(availableItemIds::contains).orElse(true);
}
}
@@ -0,0 +1,62 @@
package dev.projectcapture.engine.model;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public record Genome(
int schemaVersion,
long seed,
Map<String, Integer> traits,
List<LineageContribution> lineages,
Set<String> revealedTraits
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public static final int TOTAL_BASIS_POINTS = 10_000;
public static final int MAX_LINEAGES = 4;
public Genome {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported genome schema version: " + schemaVersion);
}
Checks.noNulls(traits, "traits");
var copiedTraits = new LinkedHashMap<String, Integer>();
traits.forEach((key, value) -> copiedTraits.put(
Checks.text(key, "trait name"), Checks.range(value, 0, 31, "trait value")));
traits = Map.copyOf(copiedTraits);
if (traits.isEmpty()) {
throw new IllegalArgumentException("traits must not be empty");
}
Checks.noNulls(lineages, "lineages");
lineages = List.copyOf(lineages);
if (lineages.isEmpty() || lineages.size() > MAX_LINEAGES) {
throw new IllegalArgumentException("lineages must contain between one and four entries");
}
if (new HashSet<>(lineages.stream().map(LineageContribution::speciesId).toList()).size()
!= lineages.size()) {
throw new IllegalArgumentException("lineage species must be unique");
}
int total = lineages.stream().mapToInt(LineageContribution::basisPoints).sum();
if (total != TOTAL_BASIS_POINTS) {
throw new IllegalArgumentException("lineage contribution must total 10000 basis points");
}
Checks.noNulls(revealedTraits, "revealedTraits");
revealedTraits = Set.copyOf(revealedTraits);
if (!traits.keySet().containsAll(revealedTraits)) {
throw new IllegalArgumentException("revealedTraits must be present in traits");
}
}
public static Genome pure(long seed, String speciesId, Map<String, Integer> traits) {
return new Genome(CURRENT_SCHEMA_VERSION, seed, traits,
List.of(new LineageContribution(speciesId, TOTAL_BASIS_POINTS)), Set.of());
}
public boolean fullyAnalysed() {
return revealedTraits.size() == traits.size();
}
}
@@ -0,0 +1,70 @@
package dev.projectcapture.engine.model;
import java.util.Optional;
import java.util.UUID;
public record HabitatState(
int schemaVersion,
UUID id,
UUID ownerId,
Status status,
Optional<UUID> parentOneId,
Optional<UUID> parentTwoId,
long accumulatedActiveMillis,
long requiredActiveMillis,
long revision
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public enum Status {
EMPTY,
BREEDING,
EGG_READY,
COLLECTED,
CANCELLED
}
public HabitatState {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported habitat schema version: " + schemaVersion);
}
id = Checks.notNull(id, "id");
ownerId = Checks.notNull(ownerId, "ownerId");
status = Checks.notNull(status, "status");
parentOneId = Checks.optional(parentOneId, "parentOneId");
parentTwoId = Checks.optional(parentTwoId, "parentTwoId");
Checks.nonNegative(accumulatedActiveMillis, "accumulatedActiveMillis");
Checks.nonNegative(requiredActiveMillis, "requiredActiveMillis");
Checks.nonNegative(revision, "revision");
boolean hasBothParents = parentOneId.isPresent() && parentTwoId.isPresent();
if (parentOneId.equals(parentTwoId) && parentOneId.isPresent()) {
throw new IllegalArgumentException("parents must be different creatures");
}
if (status == Status.EMPTY && (parentOneId.isPresent() || parentTwoId.isPresent()
|| accumulatedActiveMillis != 0 || requiredActiveMillis != 0)) {
throw new IllegalArgumentException("empty habitat cannot contain breeding progress");
}
if (status != Status.EMPTY && !hasBothParents) {
throw new IllegalArgumentException("non-empty habitat must contain two parents");
}
if (status != Status.EMPTY && requiredActiveMillis == 0) {
throw new IllegalArgumentException("active habitat must have a positive required duration");
}
if (accumulatedActiveMillis > requiredActiveMillis) {
throw new IllegalArgumentException("breeding progress cannot exceed required duration");
}
if (status == Status.BREEDING && accumulatedActiveMillis >= requiredActiveMillis) {
throw new IllegalArgumentException("completed progress must use EGG_READY status");
}
if ((status == Status.EGG_READY || status == Status.COLLECTED)
&& accumulatedActiveMillis != requiredActiveMillis) {
throw new IllegalArgumentException("ready or collected habitat must have complete progress");
}
}
public static HabitatState empty(UUID id, UUID ownerId) {
return new HabitatState(CURRENT_SCHEMA_VERSION, id, ownerId, Status.EMPTY,
Optional.empty(), Optional.empty(), 0, 0, 0);
}
}
@@ -0,0 +1,8 @@
package dev.projectcapture.engine.model;
public record LineageContribution(String speciesId, int basisPoints) {
public LineageContribution {
speciesId = Checks.namespacedId(speciesId, "speciesId");
Checks.range(basisPoints, 1, Genome.TOTAL_BASIS_POINTS, "basisPoints");
}
}
@@ -0,0 +1,36 @@
package dev.projectcapture.engine.model;
public record MoveDefinition(
int schemaVersion,
String id,
String displayName,
ElementType type,
Category category,
int power,
double accuracy,
int priority
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public enum Category {
PHYSICAL,
SPECIAL,
STATUS
}
public MoveDefinition {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported move schema version: " + schemaVersion);
}
id = Checks.namespacedId(id, "id");
displayName = Checks.text(displayName, "displayName");
type = Checks.notNull(type, "type");
category = Checks.notNull(category, "category");
Checks.range(power, 0, 250, "power");
Checks.range(accuracy, 0.0, 1.0, "accuracy");
Checks.range(priority, -7, 7, "priority");
if (category != Category.STATUS && power == 0) {
throw new IllegalArgumentException("Damaging moves must have positive power");
}
}
}
@@ -0,0 +1,38 @@
package dev.projectcapture.engine.model;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public record Party(
int schemaVersion,
UUID ownerId,
List<UUID> creatureIds,
Optional<UUID> activeCompanionId,
long revision
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public static final int MAX_SIZE = 6;
public Party {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported party schema version: " + schemaVersion);
}
ownerId = Checks.notNull(ownerId, "ownerId");
Checks.noNulls(creatureIds, "creatureIds");
creatureIds = List.copyOf(creatureIds);
if (creatureIds.size() > MAX_SIZE || new HashSet<>(creatureIds).size() != creatureIds.size()) {
throw new IllegalArgumentException("party must contain at most six unique creatures");
}
activeCompanionId = Checks.optional(activeCompanionId, "activeCompanionId");
if (activeCompanionId.isPresent() && !creatureIds.contains(activeCompanionId.orElseThrow())) {
throw new IllegalArgumentException("active companion must be part of the party");
}
Checks.nonNegative(revision, "revision");
}
public static Party empty(UUID ownerId) {
return new Party(CURRENT_SCHEMA_VERSION, ownerId, List.of(), Optional.empty(), 0);
}
}
@@ -0,0 +1,30 @@
package dev.projectcapture.engine.model;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
public record PlayerInventory(
int schemaVersion,
UUID ownerId,
Set<UUID> creatureIds,
Map<String, Integer> items,
long revision
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public PlayerInventory {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported inventory schema version: " + schemaVersion);
}
ownerId = Checks.notNull(ownerId, "ownerId");
Checks.noNulls(creatureIds, "creatureIds");
creatureIds = Set.copyOf(creatureIds);
Checks.noNulls(items, "items");
items = items.entrySet().stream().collect(Collectors.toUnmodifiableMap(
entry -> Checks.namespacedId(entry.getKey(), "itemId"),
entry -> Checks.range(entry.getValue(), 1, 1_000_000, "item quantity")));
Checks.nonNegative(revision, "revision");
}
}
@@ -0,0 +1,35 @@
package dev.projectcapture.engine.model;
import java.util.Set;
public record SpawnRule(
Set<String> biomeTags,
Set<TimeOfDay> times,
int weight,
int minimumLevel,
int maximumLevel
) {
public enum TimeOfDay {
DAWN,
DAY,
DUSK,
NIGHT
}
public SpawnRule {
Checks.noNulls(biomeTags, "biomeTags");
biomeTags = biomeTags.stream().map(tag -> Checks.namespacedId(tag, "biomeTag"))
.collect(java.util.stream.Collectors.toUnmodifiableSet());
if (biomeTags.isEmpty()) {
throw new IllegalArgumentException("biomeTags must not be empty");
}
Checks.noNulls(times, "times");
times = Set.copyOf(times);
if (times.isEmpty()) {
throw new IllegalArgumentException("times must not be empty");
}
Checks.range(weight, 1, 1_000_000, "weight");
Checks.range(minimumLevel, 1, 100, "minimumLevel");
Checks.range(maximumLevel, minimumLevel, 100, "maximumLevel");
}
}
@@ -0,0 +1,67 @@
package dev.projectcapture.engine.model;
import java.util.HashSet;
import java.util.List;
public record SpeciesDefinition(
int schemaVersion,
String id,
String displayName,
List<ElementType> types,
Rarity rarity,
BaseStats baseStats,
int captureRate,
String basicMoveId,
List<String> commandMoveIds,
List<EvolutionRule> evolutions,
List<SpawnRule> spawnRules
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public enum Rarity {
COMMON(1.0),
UNCOMMON(0.85),
RARE(0.65),
EPIC(0.45),
LEGENDARY(0.20);
private final double captureMultiplier;
Rarity(double captureMultiplier) {
this.captureMultiplier = captureMultiplier;
}
public double captureMultiplier() {
return captureMultiplier;
}
}
public SpeciesDefinition {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported species schema version: " + schemaVersion);
}
id = Checks.namespacedId(id, "id");
displayName = Checks.text(displayName, "displayName");
Checks.noNulls(types, "types");
types = List.copyOf(types);
if (types.isEmpty() || types.size() > 2 || new HashSet<>(types).size() != types.size()) {
throw new IllegalArgumentException("types must contain one or two unique values");
}
rarity = Checks.notNull(rarity, "rarity");
baseStats = Checks.notNull(baseStats, "baseStats");
Checks.range(captureRate, 1, 255, "captureRate");
basicMoveId = Checks.namespacedId(basicMoveId, "basicMoveId");
Checks.noNulls(commandMoveIds, "commandMoveIds");
commandMoveIds = commandMoveIds.stream()
.map(move -> Checks.namespacedId(move, "commandMoveId"))
.toList();
if (commandMoveIds.size() != 3 || new HashSet<>(commandMoveIds).size() != 3
|| commandMoveIds.contains(basicMoveId)) {
throw new IllegalArgumentException("commandMoveIds must contain exactly three unique non-basic moves");
}
Checks.noNulls(evolutions, "evolutions");
evolutions = List.copyOf(evolutions);
Checks.noNulls(spawnRules, "spawnRules");
spawnRules = List.copyOf(spawnRules);
}
}
@@ -0,0 +1,26 @@
package dev.projectcapture.engine.model;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
public record TradeOffer(
UUID ownerId,
Set<UUID> creatureIds,
Map<String, Integer> items
) {
public TradeOffer {
ownerId = Checks.notNull(ownerId, "ownerId");
Checks.noNulls(creatureIds, "creatureIds");
creatureIds = Set.copyOf(creatureIds);
Checks.noNulls(items, "items");
items = items.entrySet().stream().collect(Collectors.toUnmodifiableMap(
entry -> Checks.namespacedId(entry.getKey(), "itemId"),
entry -> Checks.range(entry.getValue(), 1, 1_000_000, "item quantity")));
}
public boolean isEmpty() {
return creatureIds.isEmpty() && items.isEmpty();
}
}
@@ -0,0 +1,59 @@
package dev.projectcapture.engine.model;
import java.util.Set;
import java.util.UUID;
public record TradeTransaction(
int schemaVersion,
UUID id,
UUID playerOneId,
UUID playerTwoId,
TradeOffer playerOneOffer,
TradeOffer playerTwoOffer,
Set<UUID> acceptedBy,
Status status,
long revision
) {
public static final int CURRENT_SCHEMA_VERSION = 1;
public enum Status {
OPEN,
LOCKED,
COMMITTED,
CANCELLED
}
public TradeTransaction {
if (schemaVersion != CURRENT_SCHEMA_VERSION) {
throw new IllegalArgumentException("Unsupported trade schema version: " + schemaVersion);
}
id = Checks.notNull(id, "id");
playerOneId = Checks.notNull(playerOneId, "playerOneId");
playerTwoId = Checks.notNull(playerTwoId, "playerTwoId");
if (playerOneId.equals(playerTwoId)) {
throw new IllegalArgumentException("trade players must be different");
}
playerOneOffer = Checks.notNull(playerOneOffer, "playerOneOffer");
playerTwoOffer = Checks.notNull(playerTwoOffer, "playerTwoOffer");
if (!playerOneOffer.ownerId().equals(playerOneId) || !playerTwoOffer.ownerId().equals(playerTwoId)) {
throw new IllegalArgumentException("offer owners must match trade players");
}
if (playerOneOffer.isEmpty() && playerTwoOffer.isEmpty()) {
throw new IllegalArgumentException("at least one trade offer must not be empty");
}
Checks.noNulls(acceptedBy, "acceptedBy");
acceptedBy = Set.copyOf(acceptedBy);
var participants = Set.of(playerOneId, playerTwoId);
if (!participants.containsAll(acceptedBy)) {
throw new IllegalArgumentException("only trade participants may accept");
}
status = Checks.notNull(status, "status");
if ((status == Status.LOCKED || status == Status.COMMITTED) && !acceptedBy.equals(participants)) {
throw new IllegalArgumentException("locked or committed trade requires both acceptances");
}
if (status == Status.OPEN && acceptedBy.size() == 2) {
throw new IllegalArgumentException("fully accepted trade must be locked");
}
Checks.nonNegative(revision, "revision");
}
}
@@ -0,0 +1,169 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.BattleEvent;
import dev.projectcapture.engine.model.BattleParticipant;
import dev.projectcapture.engine.model.BattleState;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.MoveDefinition;
import dev.projectcapture.engine.model.SpeciesDefinition;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SplittableRandom;
import java.util.UUID;
public final class BattleService {
public BattleState create(UUID battleId, BattleParticipant first, BattleParticipant second) {
if (first == null || second == null) {
throw new NullPointerException("battle participants must not be null");
}
if (first.isFainted() || second.isFainted()) {
throw new IllegalArgumentException("fainted creatures cannot start a battle");
}
return new BattleState(BattleState.CURRENT_SCHEMA_VERSION, battleId, first, second,
0, BattleState.Status.ACTIVE, Optional.empty(), List.of());
}
public BattleParticipant participant(CreatureInstance creature, SpeciesDefinition species) {
if (creature == null || species == null) {
throw new NullPointerException("creature and species must not be null");
}
if (!creature.speciesId().equals(species.id())) {
throw new IllegalArgumentException("species does not match creature");
}
UUID ownerId = creature.ownerId().orElseThrow(() ->
new IllegalArgumentException("battle creature must have an owner"));
int maximumHealth = species.baseStats().healthAtLevel(creature.level());
if (creature.currentHealth() > maximumHealth) {
throw new IllegalArgumentException("creature health exceeds species maximum");
}
return new BattleParticipant(creature.id(), ownerId, creature.speciesId(), creature.level(),
creature.currentHealth(), maximumHealth, species.baseStats().attackAtLevel(creature.level()),
species.baseStats().defenceAtLevel(creature.level()), species.baseStats().speedAtLevel(creature.level()),
creature.basicMoveId(), creature.commandMoveIds());
}
public BattleState nextTurn(
BattleState battle,
Map<UUID, String> commandedMoves,
Map<String, MoveDefinition> moveCatalog,
long seed
) {
if (battle == null || commandedMoves == null || moveCatalog == null) {
throw new NullPointerException("battle turn inputs must not be null");
}
if (battle.status() != BattleState.Status.ACTIVE) {
throw new IllegalStateException("battle is not active");
}
Set<UUID> participants = Set.of(
battle.participantOne().creatureId(), battle.participantTwo().creatureId());
if (!participants.containsAll(commandedMoves.keySet()) || commandedMoves.values().stream().anyMatch(java.util.Objects::isNull)) {
throw new IllegalArgumentException("commands must reference battle participants and non-null moves");
}
var actions = new ArrayList<Action>();
actions.add(actionFor(battle.participantOne(), commandedMoves, moveCatalog));
actions.add(actionFor(battle.participantTwo(), commandedMoves, moveCatalog));
actions.sort((left, right) -> {
int comparison = Integer.compare(right.move().priority(), left.move().priority());
if (comparison == 0) {
comparison = Integer.compare(right.actor().speed(), left.actor().speed());
}
if (comparison == 0) {
comparison = left.actor().creatureId().compareTo(right.actor().creatureId());
}
return comparison;
});
var current = new HashMap<UUID, BattleParticipant>();
current.put(battle.participantOne().creatureId(), battle.participantOne());
current.put(battle.participantTwo().creatureId(), battle.participantTwo());
var random = new SplittableRandom(seed ^ battle.id().getMostSignificantBits()
^ battle.id().getLeastSignificantBits() ^ battle.turn());
var events = new ArrayList<BattleEvent>();
for (var action : actions) {
var actor = current.get(action.actor().creatureId());
if (actor.isFainted()) {
continue;
}
UUID targetId = actor.creatureId().equals(battle.participantOne().creatureId())
? battle.participantTwo().creatureId()
: battle.participantOne().creatureId();
var target = current.get(targetId);
if (target.isFainted()) {
continue;
}
boolean hit = random.nextDouble() < action.move().accuracy();
int damage = hit ? Math.min(target.currentHealth(), damage(actor, target, action.move(), random)) : 0;
int remainingHealth = Math.max(0, target.currentHealth() - damage);
var updatedTarget = withHealth(target, remainingHealth);
current.put(targetId, updatedTarget);
events.add(new BattleEvent(actor.creatureId(), targetId, action.move().id(), action.automatic(),
hit, damage, remainingHealth));
}
var first = current.get(battle.participantOne().creatureId());
var second = current.get(battle.participantTwo().creatureId());
Optional<UUID> winner = Optional.empty();
var status = BattleState.Status.ACTIVE;
if (first.isFainted() || second.isFainted()) {
status = BattleState.Status.COMPLETED;
winner = Optional.of(first.isFainted() ? second.creatureId() : first.creatureId());
}
return new BattleState(battle.schemaVersion(), battle.id(), first, second, battle.turn() + 1,
status, winner, events);
}
public BattleState cancel(BattleState battle) {
if (battle.status() != BattleState.Status.ACTIVE) {
throw new IllegalStateException("only active battles can be cancelled");
}
return new BattleState(battle.schemaVersion(), battle.id(), battle.participantOne(),
battle.participantTwo(), battle.turn(), BattleState.Status.CANCELLED,
Optional.empty(), List.of());
}
private static Action actionFor(
BattleParticipant participant,
Map<UUID, String> commands,
Map<String, MoveDefinition> moveCatalog
) {
boolean automatic = !commands.containsKey(participant.creatureId());
String moveId = automatic ? participant.basicMoveId() : commands.get(participant.creatureId());
if (!automatic && !participant.commandMoveIds().contains(moveId)) {
throw new IllegalArgumentException("move is not one of the creature's three commands: " + moveId);
}
MoveDefinition move = Optional.ofNullable(moveCatalog.get(moveId))
.orElseThrow(() -> new IllegalArgumentException("missing move definition: " + moveId));
return new Action(participant, move, automatic);
}
private static int damage(
BattleParticipant attacker,
BattleParticipant defender,
MoveDefinition move,
SplittableRandom random
) {
if (move.category() == MoveDefinition.Category.STATUS) {
return 0;
}
double base = (((2.0 * attacker.level() / 5.0 + 2.0) * move.power()
* attacker.attack() / defender.defence()) / 50.0) + 2.0;
double variance = 0.85 + random.nextDouble() * 0.15;
return Math.max(1, (int) Math.floor(base * variance));
}
private static BattleParticipant withHealth(BattleParticipant participant, int health) {
return new BattleParticipant(participant.creatureId(), participant.ownerId(), participant.speciesId(),
participant.level(), health, participant.maximumHealth(), participant.attack(), participant.defence(),
participant.speed(), participant.basicMoveId(), participant.commandMoveIds());
}
private record Action(BattleParticipant actor, MoveDefinition move, boolean automatic) {
}
}
@@ -0,0 +1,142 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.CreatureEgg;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.HabitatState;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.SplittableRandom;
import java.util.UUID;
public final class BreedingService {
private final GeneticsService geneticsService;
public BreedingService(GeneticsService geneticsService) {
this.geneticsService = java.util.Objects.requireNonNull(geneticsService, "geneticsService must not be null");
}
public HabitatState start(
HabitatState habitat,
CreatureInstance parentOne,
CreatureInstance parentTwo,
Duration requiredActiveTime,
long expectedRevision
) {
requireRevision(habitat, expectedRevision);
if (habitat.status() != HabitatState.Status.EMPTY) {
throw new IllegalStateException("habitat is not empty");
}
if (parentOne == null || parentTwo == null || requiredActiveTime == null) {
throw new NullPointerException("breeding inputs must not be null");
}
if (parentOne.id().equals(parentTwo.id())) {
throw new IllegalArgumentException("breeding parents must be different creatures");
}
if (parentOne.ownerId().isEmpty() || parentTwo.ownerId().isEmpty()
|| !parentOne.ownerId().orElseThrow().equals(habitat.ownerId())
|| !parentTwo.ownerId().orElseThrow().equals(habitat.ownerId())) {
throw new IllegalArgumentException("habitat owner must own both parents");
}
long requiredMillis = positiveMillis(requiredActiveTime);
return new HabitatState(habitat.schemaVersion(), habitat.id(), habitat.ownerId(),
HabitatState.Status.BREEDING, Optional.of(parentOne.id()), Optional.of(parentTwo.id()),
0, requiredMillis, habitat.revision() + 1);
}
public HabitatState advance(
HabitatState habitat,
Duration elapsed,
boolean serverActive,
long expectedRevision
) {
requireRevision(habitat, expectedRevision);
if (elapsed == null || elapsed.isNegative()) {
throw new IllegalArgumentException("elapsed duration must not be null or negative");
}
if (habitat.status() != HabitatState.Status.BREEDING) {
throw new IllegalStateException("habitat is not breeding");
}
long elapsedMillis = elapsed.toMillis();
if (!serverActive || elapsedMillis == 0) {
return habitat;
}
long remaining = habitat.requiredActiveMillis() - habitat.accumulatedActiveMillis();
long progressed = Math.min(remaining, elapsedMillis);
long accumulated = habitat.accumulatedActiveMillis() + progressed;
var status = accumulated == habitat.requiredActiveMillis()
? HabitatState.Status.EGG_READY
: HabitatState.Status.BREEDING;
return new HabitatState(habitat.schemaVersion(), habitat.id(), habitat.ownerId(), status,
habitat.parentOneId(), habitat.parentTwoId(), accumulated,
habitat.requiredActiveMillis(), habitat.revision() + 1);
}
public EggCollection collectEgg(
HabitatState habitat,
CreatureInstance parentOne,
CreatureInstance parentTwo,
String childSpeciesId,
long seed,
Instant createdAt,
long expectedRevision
) {
requireRevision(habitat, expectedRevision);
if (habitat.status() != HabitatState.Status.EGG_READY) {
throw new IllegalStateException("egg is not ready");
}
if (parentOne == null || parentTwo == null || childSpeciesId == null || createdAt == null) {
throw new NullPointerException("egg inputs must not be null");
}
if (!habitat.parentOneId().orElseThrow().equals(parentOne.id())
|| !habitat.parentTwoId().orElseThrow().equals(parentTwo.id())) {
throw new IllegalArgumentException("parents do not match habitat");
}
var random = new SplittableRandom(seed);
var eggId = new UUID(random.nextLong(), random.nextLong());
var genome = geneticsService.breed(parentOne.genome(), parentTwo.genome(), seed);
var egg = new CreatureEgg(CreatureEgg.CURRENT_SCHEMA_VERSION, eggId, habitat.ownerId(), childSpeciesId,
parentOne.id(), parentTwo.id(), genome, createdAt);
var collected = new HabitatState(habitat.schemaVersion(), habitat.id(), habitat.ownerId(),
HabitatState.Status.COLLECTED, habitat.parentOneId(), habitat.parentTwoId(),
habitat.accumulatedActiveMillis(), habitat.requiredActiveMillis(), habitat.revision() + 1);
return new EggCollection(collected, egg);
}
public HabitatState cancel(HabitatState habitat, long expectedRevision) {
requireRevision(habitat, expectedRevision);
if (habitat.status() != HabitatState.Status.BREEDING
&& habitat.status() != HabitatState.Status.EGG_READY) {
throw new IllegalStateException("only active breeding can be cancelled");
}
return new HabitatState(habitat.schemaVersion(), habitat.id(), habitat.ownerId(),
HabitatState.Status.CANCELLED, habitat.parentOneId(), habitat.parentTwoId(),
habitat.accumulatedActiveMillis(), habitat.requiredActiveMillis(), habitat.revision() + 1);
}
private static long positiveMillis(Duration duration) {
if (duration.isNegative() || duration.isZero()) {
throw new IllegalArgumentException("required active time must be positive");
}
long millis = duration.toMillis();
if (millis <= 0) {
throw new IllegalArgumentException("required active time must be at least one millisecond");
}
return millis;
}
private static void requireRevision(HabitatState habitat, long expected) {
if (habitat.revision() != expected) {
throw new StaleRevisionException(expected, habitat.revision());
}
}
public record EggCollection(HabitatState habitat, CreatureEgg egg) {
public EggCollection {
if (habitat == null || egg == null) {
throw new NullPointerException("egg collection values must not be null");
}
}
}
}
@@ -0,0 +1,50 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.CaptureContext;
import java.util.SplittableRandom;
public final class CaptureService {
private static final double MIN_PROBABILITY = 0.005;
private static final double MAX_PROBABILITY = 0.995;
public CaptureResult attempt(CaptureContext context, long seed) {
if (context == null) {
throw new NullPointerException("context must not be null");
}
double probability = probability(context);
double roll = new SplittableRandom(seed).nextDouble();
return new CaptureResult(probability, roll, roll < probability);
}
public double probability(CaptureContext context) {
if (context == null) {
throw new NullPointerException("context must not be null");
}
double healthFactor = (3.0 * context.maximumHealth() - 2.0 * context.currentHealth())
/ (3.0 * context.maximumHealth());
double baseRate = context.captureRate() / 255.0;
double levelFactor = 0.55 + (100 - context.level()) * 0.0045;
double raw = baseRate
* context.rarity().captureMultiplier()
* healthFactor
* levelFactor
* context.deviceMultiplier()
* context.statusCondition().captureMultiplier();
return Math.clamp(raw, MIN_PROBABILITY, MAX_PROBABILITY);
}
public record CaptureResult(double probability, double roll, boolean captured) {
public CaptureResult {
if (!Double.isFinite(probability) || probability < 0.0 || probability > 1.0) {
throw new IllegalArgumentException("probability must be between zero and one");
}
if (!Double.isFinite(roll) || roll < 0.0 || roll >= 1.0) {
throw new IllegalArgumentException("roll must be in [0, 1)");
}
if (captured != (roll < probability)) {
throw new IllegalArgumentException("captured must match roll and probability");
}
}
}
}
@@ -0,0 +1,120 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.DuelRules;
import dev.projectcapture.engine.model.DuelSession;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
public final class DuelService {
public DuelSession request(UUID sessionId, UUID challengerId, UUID opponentId, DuelRules rules) {
return new DuelSession(DuelSession.CURRENT_SCHEMA_VERSION, sessionId, challengerId, opponentId,
rules, Set.of(challengerId), DuelSession.Status.REQUESTED,
Optional.empty(), Optional.empty(), 0);
}
public DuelSession accept(DuelSession session, UUID actorId, long expectedRevision) {
requireRevision(session, expectedRevision);
requireParticipant(session, actorId);
if (session.status() != DuelSession.Status.REQUESTED) {
throw new IllegalStateException("only requested duels can be accepted");
}
if (session.acceptedBy().contains(actorId)) {
return session;
}
var accepted = new HashSet<>(session.acceptedBy());
accepted.add(actorId);
var status = accepted.size() == 2 ? DuelSession.Status.ACTIVE : DuelSession.Status.REQUESTED;
return copy(session, accepted, status, Optional.empty(), Optional.empty(), session.revision() + 1);
}
public DuelSession cancelRequest(
DuelSession session,
UUID actorId,
String reason,
long expectedRevision
) {
requireRevision(session, expectedRevision);
requireParticipant(session, actorId);
if (session.status() != DuelSession.Status.REQUESTED) {
throw new IllegalStateException("only requested duels can be cancelled");
}
return copy(session, session.acceptedBy(), DuelSession.Status.CANCELLED,
Optional.empty(), Optional.of(requireReason(reason)), session.revision() + 1);
}
public DuelSession forfeit(DuelSession session, UUID forfeitingPlayerId, long expectedRevision) {
requireRevision(session, expectedRevision);
requireParticipant(session, forfeitingPlayerId);
if (session.status() != DuelSession.Status.ACTIVE) {
throw new IllegalStateException("only active duels can be forfeited");
}
UUID winner = forfeitingPlayerId.equals(session.challengerId())
? session.opponentId()
: session.challengerId();
return copy(session, session.acceptedBy(), DuelSession.Status.COMPLETED,
Optional.of(winner), Optional.of("forfeit"), session.revision() + 1);
}
public DuelSession leaveZone(DuelSession session, UUID leavingPlayerId, long expectedRevision) {
requireRevision(session, expectedRevision);
requireParticipant(session, leavingPlayerId);
if (session.status() != DuelSession.Status.ACTIVE) {
throw new IllegalStateException("only active duel players can leave the zone");
}
UUID winner = leavingPlayerId.equals(session.challengerId())
? session.opponentId()
: session.challengerId();
return copy(session, session.acceptedBy(), DuelSession.Status.COMPLETED,
Optional.of(winner), Optional.of("left-zone"), session.revision() + 1);
}
public DuelSession complete(
DuelSession session,
UUID winnerId,
String reason,
long expectedRevision
) {
requireRevision(session, expectedRevision);
requireParticipant(session, winnerId);
if (session.status() != DuelSession.Status.ACTIVE) {
throw new IllegalStateException("only active duels can be completed");
}
return copy(session, session.acceptedBy(), DuelSession.Status.COMPLETED,
Optional.of(winnerId), Optional.of(requireReason(reason)), session.revision() + 1);
}
private static DuelSession copy(
DuelSession session,
Set<UUID> acceptedBy,
DuelSession.Status status,
Optional<UUID> winner,
Optional<String> reason,
long revision
) {
return new DuelSession(session.schemaVersion(), session.id(), session.challengerId(),
session.opponentId(), session.rules(), acceptedBy, status, winner, reason, revision);
}
private static String requireReason(String reason) {
if (reason == null || reason.isBlank()) {
throw new IllegalArgumentException("reason must not be blank");
}
return reason.strip();
}
private static void requireParticipant(DuelSession session, UUID actorId) {
if (actorId == null || (!actorId.equals(session.challengerId())
&& !actorId.equals(session.opponentId()))) {
throw new IllegalArgumentException("actor is not a duel participant");
}
}
private static void requireRevision(DuelSession session, long expected) {
if (session.revision() != expected) {
throw new StaleRevisionException(expected, session.revision());
}
}
}
@@ -0,0 +1,59 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.EvolutionRule;
import dev.projectcapture.engine.model.SpeciesDefinition;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public final class EvolutionService {
public EvolutionResult evolve(
CreatureInstance creature,
SpeciesDefinition currentSpecies,
Map<String, SpeciesDefinition> speciesCatalog,
Set<String> availableItemIds,
long expectedRevision
) {
requireRevision(creature.revision(), expectedRevision);
if (!creature.speciesId().equals(currentSpecies.id())) {
throw new IllegalArgumentException("current species does not match creature");
}
if (speciesCatalog == null || availableItemIds == null) {
throw new NullPointerException("catalog and item ids must not be null");
}
EvolutionRule rule = currentSpecies.evolutions().stream()
.filter(candidate -> candidate.isEligible(creature.level(), availableItemIds))
.findFirst()
.orElseThrow(() -> new IllegalStateException("creature is not eligible for evolution"));
SpeciesDefinition target = Optional.ofNullable(speciesCatalog.get(rule.targetSpeciesId()))
.orElseThrow(() -> new IllegalArgumentException("missing target species: " + rule.targetSpeciesId()));
int oldMaximum = currentSpecies.baseStats().healthAtLevel(creature.level());
int newMaximum = target.baseStats().healthAtLevel(creature.level());
int newHealth = creature.currentHealth() == 0
? 0
: Math.clamp((int) Math.ceil(creature.currentHealth() * (newMaximum / (double) oldMaximum)), 1, newMaximum);
var evolved = new CreatureInstance(
creature.schemaVersion(), creature.id(), target.id(), creature.nickname(), creature.ownerId(),
creature.level(), creature.experience(), newHealth, creature.genome(), target.basicMoveId(),
target.commandMoveIds(), creature.createdAt(), creature.revision() + 1);
return new EvolutionResult(evolved, rule.requiredItemId());
}
private static void requireRevision(long actual, long expected) {
if (actual != expected) {
throw new StaleRevisionException(expected, actual);
}
}
public record EvolutionResult(CreatureInstance creature, Optional<String> consumedItemId) {
public EvolutionResult {
if (creature == null || consumedItemId == null) {
throw new NullPointerException("evolution result values must not be null");
}
}
}
}
@@ -0,0 +1,76 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.SpeciesDefinition;
public final class ExperienceService {
public static final int MAX_LEVEL = 100;
public long thresholdForLevel(int level) {
if (level < 1 || level > MAX_LEVEL) {
throw new IllegalArgumentException("level must be between 1 and 100");
}
long levelOffset = level - 1L;
return levelOffset * levelOffset * levelOffset * 100L;
}
public int levelForExperience(long experience) {
if (experience < 0) {
throw new IllegalArgumentException("experience must not be negative");
}
int low = 1;
int high = MAX_LEVEL;
while (low < high) {
int middle = (low + high + 1) >>> 1;
if (thresholdForLevel(middle) <= experience) {
low = middle;
} else {
high = middle - 1;
}
}
return low;
}
public CreatureInstance grantExperience(
CreatureInstance creature,
SpeciesDefinition species,
long amount,
long expectedRevision
) {
requireRevision(creature.revision(), expectedRevision);
if (!creature.speciesId().equals(species.id())) {
throw new IllegalArgumentException("species does not match creature");
}
if (amount < 0) {
throw new IllegalArgumentException("experience amount must not be negative");
}
if (levelForExperience(creature.experience()) != creature.level()) {
throw new IllegalStateException("creature level and experience are inconsistent");
}
if (amount == 0 || creature.level() == MAX_LEVEL) {
return creature;
}
long maximumExperience = thresholdForLevel(MAX_LEVEL);
long newExperience = creature.experience() >= maximumExperience - amount
? maximumExperience
: creature.experience() + amount;
int newLevel = levelForExperience(newExperience);
int health = creature.currentHealth();
if (health > 0 && newLevel > creature.level()) {
int oldMaximum = species.baseStats().healthAtLevel(creature.level());
int newMaximum = species.baseStats().healthAtLevel(newLevel);
health = Math.min(newMaximum, health + (newMaximum - oldMaximum));
}
return new CreatureInstance(
creature.schemaVersion(), creature.id(), creature.speciesId(), creature.nickname(), creature.ownerId(),
newLevel, newExperience, health, creature.genome(), creature.basicMoveId(),
creature.commandMoveIds(), creature.createdAt(), creature.revision() + 1);
}
private static void requireRevision(long actual, long expected) {
if (actual != expected) {
throw new StaleRevisionException(expected, actual);
}
}
}
@@ -0,0 +1,86 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.Genome;
import dev.projectcapture.engine.model.LineageContribution;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import java.util.TreeSet;
public final class GeneticsService {
private static final double MUTATION_CHANCE = 0.08;
public Genome breed(Genome parentOne, Genome parentTwo, long seed) {
if (parentOne == null || parentTwo == null) {
throw new NullPointerException("parent genomes must not be null");
}
var random = new SplittableRandom(seed);
var traitNames = new TreeSet<String>();
traitNames.addAll(parentOne.traits().keySet());
traitNames.addAll(parentTwo.traits().keySet());
var traits = new HashMap<String, Integer>();
for (var traitName : traitNames) {
Integer first = parentOne.traits().get(traitName);
Integer second = parentTwo.traits().get(traitName);
int inherited;
if (first == null) {
inherited = second;
} else if (second == null) {
inherited = first;
} else {
inherited = random.nextBoolean() ? first : second;
}
if (random.nextDouble() < MUTATION_CHANCE) {
inherited = Math.clamp(inherited + (random.nextBoolean() ? 1 : -1), 0, 31);
}
traits.put(traitName, inherited);
}
return new Genome(Genome.CURRENT_SCHEMA_VERSION, seed, traits,
mergeLineages(parentOne, parentTwo), java.util.Set.of());
}
private static List<LineageContribution> mergeLineages(Genome first, Genome second) {
var rawWeights = new HashMap<String, Long>();
first.lineages().forEach(lineage -> rawWeights.merge(
lineage.speciesId(), (long) lineage.basisPoints(), Long::sum));
second.lineages().forEach(lineage -> rawWeights.merge(
lineage.speciesId(), (long) lineage.basisPoints(), Long::sum));
var selected = rawWeights.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry::getKey))
.limit(Genome.MAX_LINEAGES)
.toList();
long selectedTotal = selected.stream().mapToLong(Map.Entry::getValue).sum();
int distributable = Genome.TOTAL_BASIS_POINTS - selected.size();
int[] allocations = new int[selected.size()];
long[] remainders = new long[selected.size()];
int allocated = 0;
for (int index = 0; index < selected.size(); index++) {
long numerator = selected.get(index).getValue() * distributable;
allocations[index] = 1 + (int) (numerator / selectedTotal);
remainders[index] = numerator % selectedTotal;
allocated += allocations[index];
}
var remainderOrder = new ArrayList<Integer>();
for (int index = 0; index < selected.size(); index++) {
remainderOrder.add(index);
}
remainderOrder.sort(Comparator.<Integer>comparingLong(index -> remainders[index]).reversed()
.thenComparing(index -> selected.get(index).getKey()));
for (int remainder = Genome.TOTAL_BASIS_POINTS - allocated, index = 0; remainder > 0; remainder--, index++) {
allocations[remainderOrder.get(index % remainderOrder.size())]++;
}
var lineages = new ArrayList<LineageContribution>();
for (int index = 0; index < selected.size(); index++) {
lineages.add(new LineageContribution(selected.get(index).getKey(), allocations[index]));
}
lineages.sort(Comparator.comparingInt(LineageContribution::basisPoints).reversed()
.thenComparing(LineageContribution::speciesId));
return List.copyOf(lineages);
}
}
@@ -0,0 +1,26 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.Genome;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.SplittableRandom;
public final class GenomeAnalysisService {
public Genome revealNext(Genome genome) {
if (genome == null) {
throw new NullPointerException("genome must not be null");
}
if (genome.fullyAnalysed()) {
return genome;
}
var hidden = new ArrayList<>(genome.traits().keySet());
hidden.removeAll(genome.revealedTraits());
hidden.sort(String::compareTo);
var random = new SplittableRandom(genome.seed() ^ (0x9E3779B97F4A7C15L * genome.revealedTraits().size()));
String revealed = hidden.get(random.nextInt(hidden.size()));
var revealedTraits = new HashSet<>(genome.revealedTraits());
revealedTraits.add(revealed);
return new Genome(genome.schemaVersion(), genome.seed(), genome.traits(), genome.lineages(), revealedTraits);
}
}
@@ -0,0 +1,58 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.Party;
import java.util.ArrayList;
import java.util.Optional;
import java.util.UUID;
public final class PartyService {
public Party add(Party party, UUID creatureId, long expectedRevision) {
requireRevision(party, expectedRevision);
if (creatureId == null) {
throw new NullPointerException("creatureId must not be null");
}
if (party.creatureIds().contains(creatureId)) {
return party;
}
if (party.creatureIds().size() == Party.MAX_SIZE) {
throw new IllegalStateException("party is full");
}
var creatures = new ArrayList<>(party.creatureIds());
creatures.add(creatureId);
return new Party(party.schemaVersion(), party.ownerId(), creatures,
party.activeCompanionId(), party.revision() + 1);
}
public Party remove(Party party, UUID creatureId, long expectedRevision) {
requireRevision(party, expectedRevision);
if (!party.creatureIds().contains(creatureId)) {
return party;
}
var creatures = new ArrayList<>(party.creatureIds());
creatures.remove(creatureId);
var companion = party.activeCompanionId().filter(id -> !id.equals(creatureId));
return new Party(party.schemaVersion(), party.ownerId(), creatures, companion, party.revision() + 1);
}
public Party setActiveCompanion(Party party, Optional<UUID> creatureId, long expectedRevision) {
requireRevision(party, expectedRevision);
if (creatureId == null) {
throw new NullPointerException("creatureId must not be null");
}
if (creatureId.isPresent() && !party.creatureIds().contains(creatureId.orElseThrow())) {
throw new IllegalArgumentException("active companion must be in the party");
}
if (party.activeCompanionId().equals(creatureId)) {
return party;
}
return new Party(party.schemaVersion(), party.ownerId(), party.creatureIds(), creatureId,
party.revision() + 1);
}
private static void requireRevision(Party party, long expected) {
if (party.revision() != expected) {
throw new StaleRevisionException(expected, party.revision());
}
}
}
@@ -0,0 +1,69 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.SpawnRule;
import dev.projectcapture.engine.model.SpeciesDefinition;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.SplittableRandom;
public final class SpawnService {
public Optional<SpawnSelection> select(
List<SpeciesDefinition> species,
String biomeTag,
SpawnRule.TimeOfDay time,
long seed
) {
if (species == null || biomeTag == null || time == null) {
throw new NullPointerException("spawn inputs must not be null");
}
var candidates = new ArrayList<Candidate>();
species.stream().sorted(Comparator.comparing(SpeciesDefinition::id)).forEach(definition ->
definition.spawnRules().stream()
.filter(rule -> rule.biomeTags().contains(biomeTag) && rule.times().contains(time))
.forEach(rule -> candidates.add(new Candidate(definition, rule,
Math.multiplyExact((long) rule.weight(), rarityWeight(definition.rarity()))))));
if (candidates.isEmpty()) {
return Optional.empty();
}
long totalWeight = candidates.stream().mapToLong(Candidate::weight).reduce(0, Math::addExact);
var random = new SplittableRandom(seed);
long draw = random.nextLong(totalWeight);
Candidate selected = candidates.getLast();
for (var candidate : candidates) {
if (draw < candidate.weight()) {
selected = candidate;
break;
}
draw -= candidate.weight();
}
int level = random.nextInt(selected.rule().minimumLevel(), selected.rule().maximumLevel() + 1);
return Optional.of(new SpawnSelection(selected.species().id(), level));
}
private static long rarityWeight(SpeciesDefinition.Rarity rarity) {
return switch (rarity) {
case COMMON -> 100;
case UNCOMMON -> 60;
case RARE -> 25;
case EPIC -> 8;
case LEGENDARY -> 1;
};
}
private record Candidate(SpeciesDefinition species, SpawnRule rule, long weight) {
}
public record SpawnSelection(String speciesId, int level) {
public SpawnSelection {
if (speciesId == null || speciesId.isBlank()) {
throw new IllegalArgumentException("speciesId must not be blank");
}
if (level < 1 || level > 100) {
throw new IllegalArgumentException("level must be between 1 and 100");
}
}
}
}
@@ -0,0 +1,9 @@
package dev.projectcapture.engine.service;
public final class StaleRevisionException extends IllegalStateException {
private static final long serialVersionUID = 1L;
public StaleRevisionException(long expected, long actual) {
super("Stale revision: expected " + expected + " but was " + actual);
}
}
@@ -0,0 +1,167 @@
package dev.projectcapture.engine.service;
import dev.projectcapture.engine.model.PlayerInventory;
import dev.projectcapture.engine.model.TradeOffer;
import dev.projectcapture.engine.model.TradeTransaction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public final class TradeService {
public TradeTransaction create(UUID transactionId, TradeOffer playerOneOffer, TradeOffer playerTwoOffer) {
return new TradeTransaction(TradeTransaction.CURRENT_SCHEMA_VERSION, transactionId,
playerOneOffer.ownerId(), playerTwoOffer.ownerId(), playerOneOffer, playerTwoOffer,
Set.of(), TradeTransaction.Status.OPEN, 0);
}
public TradeTransaction accept(TradeTransaction transaction, UUID actorId, long expectedRevision) {
requireRevision(transaction.revision(), expectedRevision);
requireParticipant(transaction, actorId);
if (transaction.status() != TradeTransaction.Status.OPEN) {
throw new IllegalStateException("only open trades can be accepted");
}
if (transaction.acceptedBy().contains(actorId)) {
return transaction;
}
var accepted = new HashSet<>(transaction.acceptedBy());
accepted.add(actorId);
var status = accepted.size() == 2 ? TradeTransaction.Status.LOCKED : TradeTransaction.Status.OPEN;
return copy(transaction, accepted, status, transaction.revision() + 1);
}
public TradeTransaction cancel(TradeTransaction transaction, UUID actorId, long expectedRevision) {
requireRevision(transaction.revision(), expectedRevision);
requireParticipant(transaction, actorId);
if (transaction.status() == TradeTransaction.Status.COMMITTED
|| transaction.status() == TradeTransaction.Status.CANCELLED) {
throw new IllegalStateException("terminal trade cannot be cancelled");
}
return copy(transaction, transaction.acceptedBy(), TradeTransaction.Status.CANCELLED,
transaction.revision() + 1);
}
public TradeCommitResult commit(
TradeTransaction transaction,
PlayerInventory playerOneInventory,
PlayerInventory playerTwoInventory,
long expectedTradeRevision,
long expectedPlayerOneRevision,
long expectedPlayerTwoRevision
) {
requireRevision(transaction.revision(), expectedTradeRevision);
requireRevision(playerOneInventory.revision(), expectedPlayerOneRevision);
requireRevision(playerTwoInventory.revision(), expectedPlayerTwoRevision);
if (transaction.status() != TradeTransaction.Status.LOCKED) {
throw new IllegalStateException("trade must be locked before commit");
}
if (!playerOneInventory.ownerId().equals(transaction.playerOneId())
|| !playerTwoInventory.ownerId().equals(transaction.playerTwoId())) {
throw new IllegalArgumentException("inventory owners do not match transaction");
}
var inventoryOverlap = new HashSet<>(playerOneInventory.creatureIds());
inventoryOverlap.retainAll(playerTwoInventory.creatureIds());
if (!inventoryOverlap.isEmpty()) {
throw new IllegalStateException("a creature cannot exist in both inventories");
}
validateOffer(transaction.playerOneOffer(), playerOneInventory);
validateOffer(transaction.playerTwoOffer(), playerTwoInventory);
// All checks and calculations happen on detached copies. If any calculation fails,
// no new aggregate is returned and both source snapshots remain unchanged.
var oneCreatures = exchangeCreatures(playerOneInventory.creatureIds(), transaction.playerOneOffer(),
transaction.playerTwoOffer());
var twoCreatures = exchangeCreatures(playerTwoInventory.creatureIds(), transaction.playerTwoOffer(),
transaction.playerOneOffer());
var oneItems = exchangeItems(playerOneInventory.items(), transaction.playerOneOffer(),
transaction.playerTwoOffer());
var twoItems = exchangeItems(playerTwoInventory.items(), transaction.playerTwoOffer(),
transaction.playerOneOffer());
var updatedOne = new PlayerInventory(playerOneInventory.schemaVersion(), playerOneInventory.ownerId(),
oneCreatures, oneItems, playerOneInventory.revision() + 1);
var updatedTwo = new PlayerInventory(playerTwoInventory.schemaVersion(), playerTwoInventory.ownerId(),
twoCreatures, twoItems, playerTwoInventory.revision() + 1);
var committed = copy(transaction, transaction.acceptedBy(), TradeTransaction.Status.COMMITTED,
transaction.revision() + 1);
return new TradeCommitResult(committed, updatedOne, updatedTwo);
}
private static void validateOffer(TradeOffer offer, PlayerInventory inventory) {
if (!inventory.creatureIds().containsAll(offer.creatureIds())) {
throw new IllegalStateException("offered creature is no longer owned");
}
offer.items().forEach((itemId, quantity) -> {
if (inventory.items().getOrDefault(itemId, 0) < quantity) {
throw new IllegalStateException("offered item quantity is no longer available: " + itemId);
}
});
}
private static Set<UUID> exchangeCreatures(Set<UUID> source, TradeOffer outgoing, TradeOffer incoming) {
var result = new HashSet<>(source);
result.removeAll(outgoing.creatureIds());
for (var creatureId : incoming.creatureIds()) {
if (!result.add(creatureId)) {
throw new IllegalStateException("receiving inventory already contains creature: " + creatureId);
}
}
return Set.copyOf(result);
}
private static Map<String, Integer> exchangeItems(
Map<String, Integer> source,
TradeOffer outgoing,
TradeOffer incoming
) {
var result = new HashMap<>(source);
outgoing.items().forEach((itemId, quantity) -> {
int remaining = result.getOrDefault(itemId, 0) - quantity;
if (remaining == 0) {
result.remove(itemId);
} else {
result.put(itemId, remaining);
}
});
incoming.items().forEach((itemId, quantity) -> result.merge(itemId, quantity, Math::addExact));
return Map.copyOf(result);
}
private static TradeTransaction copy(
TradeTransaction transaction,
Set<UUID> acceptedBy,
TradeTransaction.Status status,
long revision
) {
return new TradeTransaction(transaction.schemaVersion(), transaction.id(), transaction.playerOneId(),
transaction.playerTwoId(), transaction.playerOneOffer(), transaction.playerTwoOffer(),
acceptedBy, status, revision);
}
private static void requireParticipant(TradeTransaction transaction, UUID actorId) {
if (actorId == null || (!actorId.equals(transaction.playerOneId())
&& !actorId.equals(transaction.playerTwoId()))) {
throw new IllegalArgumentException("actor is not a trade participant");
}
}
private static void requireRevision(long actual, long expected) {
if (actual != expected) {
throw new StaleRevisionException(expected, actual);
}
}
public record TradeCommitResult(
TradeTransaction transaction,
PlayerInventory playerOneInventory,
PlayerInventory playerTwoInventory
) {
public TradeCommitResult {
if (transaction == null || playerOneInventory == null || playerTwoInventory == null) {
throw new NullPointerException("trade commit values must not be null");
}
}
}
}
@@ -0,0 +1,96 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.BattleParticipant;
import dev.projectcapture.engine.model.BattleState;
import dev.projectcapture.engine.model.MoveDefinition;
import dev.projectcapture.engine.service.BattleService;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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;
class BattleServiceTest {
private static final UUID FIRST_CREATURE = new UUID(20, 1);
private static final UUID SECOND_CREATURE = new UUID(20, 2);
private static final UUID BATTLE_ID = new UUID(30, 1);
private final BattleService service = new BattleService();
@Test
void missingCommandProducesAutomaticBasicAttackAndExplicitCommandUsesAbility() {
var battle = service.create(BATTLE_ID, participant(FIRST_CREATURE, TestFixtures.OWNER_ONE, 60, 50, 50),
participant(SECOND_CREATURE, TestFixtures.OWNER_TWO, 50, 50, 40));
var result = service.nextTurn(battle, Map.of(FIRST_CREATURE, TestFixtures.COMMANDS.getFirst()),
TestFixtures.moves(), 123);
assertEquals(2, result.lastTurnEvents().size());
var firstEvent = result.lastTurnEvents().stream()
.filter(event -> event.actorCreatureId().equals(FIRST_CREATURE)).findFirst().orElseThrow();
var secondEvent = result.lastTurnEvents().stream()
.filter(event -> event.actorCreatureId().equals(SECOND_CREATURE)).findFirst().orElseThrow();
assertFalse(firstEvent.automaticBasicAttack());
assertEquals(TestFixtures.COMMANDS.getFirst(), firstEvent.moveId());
assertTrue(secondEvent.automaticBasicAttack());
assertEquals(TestFixtures.BASIC, secondEvent.moveId());
}
@Test
void battleTurnIsFullyDeterministicForStateAndSeed() {
var battle = service.create(BATTLE_ID, participant(FIRST_CREATURE, TestFixtures.OWNER_ONE, 100, 50, 50),
participant(SECOND_CREATURE, TestFixtures.OWNER_TWO, 100, 50, 50));
assertEquals(
service.nextTurn(battle, Map.of(), TestFixtures.moves(), 999),
service.nextTurn(battle, Map.of(), TestFixtures.moves(), 999));
}
@Test
void fasterKnockoutStopsFaintedCreatureFromActing() {
var fast = participant(FIRST_CREATURE, TestFixtures.OWNER_ONE, 20, 100_000, 1_000);
var fragile = new BattleParticipant(SECOND_CREATURE, TestFixtures.OWNER_TWO, "projectcapture:test",
50, 10, 10, 1, 1, 1, TestFixtures.BASIC, TestFixtures.COMMANDS);
var result = service.nextTurn(service.create(BATTLE_ID, fast, fragile), Map.of(), TestFixtures.moves(), 1);
assertEquals(BattleState.Status.COMPLETED, result.status());
assertEquals(FIRST_CREATURE, result.winnerCreatureId().orElseThrow());
assertEquals(1, result.lastTurnEvents().size());
assertEquals(0, result.participantTwo().currentHealth());
}
@Test
void rejectsFourthOrUnknownCommand() {
var battle = service.create(BATTLE_ID, participant(FIRST_CREATURE, TestFixtures.OWNER_ONE, 50, 50, 50),
participant(SECOND_CREATURE, TestFixtures.OWNER_TWO, 50, 50, 50));
assertThrows(IllegalArgumentException.class, () -> service.nextTurn(battle,
Map.of(FIRST_CREATURE, "projectcapture:not_equipped"), TestFixtures.moves(), 1));
assertThrows(IllegalArgumentException.class, () -> service.nextTurn(battle,
Map.of(UUID.randomUUID(), TestFixtures.COMMANDS.getFirst()), TestFixtures.moves(), 1));
}
@Test
void missedAttackDealsNoDamageAndCancellationIsTerminal() {
var moves = new HashMap<>(TestFixtures.moves());
moves.put(TestFixtures.BASIC, TestFixtures.move(TestFixtures.BASIC, 40, 0.0, 0));
var battle = service.create(BATTLE_ID, participant(FIRST_CREATURE, TestFixtures.OWNER_ONE, 50, 50, 50),
participant(SECOND_CREATURE, TestFixtures.OWNER_TWO, 50, 50, 50));
var result = service.nextTurn(battle, Map.of(), moves, 1);
assertTrue(result.lastTurnEvents().stream().noneMatch(event -> event.hit() || event.damage() != 0));
assertEquals(50, result.participantOne().currentHealth());
assertEquals(50, result.participantTwo().currentHealth());
var cancelled = service.cancel(result);
assertEquals(BattleState.Status.CANCELLED, cancelled.status());
assertThrows(IllegalStateException.class,
() -> service.nextTurn(cancelled, Map.of(), moves, 2));
}
private static BattleParticipant participant(UUID creatureId, UUID ownerId, int health, int attack, int speed) {
return new BattleParticipant(creatureId, ownerId, "projectcapture:test", 50,
health, health, attack, 50, speed, TestFixtures.BASIC, TestFixtures.COMMANDS);
}
}
@@ -0,0 +1,72 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.CaptureContext;
import dev.projectcapture.engine.model.SpawnRule;
import dev.projectcapture.engine.model.SpeciesDefinition;
import dev.projectcapture.engine.service.CaptureService;
import dev.projectcapture.engine.service.SpawnService;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CaptureAndSpawnServiceTest {
private final CaptureService captureService = new CaptureService();
@Test
void captureIsDeterministicForTheSameSeed() {
var context = context(70, 100, CaptureContext.StatusCondition.PARALYSED);
var first = captureService.attempt(context, 42);
var second = captureService.attempt(context, 42);
assertEquals(first, second);
}
@Test
void lowerHealthAndStrongStatusIncreaseCaptureProbability() {
double healthy = captureService.probability(context(100, 100, CaptureContext.StatusCondition.NONE));
double weakened = captureService.probability(context(10, 100, CaptureContext.StatusCondition.ASLEEP));
assertTrue(weakened > healthy);
assertTrue(healthy >= 0.005);
assertTrue(weakened <= 0.995);
}
@Test
void spawnSelectionFiltersBiomeAndTimeAndIsDeterministic() {
var forestRule = new SpawnRule(Set.of("hytale:forest"), Set.of(SpawnRule.TimeOfDay.DAY),
100, 3, 7);
var caveRule = new SpawnRule(Set.of("hytale:cave"), Set.of(SpawnRule.TimeOfDay.NIGHT),
100, 20, 20);
var forestSpecies = TestFixtures.species("projectcapture:forestling", List.of(), List.of(forestRule));
var caveSpecies = TestFixtures.species("projectcapture:caveling", List.of(), List.of(caveRule));
var service = new SpawnService();
var first = service.select(List.of(caveSpecies, forestSpecies), "hytale:forest",
SpawnRule.TimeOfDay.DAY, 999).orElseThrow();
var second = service.select(List.of(forestSpecies, caveSpecies), "hytale:forest",
SpawnRule.TimeOfDay.DAY, 999).orElseThrow();
assertEquals(first, second);
assertEquals("projectcapture:forestling", first.speciesId());
assertTrue(first.level() >= 3 && first.level() <= 7);
}
@Test
void spawnSelectionReturnsEmptyWhenNothingMatches() {
var rule = new SpawnRule(Set.of("hytale:forest"), Set.of(SpawnRule.TimeOfDay.DAY), 1, 1, 1);
var species = TestFixtures.species("projectcapture:forestling", List.of(), List.of(rule));
assertFalse(new SpawnService().select(List.of(species), "hytale:desert",
SpawnRule.TimeOfDay.DAY, 1).isPresent());
}
private static CaptureContext context(
int currentHealth,
int maximumHealth,
CaptureContext.StatusCondition status
) {
return new CaptureContext(120, SpeciesDefinition.Rarity.UNCOMMON, 25, currentHealth, maximumHealth,
1.0, status);
}
}
@@ -0,0 +1,76 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.DuelRules;
import dev.projectcapture.engine.model.DuelSession;
import dev.projectcapture.engine.service.DuelService;
import dev.projectcapture.engine.service.StaleRevisionException;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DuelServiceTest {
private final DuelService service = new DuelService();
@Test
void acceptedDuelUsesNaturalLevelsAndDisablesPlayerWeapons() {
var requested = request();
assertTrue(requested.rules().naturalLevels());
assertTrue(requested.rules().playerWeaponsDisabled());
assertEquals(DuelSession.Status.REQUESTED, requested.status());
var active = service.accept(requested, TestFixtures.OWNER_TWO, requested.revision());
assertEquals(DuelSession.Status.ACTIVE, active.status());
assertEquals(2, active.acceptedBy().size());
}
@Test
void forfeitAndLeavingZoneAwardVictoryToOtherPlayer() {
var active = active();
var forfeited = service.forfeit(active, TestFixtures.OWNER_ONE, active.revision());
assertEquals(DuelSession.Status.COMPLETED, forfeited.status());
assertEquals(TestFixtures.OWNER_TWO, forfeited.winnerId().orElseThrow());
assertEquals("forfeit", forfeited.completionReason().orElseThrow());
var another = active();
var leftZone = service.leaveZone(another, TestFixtures.OWNER_TWO, another.revision());
assertEquals(TestFixtures.OWNER_ONE, leftZone.winnerId().orElseThrow());
assertEquals("left-zone", leftZone.completionReason().orElseThrow());
}
@Test
void requestCanBeCancelledButTerminalOrStaleActionsFail() {
var requested = request();
var cancelled = service.cancelRequest(requested, TestFixtures.OWNER_TWO, "declined", 0);
assertEquals(DuelSession.Status.CANCELLED, cancelled.status());
assertEquals("declined", cancelled.completionReason().orElseThrow());
assertThrows(IllegalStateException.class,
() -> service.accept(cancelled, TestFixtures.OWNER_TWO, cancelled.revision()));
var active = active();
assertThrows(StaleRevisionException.class,
() -> service.complete(active, TestFixtures.OWNER_ONE, "knockout", 0));
assertThrows(IllegalArgumentException.class,
() -> service.forfeit(active, UUID.randomUUID(), active.revision()));
}
@Test
void duelRulesRejectWeaponDamageLevelScalingAndUnsafeZoneSizes() {
assertThrows(IllegalArgumentException.class, () -> new DuelRules(false, true, 32));
assertThrows(IllegalArgumentException.class, () -> new DuelRules(true, false, 32));
assertThrows(IllegalArgumentException.class, () -> new DuelRules(true, true, 1));
}
private DuelSession request() {
return service.request(new UUID(60, 1), TestFixtures.OWNER_ONE, TestFixtures.OWNER_TWO,
DuelRules.defaults());
}
private DuelSession active() {
var requested = request();
return service.accept(requested, TestFixtures.OWNER_TWO, requested.revision());
}
}
@@ -0,0 +1,123 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.Genome;
import dev.projectcapture.engine.model.HabitatState;
import dev.projectcapture.engine.model.LineageContribution;
import dev.projectcapture.engine.service.BreedingService;
import dev.projectcapture.engine.service.GeneticsService;
import dev.projectcapture.engine.service.GenomeAnalysisService;
import dev.projectcapture.engine.service.StaleRevisionException;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class GeneticsAndBreedingTest {
@Test
void geneticsIsDeterministicAndLimitsHybridsToFourLineages() {
var first = genome(1, List.of(
new LineageContribution("projectcapture:a", 4_000),
new LineageContribution("projectcapture:b", 3_000),
new LineageContribution("projectcapture:c", 2_000),
new LineageContribution("projectcapture:d", 1_000)));
var second = genome(2, List.of(
new LineageContribution("projectcapture:e", 4_000),
new LineageContribution("projectcapture:f", 3_000),
new LineageContribution("projectcapture:g", 2_000),
new LineageContribution("projectcapture:h", 1_000)));
var service = new GeneticsService();
var childOne = service.breed(first, second, 12345);
var childTwo = service.breed(first, second, 12345);
assertEquals(childOne, childTwo);
assertTrue(childOne.lineages().size() <= Genome.MAX_LINEAGES);
assertEquals(Genome.TOTAL_BASIS_POINTS,
childOne.lineages().stream().mapToInt(LineageContribution::basisPoints).sum());
assertNotEquals(service.breed(first, second, 12346).seed(), childOne.seed());
}
@Test
void geneAnalysisRevealsExactlyOneNewTraitPerStep() {
var analysis = new GenomeAnalysisService();
Genome genome = TestFixtures.genome(77, "projectcapture:a");
for (int expected = 1; expected <= genome.traits().size(); expected++) {
genome = analysis.revealNext(genome);
assertEquals(expected, genome.revealedTraits().size());
}
assertTrue(genome.fullyAnalysed());
assertSame(genome, analysis.revealNext(genome));
}
@Test
void breedingProgressesOnlyDuringActiveServerTimeAndClampsAtReady() {
var species = TestFixtures.species("projectcapture:a");
var first = TestFixtures.creature(new UUID(5, 1), species, TestFixtures.OWNER_ONE, 10, 1);
var second = TestFixtures.creature(new UUID(5, 2), species, TestFixtures.OWNER_ONE, 10, 2);
var service = new BreedingService(new GeneticsService());
var empty = HabitatState.empty(new UUID(8, 1), TestFixtures.OWNER_ONE);
var breeding = service.start(empty, first, second, Duration.ofSeconds(10), 0);
var offline = service.advance(breeding, Duration.ofHours(8), false, breeding.revision());
assertSame(breeding, offline);
var halfway = service.advance(breeding, Duration.ofSeconds(4), true, breeding.revision());
assertEquals(4_000, halfway.accumulatedActiveMillis());
assertEquals(HabitatState.Status.BREEDING, halfway.status());
var ready = service.advance(halfway, Duration.ofSeconds(30), true, halfway.revision());
assertEquals(10_000, ready.accumulatedActiveMillis());
assertEquals(HabitatState.Status.EGG_READY, ready.status());
}
@Test
void collectingEggIsDeterministicAndTerminal() {
var species = TestFixtures.species("projectcapture:a");
var first = TestFixtures.creature(new UUID(6, 1), species, TestFixtures.OWNER_ONE, 10, 1);
var second = TestFixtures.creature(new UUID(6, 2), species, TestFixtures.OWNER_ONE, 10, 2);
var service = new BreedingService(new GeneticsService());
var breeding = service.start(HabitatState.empty(new UUID(9, 1), TestFixtures.OWNER_ONE),
first, second, Duration.ofMillis(1), 0);
var ready = service.advance(breeding, Duration.ofMillis(1), true, breeding.revision());
var firstResult = service.collectEgg(ready, first, second, "projectcapture:a", 88,
Instant.parse("2026-01-01T00:00:00Z"), ready.revision());
var secondResult = service.collectEgg(ready, first, second, "projectcapture:a", 88,
Instant.parse("2026-01-01T00:00:00Z"), ready.revision());
assertEquals(firstResult, secondResult);
assertEquals(HabitatState.Status.COLLECTED, firstResult.habitat().status());
assertEquals(first.id(), firstResult.egg().parentOneId());
assertThrows(IllegalStateException.class, () -> service.collectEgg(firstResult.habitat(), first, second,
"projectcapture:a", 88, Instant.EPOCH, firstResult.habitat().revision()));
}
@Test
void breedingRejectsWrongOwnerAndStaleUpdatesAndCanBeCancelled() {
var species = TestFixtures.species("projectcapture:a");
var owned = TestFixtures.creature(new UUID(7, 1), species, TestFixtures.OWNER_ONE, 10, 1);
var foreign = TestFixtures.creature(new UUID(7, 2), species, TestFixtures.OWNER_TWO, 10, 2);
var service = new BreedingService(new GeneticsService());
var empty = HabitatState.empty(new UUID(10, 1), TestFixtures.OWNER_ONE);
assertThrows(IllegalArgumentException.class,
() -> service.start(empty, owned, foreign, Duration.ofSeconds(1), 0));
var second = TestFixtures.creature(new UUID(7, 3), species, TestFixtures.OWNER_ONE, 10, 3);
var breeding = service.start(empty, owned, second, Duration.ofSeconds(1), 0);
assertThrows(StaleRevisionException.class,
() -> service.advance(breeding, Duration.ofMillis(1), true, 0));
assertEquals(HabitatState.Status.CANCELLED,
service.cancel(breeding, breeding.revision()).status());
}
private static Genome genome(long seed, List<LineageContribution> lineages) {
return new Genome(Genome.CURRENT_SCHEMA_VERSION, seed,
Map.of("vitality", 1, "strength", 31, "agility", 15), lineages, Set.of());
}
}
@@ -0,0 +1,105 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.BaseStats;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.Genome;
import dev.projectcapture.engine.model.HabitatState;
import dev.projectcapture.engine.model.LineageContribution;
import dev.projectcapture.engine.model.Party;
import dev.projectcapture.engine.model.SpeciesDefinition;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ModelInvariantTest {
@Test
void rejectsInvalidNamespacedIdsAndStats() {
assertThrows(IllegalArgumentException.class, () -> TestFixtures.species("Bulbasaur"));
assertThrows(IllegalArgumentException.class, () -> new BaseStats(0, 1, 1, 1, 1, 1));
}
@Test
void speciesRequiresExactlyThreeUniqueCommandMoves() {
assertThrows(IllegalArgumentException.class, () -> new SpeciesDefinition(
SpeciesDefinition.CURRENT_SCHEMA_VERSION, "projectcapture:test", "Test",
List.of(dev.projectcapture.engine.model.ElementType.NORMAL), SpeciesDefinition.Rarity.COMMON,
TestFixtures.stats(), 100, TestFixtures.BASIC,
List.of("projectcapture:a", "projectcapture:a", "projectcapture:b"), List.of(), List.of()));
}
@Test
void genomeRequiresOneToFourUniqueLineagesTotallingOneHundredPercent() {
assertThrows(IllegalArgumentException.class, () -> new Genome(Genome.CURRENT_SCHEMA_VERSION, 1,
Map.of("trait", 1), List.of(
new LineageContribution("projectcapture:a", 2_500),
new LineageContribution("projectcapture:b", 2_500),
new LineageContribution("projectcapture:c", 2_000),
new LineageContribution("projectcapture:d", 2_000),
new LineageContribution("projectcapture:e", 1_000)), Set.of()));
assertThrows(IllegalArgumentException.class, () -> new Genome(Genome.CURRENT_SCHEMA_VERSION, 1,
Map.of("trait", 1), List.of(new LineageContribution("projectcapture:a", 9_999)), Set.of()));
assertThrows(IllegalArgumentException.class, () -> new Genome(Genome.CURRENT_SCHEMA_VERSION, 1,
Map.of("trait", 1), List.of(new LineageContribution("projectcapture:a", 10_000)),
Set.of("unknown")));
}
@Test
void aggregateCollectionsAreDefensivelyCopied() {
var traits = new HashMap<String, Integer>();
traits.put("trait", 1);
var genome = Genome.pure(4, "projectcapture:test", traits);
traits.put("later", 2);
assertEquals(Map.of("trait", 1), genome.traits());
var ids = new ArrayList<UUID>();
ids.add(TestFixtures.OWNER_ONE);
var party = new Party(Party.CURRENT_SCHEMA_VERSION, TestFixtures.OWNER_ONE, ids,
Optional.of(TestFixtures.OWNER_ONE), 0);
ids.clear();
assertEquals(List.of(TestFixtures.OWNER_ONE), party.creatureIds());
assertThrows(UnsupportedOperationException.class, () -> party.creatureIds().clear());
}
@Test
void partyAndCreatureEnforceGameplayLimits() {
var seven = java.util.stream.IntStream.range(0, 7)
.mapToObj(index -> new UUID(0, index + 10L)).toList();
assertThrows(IllegalArgumentException.class, () -> new Party(
Party.CURRENT_SCHEMA_VERSION, TestFixtures.OWNER_ONE, seven, Optional.empty(), 0));
assertThrows(IllegalArgumentException.class, () -> new Party(
Party.CURRENT_SCHEMA_VERSION, TestFixtures.OWNER_ONE, List.of(),
Optional.of(UUID.randomUUID()), 0));
var species = TestFixtures.species("projectcapture:test");
assertThrows(IllegalArgumentException.class, () -> new CreatureInstance(
CreatureInstance.CURRENT_SCHEMA_VERSION, UUID.randomUUID(), species.id(), Optional.of("x".repeat(33)),
Optional.empty(), 1, 0, 1, TestFixtures.genome(1, species.id()),
species.basicMoveId(), species.commandMoveIds(), Instant.EPOCH, 0));
}
@Test
void habitatRejectsImpossibleProgress() {
assertThrows(IllegalArgumentException.class, () -> new HabitatState(
HabitatState.CURRENT_SCHEMA_VERSION, UUID.randomUUID(), TestFixtures.OWNER_ONE,
HabitatState.Status.BREEDING, Optional.of(UUID.randomUUID()), Optional.of(UUID.randomUUID()),
1_000, 1_000, 0));
assertThrows(IllegalArgumentException.class, () -> new HabitatState(
HabitatState.CURRENT_SCHEMA_VERSION, UUID.randomUUID(), TestFixtures.OWNER_ONE,
HabitatState.Status.EGG_READY, Optional.of(UUID.randomUUID()), Optional.of(UUID.randomUUID()),
999, 1_000, 0));
assertThrows(IllegalArgumentException.class, () -> new HabitatState(
HabitatState.CURRENT_SCHEMA_VERSION, UUID.randomUUID(), TestFixtures.OWNER_ONE,
HabitatState.Status.EMPTY, Optional.of(UUID.randomUUID()), Optional.empty(),
0, 0, 0));
}
}
@@ -0,0 +1,99 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.ElementType;
import dev.projectcapture.engine.model.EvolutionRule;
import dev.projectcapture.engine.model.Party;
import dev.projectcapture.engine.model.SpeciesDefinition;
import dev.projectcapture.engine.service.EvolutionService;
import dev.projectcapture.engine.service.ExperienceService;
import dev.projectcapture.engine.service.PartyService;
import dev.projectcapture.engine.service.StaleRevisionException;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ProgressionEvolutionPartyTest {
@Test
void experienceCurveIsMonotonicAndCapsAtLevelOneHundred() {
var service = new ExperienceService();
assertEquals(0, service.thresholdForLevel(1));
assertEquals(100, service.thresholdForLevel(2));
assertEquals(100, service.levelForExperience(Long.MAX_VALUE));
for (int level = 2; level <= 100; level++) {
assertTrue(service.thresholdForLevel(level) > service.thresholdForLevel(level - 1));
assertEquals(level, service.levelForExperience(service.thresholdForLevel(level)));
}
}
@Test
void grantingExperienceLevelsCreatureAndPreservesFaintedState() {
var species = TestFixtures.species("projectcapture:sprout");
var creature = TestFixtures.creature(UUID.randomUUID(), species, TestFixtures.OWNER_ONE, 1, 4);
var service = new ExperienceService();
var levelled = service.grantExperience(creature, species, service.thresholdForLevel(5), 0);
assertEquals(5, levelled.level());
assertEquals(1, levelled.revision());
assertTrue(levelled.currentHealth() > creature.currentHealth());
assertThrows(StaleRevisionException.class,
() -> service.grantExperience(levelled, species, 1, 0));
var fainted = new dev.projectcapture.engine.model.CreatureInstance(
creature.schemaVersion(), creature.id(), creature.speciesId(), creature.nickname(), creature.ownerId(),
creature.level(), creature.experience(), 0, creature.genome(), creature.basicMoveId(),
creature.commandMoveIds(), creature.createdAt(), creature.revision());
assertEquals(0, service.grantExperience(fainted, species, service.thresholdForLevel(3), 0).currentHealth());
}
@Test
void evolutionAppliesFirstEligibleRuleAndTargetMoveSet() {
var rule = new EvolutionRule("projectcapture:bloom", 16, Optional.of("projectcapture:leaf_stone"));
var current = TestFixtures.species("projectcapture:sprout", List.of(rule), List.of());
var target = new SpeciesDefinition(SpeciesDefinition.CURRENT_SCHEMA_VERSION, "projectcapture:bloom", "Bloom",
List.of(ElementType.GRASS), SpeciesDefinition.Rarity.UNCOMMON,
new dev.projectcapture.engine.model.BaseStats(80, 80, 80, 80, 80, 80), 90,
"projectcapture:slam", List.of("projectcapture:a", "projectcapture:b", "projectcapture:c"),
List.of(), List.of());
var creature = TestFixtures.creature(UUID.randomUUID(), current, TestFixtures.OWNER_ONE, 16, 2);
assertThrows(IllegalStateException.class, () -> new EvolutionService().evolve(
creature, current, Map.of(target.id(), target), Set.of(), 0));
var result = new EvolutionService().evolve(creature, current, Map.of(target.id(), target),
Set.of("projectcapture:leaf_stone"), 0);
assertEquals(target.id(), result.creature().speciesId());
assertEquals(target.basicMoveId(), result.creature().basicMoveId());
assertEquals(creature.id(), result.creature().id());
assertSame(creature.genome(), result.creature().genome());
assertEquals(Optional.of("projectcapture:leaf_stone"), result.consumedItemId());
}
@Test
void partySupportsSixMembersAndOneVisibleCompanion() {
var service = new PartyService();
Party party = Party.empty(TestFixtures.OWNER_ONE);
var ids = new ArrayList<UUID>();
for (int index = 0; index < Party.MAX_SIZE; index++) {
var id = new UUID(10, index);
ids.add(id);
party = service.add(party, id, party.revision());
}
Party fullParty = party;
assertThrows(IllegalStateException.class,
() -> service.add(fullParty, UUID.randomUUID(), fullParty.revision()));
party = service.setActiveCompanion(party, Optional.of(ids.getFirst()), party.revision());
assertEquals(Optional.of(ids.getFirst()), party.activeCompanionId());
party = service.remove(party, ids.getFirst(), party.revision());
assertTrue(party.activeCompanionId().isEmpty());
assertEquals(5, party.creatureIds().size());
}
}
@@ -0,0 +1,78 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.BaseStats;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.ElementType;
import dev.projectcapture.engine.model.EvolutionRule;
import dev.projectcapture.engine.model.Genome;
import dev.projectcapture.engine.model.MoveDefinition;
import dev.projectcapture.engine.model.SpawnRule;
import dev.projectcapture.engine.model.SpeciesDefinition;
import dev.projectcapture.engine.service.ExperienceService;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
final class TestFixtures {
static final UUID OWNER_ONE = UUID.fromString("00000000-0000-0000-0000-000000000001");
static final UUID OWNER_TWO = UUID.fromString("00000000-0000-0000-0000-000000000002");
static final String BASIC = "projectcapture:tackle";
static final List<String> COMMANDS = List.of(
"projectcapture:vine_whip",
"projectcapture:growl",
"projectcapture:seed_burst");
private TestFixtures() {
}
static BaseStats stats() {
return new BaseStats(50, 52, 48, 55, 50, 45);
}
static SpeciesDefinition species(String id) {
return species(id, List.of(), List.of());
}
static SpeciesDefinition species(
String id,
List<EvolutionRule> evolutions,
List<SpawnRule> spawnRules
) {
return new SpeciesDefinition(SpeciesDefinition.CURRENT_SCHEMA_VERSION, id, "Test Creature",
List.of(ElementType.GRASS), SpeciesDefinition.Rarity.COMMON, stats(), 180,
BASIC, COMMANDS, evolutions, spawnRules);
}
static Genome genome(long seed, String speciesId) {
return Genome.pure(seed, speciesId, Map.of(
"vitality", 20,
"strength", 18,
"agility", 15,
"temperament", 8));
}
static CreatureInstance creature(UUID id, SpeciesDefinition species, UUID owner, int level, long seed) {
long experience = new ExperienceService().thresholdForLevel(level);
return new CreatureInstance(CreatureInstance.CURRENT_SCHEMA_VERSION, id, species.id(), Optional.empty(),
Optional.ofNullable(owner), level, experience, species.baseStats().healthAtLevel(level),
genome(seed, species.id()), species.basicMoveId(), species.commandMoveIds(), Instant.EPOCH, 0);
}
static Map<String, MoveDefinition> moves() {
return Map.of(
BASIC, move(BASIC, 40, 1.0, 0),
COMMANDS.get(0), move(COMMANDS.get(0), 55, 1.0, 0),
COMMANDS.get(1), new MoveDefinition(MoveDefinition.CURRENT_SCHEMA_VERSION, COMMANDS.get(1),
"Growl", ElementType.NORMAL, MoveDefinition.Category.STATUS, 0, 1.0, 1),
COMMANDS.get(2), move(COMMANDS.get(2), 70, 0.85, 0));
}
static MoveDefinition move(String id, int power, double accuracy, int priority) {
return new MoveDefinition(MoveDefinition.CURRENT_SCHEMA_VERSION, id, id,
ElementType.NORMAL, MoveDefinition.Category.PHYSICAL, power, accuracy, priority);
}
}
@@ -0,0 +1,101 @@
package dev.projectcapture.engine;
import dev.projectcapture.engine.model.PlayerInventory;
import dev.projectcapture.engine.model.TradeOffer;
import dev.projectcapture.engine.model.TradeTransaction;
import dev.projectcapture.engine.service.StaleRevisionException;
import dev.projectcapture.engine.service.TradeService;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TradeServiceTest {
private static final UUID CREATURE_ONE = new UUID(40, 1);
private static final UUID CREATURE_TWO = new UUID(40, 2);
private final TradeService service = new TradeService();
@Test
void bothPlayersMustAcceptBeforeAtomicCommit() {
var open = transaction();
var oneAccepted = service.accept(open, TestFixtures.OWNER_ONE, 0);
assertEquals(TradeTransaction.Status.OPEN, oneAccepted.status());
var locked = service.accept(oneAccepted, TestFixtures.OWNER_TWO, 1);
assertEquals(TradeTransaction.Status.LOCKED, locked.status());
var result = service.commit(locked, inventoryOne(), inventoryTwo(),
locked.revision(), 0, 0);
assertEquals(TradeTransaction.Status.COMMITTED, result.transaction().status());
assertEquals(Set.of(CREATURE_TWO), result.playerOneInventory().creatureIds());
assertEquals(Set.of(CREATURE_ONE), result.playerTwoInventory().creatureIds());
assertEquals(Map.of("projectcapture:capture_device", 8, "projectcapture:herb", 1),
result.playerOneInventory().items());
assertEquals(Map.of("projectcapture:capture_device", 2, "projectcapture:herb", 4),
result.playerTwoInventory().items());
assertEquals(1, result.playerOneInventory().revision());
assertEquals(1, result.playerTwoInventory().revision());
}
@Test
void failedCommitReturnsNoPartiallyModifiedAggregate() {
var locked = lock(transaction());
var first = inventoryOne();
var missingOfferedItems = new PlayerInventory(PlayerInventory.CURRENT_SCHEMA_VERSION,
TestFixtures.OWNER_TWO, Set.of(CREATURE_TWO), Map.of(), 0);
assertThrows(IllegalStateException.class, () -> service.commit(locked, first, missingOfferedItems,
locked.revision(), 0, 0));
assertEquals(TradeTransaction.Status.LOCKED, locked.status());
assertEquals(10, first.items().get("projectcapture:capture_device"));
assertTrue(first.creatureIds().contains(CREATURE_ONE));
}
@Test
void duplicateAcceptanceIsIdempotentAndStaleRevisionIsRejected() {
var open = transaction();
var accepted = service.accept(open, TestFixtures.OWNER_ONE, 0);
assertSame(accepted, service.accept(accepted, TestFixtures.OWNER_ONE, accepted.revision()));
assertThrows(StaleRevisionException.class,
() -> service.accept(accepted, TestFixtures.OWNER_TWO, 0));
}
@Test
void cancellationPreventsCommitAndOutsidersCannotChangeTrade() {
var open = transaction();
assertThrows(IllegalArgumentException.class,
() -> service.cancel(open, UUID.randomUUID(), 0));
var cancelled = service.cancel(open, TestFixtures.OWNER_ONE, 0);
assertEquals(TradeTransaction.Status.CANCELLED, cancelled.status());
assertThrows(IllegalStateException.class,
() -> service.accept(cancelled, TestFixtures.OWNER_TWO, cancelled.revision()));
}
private TradeTransaction transaction() {
return service.create(new UUID(50, 1),
new TradeOffer(TestFixtures.OWNER_ONE, Set.of(CREATURE_ONE),
Map.of("projectcapture:capture_device", 2)),
new TradeOffer(TestFixtures.OWNER_TWO, Set.of(CREATURE_TWO),
Map.of("projectcapture:herb", 1)));
}
private TradeTransaction lock(TradeTransaction transaction) {
var one = service.accept(transaction, TestFixtures.OWNER_ONE, transaction.revision());
return service.accept(one, TestFixtures.OWNER_TWO, one.revision());
}
private static PlayerInventory inventoryOne() {
return new PlayerInventory(PlayerInventory.CURRENT_SCHEMA_VERSION, TestFixtures.OWNER_ONE,
Set.of(CREATURE_ONE), Map.of("projectcapture:capture_device", 10), 0);
}
private static PlayerInventory inventoryTwo() {
return new PlayerInventory(PlayerInventory.CURRENT_SCHEMA_VERSION, TestFixtures.OWNER_TWO,
Set.of(CREATURE_TWO), Map.of("projectcapture:herb", 5), 0);
}
}
+6
View File
@@ -0,0 +1,6 @@
org.gradle.caching=true
org.gradle.configuration-cache=true
org.gradle.parallel=true
org.gradle.warning.mode=all
org.gradle.java.installations.auto-download=false
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+65
View File
@@ -0,0 +1,65 @@
plugins {
`java-library`
}
dependencies {
api(project(":engine"))
implementation(project(":content-pokemon"))
compileOnly("com.hypixel.hytale:Server:0.5.9")
implementation("com.fasterxml.jackson.core:jackson-databind:2.20.0")
testImplementation(platform("org.junit:junit-bom:6.0.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("org.assertj:assertj-core:3.27.6")
}
tasks.jar {
enabled = false
}
val fanModJar = tasks.register<Jar>("fanModJar") {
group = "build"
description = "Packages the unofficial non-commercial fan plugin and embedded asset pack."
dependsOn(configurations.runtimeClasspath)
archiveBaseName.set("ProjectCapture")
archiveClassifier.set("fan-dev")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(sourceSets.main.get().output)
from({
configurations.runtimeClasspath.get()
.filter { it.exists() }
.map { if (it.isDirectory) it else zipTree(it) }
})
exclude("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
manifest {
attributes["Implementation-Title"] = "ProjectCapture Unofficial Fan Project"
attributes["Implementation-Version"] = project.version
attributes["ProjectCapture-Distribution"] = "UNOFFICIAL-NONCOMMERCIAL"
}
}
tasks.assemble {
dependsOn(fanModJar)
}
tasks.register<Copy>("installToDevMods") {
group = "development"
description = "Copies the fan mod only into an explicitly configured isolated dev Mods directory."
dependsOn(fanModJar)
val configuredModsDir = providers.gradleProperty("projectCapture.devModsDir")
onlyIf {
if (!configuredModsDir.isPresent) {
logger.lifecycle("Skipping install: set -PprojectCapture.devModsDir=<isolated Mods directory>.")
false
} else {
true
}
}
from(fanModJar.flatMap { it.archiveFile })
into(configuredModsDir)
}
@@ -0,0 +1,13 @@
package dev.projectcapture.hytale;
/** Keeps unstable Hytale API features outside the stable 0.5.9 integration. */
public record FeatureFlags(
boolean updateSixPersistentResources,
boolean updateSixCustomBattleUi,
boolean updateSixServerCamera
) {
public static FeatureFlags stableRelease() {
return new FeatureFlags(false, false, false);
}
}
@@ -0,0 +1,58 @@
package dev.projectcapture.hytale;
import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import com.hypixel.hytale.server.core.plugin.JavaPluginInit;
import dev.projectcapture.hytale.command.ProjectCaptureCommands;
import dev.projectcapture.hytale.content.RuntimeContentCatalog;
import dev.projectcapture.hytale.gameplay.MultiplayerCreatureService;
import dev.projectcapture.hytale.persistence.JsonStateStore;
import java.util.concurrent.CompletableFuture;
/**
* Thin Hytale entry point. Domain behavior lives in {@code engine}; this class
* owns only Hytale lifecycle and adapter wiring.
*/
public final class ProjectCapturePlugin extends JavaPlugin {
private final JsonStateStore stateStore;
private final FeatureFlags featureFlags;
private RuntimeContentCatalog contentCatalog;
private MultiplayerCreatureService multiplayerService;
public ProjectCapturePlugin(JavaPluginInit init) {
super(init);
this.stateStore = new JsonStateStore(init.getDataDirectory());
this.featureFlags = FeatureFlags.stableRelease();
}
@Override
public CompletableFuture<Void> preLoad() {
stateStore.initialize();
contentCatalog = RuntimeContentCatalog.load(getClass().getClassLoader());
multiplayerService = new MultiplayerCreatureService(stateStore, contentCatalog);
ProjectCaptureCommands.register(this, multiplayerService);
return CompletableFuture.completedFuture(null);
}
JsonStateStore stateStore() {
return stateStore;
}
FeatureFlags featureFlags() {
return featureFlags;
}
RuntimeContentCatalog contentCatalog() {
if (contentCatalog == null) {
throw new IllegalStateException("Content catalog is not loaded before preLoad");
}
return contentCatalog;
}
MultiplayerCreatureService multiplayerService() {
if (multiplayerService == null) {
throw new IllegalStateException("Multiplayer service is not loaded before preLoad");
}
return multiplayerService;
}
}
@@ -0,0 +1,170 @@
package dev.projectcapture.hytale.command;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandContext;
import com.hypixel.hytale.server.core.command.system.arguments.system.RequiredArg;
import com.hypixel.hytale.server.core.command.system.arguments.types.ArgTypes;
import com.hypixel.hytale.server.core.command.system.basecommands.AbstractCommandCollection;
import com.hypixel.hytale.server.core.command.system.basecommands.AbstractPlayerCommand;
import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import com.hypixel.hytale.server.core.universe.world.World;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import dev.projectcapture.hytale.gameplay.MultiplayerCreatureService;
import java.util.UUID;
/** Registers the server-authoritative playable multiplayer vertical-slice commands. */
public final class ProjectCaptureCommands {
private ProjectCaptureCommands() {
}
public static void register(JavaPlugin plugin, MultiplayerCreatureService service) {
plugin.getCommandRegistry().registerCommand(new RootCommand(service));
}
private static final class RootCommand extends AbstractCommandCollection {
private RootCommand(MultiplayerCreatureService service) {
super("projectcapture", "ProjectCapture creature commands");
addAliases("pc");
addSubCommand(new PartyCommand(service));
addSubCommand(new CompanionCommand(service));
addSubCommand(new CaptureCommand(service));
addSubCommand(new EncounterCommand(service));
addSubCommand(new GrantCapsulesCommand(service));
}
}
private abstract static class PlayerCommand extends AbstractPlayerCommand {
protected final MultiplayerCreatureService service;
private PlayerCommand(String name, String description, MultiplayerCreatureService service) {
super(name, description);
this.service = service;
}
protected final UUID playerId(PlayerRef player) {
return player.getUuid();
}
protected final void message(CommandContext context, String text) {
context.sendMessage(Message.raw("[ProjectCapture] " + text));
}
}
private static final class PartyCommand extends PlayerCommand {
private PartyCommand(MultiplayerCreatureService service) {
super("party", "Show your ProjectCapture party", service);
}
@Override
protected void execute(
CommandContext context,
Store<EntityStore> store,
Ref<EntityStore> playerRef,
PlayerRef player,
World world
) {
MultiplayerCreatureService.PartyView party = service.party(playerId(player));
String creatures = party.creatures().isEmpty()
? "empty"
: party.creatures().stream()
.map(creature -> creature.speciesId() + " Lv." + creature.level())
.collect(java.util.stream.Collectors.joining(", "));
message(context, "Party: " + creatures + " | Field capsules: " + party.fieldCapsules()
+ " | Companion: " + party.activeCompanionId().map(UUID::toString).orElse("none"));
}
}
private static final class CompanionCommand extends PlayerCommand {
private final RequiredArg<UUID> creatureId = withRequiredArg("creatureId", "UUID from /pc party", ArgTypes.UUID);
private CompanionCommand(MultiplayerCreatureService service) {
super("companion", "Set a captured party creature as your companion", service);
}
@Override
protected void execute(
CommandContext context,
Store<EntityStore> store,
Ref<EntityStore> playerRef,
PlayerRef player,
World world
) {
UUID id = context.get(creatureId);
service.setCompanion(playerId(player), id);
message(context, "Companion saved: " + id);
}
}
private static final class CaptureCommand extends PlayerCommand {
private CaptureCommand(MultiplayerCreatureService service) {
super("capture", "Throw one crafted field capsule at your active encounter", service);
}
@Override
protected void execute(
CommandContext context,
Store<EntityStore> store,
Ref<EntityStore> playerRef,
PlayerRef player,
World world
) {
MultiplayerCreatureService.CaptureOutcome outcome = service.capture(playerId(player), System.nanoTime());
if (outcome.captured()) {
message(context, "Captured " + outcome.creatureId().orElseThrow() + " ("
+ Math.round(outcome.probability() * 100) + "% chance)."
+ (outcome.addedToParty() ? " Added to your party." : " Your party is full; stored safely."));
} else {
message(context, "The creature broke free ("
+ Math.round(outcome.probability() * 100) + "% chance). Try again with another capsule.");
}
}
}
private static final class EncounterCommand extends PlayerCommand {
private final RequiredArg<String> speciesId = withRequiredArg("speciesId", "Namespaced species ID", ArgTypes.STRING);
private EncounterCommand(MultiplayerCreatureService service) {
super("encounter", "Development command: open a personal wild encounter", service);
requirePermission("projectcapture.debug.encounter");
}
@Override
protected void execute(
CommandContext context,
Store<EntityStore> store,
Ref<EntityStore> playerRef,
PlayerRef player,
World world
) {
MultiplayerCreatureService.EncounterView encounter = service.openEncounter(
playerId(player), context.get(speciesId), 5, System.nanoTime());
message(context, "Personal wild encounter: " + encounter.speciesId() + " Lv." + encounter.level());
}
}
private static final class GrantCapsulesCommand extends PlayerCommand {
private final RequiredArg<Integer> amount = withRequiredArg("amount", "Number of field capsules", ArgTypes.INTEGER);
private GrantCapsulesCommand(MultiplayerCreatureService service) {
super("grantcapsules", "Development command: grant crafted field-capsule test inventory", service);
requirePermission("projectcapture.debug.grantcapsules");
}
@Override
protected void execute(
CommandContext context,
Store<EntityStore> store,
Ref<EntityStore> playerRef,
PlayerRef player,
World world
) {
int requested = context.get(amount);
service.grantFieldCapsules(playerId(player), requested);
message(context, "Added " + requested + " field capsules to your server-authoritative test inventory.");
}
}
}
@@ -0,0 +1,246 @@
package dev.projectcapture.hytale.content;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.projectcapture.engine.model.BaseStats;
import dev.projectcapture.engine.model.ElementType;
import dev.projectcapture.engine.model.EvolutionRule;
import dev.projectcapture.engine.model.MoveDefinition;
import dev.projectcapture.engine.model.SpawnRule;
import dev.projectcapture.engine.model.SpeciesDefinition;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Loads the embedded, versioned fan-content documents into the Hytale-free
* engine models. Invalid or incomplete content fails during plugin pre-load.
*/
public record RuntimeContentCatalog(
Map<String, SpeciesDefinition> species,
Map<String, MoveDefinition> moves
) {
public static final String RESOURCE_ROOT = "projectcapture/content/v1/";
private static final int SCHEMA_VERSION = 1;
public RuntimeContentCatalog {
species = Map.copyOf(Objects.requireNonNull(species, "species"));
moves = Map.copyOf(Objects.requireNonNull(moves, "moves"));
if (species.isEmpty() || moves.isEmpty()) {
throw new IllegalArgumentException("Runtime content catalog must not be empty");
}
}
public static RuntimeContentCatalog load(ClassLoader classLoader) {
Objects.requireNonNull(classLoader, "classLoader");
ObjectMapper json = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
JsonNode moveDocument = read(json, classLoader, "moves.json");
JsonNode speciesDocument = read(json, classLoader, "species.json");
JsonNode spawnDocument = read(json, classLoader, "spawn-rules.json");
Map<String, MoveDefinition> moves = parseMoves(moveDocument);
Map<String, List<SpawnRule>> spawns = parseSpawns(spawnDocument);
Map<String, SpeciesDefinition> species = parseSpecies(speciesDocument, spawns);
validateReferences(species, moves);
return new RuntimeContentCatalog(species, moves);
}
private static JsonNode read(ObjectMapper json, ClassLoader classLoader, String name) {
String resource = RESOURCE_ROOT + name;
try (InputStream input = classLoader.getResourceAsStream(resource)) {
if (input == null) {
throw new IllegalStateException("Missing embedded content document: " + resource);
}
JsonNode document = json.readTree(input);
requireHeader(document, resource);
return document;
} catch (IOException exception) {
throw new IllegalStateException("Could not read embedded content document: " + resource, exception);
}
}
private static void requireHeader(JsonNode document, String resource) {
if (document == null || !document.isObject()) {
throw new IllegalStateException("Content document must be an object: " + resource);
}
if (document.path("schemaVersion").asInt(-1) != SCHEMA_VERSION) {
throw new IllegalStateException("Unsupported content schema in " + resource);
}
if (!document.path("unofficialFanContent").asBoolean(false)) {
throw new IllegalStateException("Missing unofficial fan-content marker in " + resource);
}
if (!document.path("items").isArray()) {
throw new IllegalStateException("Content document has no items array: " + resource);
}
}
private static Map<String, MoveDefinition> parseMoves(JsonNode document) {
Map<String, MoveDefinition> result = new LinkedHashMap<>();
for (JsonNode item : document.path("items")) {
MoveDefinition move = new MoveDefinition(
MoveDefinition.CURRENT_SCHEMA_VERSION,
requiredText(item, "id"),
requiredText(item, "displayName"),
ElementType.valueOf(requiredText(item, "type")),
MoveDefinition.Category.valueOf(requiredText(item, "category")),
requiredInt(item, "power"),
requiredDouble(item, "accuracy"),
requiredInt(item, "priority")
);
if (result.putIfAbsent(move.id(), move) != null) {
throw new IllegalStateException("Duplicate move ID: " + move.id());
}
}
return result;
}
private static Map<String, List<SpawnRule>> parseSpawns(JsonNode document) {
Map<String, List<SpawnRule>> result = new LinkedHashMap<>();
for (JsonNode item : document.path("items")) {
String speciesId = requiredText(item, "speciesId");
Set<String> biomes = values(item.path("biomes")).stream()
.map(value -> "projectcapture:" + value.toLowerCase(Locale.ROOT))
.collect(java.util.stream.Collectors.toUnmodifiableSet());
String time = requiredText(item, "time");
Set<SpawnRule.TimeOfDay> times = "ANY".equals(time)
? EnumSet.allOf(SpawnRule.TimeOfDay.class)
: Set.of(SpawnRule.TimeOfDay.valueOf(time));
SpawnRule rule = new SpawnRule(
biomes,
times,
requiredInt(item, "rarityWeight"),
requiredInt(item, "minimumLevel"),
requiredInt(item, "maximumLevel")
);
result.computeIfAbsent(speciesId, ignored -> new ArrayList<>()).add(rule);
}
return result;
}
private static Map<String, SpeciesDefinition> parseSpecies(
JsonNode document,
Map<String, List<SpawnRule>> spawns
) {
Map<String, SpeciesDefinition> result = new LinkedHashMap<>();
for (JsonNode item : document.path("items")) {
String id = requiredText(item, "id");
JsonNode stats = item.path("baseStats");
int power = requiredInt(stats, "power");
int guard = requiredInt(stats, "guard");
BaseStats baseStats = new BaseStats(
requiredInt(stats, "vitality"),
power,
guard,
power,
guard,
requiredInt(stats, "agility")
);
List<ElementType> types = values(item.path("types")).stream()
.map(ElementType::valueOf)
.toList();
List<EvolutionRule> evolutions = parseEvolution(item.path("evolution"));
SpeciesDefinition definition = new SpeciesDefinition(
SpeciesDefinition.CURRENT_SCHEMA_VERSION,
id,
requiredText(item, "displayName"),
types,
SpeciesDefinition.Rarity.valueOf(requiredText(item, "rarity")),
baseStats,
requiredInt(item, "captureRate"),
requiredText(item, "basicMoveId"),
values(item.path("commandMoveIds")),
evolutions,
List.copyOf(spawns.getOrDefault(id, List.of()))
);
if (definition.spawnRules().isEmpty()) {
throw new IllegalStateException("Species has no runtime spawn rule: " + id);
}
if (result.putIfAbsent(id, definition) != null) {
throw new IllegalStateException("Duplicate species ID: " + id);
}
}
return result;
}
private static List<EvolutionRule> parseEvolution(JsonNode evolution) {
if (evolution.isMissingNode() || evolution.isNull()) {
return List.of();
}
String method = requiredText(evolution, "method");
int minimumLevel = "LEVEL".equals(method) ? requiredInt(evolution, "minimumLevel") : 1;
Optional<String> item = "ITEM".equals(method)
? Optional.of(requiredText(evolution, "itemId"))
: Optional.empty();
return List.of(new EvolutionRule(requiredText(evolution, "targetSpeciesId"), minimumLevel, item));
}
private static void validateReferences(
Map<String, SpeciesDefinition> species,
Map<String, MoveDefinition> moves
) {
for (SpeciesDefinition definition : species.values()) {
if (!moves.containsKey(definition.basicMoveId())) {
throw new IllegalStateException("Unknown basic move for " + definition.id());
}
for (String moveId : definition.commandMoveIds()) {
if (!moves.containsKey(moveId)) {
throw new IllegalStateException("Unknown command move for " + definition.id() + ": " + moveId);
}
}
for (EvolutionRule evolution : definition.evolutions()) {
if (!species.containsKey(evolution.targetSpeciesId())) {
throw new IllegalStateException(
"Unknown evolution target for " + definition.id() + ": " + evolution.targetSpeciesId());
}
}
}
}
private static List<String> values(JsonNode array) {
if (!array.isArray() || array.isEmpty()) {
throw new IllegalStateException("Expected a non-empty string array");
}
List<String> result = new ArrayList<>();
for (JsonNode value : array) {
if (!value.isTextual() || value.textValue().isBlank()) {
throw new IllegalStateException("Expected a non-blank string array value");
}
result.add(value.textValue());
}
return List.copyOf(result);
}
private static String requiredText(JsonNode node, String field) {
JsonNode value = node.path(field);
if (!value.isTextual() || value.textValue().isBlank()) {
throw new IllegalStateException("Missing non-blank text field: " + field);
}
return value.textValue();
}
private static int requiredInt(JsonNode node, String field) {
JsonNode value = node.path(field);
if (!value.isIntegralNumber() || !value.canConvertToInt()) {
throw new IllegalStateException("Missing integer field: " + field);
}
return value.intValue();
}
private static double requiredDouble(JsonNode node, String field) {
JsonNode value = node.path(field);
if (!value.isNumber()) {
throw new IllegalStateException("Missing numeric field: " + field);
}
return value.doubleValue();
}
}
@@ -0,0 +1,355 @@
package dev.projectcapture.hytale.gameplay;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import dev.projectcapture.engine.model.CaptureContext;
import dev.projectcapture.engine.model.CreatureInstance;
import dev.projectcapture.engine.model.Genome;
import dev.projectcapture.engine.model.LineageContribution;
import dev.projectcapture.engine.model.Party;
import dev.projectcapture.engine.model.SpeciesDefinition;
import dev.projectcapture.engine.service.CaptureService;
import dev.projectcapture.engine.service.PartyService;
import dev.projectcapture.hytale.content.RuntimeContentCatalog;
import dev.projectcapture.hytale.persistence.JsonStateStore;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
* Server-authoritative multiplayer state for the playable capture vertical slice.
* Every mutation is synchronized and atomically persisted through JsonStateStore.
*/
public final class MultiplayerCreatureService {
private static final int STATE_SCHEMA_VERSION = 1;
private static final String SAVE_ID = "multiplayer";
private static final String FIELD_CAPSULE = "projectcapture:field-capsule";
private final JsonStateStore stateStore;
private final RuntimeContentCatalog catalog;
private final CaptureService captureService = new CaptureService();
private final PartyService partyService = new PartyService();
private final ObjectMapper json = new ObjectMapper();
private final Map<UUID, PlayerProfile> players = new HashMap<>();
public MultiplayerCreatureService(JsonStateStore stateStore, RuntimeContentCatalog catalog) {
this.stateStore = java.util.Objects.requireNonNull(stateStore, "stateStore");
this.catalog = java.util.Objects.requireNonNull(catalog, "catalog");
load();
}
public synchronized EncounterView openEncounter(UUID playerId, String speciesId, int level, long seed) {
SpeciesDefinition species = species(speciesId);
if (level < 1 || level > 100) {
throw new IllegalArgumentException("Encounter level must be between 1 and 100");
}
PlayerProfile profile = player(playerId);
CreatureInstance wild = newCreature(species, Optional.empty(), level, seed);
profile.encounter = wild;
persist();
return toEncounterView(wild);
}
public synchronized CaptureOutcome capture(UUID playerId, long seed) {
PlayerProfile profile = player(playerId);
CreatureInstance wild = Optional.ofNullable(profile.encounter)
.orElseThrow(() -> new IllegalStateException("No active encounter for this player"));
int capsules = profile.items.getOrDefault(FIELD_CAPSULE, 0);
if (capsules < 1) {
throw new IllegalStateException("A crafted field capsule is required to capture a creature");
}
SpeciesDefinition species = species(wild.speciesId());
int maximumHealth = species.baseStats().healthAtLevel(wild.level());
CaptureService.CaptureResult result = captureService.attempt(new CaptureContext(
species.captureRate(), species.rarity(), wild.level(), wild.currentHealth(), maximumHealth,
1.0, CaptureContext.StatusCondition.NONE
), seed);
decrement(profile.items, FIELD_CAPSULE);
if (!result.captured()) {
persist();
return new CaptureOutcome(false, result.probability(), result.roll(), Optional.empty(), false);
}
CreatureInstance owned = new CreatureInstance(
wild.schemaVersion(), wild.id(), wild.speciesId(), wild.nickname(), Optional.of(playerId),
wild.level(), wild.experience(), wild.currentHealth(), wild.genome(), wild.basicMoveId(),
wild.commandMoveIds(), wild.createdAt(), wild.revision() + 1
);
profile.creatures.put(owned.id(), owned);
boolean addedToParty = profile.party.creatureIds().size() < Party.MAX_SIZE;
if (addedToParty) {
profile.party = partyService.add(profile.party, owned.id(), profile.party.revision());
}
profile.encounter = null;
persist();
return new CaptureOutcome(true, result.probability(), result.roll(), Optional.of(owned.id()), addedToParty);
}
public synchronized void grantFieldCapsules(UUID playerId, int amount) {
if (amount < 1 || amount > 999) {
throw new IllegalArgumentException("Amount must be between 1 and 999");
}
PlayerProfile profile = player(playerId);
profile.items.merge(FIELD_CAPSULE, amount, Math::addExact);
persist();
}
public synchronized PartyView party(UUID playerId) {
PlayerProfile profile = player(playerId);
List<CreatureView> creatures = profile.party.creatureIds().stream()
.map(profile.creatures::get)
.filter(java.util.Objects::nonNull)
.map(this::toCreatureView)
.toList();
return new PartyView(profile.party.revision(), creatures, profile.party.activeCompanionId(),
profile.items.getOrDefault(FIELD_CAPSULE, 0));
}
public synchronized void setCompanion(UUID playerId, UUID creatureId) {
PlayerProfile profile = player(playerId);
if (!profile.creatures.containsKey(creatureId)) {
throw new IllegalArgumentException("Creature does not belong to this player");
}
profile.party = partyService.setActiveCompanion(profile.party, Optional.of(creatureId), profile.party.revision());
persist();
}
public synchronized Optional<EncounterView> activeEncounter(UUID playerId) {
return Optional.ofNullable(player(playerId).encounter).map(this::toEncounterView);
}
private SpeciesDefinition species(String speciesId) {
SpeciesDefinition species = catalog.species().get(speciesId);
if (species == null) {
throw new IllegalArgumentException("Unknown species: " + speciesId);
}
return species;
}
private PlayerProfile player(UUID playerId) {
if (playerId == null) {
throw new NullPointerException("playerId must not be null");
}
return players.computeIfAbsent(playerId, PlayerProfile::new);
}
private CreatureInstance newCreature(SpeciesDefinition species, Optional<UUID> ownerId, int level, long seed) {
int maximumHealth = species.baseStats().healthAtLevel(level);
Map<String, Integer> traits = Map.of(
"resilience", Math.floorMod(seed, 32),
"instinct", Math.floorMod(seed >>> 5, 32),
"temperament", Math.floorMod(seed >>> 10, 32)
);
return new CreatureInstance(
CreatureInstance.CURRENT_SCHEMA_VERSION,
UUID.randomUUID(),
species.id(),
Optional.empty(),
ownerId,
level,
experienceFor(level),
maximumHealth,
Genome.pure(seed, species.id(), traits),
species.basicMoveId(),
species.commandMoveIds(),
Instant.now(),
0
);
}
private static long experienceFor(int level) {
long offset = level - 1L;
return offset * offset * offset * 100L;
}
private void load() {
JsonNode root = stateStore.read(SAVE_ID);
if (root == null) {
return;
}
if (root.path("schemaVersion").asInt(-1) != STATE_SCHEMA_VERSION) {
throw new IllegalStateException("Unsupported multiplayer state schema");
}
JsonNode playerArray = root.path("players");
if (!playerArray.isArray()) {
throw new IllegalStateException("Invalid multiplayer state: players is not an array");
}
for (JsonNode node : playerArray) {
UUID owner = UUID.fromString(requiredText(node, "ownerId"));
PlayerProfile profile = new PlayerProfile(owner);
for (JsonNode creatureNode : node.path("creatures")) {
CreatureInstance creature = readCreature(creatureNode);
if (!creature.ownerId().equals(Optional.of(owner))) {
throw new IllegalStateException("Persisted creature ownership mismatch");
}
profile.creatures.put(creature.id(), creature);
}
List<UUID> partyIds = new ArrayList<>();
for (JsonNode id : node.path("party")) {
partyIds.add(UUID.fromString(id.asText()));
}
Optional<UUID> companion = optionalUuid(node, "activeCompanionId");
profile.party = new Party(Party.CURRENT_SCHEMA_VERSION, owner, partyIds, companion,
node.path("partyRevision").asLong(0));
node.path("items").properties().forEach(entry -> profile.items.put(entry.getKey(), entry.getValue().asInt()));
JsonNode encounter = node.path("encounter");
if (!encounter.isMissingNode() && !encounter.isNull()) {
profile.encounter = readCreature(encounter);
if (profile.encounter.ownerId().isPresent()) {
throw new IllegalStateException("Wild encounter cannot have an owner");
}
}
players.put(owner, profile);
}
}
private void persist() {
ObjectNode root = json.createObjectNode().put("schemaVersion", STATE_SCHEMA_VERSION);
ArrayNode playerArray = root.putArray("players");
players.values().stream().sorted(java.util.Comparator.comparing(profile -> profile.ownerId.toString()))
.forEach(profile -> writeProfile(playerArray.addObject(), profile));
stateStore.write(SAVE_ID, root);
}
private void writeProfile(ObjectNode node, PlayerProfile profile) {
node.put("ownerId", profile.ownerId.toString());
node.put("partyRevision", profile.party.revision());
profile.party.activeCompanionId().ifPresent(id -> node.put("activeCompanionId", id.toString()));
ArrayNode party = node.putArray("party");
profile.party.creatureIds().forEach(id -> party.add(id.toString()));
ObjectNode items = node.putObject("items");
profile.items.forEach(items::put);
ArrayNode creatures = node.putArray("creatures");
profile.creatures.values().stream().sorted(java.util.Comparator.comparing(creature -> creature.id().toString()))
.forEach(creature -> writeCreature(creatures.addObject(), creature));
if (profile.encounter != null) {
writeCreature(node.putObject("encounter"), profile.encounter);
}
}
private static void writeCreature(ObjectNode node, CreatureInstance creature) {
node.put("id", creature.id().toString());
node.put("speciesId", creature.speciesId());
creature.ownerId().ifPresent(owner -> node.put("ownerId", owner.toString()));
creature.nickname().ifPresent(nickname -> node.put("nickname", nickname));
node.put("level", creature.level());
node.put("experience", creature.experience());
node.put("currentHealth", creature.currentHealth());
node.put("basicMoveId", creature.basicMoveId());
node.put("createdAtEpochMilli", creature.createdAt().toEpochMilli());
node.put("revision", creature.revision());
ArrayNode commands = node.putArray("commandMoveIds");
creature.commandMoveIds().forEach(commands::add);
ObjectNode genome = node.putObject("genome");
genome.put("seed", creature.genome().seed());
ObjectNode traits = genome.putObject("traits");
creature.genome().traits().forEach(traits::put);
ArrayNode revealed = genome.putArray("revealedTraits");
creature.genome().revealedTraits().forEach(revealed::add);
}
private CreatureInstance readCreature(JsonNode node) {
String speciesId = requiredText(node, "speciesId");
Map<String, Integer> traits = new LinkedHashMap<>();
node.path("genome").path("traits").properties().forEach(entry -> traits.put(entry.getKey(), entry.getValue().asInt()));
List<String> commands = new ArrayList<>();
node.path("commandMoveIds").forEach(command -> commands.add(command.asText()));
java.util.Set<String> revealed = new java.util.LinkedHashSet<>();
node.path("genome").path("revealedTraits").forEach(value -> revealed.add(value.asText()));
return new CreatureInstance(
CreatureInstance.CURRENT_SCHEMA_VERSION,
UUID.fromString(requiredText(node, "id")),
speciesId,
optionalText(node, "nickname"),
optionalUuid(node, "ownerId"),
node.path("level").asInt(),
node.path("experience").asLong(),
node.path("currentHealth").asInt(),
new Genome(
Genome.CURRENT_SCHEMA_VERSION,
node.path("genome").path("seed").asLong(),
traits,
List.of(new LineageContribution(speciesId, Genome.TOTAL_BASIS_POINTS)),
revealed),
requiredText(node, "basicMoveId"),
commands,
Instant.ofEpochMilli(node.path("createdAtEpochMilli").asLong()),
node.path("revision").asLong()
);
}
private static void decrement(Map<String, Integer> items, String itemId) {
int current = items.getOrDefault(itemId, 0);
if (current <= 1) {
items.remove(itemId);
} else {
items.put(itemId, current - 1);
}
}
private static String requiredText(JsonNode node, String name) {
String value = node.path(name).asText("");
if (value.isBlank()) {
throw new IllegalStateException("Missing persisted field: " + name);
}
return value;
}
private static Optional<String> optionalText(JsonNode node, String name) {
String value = node.path(name).asText("");
return value.isBlank() ? Optional.empty() : Optional.of(value);
}
private static Optional<UUID> optionalUuid(JsonNode node, String name) {
String value = node.path(name).asText("");
return value.isBlank() ? Optional.empty() : Optional.of(UUID.fromString(value));
}
private CreatureView toCreatureView(CreatureInstance creature) {
return new CreatureView(creature.id(), creature.speciesId(), creature.level(), creature.currentHealth());
}
private EncounterView toEncounterView(CreatureInstance creature) {
return new EncounterView(creature.id(), creature.speciesId(), creature.level(), creature.currentHealth());
}
private static final class PlayerProfile {
private final UUID ownerId;
private final Map<UUID, CreatureInstance> creatures = new LinkedHashMap<>();
private final Map<String, Integer> items = new LinkedHashMap<>();
private Party party;
private CreatureInstance encounter;
private PlayerProfile(UUID ownerId) {
this.ownerId = ownerId;
this.party = Party.empty(ownerId);
}
}
public record EncounterView(UUID creatureId, String speciesId, int level, int currentHealth) {
}
public record CreatureView(UUID creatureId, String speciesId, int level, int currentHealth) {
}
public record PartyView(long revision, List<CreatureView> creatures, Optional<UUID> activeCompanionId, int fieldCapsules) {
public PartyView {
creatures = List.copyOf(creatures);
activeCompanionId = Optional.ofNullable(activeCompanionId).orElseThrow();
}
}
public record CaptureOutcome(boolean captured, double probability, double roll, Optional<UUID> creatureId, boolean addedToParty) {
public CaptureOutcome {
creatureId = Optional.ofNullable(creatureId).orElseThrow();
}
}
}
@@ -0,0 +1,107 @@
package dev.projectcapture.hytale.persistence;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
/**
* Atomic JSON persistence rooted in Hytale's plugin data directory. Paths are
* logical save identifiers, never caller-controlled filesystem paths.
*/
public final class JsonStateStore {
public static final int CURRENT_SCHEMA_VERSION = 1;
private final Path root;
private final ObjectMapper mapper;
public JsonStateStore(Path pluginDataDirectory) {
this.root = Objects.requireNonNull(pluginDataDirectory, "pluginDataDirectory")
.toAbsolutePath()
.normalize()
.resolve("state");
this.mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
}
public void initialize() {
try {
Files.createDirectories(root);
} catch (IOException exception) {
throw new StateStoreException("Unable to initialize ProjectCapture state directory", exception);
}
}
public synchronized void write(String saveId, JsonNode payload) {
Path destination = resolveSaveId(saveId);
Path temporary = destination.resolveSibling(destination.getFileName() + ".tmp");
try {
Files.createDirectories(destination.getParent());
mapper.writeValue(temporary.toFile(), new StateEnvelope(CURRENT_SCHEMA_VERSION, payload));
try {
Files.move(
temporary,
destination,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING
);
} catch (AtomicMoveNotSupportedException ignored) {
Files.move(temporary, destination, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException exception) {
throw new StateStoreException("Unable to persist save " + saveId, exception);
}
}
public synchronized JsonNode read(String saveId) {
Path source = resolveSaveId(saveId);
if (!Files.exists(source)) {
return null;
}
try {
StateEnvelope envelope = mapper.readValue(source.toFile(), StateEnvelope.class);
if (envelope.schemaVersion() != CURRENT_SCHEMA_VERSION) {
throw new StateStoreException(
"Unsupported state schema " + envelope.schemaVersion() + " for " + saveId
);
}
return envelope.payload();
} catch (IOException exception) {
throw new StateStoreException("Unable to read save " + saveId, exception);
}
}
private Path resolveSaveId(String saveId) {
if (saveId == null || !saveId.matches("[a-z0-9][a-z0-9._-]{0,63}")) {
throw new IllegalArgumentException("Invalid logical save id");
}
Path result = root.resolve(saveId + ".json").normalize();
if (!result.startsWith(root)) {
throw new IllegalArgumentException("Save path escapes plugin state root");
}
return result;
}
public record StateEnvelope(int schemaVersion, JsonNode payload) {
public StateEnvelope {
Objects.requireNonNull(payload, "payload");
}
}
public static final class StateStoreException extends RuntimeException {
private static final long serialVersionUID = 1L;
public StateStoreException(String message) {
super(message);
}
public StateStoreException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -0,0 +1,12 @@
package dev.projectcapture.hytale.ports;
import java.util.UUID;
/** Server-driven UI boundary; no client mod or client hook is assumed. */
public interface UiPort {
void showCaptureResult(UUID playerId, UUID creatureId, boolean captured);
void showBattleCommands(UUID playerId, UUID creatureId, String basicMove, String[] commandedMoves);
void showUnofficialFanProjectNotice(UUID playerId);
}
@@ -0,0 +1,20 @@
package dev.projectcapture.hytale.ports;
import java.util.List;
import java.util.UUID;
/** Stable boundary between domain services and the evolving Hytale world API. */
public interface WorldPort {
void spawnWildCreature(String speciesId, SpawnPoint point, long deterministicSeed);
void despawnCreature(UUID creatureId);
void setVisibleCompanion(UUID playerId, UUID creatureId);
void clearVisibleCompanion(UUID playerId);
List<SpawnPoint> eligibleSpawnPoints(String biomeId, String timeBand);
record SpawnPoint(String worldId, double x, double y, double z, String biomeId) {}
}
@@ -0,0 +1,10 @@
{
"schemaVersion": 1,
"namespace": "projectcapture",
"distribution": "UNOFFICIAL_NONCOMMERCIAL_FAN_PROJECT",
"unofficialFanContent": true,
"nonCommercial": true,
"rightsReviewRequired": true,
"contentModule": "content-pokemon",
"notes": "Runtime-facing index only. Definitions are original ProjectCapture production files; Pokemon ownership remains with the respective rights holders."
}
@@ -0,0 +1,17 @@
{
"Group": "dev.projectcapture",
"Name": "ProjectCapture",
"Version": "0.1.0",
"Description": "Unofficial, open-source and non-commercial Pokemon fan mod",
"Authors": [
{
"Name": "Christian Schindler"
}
],
"ServerVersion": "0.5.9",
"Dependencies": {},
"OptionalDependencies": {},
"DisabledByDefault": false,
"IncludesAssetPack": true,
"Main": "dev.projectcapture.hytale.ProjectCapturePlugin"
}
@@ -0,0 +1,46 @@
package dev.projectcapture.hytale.content;
import dev.projectcapture.engine.model.ElementType;
import dev.projectcapture.engine.model.SpawnRule;
import dev.projectcapture.engine.service.SpawnService;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class RuntimeContentCatalogTest {
@Test
void loadsAllFanSpeciesAndMovesIntoEngineModels() {
RuntimeContentCatalog catalog = RuntimeContentCatalog.load(getClass().getClassLoader());
assertThat(catalog.species()).hasSize(12);
assertThat(catalog.moves()).hasSize(17);
assertThat(catalog.species().get("projectcapture:bulbasaur").types())
.containsExactly(ElementType.GRASS, ElementType.POISON);
assertThat(catalog.species().get("projectcapture:charizard").types())
.containsExactly(ElementType.FIRE, ElementType.FLYING);
}
@Test
void embeddedCatalogCanDriveDeterministicSpawnSelection() {
RuntimeContentCatalog catalog = RuntimeContentCatalog.load(getClass().getClassLoader());
SpawnService service = new SpawnService();
SpawnService.SpawnSelection first = service.select(
List.copyOf(catalog.species().values()),
"projectcapture:forest",
SpawnRule.TimeOfDay.DAY,
42L
).orElseThrow();
SpawnService.SpawnSelection second = service.select(
List.copyOf(catalog.species().values()),
"projectcapture:forest",
SpawnRule.TimeOfDay.DAY,
42L
).orElseThrow();
assertThat(second).isEqualTo(first);
assertThat(first.speciesId()).isIn("projectcapture:bulbasaur", "projectcapture:pikachu");
}
}
@@ -0,0 +1,57 @@
package dev.projectcapture.hytale.gameplay;
import dev.projectcapture.hytale.content.RuntimeContentCatalog;
import dev.projectcapture.hytale.persistence.JsonStateStore;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class MultiplayerCreatureServiceTest {
@TempDir
Path temporaryDirectory;
@Test
void captureIsPlayerScopedAndSurvivesServerRestart() {
JsonStateStore store = initializedStore();
MultiplayerCreatureService service = new MultiplayerCreatureService(store, catalog());
UUID firstPlayer = UUID.randomUUID();
UUID secondPlayer = UUID.randomUUID();
service.grantFieldCapsules(firstPlayer, 200);
service.openEncounter(firstPlayer, "projectcapture:bulbasaur", 4, 42L);
assertThatThrownBy(() -> service.capture(secondPlayer, 7L))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No active encounter");
MultiplayerCreatureService.CaptureOutcome outcome = null;
for (long seed = 1; seed < 10_000 && (outcome == null || !outcome.captured()); seed++) {
outcome = service.capture(firstPlayer, seed);
}
assertThat(outcome).isNotNull();
assertThat(outcome.captured()).isTrue();
UUID captured = outcome.creatureId().orElseThrow();
service.setCompanion(firstPlayer, captured);
MultiplayerCreatureService restarted = new MultiplayerCreatureService(store, catalog());
MultiplayerCreatureService.PartyView party = restarted.party(firstPlayer);
assertThat(party.creatures()).extracting(MultiplayerCreatureService.CreatureView::creatureId).contains(captured);
assertThat(party.activeCompanionId()).contains(captured);
assertThat(restarted.party(secondPlayer).creatures()).isEmpty();
}
private JsonStateStore initializedStore() {
JsonStateStore store = new JsonStateStore(temporaryDirectory);
store.initialize();
return store;
}
private RuntimeContentCatalog catalog() {
return RuntimeContentCatalog.load(getClass().getClassLoader());
}
}
@@ -0,0 +1,45 @@
package dev.projectcapture.hytale.persistence;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class JsonStateStoreTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@TempDir
Path temporaryDirectory;
@Test
void roundTripsVersionedState() {
JsonStateStore store = new JsonStateStore(temporaryDirectory);
store.initialize();
store.write("player-01", MAPPER.createObjectNode().put("partySize", 6));
assertThat(store.read("player-01").path("partySize").asInt()).isEqualTo(6);
}
@Test
void rejectsFilesystemPathsAsSaveIds() {
JsonStateStore store = new JsonStateStore(temporaryDirectory);
store.initialize();
assertThatThrownBy(() -> store.write("../../launcher", MAPPER.createObjectNode()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Invalid logical save id");
}
@Test
void missingStateReturnsNull() {
JsonStateStore store = new JsonStateStore(temporaryDirectory);
store.initialize();
assertThat(store.read("missing")).isNull();
}
}
+8
View File
@@ -0,0 +1,8 @@
rootProject.name = "ProjectCapture"
include(
"engine",
"hytale-adapter",
"content-pokemon",
"content-tools",
)