feat(game): open the mart shop and key items by the ids the client reads (#151)

This commit is contained in:
Fiereu authored and GitHub committed 2026-08-10 14:52:44 +02:00
1 parent a69fd0d07f
commit 499d20fdb3
46 files changed
+7863 -269

No files matched your search

-3
View File
@@ -4,9 +4,6 @@
[submodule "decomp/pokefirered"] [submodule "decomp/pokefirered"]
path = decomp/pokefirered path = decomp/pokefirered
url = https://github.com/pret/pokefirered.git url = https://github.com/pret/pokefirered.git
[submodule "decomp/pokeblack"]
path = decomp/pokeblack
url = https://github.com/pokemodding/pokeblack.git
[submodule "decomp/pokeheartgold"] [submodule "decomp/pokeheartgold"]
path = decomp/pokeheartgold path = decomp/pokeheartgold
url = https://github.com/pret/pokeheartgold.git url = https://github.com/pret/pokeheartgold.git
+5 -3
View File
@@ -20,7 +20,7 @@ The goal is it to provide a free and open-source alternative to the PokeMMO serv
## Building ## Building
The map data is generated at build time from the [pret](https://github.com/pret) Game data is generated at build time from the [pret](https://github.com/pret)
decompilation projects, which are vendored as git submodules under `decomp/`. decompilation projects, which are vendored as git submodules under `decomp/`.
Clone the repository with its submodules: Clone the repository with its submodules:
@@ -30,8 +30,10 @@ git clone --recurse-submodules <repo-url>
git submodule update --init --recursive git submodule update --init --recursive
``` ```
Without the submodules the `:maps` build fails, because the generator has no Without the submodules the `:codegen` build fails, because the generators have no
decomp data to read. decomp data to read. The one exception is `decomp/pokeblack`, which holds the
item data as committed files rather than a submodule, because its source
repository is private.
### ROMs ### ROMs
+8 -7
View File
@@ -13,6 +13,7 @@ dependencies {
"generatorImplementation"(libs.jte) "generatorImplementation"(libs.jte)
"generatorImplementation"(libs.kotlinx.serialization.json) "generatorImplementation"(libs.kotlinx.serialization.json)
testImplementation(sourceSets["generator"].output) testImplementation(sourceSets["generator"].output)
testImplementation(libs.kotlinx.serialization.json)
testImplementation(libs.bundles.kotest) testImplementation(libs.bundles.kotest)
} }
@@ -28,6 +29,11 @@ val regionSources =
// is the canonical pick, same as byRegion is for maps. // is the canonical pick, same as byRegion is for maps.
val sourceDecompDir = rootProject.layout.projectDirectory.dir("decomp/pokeemerald") val sourceDecompDir = rootProject.layout.projectDirectory.dir("decomp/pokeemerald")
// The Gen 5 table the live client speaks, not the GBA decomps, which number the same items
// differently. Committed rather than a submodule because openmmo-org/pokeblack is private, taken
// from its src/data/items.json and container 54 of its src/data/text1.json.
val itemDataDir = rootProject.layout.projectDirectory.dir("decomp/pokeblack")
// ROMs (gitignored) that dialog codegen reads offsets from // ROMs (gitignored) that dialog codegen reads offsets from
val romsDir = rootProject.layout.projectDirectory.dir("roms") val romsDir = rootProject.layout.projectDirectory.dir("roms")
@@ -41,15 +47,10 @@ jteCodegen {
"$region|${rootProject.layout.projectDirectory.dir("decomp/$decomp").asFile.absolutePath}" "$region|${rootProject.layout.projectDirectory.dir("decomp/$decomp").asFile.absolutePath}"
}) })
} }
// Item ids scripts hand to giveItem. Both GBA games number items the same, so one decomp is
// enough, like moves and species. The client holds one item table per region, so the region
// decides what a number means. Checked against a real client: region 0 reads 3, 4 and 13 as
// Great Ball, Poke Ball and Potion, matching the decomp, while region 1 and region 5 read the
// same numbers as unrelated items.
register("item") { register("item") {
mainClass.set("de.fiereu.openmmo.codegen.item.Main") mainClass.set("de.fiereu.openmmo.codegen.item.Main")
inputDirs.from(sourceDecompDir) inputDirs.from(itemDataDir)
extraArgs.set(listOf("kanto|${sourceDecompDir.asFile.absolutePath}")) extraArgs.set(listOf(itemDataDir.asFile.absolutePath))
} }
register("moves") { register("moves") {
mainClass.set("de.fiereu.openmmo.codegen.move.Main") mainClass.set("de.fiereu.openmmo.codegen.move.Main")
+7 -5
View File
@@ -1,15 +1,17 @@
@import java.util.List @import java.util.List
@import de.fiereu.openmmo.codegen.item.ParsedItem @import de.fiereu.openmmo.codegen.item.ParsedItem
@import de.fiereu.openmmo.codegen.item.RenderUtil
@param List<ParsedItem> items @param List<ParsedItem> items
package de.fiereu.openmmo.items.generated package de.fiereu.openmmo.items.generated
/** import de.fiereu.openmmo.items.ItemDef
* Item ids the client uses, already carrying the region prefix of the decomp they were read from.
* Generated from the GBA decomp item header, do not edit by hand. /** Generated, do not edit by hand. The KDoc on an entry is the wire ids it answers to. */
*/
object Items { object Items {
@for(ParsedItem item : items) @for(ParsedItem item : items)
const val ${item.getName()} = ${item.getId()} ${RenderUtil.INSTANCE.declaration(item)}
@endfor @endfor
private fun item(name: String, price: Int) = ItemDef(name, price)
} }
@@ -0,0 +1,25 @@
@import java.util.List
@import de.fiereu.openmmo.codegen.item.ParsedItem
@import de.fiereu.openmmo.codegen.item.RenderUtil
@param List<List<ParsedItem>> chunks
package de.fiereu.openmmo.items.generated
import de.fiereu.openmmo.items.ItemRegistry
internal object GeneratedItems {
fun loadInto(reg: ItemRegistry) {
@for(int i = 0; i < chunks.size(); i++)
registerChunk${i}(reg)
@endfor
}
@for(int c = 0; c < chunks.size(); c++)
private fun registerChunk${c}(reg: ItemRegistry) {
@for(ParsedItem item : chunks.get(c))
${RenderUtil.INSTANCE.register(item)}
@endfor
}
@endfor
}
@@ -0,0 +1,68 @@
package de.fiereu.openmmo.codegen.item
import java.io.File
import java.text.Normalizer
import java.util.Locale
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
// A wire id is regionId * 1000 + index, and the client answers in the region 5 table.
private const val ITEM_REGION_BLOCK = 5000
private val PLACEHOLDER_NAMES = setOf("None", "?????", "???", "-", "?", "")
/** A name's position in `item_names.json` is the index `items.json` keys by. */
class ItemDataParser(private val dataDir: File) {
private val json = Json { ignoreUnknownKeys = true }
fun parseAll(): List<ParsedItem> {
val itemsFile = File(dataDir, "items.json")
val namesFile = File(dataDir, "item_names.json")
require(itemsFile.exists() && namesFile.exists()) {
"Item data not found at $dataDir (missing ${itemsFile.name} or ${namesFile.name})"
}
val names =
json.parseToJsonElement(namesFile.readText()).jsonArray.map { it.jsonPrimitive.content }
val prices =
json.parseToJsonElement(itemsFile.readText()).jsonArray.associate { entry ->
val obj = entry.jsonObject
obj.getValue("index").jsonPrimitive.int to obj.getValue("price").jsonPrimitive.int
}
return names
.withIndex()
.filterNot { (index, name) -> index == 0 || name.trim() in PLACEHOLDER_NAMES }
.mapNotNull { (index, name) ->
val identifier = identifierOf(name)
if (identifier.isEmpty()) null else Triple(identifier, name, index)
}
.groupBy { it.first }
.map { (identifier, group) ->
// Two different names normalising the same would silently become one item.
val grouped = group.map { it.second }.distinct()
check(grouped.size == 1) { "Items $grouped all derive the identifier $identifier" }
val lowest = group.minBy { it.third }
ParsedItem(
identifier = identifier,
name = lowest.second,
price = prices[lowest.third] ?: 0,
ids = group.map { ITEM_REGION_BLOCK + it.third }.sorted(),
)
}
.sortedBy { it.ids.first() }
}
/** Turns a display name into a Kotlin constant name: "Poké Ball" becomes POKE_BALL. */
private fun identifierOf(name: String): String =
Normalizer.normalize(name, Normalizer.Form.NFD)
.replace(Regex("\\p{Mn}+"), "")
.uppercase(Locale.ROOT)
.replace(Regex("[^A-Z0-9]+"), "_")
.trim('_')
.let { if (it.firstOrNull()?.isDigit() == true) "_$it" else it }
}
@@ -1,30 +0,0 @@
package de.fiereu.openmmo.codegen.item
import java.io.File
/**
* Reads the item constants out of a GBA decomp header. The two GBA decomps use the same item
* numbering, so one decomp is the single source of truth, the same way moves and species are.
*
* The client keys an item by `regionId * 1000 + itemId` and holds one item table per region.
* [regionId] picks the table that matches the decomp's own numbering, which leaves the Poke Ball at
* its decomp 4.
*/
class ItemParser(private val decompDir: File, private val regionId: Int) {
fun parseAll(): List<ParsedItem> {
val header = File(decompDir, "include/constants/items.h")
require(header.exists()) { "Missing ${header.path}" }
val define = Regex("""^#define\s+ITEM_([A-Z0-9_]+)\s+(\d+)\s*$""")
// ITEMS_COUNT closes the item list. Everything after it reuses the ITEM_ prefix for unrelated
// constants like the bag usage types, so parsing stops there.
return header
.readLines()
.takeWhile { !it.trimStart().startsWith("#define ITEMS_COUNT") }
.mapNotNull { define.find(it.trim()) }
.map { ParsedItem(it.groupValues[1], regionId * 1000 + it.groupValues[2].toInt()) }
// Placeholder slots are named after their hex index, for example ITEM_15C.
.filterNot { it.name.first().isDigit() }
.distinctBy(ParsedItem::name)
}
}
@@ -10,6 +10,7 @@ class ItemsRenderer(
private val templatesDir: File, private val templatesDir: File,
private val outputDir: File, private val outputDir: File,
private val classCacheDir: File, private val classCacheDir: File,
private val registryChunkSize: Int = 50,
) { ) {
fun render(items: List<ParsedItem>) { fun render(items: List<ParsedItem>) {
@@ -28,6 +29,9 @@ class ItemsRenderer(
FileOutput(File(packageRoot, "Items.kt").toPath()).use { out -> FileOutput(File(packageRoot, "Items.kt").toPath()).use { out ->
engine.render("Items.jte", mapOf("items" to items), out) engine.render("Items.jte", mapOf("items" to items), out)
} }
FileOutput(File(packageRoot, "GeneratedItems.kt").toPath()).use { out ->
engine.render("ItemsRegistry.jte", mapOf("chunks" to items.chunked(registryChunkSize)), out)
}
} }
private companion object { private companion object {
@@ -2,23 +2,21 @@
package de.fiereu.openmmo.codegen.item package de.fiereu.openmmo.codegen.item
import de.fiereu.openmmo.common.enums.Region
import java.io.File import java.io.File
fun main(args: Array<String>) { fun main(args: Array<String>) {
require(args.size >= 4) { require(args.size >= 4) {
"Usage: <output-dir> <templates-dir> <class-cache-dir> <region|decomp> got ${args.toList()}" "Usage: <output-dir> <templates-dir> <class-cache-dir> <item-data-dir> got ${args.toList()}"
} }
val outputDir = File(args[0]) val outputDir = File(args[0])
val templatesDir = File(args[1]) val templatesDir = File(args[1])
val classCacheDir = File(args[2]) val classCacheDir = File(args[2])
val (region, decomp) = args[3].split("|") val dataDir = File(args[3])
val decompDir = File(decomp)
val regionId = Region.valueOf(region.uppercase()).wireValue.toInt()
println("[item] parsing $region items from $decompDir") println("[item] parsing from $dataDir")
val items = ItemParser(decompDir, regionId).parseAll() val items = ItemDataParser(dataDir).parseAll()
println("[item] parsed ${items.size} items. writing to $outputDir") val ids = items.sumOf { it.ids.size }
println("[item] parsed ${items.size} items carrying $ids ids. writing to $outputDir")
ItemsRenderer(templatesDir, outputDir, classCacheDir).render(items) ItemsRenderer(templatesDir, outputDir, classCacheDir).render(items)
println("[item] done") println("[item] done")
} }
@@ -1,4 +1,9 @@
package de.fiereu.openmmo.codegen.item package de.fiereu.openmmo.codegen.item
/** One item constant: the decomp name without its ITEM_ prefix and the id the client uses. */ /** [ids] is a list because the table lists some items in more than one slot. */
data class ParsedItem(val name: String, val id: Int) data class ParsedItem(
val identifier: String,
val name: String,
val price: Int,
val ids: List<Int>,
)
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.codegen.item
object RenderUtil {
fun declaration(item: ParsedItem): String =
" /** ${item.ids.joinToString(", ")} */\n" +
" val ${item.identifier} = item(${escapeString(item.name)}, ${item.price})"
fun register(item: ParsedItem): String =
"reg.register(Items.${item.identifier}, ${item.ids.joinToString(", ")})"
private fun escapeString(s: String): String =
"\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
}
@@ -0,0 +1,6 @@
package de.fiereu.openmmo.items
/** Not a data class on purpose. The catalogue instance is the identity, so equality is by it. */
class ItemDef(val name: String, val price: Int) {
override fun toString(): String = name
}
@@ -0,0 +1,42 @@
package de.fiereu.openmmo.items
import de.fiereu.openmmo.items.generated.GeneratedItems
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ItemRegistry @Inject constructor() {
private val byId = ConcurrentHashMap<Int, ItemDef>()
private val idsByItem = ConcurrentHashMap<ItemDef, List<Int>>()
init {
GeneratedItems.loadInto(this)
}
fun register(item: ItemDef, vararg ids: Int) {
for (id in ids) {
val previous = byId.put(id, item)
// Generated data, so a clash is a codegen bug rather than bad input.
check(previous == null || previous === item) {
"Item id $id is claimed by both ${previous?.name} and ${item.name}"
}
}
idsByItem.merge(item, ids.toList()) { old, new -> (old + new).distinct().sorted() }
}
fun get(id: Int): ItemDef? = byId[id]
fun idsOf(item: ItemDef): List<Int> = idsByItem[item].orEmpty()
/** An item with several ids is named by its lowest. */
fun idOf(item: ItemDef): Int =
idsOf(item).firstOrNull() ?: error("Item '${item.name}' has no id in this build")
fun idOrNull(item: ItemDef): Int? = idsOf(item).firstOrNull()
fun all(): Collection<ItemDef> = idsByItem.keys
fun size(): Int = idsByItem.size
}
@@ -0,0 +1,72 @@
package de.fiereu.openmmo.codegen.item
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.shouldBe
import java.io.File
private fun dataDir(names: List<String>, prices: Map<Int, Int>): File {
val dir = kotlin.io.path.createTempDirectory("item-data").toFile()
dir.resolve("item_names.json").writeText(names.joinToString(",", "[", "]") { "\"$it\"" })
dir.resolve("items.json")
.writeText(
prices.entries.joinToString(",", "[", "]") { (index, price) ->
"""{"index":$index,"price":$price,"hold_effect":0}"""
})
return dir
}
class ItemDataParserTest :
FunSpec({
test("reads a name and its price into the region 5 id block") {
val items =
ItemDataParser(
dataDir(
listOf("None", "Master Ball", "Ultra Ball", "Poké Ball"),
mapOf(1 to 0, 2 to 1200, 3 to 200)))
.parseAll()
items.single { it.identifier == "POKE_BALL" } shouldBe
ParsedItem("POKE_BALL", "Poké Ball", 200, listOf(5003))
}
test("collects every slot sharing a name into one item with several ids") {
val items =
ItemDataParser(
dataDir(
listOf("None", "Potion", "Antidote", "Potion"),
mapOf(1 to 300, 2 to 100, 3 to 300)))
.parseAll()
items.single { it.identifier == "POTION" }.ids shouldContainExactly listOf(5001, 5003)
}
test("skips index 0 and the placeholder slots") {
val items =
ItemDataParser(dataDir(listOf("None", "?????", "-", "", "Potion"), mapOf(4 to 300)))
.parseAll()
items.map { it.identifier } shouldContainExactly listOf("POTION")
}
test("derives identifiers that are legal Kotlin names") {
val names = listOf("None", "Poké Ball", "Parlyz Heal", "Up-Grade", "10 Coins", "X Attack")
val items = ItemDataParser(dataDir(names, emptyMap())).parseAll()
items.map { it.identifier } shouldContainExactly
listOf("POKE_BALL", "PARLYZ_HEAL", "UP_GRADE", "_10_COINS", "X_ATTACK")
}
test("prices an item the table has no entry for at zero") {
val items = ItemDataParser(dataDir(listOf("None", "Parcel"), emptyMap())).parseAll()
items.single().price shouldBe 0
}
test("fails loudly when the vendored data is missing") {
val empty = kotlin.io.path.createTempDirectory("item-data-empty").toFile()
shouldThrow<IllegalArgumentException> { ItemDataParser(empty).parseAll() }
}
})
@@ -1,41 +0,0 @@
package de.fiereu.openmmo.codegen.item
import de.fiereu.openmmo.common.enums.Region
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class ItemParserTest :
FunSpec({
test("prefixes decomp item ids with their region and stops at the list end") {
val decomp = kotlin.io.path.createTempDirectory("items").toFile()
decomp.resolve("include/constants").mkdirs()
decomp
.resolve("include/constants/items.h")
.writeText(
"""
#define ITEM_NONE 0
#define ITEM_GREAT_BALL 3
#define ITEM_POKE_BALL 4
#define ITEM_15C 348
#define ITEM_LIST_END 0xFFFF
#define ITEMS_COUNT 377
#define ITEM_USE_MAIL 0
#define ITEM_HAS_EFFECT(item) ((item) >= ITEM_POTION)
"""
.trimIndent())
ItemParser(decomp, Region.KANTO.wireValue.toInt()).parseAll() shouldBe
listOf(
ParsedItem("NONE", 0),
ParsedItem("GREAT_BALL", 3),
ParsedItem("POKE_BALL", 4),
)
ItemParser(decomp, Region.HOENN.wireValue.toInt()).parseAll() shouldBe
listOf(
ParsedItem("NONE", 1000),
ParsedItem("GREAT_BALL", 1003),
ParsedItem("POKE_BALL", 1004),
)
}
})
@@ -0,0 +1,78 @@
package de.fiereu.openmmo.items
import de.fiereu.openmmo.items.generated.Items
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
class ItemRegistryTest :
FunSpec({
// Kotest shares the spec instance, so the tests that register have to work on their own
// registry rather than a shared one.
fun registry() = ItemRegistry()
test("loads the generated catalogue") { registry().size() shouldBeGreaterThan 500 }
test("resolves the ids the live client sends") {
val items = registry()
items.idOf(Items.POKE_BALL) shouldBe 5004
items.idOf(Items.POTION) shouldBe 5017
items.idOf(Items.ANTIDOTE) shouldBe 5018
items.idOf(Items.PARLYZ_HEAL) shouldBe 5022
items.idOf(Items.PARCEL) shouldBe 5459
}
test("carries the price the item table gives") {
Items.POKE_BALL.price shouldBe 200
Items.POTION.price shouldBe 300
Items.ANTIDOTE.price shouldBe 100
Items.PARLYZ_HEAL.price shouldBe 200
}
test("round trips every item through its ids") {
val items = registry()
for (item in items.all()) {
for (id in items.idsOf(item)) {
items.get(id) shouldBe item
}
}
}
test("answers nothing for an id no item claims") { registry().get(1).shouldBeNull() }
test("an item is its identity, so a look-alike does not resolve") {
val items = registry()
items.idOrNull(ItemDef(Items.POTION.name, Items.POTION.price)).shouldBeNull()
}
test("refuses an id already claimed by another item") {
val items = registry()
shouldThrow<IllegalStateException> {
items.register(ItemDef("Impostor", 0), items.idOf(Items.POTION))
}
}
test("registering the same item twice merges its ids") {
val items = registry()
val item = ItemDef("Multi", 10)
items.register(item, 90002)
items.register(item, 90001, 90002)
items.idsOf(item) shouldContainExactly listOf(90001, 90002)
items.idOf(item) shouldBe 90001
}
test("throws by name for an item this build has no id for") {
val thrown = shouldThrow<IllegalStateException> { registry().idOf(ItemDef("Teachy TV", 0)) }
thrown.message shouldBe "Item 'Teachy TV' has no id in this build"
}
})
+629
View File
@@ -0,0 +1,629 @@
[
"None",
"Master Ball",
"Ultra Ball",
"Great Ball",
"Poké Ball",
"Safari Ball",
"Net Ball",
"Dive Ball",
"Nest Ball",
"Repeat Ball",
"Timer Ball",
"Luxury Ball",
"Premier Ball",
"Dusk Ball",
"Heal Ball",
"Quick Ball",
"Cherish Ball",
"Potion",
"Antidote",
"Burn Heal",
"Ice Heal",
"Awakening",
"Parlyz Heal",
"Full Restore",
"Max Potion",
"Hyper Potion",
"Super Potion",
"Full Heal",
"Revive",
"Max Revive",
"Fresh Water",
"Soda Pop",
"Lemonade",
"Moomoo Milk",
"EnergyPowder",
"Energy Root",
"Heal Powder",
"Revival Herb",
"Ether",
"Max Ether",
"Elixir",
"Max Elixir",
"Lava Cookie",
"Berry Juice",
"Sacred Ash",
"HP Up",
"Protein",
"Iron",
"Carbos",
"Calcium",
"Rare Candy",
"PP Up",
"Zinc",
"PP Max",
"Old Gateau",
"Guard Spec.",
"Dire Hit",
"X Attack",
"X Defend",
"X Speed",
"X Accuracy",
"X Special",
"X Sp. Def",
"Poké Doll",
"Fluffy Tail",
"Blue Flute",
"Yellow Flute",
"Red Flute",
"Black Flute",
"White Flute",
"Shoal Salt",
"Shoal Shell",
"Red Shard",
"Blue Shard",
"Yellow Shard",
"Green Shard",
"Super Repel",
"Max Repel",
"Escape Rope",
"Repel",
"Sun Stone",
"Moon Stone",
"Fire Stone",
"Thunderstone",
"Water Stone",
"Leaf Stone",
"TinyMushroom",
"Big Mushroom",
"Pearl",
"Big Pearl",
"Stardust",
"Star Piece",
"Nugget",
"Heart Scale",
"Honey",
"Growth Mulch",
"Damp Mulch",
"Stable Mulch",
"Gooey Mulch",
"Root Fossil",
"Claw Fossil",
"Helix Fossil",
"Dome Fossil",
"Old Amber",
"Armor Fossil",
"Skull Fossil",
"Rare Bone",
"Shiny Stone",
"Dusk Stone",
"Dawn Stone",
"Oval Stone",
"Odd Keystone",
"Griseous Orb",
"???",
"???",
"???",
"Douse Drive",
"Shock Drive",
"Burn Drive",
"Chill Drive",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"???",
"Sweet Heart",
"Adamant Orb",
"Lustrous Orb",
"Greet Mail",
"Favored Mail",
"RSVP Mail",
"Thanks Mail",
"Inquiry Mail",
"Like Mail",
"Reply Mail",
"BridgeMail S",
"BridgeMail D",
"BridgeMail T",
"BridgeMail V",
"BridgeMail M",
"Cheri Berry",
"Chesto Berry",
"Pecha Berry",
"Rawst Berry",
"Aspear Berry",
"Leppa Berry",
"Oran Berry",
"Persim Berry",
"Lum Berry",
"Sitrus Berry",
"Figy Berry",
"Wiki Berry",
"Mago Berry",
"Aguav Berry",
"Iapapa Berry",
"Razz Berry",
"Bluk Berry",
"Nanab Berry",
"Wepear Berry",
"Pinap Berry",
"Pomeg Berry",
"Kelpsy Berry",
"Qualot Berry",
"Hondew Berry",
"Grepa Berry",
"Tamato Berry",
"Cornn Berry",
"Magost Berry",
"Rabuta Berry",
"Nomel Berry",
"Spelon Berry",
"Pamtre Berry",
"Watmel Berry",
"Durin Berry",
"Belue Berry",
"Occa Berry",
"Passho Berry",
"Wacan Berry",
"Rindo Berry",
"Yache Berry",
"Chople Berry",
"Kebia Berry",
"Shuca Berry",
"Coba Berry",
"Payapa Berry",
"Tanga Berry",
"Charti Berry",
"Kasib Berry",
"Haban Berry",
"Colbur Berry",
"Babiri Berry",
"Chilan Berry",
"Liechi Berry",
"Ganlon Berry",
"Salac Berry",
"Petaya Berry",
"Apicot Berry",
"Lansat Berry",
"Starf Berry",
"Enigma Berry",
"Micle Berry",
"Custap Berry",
"Jaboca Berry",
"Rowap Berry",
"BrightPowder",
"White Herb",
"Macho Brace",
"Exp. Share",
"Quick Claw",
"Soothe Bell",
"Mental Herb",
"Choice Band",
"King's Rock",
"SilverPowder",
"Amulet Coin",
"Cleanse Tag",
"Soul Dew",
"DeepSeaTooth",
"DeepSeaScale",
"Smoke Ball",
"Everstone",
"Focus Band",
"Lucky Egg",
"Scope Lens",
"Metal Coat",
"Leftovers",
"Dragon Scale",
"Light Ball",
"Soft Sand",
"Hard Stone",
"Miracle Seed",
"BlackGlasses",
"Black Belt",
"Magnet",
"Mystic Water",
"Sharp Beak",
"Poison Barb",
"NeverMeltIce",
"Spell Tag",
"TwistedSpoon",
"Charcoal",
"Dragon Fang",
"Silk Scarf",
"Up-Grade",
"Shell Bell",
"Sea Incense",
"Lax Incense",
"Lucky Punch",
"Metal Powder",
"Thick Club",
"Stick",
"Red Scarf",
"Blue Scarf",
"Pink Scarf",
"Green Scarf",
"Yellow Scarf",
"Wide Lens",
"Muscle Band",
"Wise Glasses",
"Expert Belt",
"Light Clay",
"Life Orb",
"Power Herb",
"Toxic Orb",
"Flame Orb",
"Quick Powder",
"Focus Sash",
"Zoom Lens",
"Metronome",
"Iron Ball",
"Lagging Tail",
"Destiny Knot",
"Black Sludge",
"Icy Rock",
"Smooth Rock",
"Heat Rock",
"Damp Rock",
"Grip Claw",
"Choice Scarf",
"Sticky Barb",
"Power Bracer",
"Power Belt",
"Power Lens",
"Power Band",
"Power Anklet",
"Power Weight",
"Shed Shell",
"Big Root",
"Choice Specs",
"Flame Plate",
"Splash Plate",
"Zap Plate",
"Meadow Plate",
"Icicle Plate",
"Fist Plate",
"Toxic Plate",
"Earth Plate",
"Sky Plate",
"Mind Plate",
"Insect Plate",
"Stone Plate",
"Spooky Plate",
"Draco Plate",
"Dread Plate",
"Iron Plate",
"Odd Incense",
"Rock Incense",
"Full Incense",
"Wave Incense",
"Rose Incense",
"Luck Incense",
"Pure Incense",
"Protector",
"Electirizer",
"Magmarizer",
"Dubious Disc",
"Reaper Cloth",
"Razor Claw",
"Razor Fang",
"TM01",
"TM02",
"TM03",
"TM04",
"TM05",
"TM06",
"TM07",
"TM08",
"TM09",
"TM10",
"TM11",
"TM12",
"TM13",
"TM14",
"TM15",
"TM16",
"TM17",
"TM18",
"TM19",
"TM20",
"TM21",
"TM22",
"TM23",
"TM24",
"TM25",
"TM26",
"TM27",
"TM28",
"TM29",
"TM30",
"TM31",
"TM32",
"TM33",
"TM34",
"TM35",
"TM36",
"TM37",
"TM38",
"TM39",
"TM40",
"TM41",
"TM42",
"TM43",
"TM44",
"TM45",
"TM46",
"TM47",
"TM48",
"TM49",
"TM50",
"TM51",
"TM52",
"TM53",
"TM54",
"TM55",
"TM56",
"TM57",
"TM58",
"TM59",
"TM60",
"TM61",
"TM62",
"TM63",
"TM64",
"TM65",
"TM66",
"TM67",
"TM68",
"TM69",
"TM70",
"TM71",
"TM72",
"TM73",
"TM74",
"TM75",
"TM76",
"TM77",
"TM78",
"TM79",
"TM80",
"TM81",
"TM82",
"TM83",
"TM84",
"TM85",
"TM86",
"TM87",
"TM88",
"TM89",
"TM90",
"TM91",
"TM92",
"HM01",
"HM02",
"HM03",
"HM04",
"HM05",
"HM06",
"???",
"???",
"Explorer Kit",
"Loot Sack",
"Rule Book",
"Poké Radar",
"Point Card",
"Journal",
"Seal Case",
"Fashion Case",
"Seal Bag",
"Pal Pad",
"Works Key",
"Old Charm",
"Galactic Key",
"Red Chain",
"Town Map",
"Vs. Seeker",
"Coin Case",
"Old Rod",
"Good Rod",
"Super Rod",
"Sprayduck",
"Poffin Case",
"Bicycle",
"Suite Key",
"Oak's Letter",
"Lunar Wing",
"Member Card",
"Azure Flute",
"S.S. Ticket",
"Contest Pass",
"Magma Stone",
"Parcel",
"Coupon 1",
"Coupon 2",
"Coupon 3",
"Storage Key",
"SecretPotion",
"Vs. Recorder",
"Gracidea",
"Secret Key",
"Apricorn Box",
"Unown Report",
"Berry Pots",
"Dowsing MCHN",
"Blue Card",
"SlowpokeTail",
"Clear Bell",
"Card Key",
"Basement Key",
"SquirtBottle",
"Red Scale",
"Lost Item",
"Pass",
"Machine Part",
"Silver Wing",
"Rainbow Wing",
"Mystery Egg",
"Red Apricorn",
"Blu Apricorn",
"Ylw Apricorn",
"Grn Apricorn",
"Pnk Apricorn",
"Wht Apricorn",
"Blk Apricorn",
"Fast Ball",
"Level Ball",
"Lure Ball",
"Heavy Ball",
"Love Ball",
"Friend Ball",
"Moon Ball",
"Sport Ball",
"Park Ball",
"Photo Album",
"GB Sounds",
"Tidal Bell",
"RageCandyBar",
"Data Card 01",
"Data Card 02",
"Data Card 03",
"Data Card 04",
"Data Card 05",
"Data Card 06",
"Data Card 07",
"Data Card 08",
"Data Card 09",
"Data Card 10",
"Data Card 11",
"Data Card 12",
"Data Card 13",
"Data Card 14",
"Data Card 15",
"Data Card 16",
"Data Card 17",
"Data Card 18",
"Data Card 19",
"Data Card 20",
"Data Card 21",
"Data Card 22",
"Data Card 23",
"Data Card 24",
"Data Card 25",
"Data Card 26",
"Data Card 27",
"Jade Orb",
"Lock Capsule",
"Red Orb",
"Blue Orb",
"Enigma Stone",
"Prism Scale",
"Eviolite",
"Float Stone",
"Rocky Helmet",
"Air Balloon",
"Red Card",
"Ring Target",
"Binding Band",
"Absorb Bulb",
"Cell Battery",
"Eject Button",
"Fire Gem",
"Water Gem",
"Electric Gem",
"Grass Gem",
"Ice Gem",
"Fighting Gem",
"Poison Gem",
"Ground Gem",
"Flying Gem",
"Psychic Gem",
"Bug Gem",
"Rock Gem",
"Ghost Gem",
"Dragon Gem",
"Dark Gem",
"Steel Gem",
"Normal Gem",
"Health Wing",
"Muscle Wing",
"Resist Wing",
"Genius Wing",
"Clever Wing",
"Swift Wing",
"Pretty Wing",
"Cover Fossil",
"Plume Fossil",
"Liberty Pass",
"Pass Orb",
"Dream Ball",
"Poké Toy",
"Prop Case",
"Dragon Skull",
"BalmMushroom",
"Big Nugget",
"Pearl String",
"Comet Shard",
"Relic Copper",
"Relic Silver",
"Relic Gold",
"Relic Vase",
"Relic Band",
"Relic Statue",
"Relic Crown",
"Casteliacone",
"Dire Hit 2",
"X Speed 2",
"X Special 2",
"X Sp. Def 2",
"X Defend 2",
"X Attack 2",
"X Accuracy 2",
"X Speed 3",
"X Special 3",
"X Sp. Def 3",
"X Defend 3",
"X Attack 3",
"X Accuracy 3",
"X Speed 6",
"X Special 6",
"X Sp. Def 6",
"X Defend 6",
"X Attack 6",
"X Accuracy 6",
"Ability Urge",
"Item Drop",
"Item Urge",
"Reset Urge",
"Dire Hit 3",
"Light Stone",
"Dark Stone",
"TM93",
"TM94",
"TM95",
"Xtransceiver",
"???",
"Gram 1",
"Gram 2",
"Gram 3",
"Xtransceiver"
]
File diff suppressed because it is too large. Load diff
@@ -67,12 +67,18 @@ end of your function.
| `warp MAP, x, y` | `ctx.warp(region, bank, map, x, y, facing)` | | `warp MAP, x, y` | `ctx.warp(region, bank, map, x, y, facing)` |
| `setdynamicwarp ...` | `ctx.setDynamicWarp(region, bank, map, x, y, facing)` | | `setdynamicwarp ...` | `ctx.setDynamicWarp(region, bank, map, x, y, facing)` |
Item ids come from the generated `Items` object, never a raw number: Items are named, never numbered: `ctx.giveItem(Items.POKE_BALL, 5)`. A value in
`ctx.giveItem(Items.POKE_BALL, 5)`. It is generated from the decomp item header, the generated `Items` object is an identity rather than an id, and `ItemRegistry`
so every item the games know about is in it. The client keys an item by maps it to the ids the wire uses, so a script never sees a number and an item
`regionId * 1000 + itemId` and holds one item table per region, so the ids in listed twice in the client's table still resolves. Services translate at the
`Items` sit in the region whose table matches the decomp numbering. Sending the point they build a packet.
same number under another region reaches a different item entirely.
`Items` is generated from the Gen 5 table the live client speaks, so it holds
what the client can actually show. An item the decomp has and the client does not
is simply absent, and naming it fails the build rather than handing the player
something that arrives as another item or as nothing. The Teachy TV in Viridian
City is the case that came up first. Where the decomp's item does not exist,
drop the reward and say so, rather than substituting a different one.
`ctx.warp` continues into the destination map's ON_TRANSITION and ON_FRAME `ctx.warp` continues into the destination map's ON_TRANSITION and ON_FRAME
scripts on the same coroutine, exactly the way the decomp's `warp` does, so a scripts on the same coroutine, exactly the way the decomp's `warp` does, so a
@@ -30,7 +30,7 @@ Gradle task (`generateMaps`, `generateMoves`, `generatePokemon`, ...).
## Pick a data source first ## Pick a data source first
There are two ways to choose which decomp to read from: There are three ways to choose which decomp to read from:
- **By region:** for data that is different in each region, like maps. Hoenn - **By region:** for data that is different in each region, like maps. Hoenn
maps come from `pokeemerald`, Kanto maps from `pokefirered`. The generator gets maps come from `pokeemerald`, Kanto maps from `pokefirered`. The generator gets
@@ -39,13 +39,21 @@ There are two ways to choose which decomp to read from:
and species. We just read one decomp (`pokeemerald`). Where the two games and species. We just read one decomp (`pokeemerald`). Where the two games
disagree on a detail (a wild held item, a flee rate) we accept the values from disagree on a detail (a wild held item, a flee rate) we accept the values from
that one decomp instead of trying to merge them. that one decomp instead of trying to merge them.
- **Whatever the live client speaks:** for data the client indexes itself, like
items. The retail client answers in the Gen 5 table no matter which region the
player is in, so `generateItem` reads `decomp/pokeblack` and the GBA numbering
never enters the picture.
Rule of thumb: if the same thing (a move, a Pokémon) exists in both games, use a Rule of thumb: if the same thing (a move, a Pokémon) exists in both games, use a
single source. If the thing belongs to one region, use by-region. single source. If the thing belongs to one region, use by-region. If the client
is the one doing the lookup, follow the client.
> **Note:** the NDS decomps (`pokeblack`, `pokeheartgold`, `pokeplatinum`) are > **Note:** the NDS decomps (`pokeheartgold`, `pokeplatinum`) are submodules but
> **not implemented yet**. They use 3D maps and a different data format, so only > **not implemented**. They use 3D maps and a different data format, so every
> the GBA decomps (`pokeemerald`, `pokefirered`) are wired up today. > generator but the item one reads the GBA decomps (`pokeemerald`,
> `pokefirered`). Item data is the exception: it comes from two JSON files
> extracted from the Gen 5 decomp and committed under `decomp/pokeblack`, whose
> source repository is private and so cannot be a submodule.
## The pieces of a generator ## The pieces of a generator
@@ -106,7 +106,7 @@ object GameProtocol : Protocol() {
bidi<EntityInteractPacket>(0x22u, EntityInteractPacketCodec) bidi<EntityInteractPacket>(0x22u, EntityInteractPacketCodec)
c2s<ExchangeItemRequestPacket>(0x23u, ExchangeItemRequestPacketCodec) c2s<ExchangeItemRequestPacket>(0x23u, ExchangeItemRequestPacketCodec)
s2c<EventOverlayStatePacket>(0x23u, EventOverlayStatePacketCodec) s2c<ShopCatalogPacket>(0x23u, ShopCatalogPacketCodec)
c2s<ShopSellRequestPacket>(0x24u, ShopSellRequestPacketCodec) c2s<ShopSellRequestPacket>(0x24u, ShopSellRequestPacketCodec)
s2c<NpcPanelTogglePacket>(0x24u, NpcPanelTogglePacketCodec) s2c<NpcPanelTogglePacket>(0x24u, NpcPanelTogglePacketCodec)
@@ -1,134 +0,0 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.*
private const val GRID_OVERLAY_TYPE: Int = 1
data class OverlayGridPoint(val x: Short, val y: Short)
data class OverlayRegion(
val regionId: Short,
val secondary: Short,
val gridPoints: List<OverlayGridPoint>?,
val value: Int?,
)
data class OverlayHole(val regionId: Short, val secondary: Short)
data class EventOverlayStatePacket(
val active: Boolean,
val overlayType: Byte,
val flagBits: Byte,
val ignoredEnum: Byte,
val timeRemaining: Int?,
val valueA: Int?,
val valueB: Int?,
val anchorEntityId: Long?,
val regions: List<OverlayRegion>,
val holes: List<OverlayHole>,
)
object EventOverlayStatePacketCodec : PacketCodec<EventOverlayStatePacket>() {
override fun CodecScope<EventOverlayStatePacket>.body(): EventOverlayStatePacket {
val codec = EventOverlayStateCodec
return field(codec) { it }
}
}
private val EventOverlayStateCodec: Codec<EventOverlayStatePacket> =
object : Codec<EventOverlayStatePacket> {
override fun read(buf: ReadBuffer): EventOverlayStatePacket {
val typeByte = S8.read(buf)
val active = typeByte.toInt() != -1
if (!active) {
return EventOverlayStatePacket(
active = false,
overlayType = typeByte,
flagBits = 0,
ignoredEnum = 0,
timeRemaining = null,
valueA = null,
valueB = null,
anchorEntityId = null,
regions = emptyList(),
holes = emptyList(),
)
}
val grid = typeByte.toInt() == GRID_OVERLAY_TYPE
val flagBits = S8.read(buf)
val fb = flagBits.toInt()
val ignoredEnum = S8.read(buf)
val timeRemaining = if (fb and 32 != 0) S32LE.read(buf) else null
val valueA = if (fb and 8 != 0) S32LE.read(buf) else null
val valueB = if (fb and 16 != 0) S32LE.read(buf) else null
val anchorEntityId = if (fb and 64 != 0) S64LE.read(buf) else null
val regionCount = U16LE.read(buf)
val regions = ArrayList<OverlayRegion>(regionCount)
repeat(regionCount) {
val regionId = S16LE.read(buf)
val secondary = S16LE.read(buf)
if (grid) {
val n = U8.read(buf)
val points = ArrayList<OverlayGridPoint>(n)
repeat(n) { points.add(OverlayGridPoint(S16LE.read(buf), S16LE.read(buf))) }
regions.add(OverlayRegion(regionId, secondary, points, null))
} else {
val v = S32LE.read(buf)
regions.add(OverlayRegion(regionId, secondary, null, v))
}
}
val holes = ArrayList<OverlayHole>()
if (grid && fb and 4 != 0) {
val holeCount = U16LE.read(buf)
repeat(holeCount) { holes.add(OverlayHole(S16LE.read(buf), S16LE.read(buf))) }
}
return EventOverlayStatePacket(
active = true,
overlayType = typeByte,
flagBits = flagBits,
ignoredEnum = ignoredEnum,
timeRemaining = timeRemaining,
valueA = valueA,
valueB = valueB,
anchorEntityId = anchorEntityId,
regions = regions,
holes = holes,
)
}
override fun write(buf: WriteBuffer, value: EventOverlayStatePacket) {
S8.write(buf, value.overlayType)
if (!value.active) return
val grid = value.overlayType.toInt() == GRID_OVERLAY_TYPE
S8.write(buf, value.flagBits)
val fb = value.flagBits.toInt()
S8.write(buf, value.ignoredEnum)
if (fb and 32 != 0) S32LE.write(buf, value.timeRemaining!!)
if (fb and 8 != 0) S32LE.write(buf, value.valueA!!)
if (fb and 16 != 0) S32LE.write(buf, value.valueB!!)
if (fb and 64 != 0) S64LE.write(buf, value.anchorEntityId!!)
U16LE.write(buf, value.regions.size)
for (r in value.regions) {
S16LE.write(buf, r.regionId)
S16LE.write(buf, r.secondary)
if (grid) {
val points =
r.gridPoints ?: throw MalformedPacketException("grid overlay region missing points")
U8.write(buf, points.size)
for (p in points) {
S16LE.write(buf, p.x)
S16LE.write(buf, p.y)
}
} else {
S32LE.write(buf, r.value!!)
}
}
if (grid && fb and 4 != 0) {
U16LE.write(buf, value.holes.size)
for (h in value.holes) {
S16LE.write(buf, h.regionId)
S16LE.write(buf, h.secondary)
}
}
}
}
@@ -0,0 +1,59 @@
package de.fiereu.openmmo.net.game.packets
import de.fiereu.bytecodec.*
/** [stock] is 0x7FFF on every captured mart line, which the client reads as an endless shelf. */
data class ShopItem(
val itemId: Short,
val unknownA: Short,
val stock: Short,
val price: Int,
)
object ShopItemCodec : PacketCodec<ShopItem>() {
override fun CodecScope<ShopItem>.body(): ShopItem {
val itemId = field(S16LE) { it.itemId }
val unknownA = field(S16LE) { it.unknownA }
val stock = field(S16LE) { it.stock }
val price = field(S32LE) { it.price }
return ShopItem(itemId, unknownA, stock, price)
}
}
/**
* Opens or closes the shop window. A close is the single byte [CLOSED] with no body, so everything
* after the first byte only rides along on an open.
*/
data class ShopCatalogPacket(
val kind: Byte,
val shopId: Short? = null,
val unknownA: Int? = null,
val npcEntityId: Long? = null,
val items: List<ShopItem> = emptyList(),
) {
companion object {
const val OPEN: Byte = 0
const val CLOSED: Byte = -1
/**
* [unknownA] is the same value in every capture, across three different shops, so it is sent
* back rather than derived.
*/
fun open(shopId: Short, npcEntityId: Long, items: List<ShopItem>): ShopCatalogPacket =
ShopCatalogPacket(OPEN, shopId, CAPTURED_UNKNOWN_A, npcEntityId, items)
private const val CAPTURED_UNKNOWN_A = 0x1A5190
}
}
object ShopCatalogPacketCodec : PacketCodec<ShopCatalogPacket>() {
override fun CodecScope<ShopCatalogPacket>.body(): ShopCatalogPacket {
val kind = field(S8) { it.kind }
val open = kind == ShopCatalogPacket.OPEN
val shopId = optionalField(open, S16LE) { it.shopId }
val unknownA = optionalField(open, S32LE) { it.unknownA }
val npcEntityId = optionalField(open, S64LE) { it.npcEntityId }
val items = optionalField(open, ShopItemCodec.listPrefixed(U16LE)) { it.items }
return ShopCatalogPacket(kind, shopId, unknownA, npcEntityId, items ?: emptyList())
}
}
@@ -0,0 +1,46 @@
package de.fiereu.openmmo.net.game
import de.fiereu.openmmo.common.test.assertBytesRoundtrip
import de.fiereu.openmmo.common.test.decodeBytes
import de.fiereu.openmmo.common.test.fixture
import de.fiereu.openmmo.net.game.packets.ExchangeItemRequestPacketCodec
import de.fiereu.openmmo.net.game.packets.ShopCatalogPacket
import de.fiereu.openmmo.net.game.packets.ShopCatalogPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class ShopCatalogPacketTest :
FunSpec({
test("the viridian mart catalog decodes to its shelves and their prices") {
val bytes = fixture("game/s2c/23/mart_catalog.bin")
val packet = ShopCatalogPacketCodec.decodeBytes(bytes)
packet.kind shouldBe ShopCatalogPacket.OPEN
packet.shopId shouldBe 103
packet.npcEntityId shouldBe 0x1AD3B85EBE48E000L
packet.items.map { it.itemId.toInt() } shouldBe listOf(5004, 5017, 5018, 5022, 5019)
packet.items.map { it.price } shouldBe listOf(200, 200, 200, 300, 300)
// Every line carries the same endless shelf marker.
packet.items.map { it.stock.toInt() }.toSet() shouldBe setOf(0x7FFF)
ShopCatalogPacketCodec.assertBytesRoundtrip(bytes)
}
test("a close carries nothing but its marker") {
val bytes = fixture("game/s2c/23/shop_closed.bin")
ShopCatalogPacketCodec.decodeBytes(bytes).kind shouldBe ShopCatalogPacket.CLOSED
ShopCatalogPacketCodec.assertBytesRoundtrip(bytes)
}
test("a buy names the item and how many of it") {
val bytes = fixture("game/c2s/23/buy_poke_balls.bin")
val packet = ExchangeItemRequestPacketCodec.decodeBytes(bytes)
packet.itemEntityRef.toInt() shouldBe 5004
packet.quantity.toInt() shouldBe 3
ExchangeItemRequestPacketCodec.assertBytesRoundtrip(bytes)
}
})
@@ -15,6 +15,7 @@ import de.fiereu.openmmo.net.game.packets.CreateCharacterPacket
import de.fiereu.openmmo.net.game.packets.DeleteCharacterPacket import de.fiereu.openmmo.net.game.packets.DeleteCharacterPacket
import de.fiereu.openmmo.net.game.packets.DialogChoicePacket import de.fiereu.openmmo.net.game.packets.DialogChoicePacket
import de.fiereu.openmmo.net.game.packets.EntityInteractPacket import de.fiereu.openmmo.net.game.packets.EntityInteractPacket
import de.fiereu.openmmo.net.game.packets.ExchangeItemRequestPacket
import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket import de.fiereu.openmmo.net.game.packets.FaceDirectionPacket
import de.fiereu.openmmo.net.game.packets.JoinPacket import de.fiereu.openmmo.net.game.packets.JoinPacket
import de.fiereu.openmmo.net.game.packets.KeepAlivePacket import de.fiereu.openmmo.net.game.packets.KeepAlivePacket
@@ -26,6 +27,7 @@ import de.fiereu.openmmo.net.game.packets.RequestCharactersPacket
import de.fiereu.openmmo.net.game.packets.RequestPlayerPacket import de.fiereu.openmmo.net.game.packets.RequestPlayerPacket
import de.fiereu.openmmo.net.game.packets.RequestSocialProfilePacket import de.fiereu.openmmo.net.game.packets.RequestSocialProfilePacket
import de.fiereu.openmmo.net.game.packets.SelectCharacterPacket import de.fiereu.openmmo.net.game.packets.SelectCharacterPacket
import de.fiereu.openmmo.net.game.packets.ShopSellRequestPacket
import de.fiereu.openmmo.net.game.packets.TileInteractPacket import de.fiereu.openmmo.net.game.packets.TileInteractPacket
import de.fiereu.openmmo.net.game.packets.UnblockPlayerPacket import de.fiereu.openmmo.net.game.packets.UnblockPlayerPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleActionPacket import de.fiereu.openmmo.net.game.packets.battle.BattleActionPacket
@@ -69,6 +71,7 @@ import de.fiereu.openmmo.server.game.services.LoginService
import de.fiereu.openmmo.server.game.services.MovementService import de.fiereu.openmmo.server.game.services.MovementService
import de.fiereu.openmmo.server.game.services.MultiplayerService import de.fiereu.openmmo.server.game.services.MultiplayerService
import de.fiereu.openmmo.server.game.services.PresenceService import de.fiereu.openmmo.server.game.services.PresenceService
import de.fiereu.openmmo.server.game.services.ShopService
import de.fiereu.openmmo.server.game.services.SocialService import de.fiereu.openmmo.server.game.services.SocialService
import de.fiereu.openmmo.server.game.services.command.ChatCommandService import de.fiereu.openmmo.server.game.services.command.ChatCommandService
import de.fiereu.openmmo.server.game.session.PLAYER_STATE import de.fiereu.openmmo.server.game.session.PLAYER_STATE
@@ -95,6 +98,7 @@ constructor(
private val guildService: GuildService, private val guildService: GuildService,
private val battleService: BattleService, private val battleService: BattleService,
private val chatCommandService: ChatCommandService, private val chatCommandService: ChatCommandService,
private val shopService: ShopService,
private val scriptRunner: ScriptRunner, private val scriptRunner: ScriptRunner,
private val sessionRegistry: SessionRegistry, private val sessionRegistry: SessionRegistry,
private val characterStore: CharacterStore, private val characterStore: CharacterStore,
@@ -116,6 +120,8 @@ constructor(
onSuspend<TileInteractPacket> { event -> interactionService.onTileInteract(event) } onSuspend<TileInteractPacket> { event -> interactionService.onTileInteract(event) }
onSuspend<DialogActionResponsePacket> { event -> dialogService.onInteractive(event) } onSuspend<DialogActionResponsePacket> { event -> dialogService.onInteractive(event) }
onSuspend<DialogChoicePacket> { event -> dialogService.onDialogChoice(event) } onSuspend<DialogChoicePacket> { event -> dialogService.onDialogChoice(event) }
onSuspend<ExchangeItemRequestPacket> { event -> shopService.onBuy(event) }
onSuspend<ShopSellRequestPacket> { event -> shopService.onSell(event) }
on<AddFriendPacket> { event -> socialService.onAddFriend(event) } on<AddFriendPacket> { event -> socialService.onAddFriend(event) }
on<RemoveFriendPacket> { event -> socialService.onRemoveFriend(event) } on<RemoveFriendPacket> { event -> socialService.onRemoveFriend(event) }
@@ -5,6 +5,7 @@ import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.dialog.DialogLine import de.fiereu.openmmo.common.dialog.DialogLine
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemDef
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.packets.dialog.TextPokemonSpeciesArg import de.fiereu.openmmo.net.game.packets.dialog.TextPokemonSpeciesArg
import de.fiereu.openmmo.server.game.battle.BattleResult import de.fiereu.openmmo.server.game.battle.BattleResult
@@ -14,6 +15,7 @@ import de.fiereu.openmmo.server.game.services.DialogService
import de.fiereu.openmmo.server.game.services.MapEntryScripts import de.fiereu.openmmo.server.game.services.MapEntryScripts
import de.fiereu.openmmo.server.game.services.ScriptMovementService import de.fiereu.openmmo.server.game.services.ScriptMovementService
import de.fiereu.openmmo.server.game.services.ScriptWarpService import de.fiereu.openmmo.server.game.services.ScriptWarpService
import de.fiereu.openmmo.server.game.services.ShopService
import de.fiereu.openmmo.server.game.services.StoryClientState import de.fiereu.openmmo.server.game.services.StoryClientState
import de.fiereu.openmmo.server.game.services.StoryPlayerService import de.fiereu.openmmo.server.game.services.StoryPlayerService
import de.fiereu.openmmo.server.game.services.StoryService import de.fiereu.openmmo.server.game.services.StoryService
@@ -36,6 +38,7 @@ internal constructor(
internal val characters: CharacterStore? = null, internal val characters: CharacterStore? = null,
private val maps: MapManager? = null, private val maps: MapManager? = null,
private val entryScripts: MapEntryScripts? = null, private val entryScripts: MapEntryScripts? = null,
private val shops: ShopService? = null,
) { ) {
private val characterId: Long? private val characterId: Long?
get() = state.characterId get() = state.characterId
@@ -135,11 +138,18 @@ internal constructor(
fun healParty() = checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }.healParty(session, state) fun healParty() = checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }.healParty(session, state)
suspend fun giveItem(itemId: Int, quantity: Int = 1): Boolean = suspend fun giveItem(item: ItemDef, quantity: Int = 1): Boolean =
checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }.giveItem(session, state, itemId, quantity) checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }.giveItem(session, state, item, quantity)
/** Take an item back out of the bag, the decomp removeitem. False when the bag lacks it. */ /** Take an item back out of the bag, the decomp removeitem. False when the bag lacks it. */
suspend fun takeItem(itemId: Int, quantity: Int = 1): Boolean = giveItem(itemId, -quantity) suspend fun takeItem(item: ItemDef, quantity: Int = 1): Boolean = giveItem(item, -quantity)
/**
* Opens the mart window on [items], the decomp pokemart. It does not wait: the player shops while
* the script ends, because nothing in the capture tells the server when the window closed.
*/
fun pokemart(vararg items: ItemDef) =
checkNotNull(shops) { "Shop service is unavailable" }.open(session, entityId, items.toList())
/** Run a non-catchable, non-escapable story battle and wait for its result. */ /** Run a non-catchable, non-escapable story battle and wait for its result. */
suspend fun battle(dexId: Int, level: Int, vararg moveIds: Int): BattleResult = suspend fun battle(dexId: Int, level: Int, vararg moveIds: Int): BattleResult =
@@ -7,6 +7,7 @@ import de.fiereu.openmmo.server.game.services.DialogService
import de.fiereu.openmmo.server.game.services.MapEntryScripts import de.fiereu.openmmo.server.game.services.MapEntryScripts
import de.fiereu.openmmo.server.game.services.ScriptMovementService import de.fiereu.openmmo.server.game.services.ScriptMovementService
import de.fiereu.openmmo.server.game.services.ScriptWarpService import de.fiereu.openmmo.server.game.services.ScriptWarpService
import de.fiereu.openmmo.server.game.services.ShopService
import de.fiereu.openmmo.server.game.services.StoryPlayerService import de.fiereu.openmmo.server.game.services.StoryPlayerService
import de.fiereu.openmmo.server.game.services.StoryService import de.fiereu.openmmo.server.game.services.StoryService
import de.fiereu.openmmo.server.game.session.PlayerState import de.fiereu.openmmo.server.game.session.PlayerState
@@ -44,6 +45,7 @@ constructor(
private val characterStore: CharacterStore, private val characterStore: CharacterStore,
private val mapManager: MapManager, private val mapManager: MapManager,
private val entryScripts: MapEntryScripts, private val entryScripts: MapEntryScripts,
private val shopService: ShopService,
) { ) {
fun run(session: SessionContext, state: PlayerState, script: Script, entityId: Long) = fun run(session: SessionContext, state: PlayerState, script: Script, entityId: Long) =
runAll(session, state, listOf(script), entityId) runAll(session, state, listOf(script), entityId)
@@ -94,6 +96,7 @@ constructor(
characterStore, characterStore,
mapManager, mapManager,
entryScripts, entryScripts,
shopService,
) )
scope.launch { scope.launch {
var finished = false var finished = false
@@ -1,6 +1,7 @@
package de.fiereu.openmmo.server.game.script.generated.hoenn package de.fiereu.openmmo.server.game.script.generated.hoenn
import de.fiereu.openmmo.dialog.generated.hoenn.RustboroCity_Gym import de.fiereu.openmmo.dialog.generated.hoenn.RustboroCity_Gym
import de.fiereu.openmmo.items.generated.Items
import de.fiereu.openmmo.server.game.battle.BattleResult import de.fiereu.openmmo.server.game.battle.BattleResult
import de.fiereu.openmmo.server.game.script.Script import de.fiereu.openmmo.server.game.script.Script
import de.fiereu.openmmo.server.game.script.ScriptContext import de.fiereu.openmmo.server.game.script.ScriptContext
@@ -9,7 +10,6 @@ import de.fiereu.openmmo.story.generated.hoenn.HoennVars
private const val GEODUDE = 74 private const val GEODUDE = 74
private const val NOSEPASS = 299 private const val NOSEPASS = 299
private const val TM39_ROCK_TOMB_ITEM = 5327
/** /**
* Not ported yet. Decomp body: * Not ported yet. Decomp body:
@@ -52,7 +52,7 @@ internal object RustboroCity_Gym_EventScript_Roxanne : Script {
} }
private suspend fun giveRockTomb(ctx: ScriptContext) { private suspend fun giveRockTomb(ctx: ScriptContext) {
if (ctx.giveItem(TM39_ROCK_TOMB_ITEM)) { if (ctx.giveItem(Items.TM39)) {
ctx.setFlag(HoennFlags.FLAG_RECEIVED_TM_ROCK_TOMB) ctx.setFlag(HoennFlags.FLAG_RECEIVED_TM_ROCK_TOMB)
ctx.say(RustboroCity_Gym.ExplainRockTomb) ctx.say(RustboroCity_Gym.ExplainRockTomb)
} }
@@ -265,7 +265,7 @@ internal object PalletTown_ProfessorOaksLab_EventScript_ProfOak : Script {
private suspend fun receiveDexScene(ctx: ScriptContext) { private suspend fun receiveDexScene(ctx: ScriptContext) {
ctx.say(PalletTown_ProfessorOaksLab.OakHaveSomethingForMe) ctx.say(PalletTown_ProfessorOaksLab.OakHaveSomethingForMe)
ctx.sign(PalletTown_ProfessorOaksLab.DeliveredOaksParcel) ctx.sign(PalletTown_ProfessorOaksLab.DeliveredOaksParcel)
ctx.takeItem(Items.OAKS_PARCEL) ctx.takeItem(Items.PARCEL)
ctx.say(PalletTown_ProfessorOaksLab.OakCustomBallIOrdered) ctx.say(PalletTown_ProfessorOaksLab.OakCustomBallIOrdered)
ctx.sign(PalletTown_ProfessorOaksLab.RivalGramps) ctx.sign(PalletTown_ProfessorOaksLab.RivalGramps)
@@ -60,16 +60,16 @@ internal object ViridianCity_EventScript_TutorialTriggerRight : Script {
} }
} }
/** The old man's catching demonstration, which ends with him handing over the Teachy TV. */
private suspend fun tutorialBattle(ctx: ScriptContext) { private suspend fun tutorialBattle(ctx: ScriptContext) {
ctx.sayNpc(LOCALID_TUTORIAL_MAN, ViridianCity.ShowYouHowToCatchMons) ctx.sayNpc(LOCALID_TUTORIAL_MAN, ViridianCity.ShowYouHowToCatchMons)
// TODO Play the catching tutorial battle // TODO Play the catching tutorial battle
// The decomp runs StartOldManTutorialBattle, a scripted battle the old man fights for the // The decomp runs StartOldManTutorialBattle, a scripted battle the old man fights for the
// player. Scripted battles always use the player's own party today, so the demonstration is // player. Scripted battles always use the player's own party today, so the demonstration is
// skipped and only its reward is given. // skipped.
ctx.sayNpc(LOCALID_TUTORIAL_MAN, ViridianCity.ThatWasEducationalTakeThis) ctx.sayNpc(LOCALID_TUTORIAL_MAN, ViridianCity.ThatWasEducationalTakeThis)
ctx.setVar(KantoVars.VAR_MAP_SCENE_VIRIDIAN_CITY_OLD_MAN, 2) ctx.setVar(KantoVars.VAR_MAP_SCENE_VIRIDIAN_CITY_OLD_MAN, 2)
ctx.giveItem(Items.TEACHY_TV) // The decomp hands over a Teachy TV here. PokeMMO has no such item, so the reward is dropped
// rather than substituted, and the lines around it are all the player gets.
ctx.sayNpc(LOCALID_TUTORIAL_MAN, ViridianCity.WatchThatToLearnBasics) ctx.sayNpc(LOCALID_TUTORIAL_MAN, ViridianCity.WatchThatToLearnBasics)
} }
@@ -1,5 +1,6 @@
package de.fiereu.openmmo.server.game.script.generated.kanto package de.fiereu.openmmo.server.game.script.generated.kanto
import de.fiereu.openmmo.dialog.generated.kanto.Misc
import de.fiereu.openmmo.dialog.generated.kanto.ViridianCity_Mart import de.fiereu.openmmo.dialog.generated.kanto.ViridianCity_Mart
import de.fiereu.openmmo.items.generated.Items import de.fiereu.openmmo.items.generated.Items
import de.fiereu.openmmo.server.game.script.MovementStep.FACE_DOWN import de.fiereu.openmmo.server.game.script.MovementStep.FACE_DOWN
@@ -23,7 +24,7 @@ internal object ViridianCity_Mart_EventScript_ParcelScene : Script {
) )
ctx.sayNpc(LOCALID_MART_CLERK, ViridianCity_Mart.TakeThisToProfOak) ctx.sayNpc(LOCALID_MART_CLERK, ViridianCity_Mart.TakeThisToProfOak)
ctx.setVar(KantoVars.VAR_MAP_SCENE_VIRIDIAN_CITY_MART, 1) ctx.setVar(KantoVars.VAR_MAP_SCENE_VIRIDIAN_CITY_MART, 1)
ctx.giveItem(Items.OAKS_PARCEL) ctx.giveItem(Items.PARCEL)
ctx.sign(ViridianCity_Mart.ReceivedOaksParcelFromClerk) ctx.sign(ViridianCity_Mart.ReceivedOaksParcelFromClerk)
ctx.setVar(KantoVars.VAR_MAP_SCENE_PALLET_TOWN_PROFESSOR_OAKS_LAB, 5) ctx.setVar(KantoVars.VAR_MAP_SCENE_PALLET_TOWN_PROFESSOR_OAKS_LAB, 5)
} }
@@ -34,8 +35,8 @@ internal object ViridianCity_Mart_EventScript_Clerk : Script {
if (ctx.getVar(KantoVars.VAR_MAP_SCENE_VIRIDIAN_CITY_MART) == 1) { if (ctx.getVar(KantoVars.VAR_MAP_SCENE_VIRIDIAN_CITY_MART) == 1) {
return ctx.say(ViridianCity_Mart.SayHiToOakForMe) return ctx.say(ViridianCity_Mart.SayHiToOakForMe)
} }
// TODO Open the mart shop ctx.say(Misc.Text_MayIHelpYou)
// The decomp runs pokemart with the shop's item list. Buying and selling needs a shop verb. ctx.pokemart(Items.POKE_BALL, Items.POTION, Items.ANTIDOTE, Items.PARLYZ_HEAL)
} }
} }
@@ -7,6 +7,7 @@ import de.fiereu.openmmo.common.enums.BattleAction
import de.fiereu.openmmo.common.enums.IVs import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.items.generated.Items import de.fiereu.openmmo.items.generated.Items
import de.fiereu.openmmo.moves.MoveRegistry import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.MapLoadedAckPacket import de.fiereu.openmmo.net.game.packets.MapLoadedAckPacket
@@ -43,8 +44,6 @@ import javax.inject.Singleton
private val log = KotlinLogging.logger {} private val log = KotlinLogging.logger {}
private val POKE_BALL_ITEM: Short = Items.POKE_BALL.toShort()
/** /**
* A prompt waiting for its answer, kept after the battle ends. A trainer battle can raise one * A prompt waiting for its answer, kept after the battle ends. A trainer battle can raise one
* monster past a level more than once, so these are held per monster rather than per player. * monster past a level more than once, so these are held per monster rather than per player.
@@ -75,8 +74,11 @@ constructor(
private val speciesRegistry: SpeciesRegistry, private val speciesRegistry: SpeciesRegistry,
private val moveRegistry: MoveRegistry, private val moveRegistry: MoveRegistry,
private val trainers: TrainerRegistry, private val trainers: TrainerRegistry,
private val items: ItemRegistry,
) { ) {
private val pokeBallItemId: Short by lazy { items.idOf(Items.POKE_BALL).toShort() }
private val pendingLearns = ConcurrentHashMap<Long, PendingMoveLearn>() private val pendingLearns = ConcurrentHashMap<Long, PendingMoveLearn>()
fun onBattlePacket(event: PacketEvent<*>) { fun onBattlePacket(event: PacketEvent<*>) {
@@ -425,7 +427,7 @@ constructor(
battle.session.send( battle.session.send(
BattleListEventPacket( BattleListEventPacket(
kind = 0, kind = 0,
value = POKE_BALL_ITEM, value = pokeBallItemId,
subKind = 4, subKind = 4,
detail = BattleListEventDetail(listType = 1, value = 1), detail = BattleListEventDetail(listType = 1, value = 1),
), ),
@@ -0,0 +1,143 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.network.PacketEvent
import de.fiereu.network.SessionContext
import de.fiereu.openmmo.items.ItemDef
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.net.game.packets.ExchangeItemRequestPacket
import de.fiereu.openmmo.net.game.packets.LocalCharacterDeltaPacket
import de.fiereu.openmmo.net.game.packets.ShopCatalogPacket
import de.fiereu.openmmo.net.game.packets.ShopItem
import de.fiereu.openmmo.net.game.packets.ShopSellRequestPacket
import de.fiereu.openmmo.server.game.session.OPEN_SHOP
import de.fiereu.openmmo.server.game.session.OpenShop
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import javax.inject.Singleton
private val log = KotlinLogging.logger {}
// From the captures: every mart carries the same shop id, and a shelf the player cannot empty.
private const val MART_SHOP_ID: Short = 103
private const val ENDLESS_SHELF: Short = 0x7FFF
// A bag stack id is the item id shifted up, with the item entity tag in the low bits.
private const val ITEM_ENTITY_SHIFT = 16
@Singleton
class ShopService
@Inject
constructor(
private val characterStore: CharacterStore,
private val items: ItemRegistry,
) {
fun open(session: SessionContext, npcEntityId: Long, shelf: List<ItemDef>) {
// Deliberately the item table's price, until we know where the real one comes from. The
// mart_catalog capture charges 200 for a Potion where the table says 300.
val offered =
shelf.mapNotNull { item ->
val id = items.idOrNull(item)
if (id == null) {
log.warn { "Shop offered ${item.name}, which has no id in this build" }
null
} else {
item to ShopItem(id.toShort(), 1, ENDLESS_SHELF, item.price)
}
}
val state = session.attributes[PLAYER_STATE] ?: return
session.attributes[OPEN_SHOP] =
OpenShop(state.regionId, state.bankId, state.mapId, offered.toMap())
session.send(ShopCatalogPacket.open(MART_SHOP_ID, npcEntityId, offered.map { it.second }))
}
/** The shelf, if one is open and the player is still standing where they opened it. */
private fun openShelf(session: SessionContext): Map<ItemDef, ShopItem>? {
val open = session.attributes[OPEN_SHOP] ?: return null
val state = session.attributes[PLAYER_STATE] ?: return null
if (open.regionId != state.regionId ||
open.bankId != state.bankId ||
open.mapId != state.mapId) {
session.attributes.remove(OPEN_SHOP)
return null
}
return open.shelf
}
suspend fun onBuy(event: PacketEvent<ExchangeItemRequestPacket>) {
val session = event.session
val shelf = openShelf(session) ?: return
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return
val quantity = event.packet.quantity.toInt()
val item = items.get(event.packet.itemEntityRef.toInt())
val offer = item?.let { shelf[it] }
if (offer == null || quantity <= 0) {
log.warn {
"char=$charId asked for $quantity of ${event.packet.itemEntityRef}, not on this shelf"
}
return
}
val itemId = offer.itemId.toInt()
// A quantity is a signed Short, so a dear enough item would wrap the product negative.
val cost = offer.price.toLong() * quantity
val stored = characterStore.getCharacter(charId) ?: return
if (stored.info.money < cost) {
log.info { "char=$charId cannot afford $quantity of ${item.name} at $cost" }
return
}
// The item goes in first, so a bag that refuses it costs the player nothing.
if (!characterStore.addItem(charId, itemId, quantity)) return
if (!characterStore.addMoney(charId, -cost.toInt())) {
if (!characterStore.addItem(charId, itemId, -quantity)) {
log.error { "char=$charId keeps $quantity ${item.name} unpaid, the refund did not persist" }
}
return
}
log.info { "char=$charId bought $quantity ${item.name} for $cost" }
sendBagAndMoney(session, charId, itemId)
}
suspend fun onSell(event: PacketEvent<ShopSellRequestPacket>) {
val session = event.session
if (openShelf(session) == null) return
val charId = session.attributes[PLAYER_STATE]?.characterId ?: return
val quantity = event.packet.quantity.toInt()
val stored = characterStore.getCharacter(charId) ?: return
// The client sells the bag stack by the id the bag packet gave it, not by item id.
val itemId = (event.packet.itemEntityId shr ITEM_ENTITY_SHIFT).toInt()
val held = stored.items[itemId] ?: 0
if (quantity <= 0 || held < quantity) {
log.warn { "char=$charId offered $quantity of stack $itemId, holding $held" }
return
}
val item = items.get(itemId)
// Anything halving to nothing, a key item above all, would be deleted and paid nothing for.
if (item == null || item.price < 2) {
log.warn { "char=$charId offered stack $itemId, which a mart does not buy" }
return
}
val paid = item.price / 2 * quantity
if (!characterStore.addItem(charId, itemId, -quantity)) return
if (!characterStore.addMoney(charId, paid)) {
if (!characterStore.addItem(charId, itemId, quantity)) {
log.error { "char=$charId lost $quantity of stack $itemId, the refund did not persist" }
}
return
}
log.info { "char=$charId sold $quantity of ${item.name} for $paid" }
sendBagAndMoney(session, charId, itemId)
}
private fun sendBagAndMoney(session: SessionContext, charId: Long, itemId: Int) {
val after = characterStore.getCharacter(charId) ?: return
session.send(LocalCharacterDeltaPacket(money = after.info.money))
session.send(itemStackUpdatePacket(itemId, after.items[itemId] ?: 0))
}
}
@@ -5,9 +5,13 @@ import de.fiereu.openmmo.common.MAX_PARTY_SIZE
import de.fiereu.openmmo.common.Pokemon import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.items.ItemDef
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.moves.MoveRegistry import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket import de.fiereu.openmmo.net.game.packets.PokemonContainerPacket
import de.fiereu.openmmo.net.game.packets.SocialListEntryAddPacket import de.fiereu.openmmo.net.game.packets.SocialListEntryAddPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleAddPokemon
import de.fiereu.openmmo.net.game.packets.battle.BattleSideAddPokemonPacket
import de.fiereu.openmmo.net.game.packets.battle.ItemStack import de.fiereu.openmmo.net.game.packets.battle.ItemStack
import de.fiereu.openmmo.net.game.packets.battle.itemStacksPacket import de.fiereu.openmmo.net.game.packets.battle.itemStacksPacket
import de.fiereu.openmmo.pokemon.SpeciesRegistry import de.fiereu.openmmo.pokemon.SpeciesRegistry
@@ -29,6 +33,7 @@ constructor(
private val pokemonFactory: WildMonFactory, private val pokemonFactory: WildMonFactory,
private val species: SpeciesRegistry, private val species: SpeciesRegistry,
private val moves: MoveRegistry, private val moves: MoveRegistry,
private val items: ItemRegistry,
) { ) {
/** Gives a story Pokemon and syncs it. */ /** Gives a story Pokemon and syncs it. */
@@ -94,13 +99,13 @@ constructor(
suspend fun giveItem( suspend fun giveItem(
session: SessionContext, session: SessionContext,
state: PlayerState, state: PlayerState,
itemId: Int, item: ItemDef,
quantity: Int quantity: Int
): Boolean { ): Boolean {
val characterId = state.characterId ?: return false val characterId = state.characterId ?: return false
if (!characters.addItem(characterId, itemId, quantity)) return false if (!characters.addItem(characterId, items.idOf(item), quantity)) return false
val items = characters.getCharacter(characterId)?.items ?: return false val bag: Map<Int, Int> = characters.getCharacter(characterId)?.items ?: return false
session.send(storyItemStacksPacket(items)) session.send(storyItemStacksPacket(bag))
return true return true
} }
@@ -127,4 +132,23 @@ fun storyItemStacksPacket(items: Map<Int, Int>) =
) )
}) })
/**
* A bag stack, not a monster. The open shop window only refreshes its count when the update arrives
* as this single stack rather than as a whole new bag.
*/
fun itemStackUpdatePacket(itemId: Int, quantity: Int) =
BattleSideAddPokemonPacket(
side = 1,
pokemon =
BattleAddPokemon(
entityId = (itemId.toLong() shl 16) or ITEM_ENTITY_TAG,
frontSpriteId = itemId.toShort(),
backSpriteId = quantity.toShort(),
side = 1,
slot = 0,
partyIndex = -1,
statusEffect = null,
),
)
private const val ITEM_ENTITY_TAG = 0x5000L private const val ITEM_ENTITY_TAG = 0x5000L
@@ -146,6 +146,6 @@ val KANTO_CHECKPOINTS: List<StoryCheckpoint> =
KantoVars.VAR_STARTER_MON to 0, KantoVars.VAR_STARTER_MON to 0,
), ),
party = listOf(BULBASAUR), party = listOf(BULBASAUR),
items = mapOf(Items.OAKS_PARCEL to 1), items = mapOf(Items.PARCEL to 1),
), ),
) )
@@ -2,6 +2,7 @@ package de.fiereu.openmmo.server.game.services.command
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemDef
data class CheckpointMon(val dexId: Int, val level: Int, val moveIds: List<Int>) data class CheckpointMon(val dexId: Int, val level: Int, val moveIds: List<Int>)
@@ -20,5 +21,5 @@ data class StoryCheckpoint(
val storyFlags: Set<String>, val storyFlags: Set<String>,
val storyVars: Map<String, Int> = emptyMap(), val storyVars: Map<String, Int> = emptyMap(),
val party: List<CheckpointMon> = emptyList(), val party: List<CheckpointMon> = emptyList(),
val items: Map<Int, Int> = emptyMap(), val items: Map<ItemDef, Int> = emptyMap(),
) )
@@ -4,6 +4,7 @@ import de.fiereu.openmmo.common.CharacterPermissions
import de.fiereu.openmmo.common.enums.CharacterGender import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.Direction import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.maps.WarpTile import de.fiereu.openmmo.maps.WarpTile
import de.fiereu.openmmo.server.game.services.BattleService import de.fiereu.openmmo.server.game.services.BattleService
import de.fiereu.openmmo.server.game.services.StoryPlayerService import de.fiereu.openmmo.server.game.services.StoryPlayerService
@@ -23,6 +24,7 @@ constructor(
private val storyPlayerService: StoryPlayerService, private val storyPlayerService: StoryPlayerService,
private val warpService: WarpService, private val warpService: WarpService,
private val battleService: BattleService, private val battleService: BattleService,
private val items: ItemRegistry,
) : ChatCommand { ) : ChatCommand {
override val name = "story" override val name = "story"
override val usage = "/story [checkpoint|reset]" override val usage = "/story [checkpoint|reset]"
@@ -103,7 +105,7 @@ constructor(
characterStore.replaceProgress( characterStore.replaceProgress(
characterId = charId, characterId = charId,
party = emptyList(), party = emptyList(),
items = checkpoint.items, items = checkpoint.items.mapKeys { items.idOf(it.key) },
storyFlags = checkpoint.storyFlags, storyFlags = checkpoint.storyFlags,
storyVars = checkpoint.storyVars, storyVars = checkpoint.storyVars,
) )
@@ -1,6 +1,8 @@
package de.fiereu.openmmo.server.game.session package de.fiereu.openmmo.server.game.session
import de.fiereu.network.SessionAttribute import de.fiereu.network.SessionAttribute
import de.fiereu.openmmo.items.ItemDef
import de.fiereu.openmmo.net.game.packets.ShopItem
import de.fiereu.openmmo.net.game.packets.dialog.DialogActionResponsePacket import de.fiereu.openmmo.net.game.packets.dialog.DialogActionResponsePacket
import de.fiereu.openmmo.server.game.storage.StoredCharacter import de.fiereu.openmmo.server.game.storage.StoredCharacter
import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CompletableDeferred
@@ -25,3 +27,16 @@ val SCRIPT_SCOPE = SessionAttribute.of<CoroutineScope>("scriptScope")
* The character as it was before the running script started, so an unfinished one can be undone. * The character as it was before the running script started, so an unfinished one can be undone.
*/ */
val SCRIPT_SNAPSHOT = SessionAttribute.of<StoredCharacter>("scriptSnapshot") val SCRIPT_SNAPSHOT = SessionAttribute.of<StoredCharacter>("scriptSnapshot")
/**
* Nothing tells the server the mart window closed, so the map it opened on is recorded and a shelf
* left behind stops applying once the player walks off that map.
*/
data class OpenShop(
val regionId: Int,
val bankId: Int,
val mapId: Int,
val shelf: Map<ItemDef, ShopItem>,
)
val OPEN_SHOP = SessionAttribute.of<OpenShop>("openShop")
@@ -9,6 +9,7 @@ import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.IVs import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.moves.MoveRegistry import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket import de.fiereu.openmmo.net.game.packets.EntityMovePpPacket
import de.fiereu.openmmo.net.game.packets.EntityPresencePacket import de.fiereu.openmmo.net.game.packets.EntityPresencePacket
@@ -17,6 +18,7 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleActionSelectPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleBulkStatePacket import de.fiereu.openmmo.net.game.packets.battle.BattleBulkStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleEntityDeltaPacket import de.fiereu.openmmo.net.game.packets.battle.BattleEntityDeltaPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket import de.fiereu.openmmo.net.game.packets.battle.BattleFieldStatePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleListEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleQueuedEventPacket import de.fiereu.openmmo.net.game.packets.battle.BattleQueuedEventPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket import de.fiereu.openmmo.net.game.packets.battle.BattleSidePacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
@@ -103,6 +105,7 @@ private class Fixture(scope: CoroutineScope) {
speciesRegistry = SpeciesRegistry(), speciesRegistry = SpeciesRegistry(),
moveRegistry = MoveRegistry(), moveRegistry = MoveRegistry(),
trainers = TrainerRegistry(), trainers = TrainerRegistry(),
items = ItemRegistry(),
) )
suspend fun playerWithParty(level: Byte = 50, hp: Short = 999): Pair<FakeSession, Long> { suspend fun playerWithParty(level: Byte = 50, hp: Short = 999): Pair<FakeSession, Long> {
@@ -303,6 +306,21 @@ class BattleServiceTest :
} }
} }
test("the ball throw names the Poke Ball by the id the client knows") {
runTest {
val fx = Fixture(this)
val (session, _) = fx.playerWithParty()
session.startBattle(fx.service)
session.act(fx.service, BattleAction.ITEM)
session.sent
.filterIsInstance<BattleListEventPacket>()
.single { it.subKind == 4.toByte() }
.value shouldBe 5004.toShort()
}
}
test("a disconnect persists and removes the battle") { test("a disconnect persists and removes the battle") {
runTest { runTest {
val fx = Fixture(this) val fx = Fixture(this)
@@ -0,0 +1,230 @@
package de.fiereu.openmmo.server.game.services
import de.fiereu.network.PacketEvent
import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemDef
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.items.generated.Items
import de.fiereu.openmmo.net.game.packets.ExchangeItemRequestPacket
import de.fiereu.openmmo.net.game.packets.LocalCharacterDeltaPacket
import de.fiereu.openmmo.net.game.packets.ShopCatalogPacket
import de.fiereu.openmmo.net.game.packets.ShopSellRequestPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSideAddPokemonPacket
import de.fiereu.openmmo.server.game.session.OPEN_SHOP
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
private val SHELF = listOf(Items.POKE_BALL, Items.POTION, Items.ANTIDOTE, Items.PARLYZ_HEAL)
private const val CLERK_ENTITY = 4711L
private class ShopFixture(scope: CoroutineScope) {
val items = ItemRegistry()
val store = CharacterStore(FakeCharacterRepository(), EntityIdService(), scope)
val service = ShopService(store, items)
suspend fun shopper(): Pair<FakeSession, Long> {
val created = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN)
val session = FakeSession(created.info.id)
service.open(session, CLERK_ENTITY, SHELF)
session.sent.clear()
return session to created.info.id
}
suspend fun buy(session: FakeSession, id: Int, quantity: Int) {
service.onBuy(
PacketEvent(ExchangeItemRequestPacket(id.toShort(), quantity.toShort(), 0), session))
}
suspend fun sell(session: FakeSession, id: Int, quantity: Int) {
service.onSell(
PacketEvent(
ShopSellRequestPacket((id.toLong() shl 16) or 0x5000, quantity.toShort()), session))
}
suspend fun money(charId: Long): Int = store.getCharacter(charId)!!.info.money
suspend fun held(charId: Long, id: Int): Int = store.getCharacter(charId)!!.items[id] ?: 0
}
@OptIn(ExperimentalCoroutinesApi::class)
class ShopServiceTest :
FunSpec({
test("the shelf carries the ids and prices the client expects") {
runTest {
val fx = ShopFixture(backgroundScope)
val created = fx.store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN)
val session = FakeSession(created.info.id)
fx.service.open(session, CLERK_ENTITY, SHELF)
val catalog = session.sent.filterIsInstance<ShopCatalogPacket>().single()
catalog.npcEntityId shouldBe CLERK_ENTITY
catalog.items.map { it.itemId.toInt() to it.price } shouldContainExactly
listOf(5004 to 200, 5017 to 300, 5018 to 100, 5022 to 200)
}
}
test("an item with no id is left off the shelf rather than failing the open") {
runTest {
val fx = ShopFixture(backgroundScope)
val created = fx.store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN)
val session = FakeSession(created.info.id)
fx.service.open(session, CLERK_ENTITY, listOf(Items.POTION, ItemDef("Teachy TV", 100)))
session.sent.filterIsInstance<ShopCatalogPacket>().single().items.map {
it.itemId.toInt()
} shouldContainExactly listOf(5017)
}
}
test("buying resolves the id the client sends") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, 5017, 3)
fx.held(charId, 5017) shouldBe 3
fx.money(charId) shouldBe 30000 - 900
session.sent.filterIsInstance<LocalCharacterDeltaPacket>().single().money shouldBe 29100
}
}
test("the bought stack is announced on its own, so the open window can recount it") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, _) = fx.shopper()
fx.buy(session, 5004, 5)
val update = session.sent.filterIsInstance<BattleSideAddPokemonPacket>().single()
update.pokemon.frontSpriteId shouldBe 5004.toShort()
update.pokemon.backSpriteId shouldBe 5.toShort()
}
}
test("refuses an item this clerk does not sell") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, fx.items.idOf(Items.MASTER_BALL), 1)
fx.money(charId) shouldBe 30000
session.sent.shouldBeEmpty()
}
}
test("refuses a buy the player cannot pay for") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, 5017, 200)
fx.held(charId, 5017) shouldBe 0
fx.money(charId) shouldBe 30000
}
}
test("refuses a non-positive quantity") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, 5017, 0)
fx.buy(session, 5017, -2)
fx.money(charId) shouldBe 30000
}
}
test("selling pays half and reads the item out of the bag stack id") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, 5017, 4)
session.sent.clear()
fx.sell(session, 5017, 2)
fx.held(charId, 5017) shouldBe 2
fx.money(charId) shouldBe 30000 - 1200 + 300
session.sent
.filterIsInstance<BattleSideAddPokemonPacket>()
.single()
.pokemon
.backSpriteId shouldBe 2.toShort()
}
}
test("refuses to sell more than the bag holds") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, 5017, 1)
fx.sell(session, 5017, 2)
fx.held(charId, 5017) shouldBe 1
fx.money(charId) shouldBe 30000 - 300
}
}
test("ignores a sell with no shop open") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
fx.buy(session, 5017, 1)
session.attributes.remove(OPEN_SHOP)
session.sent.clear()
fx.sell(session, 5017, 1)
fx.held(charId, 5017) shouldBe 1
session.sent.shouldBeEmpty()
}
}
test("refuses to buy from a shelf the player has walked away from") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
session.state().mapId += 1
fx.buy(session, 5017, 1)
fx.held(charId, 5017) shouldBe 0
fx.money(charId) shouldBe 30000
session.attributes[OPEN_SHOP].shouldBeNull()
}
}
test("refuses to sell a key item, rather than deleting it for nothing") {
runTest {
val fx = ShopFixture(backgroundScope)
val (session, charId) = fx.shopper()
val townMap = fx.items.idOf(Items.TOWN_MAP)
fx.store.addItem(charId, townMap, 1)
session.sent.clear()
fx.sell(session, townMap, 1)
fx.held(charId, townMap) shouldBe 1
fx.money(charId) shouldBe 30000
session.sent.shouldBeEmpty()
}
}
})
@@ -4,6 +4,7 @@ import de.fiereu.openmmo.common.CharacterPermissions
import de.fiereu.openmmo.common.enums.CharacterGender import de.fiereu.openmmo.common.enums.CharacterGender
import de.fiereu.openmmo.common.enums.PokemonContainer import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.enums.Region import de.fiereu.openmmo.common.enums.Region
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.moves.MoveRegistry import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.net.game.packets.ChatMessagePacket import de.fiereu.openmmo.net.game.packets.ChatMessagePacket
@@ -49,6 +50,7 @@ class StoryResetTest :
val interest = InterestManager() val interest = InterestManager()
val species = SpeciesRegistry() val species = SpeciesRegistry()
val moves = MoveRegistry() val moves = MoveRegistry()
val items = ItemRegistry()
return StoryCommand( return StoryCommand(
characterStore = store, characterStore = store,
worldStateService = WorldStateService(), worldStateService = WorldStateService(),
@@ -58,6 +60,7 @@ class StoryResetTest :
WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService()), WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService()),
species, species,
moves, moves,
items,
), ),
warpService = warpService =
WarpService( WarpService(
@@ -80,7 +83,9 @@ class StoryResetTest :
speciesRegistry = species, speciesRegistry = species,
moveRegistry = moves, moveRegistry = moves,
trainers = TrainerRegistry(), trainers = TrainerRegistry(),
items = items,
), ),
items = items,
) )
} }
@@ -1,5 +1,6 @@
package de.fiereu.openmmo.server.game.testsupport package de.fiereu.openmmo.server.game.testsupport
import de.fiereu.openmmo.items.ItemRegistry
import de.fiereu.openmmo.maps.MapManager import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.moves.MoveRegistry import de.fiereu.openmmo.moves.MoveRegistry
import de.fiereu.openmmo.pokemon.LearnsetRegistry import de.fiereu.openmmo.pokemon.LearnsetRegistry
@@ -23,6 +24,7 @@ import de.fiereu.openmmo.server.game.services.NpcService
import de.fiereu.openmmo.server.game.services.PresenceService import de.fiereu.openmmo.server.game.services.PresenceService
import de.fiereu.openmmo.server.game.services.ScriptMovementService import de.fiereu.openmmo.server.game.services.ScriptMovementService
import de.fiereu.openmmo.server.game.services.ScriptWarpService import de.fiereu.openmmo.server.game.services.ScriptWarpService
import de.fiereu.openmmo.server.game.services.ShopService
import de.fiereu.openmmo.server.game.services.StoryPlayerService import de.fiereu.openmmo.server.game.services.StoryPlayerService
import de.fiereu.openmmo.server.game.services.StoryService import de.fiereu.openmmo.server.game.services.StoryService
import de.fiereu.openmmo.server.game.services.WarpService import de.fiereu.openmmo.server.game.services.WarpService
@@ -77,16 +79,18 @@ fun scriptRunner(
val species = SpeciesRegistry() val species = SpeciesRegistry()
val moves = MoveRegistry() val moves = MoveRegistry()
val wildMons = WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService()) val wildMons = WildMonFactory(species, moves, LearnsetRegistry(), EntityIdService())
val items = ItemRegistry()
return ScriptRunner( return ScriptRunner(
DialogService(), DialogService(),
story, story,
ScriptMovementService(mapManager, npcs, store), ScriptMovementService(mapManager, npcs, store),
ScriptWarpService(mapManager, mapLoad, store, presence), ScriptWarpService(mapManager, mapLoad, store, presence),
StoryPlayerService(store, wildMons, species, moves), StoryPlayerService(store, wildMons, species, moves, items),
battles, battles,
store, store,
mapManager, mapManager,
MapEntryScripts(ScriptRegistry(emptyMap()), story), MapEntryScripts(ScriptRegistry(emptyMap()), story),
ShopService(store, items),
) )
} }
@@ -105,5 +109,6 @@ private fun battleService(store: CharacterStore, interest: InterestManager): Bat
speciesRegistry = species, speciesRegistry = species,
moveRegistry = moves, moveRegistry = moves,
trainers = TrainerRegistry(), trainers = TrainerRegistry(),
items = ItemRegistry(),
) )
} }